@runfusion/fusion 0.2.5 → 0.2.6
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 +269 -47
- package/dist/client/assets/{AgentDetailView-CkuuGA1O.js → AgentDetailView-CBdzWtd-.js} +1 -1
- package/dist/client/assets/{AgentsView-CWFLMIDP.js → AgentsView-DPlnCa_B.js} +3 -3
- package/dist/client/assets/{ChatView-C_T91ebd.js → ChatView-BXzYysNG.js} +1 -1
- package/dist/client/assets/{DevServerView-ChWTzTvy.js → DevServerView-BY5cGz23.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-BMJIT7HD.js → DirectoryPicker-DZ90eSBn.js} +1 -1
- package/dist/client/assets/{DocumentsView-Co9to4Zp.css → DocumentsView-DV2DrCZb.css} +1 -1
- package/dist/client/assets/{DocumentsView-CjfVl8mZ.js → DocumentsView-lQwJmc4G.js} +1 -1
- package/dist/client/assets/{InsightsView-Rb735C9_.js → InsightsView-DUiZZ0z8.js} +1 -1
- package/dist/client/assets/{MemoryView-LLc_uNtG.js → MemoryView-DvSmMN6G.js} +1 -1
- package/dist/client/assets/{NodesView-BviqBWRA.js → NodesView-DgyM-ktg.js} +1 -1
- package/dist/client/assets/PiExtensionsManager-K7HQ08L4.css +1 -0
- package/dist/client/assets/PiExtensionsManager-wxB-q06A.js +11 -0
- package/dist/client/assets/{PluginManager-BywTPbLB.js → PluginManager-LH02ybSH.js} +1 -1
- package/dist/client/assets/PluginManager-tCFMZMLL.css +1 -0
- package/dist/client/assets/{RoadmapsView-Dhl--4vY.js → RoadmapsView-ANn2jmsU.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-CVtmwoJC.js → SetupWizardModal-UxlAtKWA.js} +1 -1
- package/dist/client/assets/{SkillsView-CG9y4fsE.js → SkillsView-DEjGh7wW.js} +1 -1
- package/dist/client/assets/{folder-open-BVDq27HP.js → folder-open-J7yPbaCt.js} +1 -1
- package/dist/client/assets/index-BdJsO65L.css +1 -0
- package/dist/client/assets/index-CHoVMPAA.js +649 -0
- package/dist/client/assets/{upload-BDvpReDO.js → upload-B_grq4hM.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/extension.js +70 -8
- package/dist/pi-claude-cli/package.json +1 -1
- package/package.json +5 -5
- package/dist/client/assets/PiExtensionsManager-CPgmJgDk.css +0 -1
- package/dist/client/assets/PiExtensionsManager-CriZBkQe.js +0 -11
- package/dist/client/assets/PluginManager-D64RIzmL.css +0 -1
- package/dist/client/assets/index-CikysL-d.js +0 -644
- package/dist/client/assets/index-Da1qmtc7.css +0 -1
|
@@ -0,0 +1,649 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-LH02ybSH.js","assets/vendor-react-K0fH_qHe.js","assets/DirectoryPicker-DZ90eSBn.js","assets/folder-open-J7yPbaCt.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/PluginManager-tCFMZMLL.css","assets/PiExtensionsManager-wxB-q06A.js","assets/PiExtensionsManager-K7HQ08L4.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-UxlAtKWA.js","assets/AgentsView-DPlnCa_B.js","assets/upload-B_grq4hM.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-lQwJmc4G.js","assets/DocumentsView-DV2DrCZb.css","assets/InsightsView-DUiZZ0z8.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-DgyM-ktg.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-BXzYysNG.js","assets/RoadmapsView-ANn2jmsU.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-DEjGh7wW.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-DvSmMN6G.js","assets/MemoryView-DhinauGs.css","assets/DevServerView-BY5cGz23.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as a,j as e,a as Na,g as Lm,R as zm,c as Cf}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 l of r)if(l.type==="childList")for(const o of l.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(r){const l={};return r.integrity&&(l.integrity=r.integrity),r.referrerPolicy&&(l.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?l.credentials="include":r.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function i(r){if(r.ep)return;r.ep=!0;const l=s(r);fetch(r.href,l)}})();/**
|
|
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 Om=(...t)=>t.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 Ef=t=>t.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 Mf=t=>t.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 Fc=t=>{const n=Mf(t);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 pl={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 Af=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Pf=a.createContext({}),_f=()=>a.useContext(Pf),Tf=a.forwardRef(({color:t,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:l,iconNode:o,...d},m)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=_f()??{},f=i??h?Number(s??u)*24/Number(n??c):s??u;return a.createElement("svg",{ref:m,...pl,width:n??c??pl.width,height:n??c??pl.height,stroke:t??g,strokeWidth:f,className:Om("lucide",p,r),...!l&&!Af(d)&&{"aria-hidden":"true"},...d},[...o.map(([b,v])=>a.createElement(b,v)),...Array.isArray(l)?l:[l]])});/**
|
|
33
|
+
* @license lucide-react v1.7.0 - ISC
|
|
34
|
+
*
|
|
35
|
+
* This source code is licensed under the ISC license.
|
|
36
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
+
*/const Qe=(t,n)=>{const s=a.forwardRef(({className:i,...r},l)=>a.createElement(Tf,{ref:l,iconNode:n,className:Om(`lucide-${Ef(Fc(t))}`,`lucide-${t}`,i),...r}));return s.displayName=Fc(t),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 Rf=[["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"}]],Ns=Qe("activity",Rf);/**
|
|
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 If=[["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"}]],qr=Qe("archive",If);/**
|
|
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 $f=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Oa=Qe("arrow-down",$f);/**
|
|
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 Df=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],sa=Qe("arrow-left",Df);/**
|
|
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 Ff=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ba=Qe("arrow-right",Ff);/**
|
|
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 Lf=[["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"}]],Bm=Qe("arrow-up-down",Lf);/**
|
|
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 zf=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],bi=Qe("arrow-up",zf);/**
|
|
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 Of=[["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"}]],Um=Qe("book-open",Of);/**
|
|
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 Bf=[["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"}]],sn=Qe("bot",Bf);/**
|
|
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 Uf=[["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"}]],uo=Qe("box",Uf);/**
|
|
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 Hf=[["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"}]],Cr=Qe("brain",Hf);/**
|
|
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 qf=[["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"}]],Hm=Qe("calendar",qf);/**
|
|
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 Vf=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Wf=Qe("check-check",Vf);/**
|
|
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 Kf=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],An=Qe("check",Kf);/**
|
|
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 Gf=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Lt=Qe("chevron-down",Gf);/**
|
|
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 Jf=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Ho=Qe("chevron-left",Jf);/**
|
|
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 Yf=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],rn=Qe("chevron-right",Yf);/**
|
|
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 Qf=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Fs=Qe("chevron-up",Qf);/**
|
|
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 Xf=[["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"}]],is=Qe("circle-alert",Xf);/**
|
|
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 Zf=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],en=Qe("circle-check-big",Zf);/**
|
|
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 eg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Vr=Qe("circle-dot",eg);/**
|
|
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 tg=[["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"}]],Lc=Qe("circle-question-mark",tg);/**
|
|
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 ng=[["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"}]],Ua=Qe("circle-x",ng);/**
|
|
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 sg=[["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"}]],ig=Qe("clipboard-list",sg);/**
|
|
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 ag=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Hi=Qe("clock",ag);/**
|
|
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 rg=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],qm=Qe("code",rg);/**
|
|
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 lg=[["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"}]],og=Qe("columns-3",lg);/**
|
|
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 cg=[["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"}]],qi=Qe("copy",cg);/**
|
|
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 dg=[["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"}]],ug=Qe("cpu",dg);/**
|
|
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 mg=[["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"}]],hg=Qe("download",mg);/**
|
|
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 pg=[["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"}]],fg=Qe("ellipsis-vertical",pg);/**
|
|
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 gg=[["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"}]],mo=Qe("ellipsis",gg);/**
|
|
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 bg=[["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"}]],xg=Qe("external-link",bg);/**
|
|
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 vg=[["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"}]],yg=Qe("eye-off",vg);/**
|
|
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 kg=[["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"}]],qo=Qe("eye",kg);/**
|
|
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 jg=[["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"}]],Ms=Qe("file-code",jg);/**
|
|
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 wg=[["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"}]],Vm=Qe("file-diff",wg);/**
|
|
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 Ng=[["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"}]],Sg=Qe("file-minus",Ng);/**
|
|
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 Cg=[["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"}]],Wm=Qe("file-pen",Cg);/**
|
|
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 Eg=[["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"}]],Mg=Qe("file-plus",Eg);/**
|
|
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 Ag=[["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"}]],Pg=Qe("file-question-mark",Ag);/**
|
|
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 _g=[["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"}]],vi=Qe("file-text",_g);/**
|
|
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 Tg=[["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"}]],Rg=Qe("file-type",Tg);/**
|
|
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 Ig=[["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"}]],Km=Qe("file",Ig);/**
|
|
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 $g=[["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"}]],ho=Qe("folder-git-2",$g);/**
|
|
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 Dg=[["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"}]],zc=Qe("folder-root",Dg);/**
|
|
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 Fg=[["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"}]],Pn=Qe("folder",Fg);/**
|
|
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 Lg=[["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"}]],Er=Qe("funnel",Lg);/**
|
|
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 zg=[["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"}]],Ls=Qe("git-branch",zg);/**
|
|
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 Og=[["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"}]],Ta=Qe("git-commit-horizontal",Og);/**
|
|
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 Bg=[["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"}]],Gm=Qe("git-merge",Bg);/**
|
|
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 Ug=[["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"}]],ts=Qe("git-pull-request",Ug);/**
|
|
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 Hg=[["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"}]],yi=Qe("globe",Hg);/**
|
|
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 qg=[["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"}]],Jm=Qe("grid-3x3",qg);/**
|
|
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 Vg=[["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"}]],Vo=Qe("grip-vertical",Vg);/**
|
|
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 Wg=[["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"}]],Kg=Qe("hard-drive",Wg);/**
|
|
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 Gg=[["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"}]],Jg=Qe("heart",Gg);/**
|
|
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 Yg=[["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"}]],Ra=Qe("history",Yg);/**
|
|
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 Qg=[["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"}]],Sa=Qe("inbox",Qg);/**
|
|
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 Xg=[["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"}]],Ym=Qe("key",Xg);/**
|
|
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 Zg=[["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"}]],ki=Qe("layers",Zg);/**
|
|
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 eb=[["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"}]],ji=Qe("layout-grid",eb);/**
|
|
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 tb=[["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=Qe("lightbulb",tb);/**
|
|
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 nb=[["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"}]],Vi=Qe("link",nb);/**
|
|
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 sb=[["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"}]],ib=Qe("list-plus",sb);/**
|
|
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 ab=[["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"}]],Wr=Qe("list-tree",ab);/**
|
|
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 rb=[["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"}]],po=Qe("list",rb);/**
|
|
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 lb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ct=Qe("loader-circle",lb);/**
|
|
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=[["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"}]],Kr=Qe("lock",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 cb=[["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"}]],Ia=Qe("mail",cb);/**
|
|
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 db=[["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"}]],fo=Qe("map",db);/**
|
|
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 ub=[["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"}]],Zs=Qe("maximize-2",ub);/**
|
|
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 mb=[["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"}]],ei=Qe("message-square",mb);/**
|
|
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 hb=[["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"}]],Ks=Qe("minimize-2",hb);/**
|
|
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 pb=[["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"}]],Gr=Qe("monitor",pb);/**
|
|
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:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]],Qm=Qe("moon",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:"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"}]],bb=Qe("move",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:"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"}]],go=Qe("package",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=[["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"}]],yb=Qe("paperclip",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 kb=[["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"}]],Ds=Qe("pause",kb);/**
|
|
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 jb=[["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"}]],Dn=Qe("pencil",jb);/**
|
|
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:"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"}]],an=Qe("play",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=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],qt=Qe("plus",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:"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"}]],Xm=Qe("radio",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:"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"}]],vn=Qe("refresh-cw",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:"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"}]],Oc=Qe("rocket",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 Mb=[["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"}]],Ab=Qe("rotate-ccw",Mb);/**
|
|
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 Pb=[["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"}]],Zm=Qe("save",Pb);/**
|
|
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 _b=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Oi=Qe("search",_b);/**
|
|
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 Tb=[["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"}]],gi=Qe("send",Tb);/**
|
|
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 Rb=[["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"}]],Mr=Qe("server",Rb);/**
|
|
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 Ib=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],$b=Qe("settings-2",Ib);/**
|
|
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:"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"}]],$a=Qe("settings",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 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"}]],Lb=Qe("shield",Fb);/**
|
|
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=[["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"}]],Ln=Qe("sparkles",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=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],cs=Qe("square",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 Bb=[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]],eh=Qe("sun",Bb);/**
|
|
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 Ub=[["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"}]],ns=Qe("target",Ub);/**
|
|
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 Hb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Os=Qe("terminal",Hb);/**
|
|
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 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"}]],Ar=Qe("text-wrap",qb);/**
|
|
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 Vb=[["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"}]],Ut=Qe("trash-2",Vb);/**
|
|
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 Wb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Kb=Qe("trending-up",Wb);/**
|
|
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 Gb=[["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"}]],Wo=Qe("triangle-alert",Gb);/**
|
|
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 Jb=[["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"}]],Bc=Qe("unlink",Jb);/**
|
|
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 Yb=[["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"}]],Pi=Qe("user",Yb);/**
|
|
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 Qb=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],Xb=Qe("users",Qb);/**
|
|
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:"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"}]],th=Qe("webhook",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 ex=[["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"}]],bo=Qe("workflow",ex);/**
|
|
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 tx=[["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"}]],nx=Qe("wrench",tx);/**
|
|
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 sx=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Ft=Qe("x",sx);/**
|
|
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 ix=[["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"}]],Sn=Qe("zap",ix);class Jr 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),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 e.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[e.jsx("div",{className:"error-boundary__icon",children:e.jsx(Wo,{size:40})}),e.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&e.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),e.jsxs("div",{className:"error-boundary__actions",children:[e.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),e.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Zn({children:t,onError:n}){return e.jsx(Jr,{level:"page",onError:n,children:t})}function mi({children:t,onError:n}){return e.jsx(Jr,{level:"modal",onError:n,children:t})}function ax({children:t,onError:n}){return e.jsx(Jr,{level:"root",onError:n,children:t})}const rx="modulepreload",lx=function(t){return"/"+t},Uc={},Zt=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let o=function(c){return Promise.all(c.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),m=d?.nonce||d?.getAttribute("nonce");r=o(s.map(c=>{if(c=lx(c),c in Uc)return;Uc[c]=!0;const u=c.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${h}`))return;const g=document.createElement("link");if(g.rel=u?"stylesheet":rx,u||(g.as="script"),g.crossOrigin="",g.href=c,m&&g.setAttribute("nonce",m),document.head.appendChild(g),u)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function l(o){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=o,window.dispatchEvent(d),!d.defaultPrevented)throw o}return r.then(o=>{for(const d of o||[])d.status==="rejected"&&l(d.reason);return n().catch(l)})},Ko="fn.authToken",Hc="token",ox="fn_token";let Bi,qc=!1,Pr=!1;const xo="fn:auth-token-recovery-required";function cx(){try{const t=window.localStorage.getItem(Ko);return t&&t.length>0?t:void 0}catch{return}}function nh(t){try{window.localStorage.setItem(Ko,t)}catch{}}function dx(){if(!(qc||typeof window>"u")){qc=!0;try{const t=new URL(window.location.href),n=t.searchParams.get(Hc);if(!n)return;nh(n),t.searchParams.delete(Hc);const s=t.pathname+(t.search?t.search:"")+t.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Wi(){if(Bi!==void 0)return Bi;const t=dx();if(t)return Bi=t,t;const n=cx();if(n)return Bi=n,n}function ux(t){Bi=t,Pr=!1,nh(t)}function mx(){Bi=void 0,Pr=!1;try{window.localStorage.removeItem(Ko)}catch{}}function Vc(t){return t==="ws:"?"http:":t==="wss:"?"https:":t}function hx(t){return t==="http:"||t==="https:"||t==="ws:"||t==="wss:"}function px(t){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!hx(t.protocol))return!1;const s=t.hostname===n.hostname,i=t.port===n.port,r=Vc(t.protocol)===Vc(n.protocol);return s&&i&&r}function fx(t){if(!(typeof window>"u"))try{const n=new URL(t,window.location.origin),s=t.startsWith("/");return{parsed:n,preserveRelativePath:s}}catch{return}}function Ps(t){const n=Wi();if(!n||typeof window>"u")return t;const s=fx(t);return!s||!px(s.parsed)?t:(s.parsed.searchParams.set(ox,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ai(t){const n=Wi();if(!n)return t;const s=new Headers(t??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function gx(t){if(!t||typeof t!="object")return!1;const n=t;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function bx(){typeof window>"u"||Pr||(Pr=!0,window.dispatchEvent(new CustomEvent(xo)))}async function xx(t){if(t.status===401)try{const n=t.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();gx(i)&&bx()}catch{}}function vx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Wi();const t=window.fetch.bind(window);window.fetch=function(s,i){const r=Wi(),l=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const m=new URL(l,window.location.origin);return m.origin!==window.location.origin?!1:m.pathname.startsWith("/api/")||m.pathname==="/api"}catch{return l.startsWith("/api/")||l==="/api"}})())return t(s,i);const d=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!d.has("Authorization")&&d.set("Authorization",`Bearer ${r}`),t(s,{...i,headers:d}).then(m=>(xx(m),m))}}class yx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function kx(t){const n=t.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Gn(t){return`/api${t}`}async function z(t,n={}){const s=Gn(t),i=Wi(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),ai(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())})(),l=await fetch(s,{...n,headers:r});if(l.status===204){if(!l.ok)throw new Error(`Request failed for ${s}: ${l.status} ${l.statusText}`);return}const o=l.headers.get("content-type")??"",d=await l.text(),m=o.includes("application/json");if(o.includes("text/html")||kx(d))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${l.status} ${l.statusText})`);if(!m){const h=d.length>160?`${d.slice(0,160)}...`:d;throw new Error(`API returned ${o||"an unknown content type"} instead of JSON for ${s}. (${l.status} ${l.statusText})${h?` Response: ${h}`:""}`)}let u;try{u=d?JSON.parse(d):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${l.status} ${l.statusText})`)}if(!l.ok){const h=u;throw new yx(h?.error||`Request failed for ${s}: ${l.status} ${l.statusText}`,l.status,h?.details)}return u}function jx(t,n,s,i,r){const l=new URLSearchParams;s&&l.set("projectId",s),i&&l.set("q",i),r&&l.set("includeArchived","1");const o=l.size>0?`?${l.toString()}`:"";return z(`/tasks${o}`)}async function _r(t,n){const i=Gn(Q(`/tasks/${t}`,n));for(let r=1;r<=2;r++){const l=await fetch(i,{headers:ai({"Content-Type":"application/json"})}),o=await l.json();if(l.ok)return o;if(r===2)throw new Error(o.error||"Request failed")}throw new Error("Request failed")}function sh(t,n){const{title:s,description:i,column:r,dependencies:l,breakIntoSubtasks:o,enabledWorkflowSteps:d,assignedAgentId:m,modelPresetId:c,modelProvider:u,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:y,reviewLevel:k,executionMode:A,priority:j}=t;return z(Q("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:l,breakIntoSubtasks:o,enabledWorkflowSteps:d,assignedAgentId:m,modelPresetId:c,modelProvider:u,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:y,reviewLevel:k,executionMode:A,priority:j})})}function Ws(t,n,s){return z(Q(`/tasks/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function wx(t,n,s,i,r,l,o,d){return z(Q("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:t,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:l,planningModelId:o})})}function Nx(t,n,s){return z(Q(`/tasks/${t}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Sx(t,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return z(Q(`/tasks/${t}${r}`,n),{method:"DELETE"})}function Cx(t,n){return z(Q(`/tasks/${t}/merge`,n),{method:"POST"})}function Ex(t,n){return z(Q(`/tasks/${t}/retry`,n),{method:"POST"})}function Mx(t,n){return z(Q(`/tasks/${t}/duplicate`,n),{method:"POST"})}function Ax(t,n){return z(Q(`/tasks/${t}/pause`,n),{method:"POST"})}function Px(t,n){return z(Q(`/tasks/${t}/unpause`,n),{method:"POST"})}function _x(t,n){return z(Q(`/tasks/${t}/archive`,n),{method:"POST"})}function Tx(t,n){return z(Q(`/tasks/${t}/unarchive`,n),{method:"POST"})}function Rx(t){return z(Q("/tasks/archive-all-done",t),{method:"POST"}).then(n=>n.archived)}function Ix(t,n){return z(Q(`/tasks/${t}/approve-plan`,n),{method:"POST"})}function $x(t,n){return z(Q(`/tasks/${t}/reject-plan`,n),{method:"POST"})}function Dx(t){return z(Q("/config",t))}function Ki(t){return z(Q("/settings",t))}function Ca(t,n){return z(Q("/settings",n),{method:"PUT",body:JSON.stringify(t)})}function lR(t){return z(Q("/memory",t))}function oR(t,n){return z(Q("/memory",n),{method:"PUT",body:JSON.stringify({content:t})})}function Wc(t){return z(Q("/memory/files",t))}function Fx(t,n){const s=`path=${encodeURIComponent(t)}`;return z(Q(`/memory/file?${s}`,n))}function Lx(t,n,s){return z(Q("/memory/file",s),{method:"PUT",body:JSON.stringify({path:t,content:n})})}function zx(t,n){let s,i=n;if(n!==void 0)s=t;else if(typeof t=="string"&&t.trim().length>0){const r=t.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return z(Q("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function cR(t){return z(Q("/memory/insights",t))}function dR(t,n){return z(Q("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:t})})}function uR(t){return z(Q("/memory/extract",t),{method:"POST"})}function mR(t){return z(Q("/memory/audit",t))}function hR(t){return z(Q("/memory/stats",t))}function Ox(t){return z(Q("/memory/backend",t))}function Bx(t){return z(Q("/memory/install-qmd",t),{method:"POST"})}function Ux(t,n){return z(Q("/memory/test",n),{method:"POST",body:JSON.stringify({query:t})})}function ia(){return z("/settings/global")}function Wt(t){return z("/settings/global",{method:"PUT",body:JSON.stringify(t)})}function Hx(t){return z(Q("/settings/scopes",t))}function pR(t){return z(Q("/settings/pi-extensions",t))}function fR(t,n){return z(Q("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:t})})}function qx(t,n){return z(Q("/settings/test-ntfy",n),{method:"POST",body:t?JSON.stringify(t):void 0})}function gR(){return z("/pi-settings")}async function bR(t){return z("/pi-settings",{method:"PUT",body:JSON.stringify(t)})}async function xR(t){return z("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:t})})}async function vR(t){return z(Q("/pi-settings/reinstall-fusion",t),{method:"POST"})}async function Da(t,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Gn(Q(`/tasks/${t}/attachments`,s)),{method:"POST",headers:ai(),body:i}),l=await r.json();if(!r.ok)throw new Error(l.error||"Upload failed");return l}async function Vx(t,n,s){return z(Q(`/tasks/${t}/attachments/${n}`,s),{method:"DELETE"})}async function Kc(t,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()}`:"",l=Q(`/tasks/${t}/logs${r}`,n),o=await fetch(Gn(l),{headers:ai()});if(!o.ok){const u=await o.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(u.error||`HTTP ${o.status}`)}const d=await o.json(),m=o.headers.has("X-Total-Count")?parseInt(o.headers.get("X-Total-Count"),10):d.length,c=o.headers.has("X-Has-More")?o.headers.get("X-Has-More")==="true":!1;return{entries:d,total:m,hasMore:c}}function Wx(t,n,s,i){return z(Q(`/tasks/${t}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Kx(t,n,s){return z(Q(`/tasks/${t}/comments/${n}`,s),{method:"DELETE"})}function Gx(t,n){return z(Q(`/tasks/${t}/documents`,n))}function Jx(t,n,s){return z(Q(`/tasks/${t}/documents/${n}/revisions`,s))}async function yR(t,n){const s=new URLSearchParams;t?.q&&s.set("q",t.q),t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.offset!==void 0&&s.set("offset",String(t.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return z(Q(r,n))}function kR(t,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return z(Q(r,t))}function Gc(t,n,s,i,r){return z(Q(`/tasks/${t}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Yx(t,n,s){return z(Q(`/tasks/${t}/documents/${n}`,s),{method:"DELETE"})}function Qx(t,n,s){return z(Q(`/tasks/${t}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Xx(t,n,s){return z(Q(`/tasks/${t}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Zx(t,n){return z(Q(`/tasks/${t}/spec/rebuild`,n),{method:"POST"})}function ev(t,n,s){return z(Q(`/tasks/${t}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Kn(){return z("/models")}function tv(){return z("/usage")}function nv(){return z("/providers/claude-cli/status")}function sv(t){return z("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:t})})}function wi(){return z("/auth/status")}function ih(t){return z("/auth/login",{method:"POST",body:JSON.stringify({provider:t})})}function ah(t){return z("/auth/logout",{method:"POST",body:JSON.stringify({provider:t})})}function rh(t,n){return z("/auth/api-key",{method:"POST",body:JSON.stringify({provider:t,apiKey:n})})}function lh(t){return z("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:t})})}function iv(t,n,s,i){return z("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s,labels:i})})}function av(t,n,s,i){return z(Q("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,issueNumber:s})})}function rv(t,n,s){return z("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s})})}function lv(t,n,s,i){return z(Q("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,prNumber:s})})}function ov(t){return z(Q("/git/remotes",t))}function oh(t){return z(Q("/git/remotes/detailed",t))}function cv(t,n,s){return z(Q("/git/remotes",s),{method:"POST",body:JSON.stringify({name:t,url:n})})}function dv(t,n){return z(Q(`/git/remotes/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function uv(t,n,s){return z(Q(`/git/remotes/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function mv(t,n,s){return z(Q(`/git/remotes/${encodeURIComponent(t)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function hv(t,n,s){return z(Q(`/tasks/${t}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function pv(t,n){return z(Q(`/tasks/${t}/pr/refresh`,n),{method:"POST"})}async function fv(t,n){return(await z(Q("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:t})})).results}function nr(t,n,s,i){return z(Q("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:t,cols:n,rows:s})})}function Jc(t,n){return z(Q(`/terminal/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function gv(t){return z(Q("/terminal/sessions",t))}function Es(t){return z(Q("/git/status",t))}function bv(t,n){const s=t?`?limit=${t}`:"";return z(Q(`/git/commits${s}`,n))}function Tr(t,n){return z(Q(`/git/commits/${t}/diff`,n))}function xv(t){return z(Q("/git/commits/ahead",t))}function vv(t,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const l=r.size>0?`?${r.toString()}`:"";return z(Q(`/git/remotes/${encodeURIComponent(t)}/commits${l}`,i))}function ca(t){return z(Q("/git/branches",t))}function yv(t,n,s){const i=`?limit=${n}`;return z(Q(`/git/branches/${encodeURIComponent(t)}/commits${i}`,s))}function kv(t){return z(Q("/git/worktrees",t))}function jv(t,n,s){return z(Q("/git/branches",s),{method:"POST",body:JSON.stringify({name:t,base:n})})}function wv(t,n){return z(Q(`/git/branches/${encodeURIComponent(t)}/checkout`,n),{method:"POST"})}function Yc(t,n,s){const i=n?"?force=true":"";return z(Q(`/git/branches/${encodeURIComponent(t)}${i}`,s),{method:"DELETE"})}function Nv(t,n){return z(Q("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:t})})}function Sv(t){return z(Q("/git/pull",t),{method:"POST"})}function Cv(t){return z(Q("/git/push",t),{method:"POST"})}function sr(t){return z(Q("/git/stashes",t))}function Ev(t,n){return z(Q("/git/stashes",n),{method:"POST",body:JSON.stringify({message:t})})}function Mv(t,n,s){return z(Q(`/git/stashes/${t}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Av(t,n){return z(Q(`/git/stashes/${t}`,n),{method:"DELETE"})}function Pv(t,n,s){const i=new URLSearchParams;return i.set("path",t),i.set("staged",String(n)),z(Q(`/git/diff/file?${i.toString()}`,s))}function _i(t){return z(Q("/git/changes",t))}function Qc(t,n){return z(Q("/git/stage",n),{method:"POST",body:JSON.stringify({files:t})})}function _v(t,n){return z(Q("/git/unstage",n),{method:"POST",body:JSON.stringify({files:t})})}function Xc(t,n){return z(Q("/git/commit",n),{method:"POST",body:JSON.stringify({message:t})})}function Tv(t,n){return z(Q("/git/discard",n),{method:"POST",body:JSON.stringify({files:t})})}function Rv(t){return z(Q("/workspaces",t))}function Iv(t,n,s){const i=new URLSearchParams({workspace:t});return n&&i.set("path",n),s&&i.set("projectId",s),z(`/files?${i.toString()}`)}function $v(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),z(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Dv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Fv(t,n,s){const i=new URLSearchParams({q:t});return n&&i.set("workspace",n),s&&i.set("projectId",s),z(`/files/search?${i.toString()}`)}function Lv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function zv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ov(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),z(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Bv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),z(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function ch(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Uv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Hv(t,n,s){return z(Q("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:t,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function qv(t,n,s,i){return z(Q("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Vv(t,n,s){return z(Q(`/planning/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dh(t,n,s){return z(Q("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Wv(t,n,s){return z(Q("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Kv(t,n,s){return z(Q("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Gv(t,n,s){return z(Q("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:t,subtasks:n})})}const vo=new Set;if(typeof window<"u"){const t=()=>{for(const n of Array.from(vo))try{n.close()}catch{}};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t)}function Jv(t,n){if(n===null||n<=0)return t;const s=t.includes("?")?"&":"?";return`${t}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ha(t,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,l=!1,o=0,d=null,m=null,c=!1;const u=p=>{const f=p.lastEventId;if(!f)return!0;const b=Number.parseInt(f,10);return Number.isFinite(b)?m!==null&&b<=m?!1:(m=b,!0):!0},h=()=>{if(l)return;const p=Jv(t,m),f=new EventSource(Ps(p));r=f,f.onopen=()=>{o=0,c=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const v=b;u(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))f.addEventListener(b,y=>{const k=y;u(k)&&v(k)});f.onerror=()=>{if(l||r!==f)return;if(f.readyState===EventSource.CONNECTING){c||(c=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),o>=i){s.onFatalError?.("Connection lost");return}c=!0,s.onConnectionStateChange?.("reconnecting"),o+=1;const v=Math.min(1e3*2**(o-1),3e4);d=setTimeout(()=>{d=null,h()},v)}};h();const g={close:()=>{l=!0,d&&(clearTimeout(d),d=null),r?.close(),vo.delete(g)},isConnected:()=>!l&&r?.readyState===EventSource.OPEN};return vo.add(g),g}function Zc(t){const n=typeof t.source=="string"&&t.source.trim().length>0?t.source.trim():"root",s=n==="root"?".":n,i=t.name,r=typeof t.packagePath=="string"&&t.packagePath.trim().length>0?t.packagePath.trim():s,l=typeof t.confidence=="number"?t.confidence:1,o=n==="root"?"root":n,d=typeof t.packageName=="string"&&t.packageName.trim().length>0?t.packageName.trim():"project";return{name:t.name,command:t.command,scriptName:i,packagePath:r,confidence:l,cwd:s,source:n,workspaceName:typeof t.packageName=="string"?t.packageName:void 0,label:`${d} · ${i} (${o})`}}function Gi(t){const n=t.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof t.previewUrl=="string"?t.previewUrl:t.detectedUrl,r=typeof t.manualPreviewUrl=="string"?t.manualPreviewUrl:t.manualUrl;return{id:typeof t.id=="string"?t.id:"",name:typeof t.name=="string"&&t.name.length>0?t.name:"default",status:s,command:typeof t.command=="string"?t.command:"",scriptName:typeof t.scriptId=="string"?t.scriptId:"",cwd:typeof t.cwd=="string"?t.cwd:"",pid:t.pid,startedAt:t.startedAt,previewUrl:i,detectedUrl:typeof t.detectedUrl=="string"?t.detectedUrl:i,detectedPort:t.detectedPort,manualPreviewUrl:r,manualUrl:typeof t.manualUrl=="string"?t.manualUrl:r,logs:Array.isArray(t.logHistory)?t.logHistory:[],exitCode:t.exitCode}}function Yv(t,n){return{id:typeof t.id=="number"&&Number.isFinite(t.id)?t.id:n,text:typeof t.text=="string"?t.text:typeof t.line=="string"?t.line:"",stream:t.stream==="stderr"?"stderr":"stdout",timestamp:typeof t.timestamp=="string"?t.timestamp:""}}function Qv(t){const s=(Array.isArray(t.lines)?t.lines:[]).map((i,r)=>Yv(i,r+1));return{lines:s,totalLines:typeof t.totalLines=="number"&&Number.isFinite(t.totalLines)?t.totalLines:s.length}}function Xv(t,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,l=t.length,o=t.map((c,u)=>({id:u+1,text:c,stream:"stdout",timestamp:""}));if(r!==null)return{lines:o.filter(c=>c.id>r).slice(0,s),totalLines:l};const d=Math.max(l-i,0),m=Math.max(d-s,0);return{lines:o.slice(m,d),totalLines:l}}function ed(t){return Array.isArray(t)?t.map(Zc):(t.candidates??[]).map(Zc)}async function Zv(t){try{const n=await z(Q("/dev-server/candidates",t));return ed(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await z(Q("/dev-server/detect",t));return ed(s)}throw n}}function Go(t){return z(Q("/dev-server/status",t)).then(Gi)}async function jR(t={},n){const s=new URLSearchParams;typeof t.maxLines=="number"&&Number.isFinite(t.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(t.maxLines)))),typeof t.offset=="number"&&Number.isFinite(t.offset)&&s.set("offset",String(Math.max(0,Math.floor(t.offset)))),typeof t.lastEventId=="number"&&Number.isFinite(t.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(t.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await z(Q(`/dev-server/logs/history${i}`,n));return Qv(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const l=await Go(n);return Xv(l.logs,t)}throw r}}function ey(t,n){const s=t.cwd??t.packagePath??".",i=t.scriptName;return z(Q("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:t.command,scriptName:i,scriptId:i,cwd:s,packagePath:t.packagePath})}).then(Gi)}function ty(t){return z(Q("/dev-server/stop",t),{method:"POST"}).then(Gi)}function ny(t){return z(Q("/dev-server/restart",t),{method:"POST"}).then(Gi)}async function sy(t,n){const s=typeof t=="string"?{url:t}:t;try{const i=await z(Q("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Gi(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await z(Q("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Gi(r)}throw i}}function wR(t){return Gn(Q("/dev-server/logs/stream",t))}async function NR(t){try{return(await z(Q("/devserver",t))).sessions??[]}catch{try{const n=await Go(t);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 SR(t,n){try{return await z(Q(`/devserver/${encodeURIComponent(t)}`,n))}catch{try{const s=await Go(n);return!t||t==="default"||t===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 CR(t,n){try{return await z(Q(`/devserver/${encodeURIComponent(t)}/start`,n),{method:"POST"})}catch{const s=await ey({command:""},n);return{config:{id:s.id??t,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 ER(t,n){try{return await z(Q(`/devserver/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}catch{const s=await ty(n);return{config:{id:s.id??t,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 MR(t,n){try{return await z(Q(`/devserver/${encodeURIComponent(t)}/restart`,n),{method:"POST"})}catch{const s=await ny(n);return{config:{id:s.id??t,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 AR(t,n,s){try{const i=await z(Q(`/devserver/${encodeURIComponent(t)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await sy({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function PR(t){try{return(await z(Q("/devserver/detect",t))).candidates??[]}catch{try{return(await Zv(t)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function _R(t,n){return Gn(Q(`/devserver/${encodeURIComponent(t)}/logs/stream`,n))}function qa(t,n,s=25e3){const i=setInterval(()=>{Bk(t,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function iy(t,n){return Gn(Q(`/planning/${encodeURIComponent(t)}/stream`,n))}function ay(t,n,s,i){const r=iy(t,n);let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ha(r,{onOpen:()=>{d(),l=qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[planning] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[planning] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Va(t,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?`${t}?${i}`:t}function ry(t){return z(Va("/routines",t))}function ly(t,n){return z(Va("/routines",n),{method:"POST",body:JSON.stringify(t)})}function td(t,n,s){return z(Va(`/routines/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function oy(t,n){await z(Va(`/routines/${t}`,n),{method:"DELETE"})}function cy(t,n){return z(Va(`/routines/${t}/trigger`,n),{method:"POST"})}function nd(t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.since!==void 0&&n.set("since",t.since),t?.type!==void 0&&n.set("type",t.type),t?.projectId&&n.set("projectId",t.projectId);const s=n.size>0?`?${n.toString()}`:"";return z(`/activity${s}`)}function dy(t){const n=Q("/activity",t);return z(n,{method:"DELETE"})}function Yr(t){return z(Q("/workflow-steps",t))}function sd(t,n){return z(Q("/workflow-steps",n),{method:"POST",body:JSON.stringify(t)})}function uy(t,n,s){return z(Q(`/workflow-steps/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function my(t,n){return z(Q(`/workflow-steps/${t}`,n),{method:"DELETE"})}function id(t,n){return z(Q(`/workflow-steps/${t}/refine`,n),{method:"POST"})}function hy(t,n){return z(Q(`/tasks/${encodeURIComponent(t)}/workflow-results`,n))}function py(){return z("/workflow-step-templates")}function fy(t,n){return z(Q(`/workflow-step-templates/${encodeURIComponent(t)}/create`,n),{method:"POST"})}function Wa(t){return z(Q("/scripts",t))}function gy(t,n,s){return z(Q("/scripts",s),{method:"POST",body:JSON.stringify({name:t,command:n})})}function by(t,n){return z(Q(`/scripts/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function uh(t,n,s){return(await z(Q("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:t,type:n})})).refined}const ir={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 mh(t){if(!(t instanceof Error))return ir.NETWORK;const n=t.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?ir.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?ir.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?t.message:ir.NETWORK}function xy(t,n){return z(Q("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:t})})}function vy(t,n,s){return z(Q(`/subtasks/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function yy(t,n){return Gn(Q(`/subtasks/${encodeURIComponent(t)}/stream`,n))}function ky(t,n,s,i){let r=null,l=null;const o=()=>{r?.stop(),r=null},d=Ha(yy(t,n),{onOpen:()=>{o(),r=qa(t,n)},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},subtasks:m=>{try{s.onSubtasks?.(JSON.parse(m.data))}catch(c){console.error("[subtasks] Failed to parse subtasks event:",c)}},error:m=>{try{const c=JSON.parse(m.data),u=typeof c=="string"&&c.length>0?c:null;s.onError?.(u||"Stream error")}catch{s.onError?.("Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{o(),s.onError?.(m)}});return l={close:()=>{o(),d.close()},isConnected:d.isConnected},l}function jy(t,n,s,i){return z(Q("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:t,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function hh(t,n,s){return z(Q("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Q(t,n){if(!n)return t;const s=t.includes("?")?"&":"?";return`${t}${s}projectId=${encodeURIComponent(n)}`}function wy(t,n,s){if(!n||n===s)return t;const i="/api",r=t.startsWith(i)?t.slice(i.length):t;return`/proxy/${encodeURIComponent(n)}${r}`}function Qr(t,n){const{nodeId:s,localNodeId:i,...r}=n??{},l=wy(t,s,i);return z(l,r)}function aa(t,n){const s=new URLSearchParams;t?.state&&s.set("state",t.state),t?.role&&s.set("role",t.role),t?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return z(`/agents${i}`)}function ph(t,n){return z(Q(`/agents/${encodeURIComponent(t)}`,n))}function Ny(t,n){return z(Q("/agents",n),{method:"POST",body:JSON.stringify(t)})}function Sy(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TR(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function RR(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function IR(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function $R(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/memory/files`,n))}function DR(t,n,s){const i=`path=${encodeURIComponent(n)}`;return z(Q(`/agents/${encodeURIComponent(t)}/memory/file?${i}`,s))}function FR(t,n,s,i){return z(Q(`/agents/${encodeURIComponent(t)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Cy(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ey(t,n){return z(Q(`/agents/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function LR(t,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return z(`/agents/${encodeURIComponent(t)}/runs${r}`)}function zR(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}`,s))}function OR(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}/logs`,s))}function BR(t,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return z(Q(`/agents/${encodeURIComponent(t)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function UR(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/runs/stop`,n),{method:"POST"})}function My(t){return z(Q("/agents/stats",t))}function HR(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/chain-of-command`,n))}function qR(t,n){const s=new URLSearchParams;t&&s.set("projectId",t),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return z(`/agents/org-tree${i?`?${i}`:""}`)}function VR(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function ad(t,n,s){return z(Q(`/tasks/${encodeURIComponent(t)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function WR(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/tasks`,n))}function KR(){return z("/agents/companies")}function GR(t,n){return z(Q("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:t})})}function JR(t,n){return z(Q("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:t})})}function YR(t,n){return z(Q(`/agents/generate/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function rd(t){return z(Q("/backups",t))}function Ay(t){return z(Q("/backups",t),{method:"POST"})}function Py(t,n){const s=Q("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(t)}`;return z(i)}function _y(t,n,s){return z(Q("/settings/import",s),{method:"POST",body:JSON.stringify({data:t,scope:n?.scope??"both",merge:n?.merge??!0})})}function ld(){return z("/projects/across-nodes")}function Ma(t,n){z("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:t,message:n})}).catch(()=>{})}function od(){return z("/nodes")}function Ty(t){return z("/nodes",{method:"POST",body:JSON.stringify(t)})}function Ry(t,n){return z(`/nodes/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function Iy(t){return z(`/nodes/${encodeURIComponent(t)}`,{method:"DELETE"})}async function $y(t){const n=await z(`/nodes/${encodeURIComponent(t)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??t,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function QR(t,n,s,i){const r=s&&s!==i?s:void 0,l=new URLSearchParams;t&&l.set("path",t),n&&l.set("showHidden","true"),r&&l.set("nodeId",r);const o=Wi();o&&l.set("fn_token",o);const d=l.toString(),m=`/browse-directory${d?`?${d}`:""}`;return z(m)}function Dy(t){return z("/projects",{method:"POST",body:JSON.stringify(t)})}function fh(t){return z(`/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}function cd(t){return z(`/projects/${encodeURIComponent(t)}/health`)}function Fy(t){return z(Q("/executor/stats",t))}function dd(t){const n=new URLSearchParams;t?.limit!==void 0&&n.set("limit",String(t.limit)),t?.since&&n.set("since",t.since),t?.projectId&&n.set("projectId",t.projectId),t?.type&&n.set("type",t.type);const s=n.size>0?`?${n.toString()}`:"";return z(`/activity-feed${s}`)}function Ly(t){return z(`/projects/${encodeURIComponent(t)}/pause`,{method:"POST"})}function zy(t){return z(`/projects/${encodeURIComponent(t)}/resume`,{method:"POST"})}function Oy(){return z("/global-concurrency")}function By(t){return z("/global-concurrency",{method:"PUT",body:JSON.stringify(t)})}function Uy(t,n){return z(`/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function gh(t,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return z(`/tasks/${encodeURIComponent(t)}/diff${r}`)}function Hy(t){return z(Q("/missions",t))}function qy(t,n){return z(Q("/missions",n),{method:"POST",body:JSON.stringify(t)})}function bh(t,n){return z(Q(`/missions/${encodeURIComponent(t)}`,n))}function Vy(t,n,s){return z(Q(`/missions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wy(t,n){return z(Q(`/missions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Ky(t,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 z(Q(`/missions/${encodeURIComponent(t)}/events${r}`,s))}function Gy(t){return z(Q("/missions/health",t))}function Jy(t,n,s){return z(Q(`/missions/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Yy(t,n,s){return z(Q(`/missions/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Qy(t,n){return z(Q(`/missions/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Xy(t,n,s){return z(Q(`/missions/milestones/${encodeURIComponent(t)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Zy(t,n,s){return z(Q(`/missions/slices/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ek(t,n){return z(Q(`/missions/slices/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function tk(t,n){return z(Q(`/missions/slices/${encodeURIComponent(t)}/activate`,n),{method:"POST"})}function nk(t,n,s){return z(Q(`/missions/slices/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function sk(t,n,s){return z(Q(`/missions/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ik(t,n){return z(Q(`/missions/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function ak(t,n,s){return z(Q(`/missions/features/${encodeURIComponent(t)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function rk(t,n){return z(Q(`/missions/features/${encodeURIComponent(t)}/unlink-task`,n),{method:"POST"})}function lk(t,n,s,i){return z(Q(`/missions/features/${encodeURIComponent(t)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ok(t,n){return z(Q(`/missions/slices/${encodeURIComponent(t)}/triage-all`,n),{method:"POST"})}function fl(t,n){return z(Q(`/missions/milestones/${encodeURIComponent(t)}/assertions`,n))}function ck(t,n,s){return z(Q(`/missions/milestones/${encodeURIComponent(t)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function dk(t,n,s){return z(Q(`/missions/assertions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uk(t,n,s){return z(Q(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function mk(t,n,s){return z(Q(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function hk(t,n){return z(Q(`/missions/assertions/${encodeURIComponent(t)}/features`,n))}function gl(t,n){return z(Q(`/missions/milestones/${encodeURIComponent(t)}/validation`,n))}function ud(t,n){return z(Q(`/missions/milestones/${encodeURIComponent(t)}/validation-telemetry`,n))}function pk(t,n){return z(Q(`/missions/features/${encodeURIComponent(t)}/validate`,n),{method:"POST"})}function md(t,n){return z(Q(`/missions/features/${encodeURIComponent(t)}/validation-loop`,n))}function fk(t,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 z(Q(`/missions/features/${encodeURIComponent(t)}/validation-runs${r}`,s)).then(l=>l.runs)}function gk(t,n){return z(Q(`/missions/validation-runs/${encodeURIComponent(t)}`,n))}function bk(t,n){return z(Q(`/missions/${encodeURIComponent(t)}/resume`,n),{method:"POST"})}function xk(t,n){return z(Q(`/missions/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}function vk(t,n){return z(Q(`/missions/${encodeURIComponent(t)}/start`,n),{method:"POST"})}function yk(t,n,s){return z(Q(`/missions/${encodeURIComponent(t)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function kk(t,n,s){return z(Q("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:t,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function jk(t,n,s,i){return z(Q("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function wk(t,n,s){return z(Q(`/missions/interview/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function xh(t,n,s){return z(Q("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Nk(t,n,s){return z(Q("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function Sk(t,n,s,i){const r=Gn(Q(`/missions/interview/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ha(r,{onOpen:()=>{d(),l=qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[mission-interview] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[mission-interview] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Ka(t,n,s){return Q(`/missions/milestones/${encodeURIComponent(t)}/interview${n}`,s)}function Ga(t,n,s){return Q(`/missions/slices/${encodeURIComponent(t)}/interview${n}`,s)}function Ck(t,n){return z(Ka(t,"/start",n),{method:"POST"})}function Ek(t,n,s,i){return z(Ka(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Mk(t,n,s,i){const r=Gn(Ka(t,`/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ha(r,{onOpen:()=>{d(),l=qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[milestone-interview] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[milestone-interview] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Ak(t,n,s){return z(Ka(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function Pk(t,n){return z(Ka(t,"/skip",n),{method:"POST"})}function _k(t,n){return z(Ga(t,"/start",n),{method:"POST"})}function Tk(t,n,s,i){return z(Ga(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Rk(t,n,s,i){const r=Gn(Ga(t,`/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ha(r,{onOpen:()=>{d(),l=qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[slice-interview] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[slice-interview] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Ik(t,n,s){return z(Ga(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function $k(t,n){return z(Ga(t,"/skip",n),{method:"POST"})}async function Dk(t,n){try{return await z(Q(`/missions/features/${encodeURIComponent(t)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function XR(t){return z(Q("/roadmaps",t))}function ZR(t,n){return z(Q("/roadmaps",n),{method:"POST",body:JSON.stringify(t)})}function eI(t,n){return z(Q(`/roadmaps/${encodeURIComponent(t)}`,n))}function tI(t,n,s){return z(Q(`/roadmaps/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function nI(t,n){return z(Q(`/roadmaps/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function sI(t,n,s){return z(Q(`/roadmaps/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function iI(t,n,s){return z(Q(`/roadmaps/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function aI(t,n){return z(Q(`/roadmaps/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function rI(t,n,s){return z(Q(`/roadmaps/milestones/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function lI(t,n,s){return z(Q(`/roadmaps/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oI(t,n){return z(Q(`/roadmaps/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function cI(t,n,s){return z(Q(`/roadmaps/${encodeURIComponent(t)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function dI(t,n,s){return z(Q(`/roadmaps/milestones/${encodeURIComponent(t)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function uI(t,n,s,i){return z(Q(`/roadmaps/features/${encodeURIComponent(t)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function mI(t,n){return z(Q(`/roadmaps/${encodeURIComponent(t)}/handoff`,n))}function hI(t,n,s,i){return z(Q(`/roadmaps/${encodeURIComponent(t)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function pI(t,n,s){return z(Q(`/roadmaps/milestones/${encodeURIComponent(t)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function Ji(t){if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return[]}}async function vh(t){const n=t?`?projectId=${encodeURIComponent(t)}`:"",s=await fetch(Gn(`/ai-sessions${n}`),{headers:ai()});return s.ok?(await s.json()).sessions??[]:[]}async function ni(t){const n=await fetch(Gn(`/ai-sessions/${encodeURIComponent(t)}`),{headers:ai()});return n.ok?n.json():null}async function Fk(t,n){const s=await z(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Lk(t,n){return z(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function zk(t,n){return z(`/ai-sessions/${encodeURIComponent(t)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Ok(t){await fetch(Gn(`/ai-sessions/${encodeURIComponent(t)}`),{method:"DELETE",headers:ai()})}function Bk(t,n){return z(Q(`/ai-sessions/${encodeURIComponent(t)}/ping`,n),{method:"POST"})}function Uk(t,n){const s=new URLSearchParams;s.set("limit",String(t.limit)),t?.offset!==void 0&&s.set("offset",String(t.offset)),t?.unreadOnly&&s.set("unreadOnly","true"),t?.type&&s.set("type",t.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return z(`/messages/inbox${i}`)}function Hk(t,n){const s=new URLSearchParams;s.set("limit",String(t.limit)),t?.offset!==void 0&&s.set("offset",String(t.offset)),t?.type&&s.set("type",t.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return z(`/messages/outbox${i}`)}function yh(t){return z(Q("/messages/unread-count",t))}function qk(t,n){return z(Q("/messages",n),{method:"POST",body:JSON.stringify(t)})}function Vk(t,n){return z(Q(`/messages/${encodeURIComponent(t)}/read`,n),{method:"POST"})}function Wk(t){return z(Q("/messages/read-all",t),{method:"POST"})}function Kk(t,n){return z(Q(`/messages/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Gk(t,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(t)}`;return z(Q(i,s))}function Jk(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/mailbox`,n))}function fI(t,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return z(`/agents/${encodeURIComponent(t)}/reflections${r}`)}function gI(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/reflections`,n),{method:"POST"})}function bI(t,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return z(`/agents/${encodeURIComponent(t)}/performance${r}`)}function xI(t,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 z(`/agents/${encodeURIComponent(t)}/ratings${r}`)}function vI(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function yI(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/ratings/summary`,n))}function kI(t,n,s){return z(Q(`/agents/${encodeURIComponent(t)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function jI(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/budget`,n))}function wI(t,n){return z(Q(`/agents/${encodeURIComponent(t)}/budget/reset`,n),{method:"POST"})}async function NI(t){return z(Q("/plugins",t))}async function SI(t,n){return z(Q("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...t})})}async function CI(t,n){return z(Q(`/plugins/${encodeURIComponent(t)}/enable`,n),{method:"POST"})}async function EI(t,n){return z(Q(`/plugins/${encodeURIComponent(t)}/disable`,n),{method:"POST"})}async function MI(t,n){return z(Q(`/plugins/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function AI(t,n){return z(Q(`/plugins/${encodeURIComponent(t)}/settings`,n))}async function PI(t,n,s){return z(Q(`/plugins/${encodeURIComponent(t)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function _I(t,n){return z(Q(`/plugins/${encodeURIComponent(t)}/reload`,n),{method:"POST"})}async function Yk(t){return z(Q("/plugins/ui-slots",t))}async function TI(t){return(await z(Q("/skills/discovered",t))).skills}async function RI(t,n,s){return z(Q("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:t,enabled:n})})}async function II(t,n,s){const i=new URLSearchParams;t&&i.set("q",t),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return z(Q(`/skills/catalog${r}`,s))}async function $I(t,n){return(await z(Q(`/skills/${encodeURIComponent(t)}/content`,n))).content}function DI(t,n){const s=new URLSearchParams;t&&s.set("projectId",t);const i=s.toString();return z(`/chat/sessions${i?`?${i}`:""}`)}async function Qk(t,n){const s=t.agentId.trim();if(!s)throw new Error("agentId is required");const i=t.modelProvider?.trim(),r=t.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const l=new URLSearchParams;return l.set("lookup","resume"),l.set("agentId",s),n&&l.set("projectId",n),i&&r&&(l.set("modelProvider",i),l.set("modelId",r)),{session:(await z(`/chat/sessions?${l.toString()}`)).sessions[0]??null}}function Xk(t,n){return z(Q("/chat/sessions",n),{method:"POST",body:JSON.stringify(t)})}function FI(t,n,s){return z(Q(`/chat/sessions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function LI(t,n){return z(Q(`/chat/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function hd(t,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 z(Q(`/chat/sessions/${encodeURIComponent(t)}/messages${r?`?${r}`:""}`,s))}function Zk(t,n){return z(Q(`/chat/sessions/${encodeURIComponent(t)}/cancel`,n),{method:"POST"})}function ej(t,n,s,i,r){const l=Gn(Q(`/chat/sessions/${encodeURIComponent(t)}/messages`,i)),o=new AbortController;let d=!1;const m=(c,u)=>{if(!(!c||!u))switch(c){case"thinking":try{s.onThinking?.(JSON.parse(u))}catch{s.onThinking?.(u)}break;case"text":try{s.onText?.(JSON.parse(u))}catch{s.onText?.(u)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(u))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(u))}catch{}break;case"done":try{s.onDone?.(JSON.parse(u))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(u);s.onError?.(h.message||h)}catch{s.onError?.(u||"Stream error")}break}};return(async()=>{try{const c=await fetch(l,{method:"POST",headers:ai({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:o.signal});if(!c.ok){const v=await c.text();let y=`Request failed: ${c.status}`;try{y=JSON.parse(v).error||y}catch{}s.onError?.(y);return}if(!c.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const u=c.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const b=(v,y=!1)=>{g+=v;const k=g.split(`
|
|
593
|
+
`);g=k.pop()||"",y&&g.length>0&&(k.push(g),g="");for(const A of k){const j=A.endsWith("\r")?A.slice(0,-1):A;if(j.startsWith("event:"))p=j.slice(6).trim();else if(j.startsWith("data:")){const _=j.slice(5);f.push(_.startsWith(" ")?_.slice(1):_)}else if(j===""){const _=f.join(`
|
|
594
|
+
`);m(p,_),p="",f=[]}}if(y&&p&&f.length>0){const A=f.join(`
|
|
595
|
+
`);m(p,A),p="",f=[]}};for(;;){const{done:v,value:y}=await u.read();if(v){b(h.decode(),!0);break}b(h.decode(y,{stream:!0}))}}catch(c){if(c instanceof DOMException&&c.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(c instanceof Error?c.message:"Connection error")}})(),{close:()=>{d=!0,o.abort()},isConnected:()=>!d}}function zI(t={},n){const s=new URLSearchParams;t.category&&s.set("category",t.category),t.status&&s.set("status",t.status),t.runId&&s.set("runId",t.runId),t.limit!==void 0&&s.set("limit",String(t.limit)),t.offset!==void 0&&s.set("offset",String(t.offset));const i=s.size>0?`?${s.toString()}`:"";return z(Q(`/insights${i}`,n))}function OI(t,n){return z(Q(`/insights/${encodeURIComponent(t)}/dismiss`,n),{method:"POST"})}function BI(t="manual",n,s){return z(Q("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:t,inputMetadata:n})})}function UI(t){return z(Q("/insights/runs",t))}function HI(t,n){return z(Q(`/insights/${encodeURIComponent(t)}/create-task`,n),{method:"POST"})}function tj({onOpenScripts:t,onRunScript:n,projectId:s}){const[i,r]=a.useState(!1),[l,o]=a.useState({}),[d,m]=a.useState(!1),[c,u]=a.useState(-1),[h,g]=a.useState(null),p=a.useRef(null),f=a.useRef(null),b=a.useRef(null),v=a.useCallback(()=>{const R=window.visualViewport;return R&&R.width>0&&R.height>0?{width:R.width,height:R.height,offsetTop:R.offsetTop,offsetLeft:R.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),y=a.useCallback(()=>{const R=f.current;if(!R)return;const E=R.getBoundingClientRect(),I=b.current,{width:L,height:ee,offsetTop:$,offsetLeft:T}=v(),S=16,Y=16,K=6,G=I?.offsetWidth||Math.max(E.width,260),P=Math.min(G,Math.max(L-S*2,160)),O=I?.offsetHeight||280,X=Math.min(O,Math.max(ee-Y*2,160)),C=E.top-$,V=E.bottom-$,de=E.left-T,B=ee-V,J=C,D=B<X&&J>B,he=Math.min(Math.max(de,S),L-S-P)+T,q=D?Math.max(Y+$,C-X-K+$):Math.min(V+K+$,ee+$-Y-X);g({top:q,left:he,width:P})},[v]),k=a.useMemo(()=>Object.entries(l).sort(([R],[E])=>R.localeCompare(E)),[l]),A=k.length>0,j=k.length+(A?1:0);a.useEffect(()=>{if(!i)return;let R=!1;return m(!0),Wa(s).then(E=>{R||o(E)}).catch(()=>{R||o({})}).finally(()=>{R||m(!1)}),()=>{R=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const R=E=>{p.current&&!p.current.contains(E.target)&&f.current&&!f.current.contains(E.target)&&r(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[i]),a.useEffect(()=>{if(!i)return;const R=E=>{E.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[i]),a.useEffect(()=>{if(i){u(-1);const R=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(R)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const R=requestAnimationFrame(()=>{y()});return()=>cancelAnimationFrame(R)},[i,d,k.length,A,y]),a.useEffect(()=>{if(!i)return;const R=()=>y();window.addEventListener("resize",R),window.addEventListener("scroll",R,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",R),E.addEventListener("scroll",R)),()=>{window.removeEventListener("resize",R),window.removeEventListener("scroll",R,!0),E&&(E.removeEventListener("resize",R),E.removeEventListener("scroll",R))}},[i,y]);const _=a.useCallback(R=>{switch(R.key){case"ArrowDown":R.preventDefault(),u(E=>E<j-1?E+1:0);break;case"ArrowUp":R.preventDefault(),u(E=>E>0?E-1:j-1);break;case"Enter":if(R.preventDefault(),c>=0)if(c<k.length){const[E,I]=k[c];M(E,I)}else A&&c===k.length&&w();break;case"Home":R.preventDefault(),u(0);break;case"End":R.preventDefault(),u(j-1);break}},[c,j,k,A]),N=a.useCallback(()=>{r(R=>!R)},[]),M=a.useCallback((R,E)=>{n(R,E),r(!1)},[n]),w=a.useCallback(()=>{t(),r(!1)},[t]);return e.jsxs("div",{className:"quick-scripts-dropdown",ref:p,children:[e.jsxs("button",{ref:f,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick:N,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[e.jsx(Os,{size:16}),e.jsx(Lt,{size:14,className:`quick-scripts-dropdown__trigger-chevron ${i?"rotate":""}`})]}),i&&e.jsx("div",{ref:b,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:_,"data-testid":"quick-scripts-dropdown",style:h?{position:"fixed",top:`${h.top}px`,left:`${h.left}px`,width:`${h.width}px`,right:"auto"}:void 0,children:d?e.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[e.jsx(ct,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts..."})]}):k.length===0?e.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[e.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:e.jsx(Os,{size:16})}),e.jsx("p",{children:"No scripts configured"}),e.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:w,children:"Add your first script"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"quick-scripts-dropdown__list",children:k.map(([R,E],I)=>e.jsxs("button",{className:`quick-scripts-dropdown__item ${c===I?"highlighted":""}`,onClick:()=>M(R,E),role:"option","aria-selected":c===I,"data-testid":`quick-script-item-${R}`,children:[e.jsx(an,{size:14,className:"quick-scripts-dropdown__item-icon"}),e.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[e.jsx("span",{className:"quick-scripts-dropdown__item-name",children:R}),e.jsx("span",{className:"quick-scripts-dropdown__item-command",title:E,children:E.length>50?`${E.slice(0,50)}...`:E})]})]},R))}),e.jsx("div",{className:"quick-scripts-dropdown__footer",children:e.jsxs("button",{className:`quick-scripts-dropdown__manage ${A&&c===k.length?"highlighted":""}`,onClick:w,"data-testid":"quick-scripts-manage",children:[e.jsx($a,{size:14}),e.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function nj(t){switch(t){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 sj({node:t,showDetails:n=!1}){if(!t||t.type==="local")return e.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:e.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:i}=nj(t.status),r=t.status==="connecting";return e.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[e.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&e.jsx("span",{className:"node-status-indicator__spinner"})}),e.jsx("span",{className:"node-status-indicator__name",children:t.name}),n&&e.jsxs("span",{className:"node-status-indicator__details",children:[t.type," · ",s]})]})}const pd=new Map,ij=6e4;function kh(t){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[l,o]=a.useState(null),d=a.useRef(!1),m=a.useRef(!1),c=a.useCallback(u=>n.filter(h=>h.slot.slotId===u),[n]);return a.useEffect(()=>{const u=t??"default";let h=!1;async function g(){const p=pd.get(u);if(p&&Date.now()<p.expiresAt){if(h||m.current)return;s(p.slots),r(!1);return}!d.current&&r(!0),o(null);try{const b=await Yk(t);if(h||m.current)return;pd.set(u,{slots:b,expiresAt:Date.now()+ij}),s(b),d.current=!0}catch(b){if(h||m.current)return;o(b instanceof Error?b.message:"Failed to fetch UI slots"),d.current=!0}finally{!h&&!m.current&&r(!1)}}return g(),()=>{h=!0}},[t]),a.useEffect(()=>{d.current=!1,m.current=!1},[t]),a.useEffect(()=>()=>{m.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:c,loading:i,error:l}),[n,c,i,l])}function Ja({slotId:t,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=kh(n);if(i||r||!t)return null;const l=s(t);return l.length===0?null:e.jsx(Jr,{level:"page",children:e.jsx(e.Fragment,{children:l.map(o=>e.jsx("div",{"data-plugin-slot":!0,"data-slot-id":o.slot.slotId,"data-plugin-id":o.pluginId,"data-component-path":o.slot.componentPath,"aria-label":o.slot.label},`${o.pluginId}-${o.slot.slotId}`))})})}function aj(){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 Xr(){const[t,n]=a.useState(aj);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)}},[]),t}const jh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function rj({projects:t,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,l]=a.useState(!1),o=a.useRef(null);a.useEffect(()=>{if(!r)return;const m=c=>{o.current&&!o.current.contains(c.target)&&l(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[r]),a.useEffect(()=>{if(!r)return;const m=c=>{c.key==="Escape"&&l(!1)};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=a.useCallback(m=>{i?.(m),l(!1)},[i]);return e.jsx("div",{className:"project-selector",ref:o,children:t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>l(m=>!m),title:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:e.jsx(Lt,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})}),r&&e.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[t.map(m=>{const c=n?.id===m.id,u=jh[m.status]?.color;return e.jsxs("button",{className:`project-selector-item${c?" project-selector-item--current":""}`,onClick:()=>d(m),role:"option","aria-selected":c,children:[e.jsx("span",{className:"project-selector-dot",style:{backgroundColor:u||"var(--text-muted)"}}),e.jsxs("div",{className:"project-selector-info",children:[e.jsx("span",{className:"project-selector-name",children:m.name}),e.jsx("span",{className:"project-selector-path",children:m.path.split("/").slice(-2).join("/")})]}),c&&e.jsx(An,{size:14,className:"project-selector-check"})]},m.id)}),e.jsx("div",{className:"project-selector-divider",role:"presentation"}),e.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),l(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function fd({size:t=16}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.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 lj({onOpenSettings:t,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:l,onOpenActivityLog:o,onOpenMailbox:d,mailboxUnreadCount:m=0,onOpenSchedules:c,onOpenGitManager:u,onOpenNodes:h,showNodesButton:g,onOpenWorkflowSteps:p,onOpenScripts:f,onRunScript:b,onToggleTerminal:v,onOpenFiles:y,filesOpen:k,globalPaused:A,enginePaused:j,onToggleGlobalPause:_,onToggleEnginePause:N,view:M="board",onChangeView:w,showSkillsTab:R,showAgentsTab:E,searchQuery:I="",onSearchChange:L,projects:ee=[],currentProject:$,onSelectProject:T,onViewAllProjects:S,projectId:Y,isElectron:K=!1,mobileNavEnabled:G,availableNodes:P=[],currentNode:O,onSelectNode:X,isRemote:C=!1,experimentalFeatures:V}){const de=Xr(),B=de==="mobile",D=B||de==="tablet",he=B&&G,[q,W]=a.useState(!1),[me,Re]=a.useState(!1),[ve,Me]=a.useState(!1),[_e,De]=a.useState(!1),[Oe,ze]=a.useState(!1),[Be,Ae]=a.useState(!1),[Ce,Ge]=a.useState(!1),[Te,Xe]=a.useState(!1),[re,Z]=a.useState(!1),[ye,ie]=a.useState({}),[Ie,pe]=a.useState(!1),Ue=a.useRef(null),dt=a.useRef(null),ht=a.useRef(null),ue=a.useRef(null),te=a.useRef(null),ke=a.useRef(null),Ne=a.useRef(!1),Ze=a.useRef(null),xe=a.useRef(null),st=a.useRef(null),Ee=a.useRef(null),He=a.useMemo(()=>P.filter(Ve=>Ve.type==="remote"),[P]),ce=He.length>0,qe=a.useMemo(()=>Object.entries(ye).sort(([Ve],[ft])=>Ve.localeCompare(ft)),[ye]),We=a.useMemo(()=>!!(V?.insights||V?.roadmap||R||V?.memoryView||V?.devServerView),[V,R]);a.useEffect(()=>{Ne.current=Oe},[Oe]),a.useEffect(()=>{if(!Oe||!D)return;let Ve=!1;return pe(!0),Wa(Y).then(ft=>{Ve||ie(ft)}).catch(()=>{Ve||ie({})}).finally(()=>{Ve||pe(!1)}),()=>{Ve=!0}},[Oe,D,Y]);const Pe=q||I.length>0,nt=(me||I.length>0)&&!ve,kt=(M==="board"||M==="list")&&!B&&L&&!ve&&I.length===0,yt=(M==="board"||M==="list")&&!B&&L;a.useEffect(()=>{I===""&&Me(!1)},[I]),a.useEffect(()=>{if(!_e)return;const Ve=ft=>{dt.current&&!dt.current.contains(ft.target)&&Ue.current&&!Ue.current.contains(ft.target)&&De(!1)};return document.addEventListener("mousedown",Ve),()=>document.removeEventListener("mousedown",Ve)},[_e]),a.useEffect(()=>{if(!re)return;const Ve=ft=>{ue.current&&!ue.current.contains(ft.target)&&ht.current&&!ht.current.contains(ft.target)&&Z(!1)};return document.addEventListener("mousedown",Ve),()=>document.removeEventListener("mousedown",Ve)},[re]),a.useEffect(()=>{if(!Be)return;const Ve=ft=>{Ze.current&&!Ze.current.contains(ft.target)&&Ae(!1)};return document.addEventListener("mousedown",Ve),()=>document.removeEventListener("mousedown",Ve)},[Be]),a.useEffect(()=>{const Ve=ft=>{if(ft.key==="Escape"){if(Xe(!1),Z(!1),Ne.current){ze(!1);return}De(!1),W(!1),Ae(!1),Ge(!1)}};return document.addEventListener("keydown",Ve),()=>document.removeEventListener("keydown",Ve)},[]),a.useEffect(()=>{if(!Ce)return;const Ve=ft=>{xe.current&&!xe.current.contains(ft.target)&&Ge(!1)};return document.addEventListener("mousedown",Ve),()=>document.removeEventListener("mousedown",Ve)},[Ce]),a.useEffect(()=>{if(!Te)return;const Ve=ft=>{st.current&&!st.current.contains(ft.target)&&Ee.current&&!Ee.current.contains(ft.target)&&Xe(!1)};return document.addEventListener("mousedown",Ve),()=>document.removeEventListener("mousedown",Ve)},[Te]);const Ct=a.useCallback(()=>{W(Ve=>!Ve)},[]),Et=a.useCallback(()=>{Re(!0),Me(!1)},[]),Pt=a.useCallback(()=>{Re(!1),Me(!0),L&&L("")},[L]),It=a.useCallback(()=>{De(Ve=>!Ve)},[]),bt=a.useCallback(Ve=>{Ve&&Ve(),De(!1),ze(!1)},[]),_t=a.useCallback(()=>{W(!1),L&&L("")},[L]);return e.jsxs("div",{className:"header-wrapper",children:[e.jsxs("header",{className:"header",children:[e.jsxs("div",{className:"header-left",children:[e.jsxs("div",{className:"header-brand",children:[e.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[e.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),e.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"})]}),e.jsx("h1",{className:"logo",children:"Fusion"})]}),B&&ee.length>=1&&T&&e.jsxs("div",{className:"mobile-project-switch",ref:xe,children:[e.jsx("button",{className:`mobile-project-switch-trigger${Ce?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ge(Ve=>!Ve),title:"Switch project","aria-label":"Switch project","aria-expanded":Ce,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:e.jsx(Lt,{size:14,className:`mobile-project-switch-chevron${Ce?" mobile-project-switch-chevron--open":""}`})}),Ce&&e.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:ee.map(Ve=>{const ft=$?.id===Ve.id,Fe=jh[Ve.status]?.color;return e.jsxs("button",{className:`mobile-project-switch-item${ft?" mobile-project-switch-item--current":""}`,onClick:()=>{T(Ve),Ge(!1)},role:"option","aria-selected":ft,"data-testid":`mobile-project-switch-item-${Ve.id}`,children:[e.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Fe||"var(--text-muted)"}}),e.jsxs("div",{className:"mobile-project-switch-info",children:[e.jsx("span",{className:"mobile-project-switch-name",children:Ve.name}),e.jsx("span",{className:"mobile-project-switch-path",children:Ve.path.split("/").slice(-2).join("/")})]}),ft&&e.jsx(An,{size:14,className:"mobile-project-switch-check"})]},Ve.id)})})]}),!D&&ee.length>=1&&S&&e.jsx(rj,{projects:ee,currentProject:$??null,onViewAll:S,onSelectProject:T}),ce&&e.jsxs("div",{className:`header-node-selector${B?" header-node-selector--mobile":""}`,ref:B?void 0:Ze,children:[e.jsx(sj,{node:O??null,showDetails:!B}),!B&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`btn-icon node-selector-trigger${Be?" node-selector-trigger--open":""}`,onClick:()=>Ae(Ve=>!Ve),title:"Switch node","aria-label":"Switch node","aria-expanded":Be,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:e.jsx(rn,{size:12,className:`node-selector-chevron${Be?" node-selector-chevron--open":""}`})}),Be&&e.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[e.jsxs("button",{className:`node-selector-option${C?"":" node-selector-option--active"}`,onClick:()=>{X?.(null),Ae(!1)},role:"option","aria-selected":!C,"data-testid":"node-option-local",children:[e.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),e.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),He.map(Ve=>e.jsxs("button",{className:`node-selector-option${O?.id===Ve.id?" node-selector-option--active":""}`,onClick:()=>{X?.(Ve),Ae(!1)},role:"option","aria-selected":O?.id===Ve.id,"data-testid":`node-option-${Ve.id}`,children:[e.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${Ve.status}`}),e.jsx("span",{className:"node-selector-option-label",children:Ve.name}),e.jsx("span",{className:"node-selector-option-status",children:Ve.status})]},Ve.id))]})]})]})]}),e.jsxs("div",{className:"header-actions",children:[he&&w&&(M==="board"||M==="list")&&e.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${M==="board"?" active":""}`,onClick:()=>w("board"),title:"Board view","aria-label":"Board view","aria-pressed":M==="board","data-testid":"mobile-view-toggle-board",children:e.jsx(ji,{size:16})}),e.jsx("button",{className:`view-toggle-btn${M==="list"?" active":""}`,onClick:()=>w("list"),title:"List view","aria-label":"List view","aria-pressed":M==="list","data-testid":"mobile-view-toggle-list",children:e.jsx(po,{size:16})})]}),L&&B&&(he||M==="board"||M==="list")&&!Pe&&e.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Ct,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:e.jsx(Oi,{size:16})}),kt&&e.jsx("button",{className:"btn-icon",onClick:Et,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:e.jsx(Oi,{size:16})}),B&&he&&l&&e.jsx("button",{className:"btn-icon",onClick:l,title:"View usage","data-testid":"mobile-header-usage-btn",children:e.jsx(Ns,{size:16})}),!he&&w&&e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${M==="board"?" active":""}`,onClick:()=>w("board"),title:"Board view","aria-label":"Board view","aria-pressed":M==="board",children:e.jsx(ji,{size:16})}),e.jsx("button",{className:`view-toggle-btn${M==="list"?" active":""}`,onClick:()=>w("list"),title:"List view","aria-label":"List view","aria-pressed":M==="list",children:e.jsx(po,{size:16})}),E&&e.jsx("button",{className:`view-toggle-btn${M==="agents"?" active":""}`,onClick:()=>w("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":M==="agents",children:e.jsx(sn,{size:16})}),e.jsx("button",{className:`view-toggle-btn${M==="missions"?" active":""}`,onClick:()=>w("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":M==="missions",children:e.jsx(ns,{size:16})}),e.jsx("button",{className:`view-toggle-btn${M==="chat"?" active":""}`,onClick:()=>w("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":M==="chat",children:e.jsx(ei,{size:16})}),e.jsx("button",{className:`view-toggle-btn${M==="documents"?" active":""}`,onClick:()=>w("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":M==="documents",children:e.jsx(vi,{size:16})}),e.jsx("button",{className:`view-toggle-btn${M==="mailbox"?" active":""}`,onClick:()=>w("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":M==="mailbox",children:e.jsx(Ia,{size:16})}),We&&e.jsxs(e.Fragment,{children:[e.jsx("button",{ref:Ee,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(M)?" active":""}`,onClick:()=>Xe(Ve=>!Ve),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Te,"data-testid":"view-toggle-overflow-trigger",children:e.jsx(Lt,{size:12})}),Te&&e.jsxs("div",{ref:st,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[V?.insights&&e.jsxs("button",{className:`view-toggle-overflow-item${M==="insights"?" active":""}`,onClick:()=>{w("insights"),Xe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[e.jsx(Ln,{size:14}),e.jsx("span",{children:"Insights"})]}),V?.roadmap&&e.jsxs("button",{className:`view-toggle-overflow-item${M==="roadmaps"?" active":""}`,onClick:()=>{w("roadmaps"),Xe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[e.jsx(fo,{size:14}),e.jsx("span",{children:"Roadmaps"})]}),R&&e.jsxs("button",{className:`view-toggle-overflow-item${M==="skills"?" active":""}`,onClick:()=>{w("skills"),Xe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[e.jsx(Sn,{size:14}),e.jsx("span",{children:"Skills"})]}),V?.memoryView&&e.jsxs("button",{className:`view-toggle-overflow-item${M==="memory"?" active":""}`,onClick:()=>{w("memory"),Xe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[e.jsx(Cr,{size:14}),e.jsx("span",{children:"Memory"})]}),V?.devServerView&&e.jsxs("button",{className:`view-toggle-overflow-item${M==="dev-server"||M==="devserver"?" active":""}`,onClick:()=>{w("devserver"),Xe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[e.jsx(Gr,{size:14}),e.jsx("span",{children:"Dev Server"}),e.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]})]})]})]}),!D&&l&&e.jsx("button",{className:"btn-icon",onClick:l,title:"View usage","data-testid":"desktop-header-usage-btn",children:e.jsx(Ns,{size:16})}),!D&&o&&e.jsx("button",{className:"btn-icon",onClick:o,title:"View Activity Log",children:e.jsx(Ra,{size:16})}),!D&&!K&&e.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:e.jsx(fd,{size:16})}),!D&&e.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:[e.jsx(zs,{size:16}),r>0&&e.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!D&&e.jsx("button",{className:"btn-icon btn-icon--terminal",onClick:v,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:e.jsx(Os,{size:16})}),!D&&y&&e.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:e.jsx(Pn,{size:16})}),!D&&u&&e.jsx("button",{className:"btn-icon",onClick:u,title:"Git Manager","data-testid":"git-manager-btn",children:e.jsx(Ls,{size:16})}),!D&&p&&e.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:e.jsx(bo,{size:16})}),!D&&f&&b&&e.jsx(tj,{onOpenScripts:f,onRunScript:b,projectId:Y}),!D&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{ref:ht,className:"btn-icon",onClick:()=>Z(Ve=>!Ve),title:"More actions","aria-label":"More actions","aria-expanded":re,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:e.jsx(mo,{size:16})}),re&&e.jsxs("div",{ref:ue,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&e.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),Z(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[e.jsx(Mr,{size:14}),e.jsx("span",{children:"Nodes"})]}),e.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{bt(c),Z(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[e.jsx(Hi,{size:14}),e.jsx("span",{children:"Automation"})]})]})]}),e.jsx("button",{className:`btn-icon${j?" btn-icon--paused":""}`,onClick:N,title:j?"Resume scheduling":"Pause scheduling",disabled:!!A,children:j?e.jsx(an,{size:16}):e.jsx(Ds,{size:16})}),e.jsx("button",{className:`btn-icon${A?" btn-icon--stopped":""}`,onClick:_,title:A?"Start AI engine":"Stop AI engine",children:A?e.jsx(an,{size:16}):e.jsx(cs,{size:16})}),!D&&e.jsx("button",{className:"btn-icon",onClick:t,title:"Settings",children:e.jsx($a,{size:16})}),e.jsx(Ja,{slotId:"header-action",projectId:Y}),D&&!he&&e.jsx("button",{ref:Ue,className:"btn-icon compact-overflow-trigger",onClick:It,title:"More header actions","aria-label":"More header actions","aria-expanded":_e,"aria-haspopup":"menu",children:e.jsx(mo,{size:16})}),D&&!he&&_e&&e.jsxs("div",{ref:dt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[ee.length>=1&&S&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(S),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[e.jsx(Jm,{size:16}),e.jsx("span",{children:"Projects"})]}),y&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[e.jsx(Pn,{size:16}),e.jsx("span",{children:"Browse Files"})]}),e.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>bt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[e.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[e.jsx(zs,{size:16}),r>0&&e.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),e.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),u&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(u),role:"menuitem","data-testid":"overflow-git-btn",children:[e.jsx(Ls,{size:16}),e.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[e.jsx(Mr,{size:16}),e.jsx("span",{children:"Nodes"})]}),!K&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(n),role:"menuitem",children:[e.jsx(fd,{size:16}),e.jsx("span",{children:"Import from GitHub"})]}),e.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[e.jsxs("div",{className:"mobile-overflow-split-row",children:[e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>bt(v),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[e.jsx(Os,{size:16}),e.jsx("span",{children:"Terminal"})]}),e.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>ze(Ve=>!Ve),role:"menuitem","aria-expanded":Oe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:e.jsx(rn,{size:14,className:`mobile-overflow-chevron${Oe?" mobile-overflow-chevron--open":""}`})})]}),Oe&&e.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Ie?e.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[e.jsx(ct,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts…"})]}):qe.length>0?e.jsxs(e.Fragment,{children:[qe.map(([Ve,ft])=>e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Ve,ft),De(!1),ze(!1)},role:"menuitem","data-testid":`overflow-script-item-${Ve}`,children:[e.jsx(an,{size:14}),e.jsx("span",{children:Ve})]},Ve)),f&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>bt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Ms,{size:14}),e.jsx("span",{children:"Manage Scripts…"})]})]}):f&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>bt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Ms,{size:14}),e.jsx("span",{children:"No scripts — add one…"})]})})]}),e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(c),role:"menuitem","data-testid":"overflow-schedules-btn",children:[e.jsx(Hi,{size:16}),e.jsx("span",{children:"Automation"})]}),o&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(o),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[e.jsx(Ra,{size:16}),e.jsx("span",{children:"View Activity Log"})]}),d&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[e.jsx(Ia,{size:16}),e.jsxs("span",{children:["Mailbox",m>0?` (${m})`:""]})]}),l&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(l),role:"menuitem","data-testid":"overflow-usage-btn",children:[e.jsx(Ns,{size:16}),e.jsx("span",{children:"View Usage"})]}),p&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[e.jsx(bo,{size:16}),e.jsx("span",{children:"Workflow Steps"})]}),e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>bt(t),role:"menuitem",children:[e.jsx($a,{size:16}),e.jsx("span",{children:"Settings"})]})]})]})]}),yt&&nt&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{className:"header-search",children:[e.jsx(Oi,{size:14,className:"header-search-icon"}),e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:I,onChange:Ve=>L(Ve.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:Pt,"aria-label":"Close search",children:e.jsx(Ft,{size:14})})]})}),L&&B&&Pe&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{ref:te,className:"header-search mobile-search-expanded",children:[e.jsx(Oi,{size:14,className:"header-search-icon"}),e.jsx("input",{ref:ke,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:I,onChange:Ve=>L(Ve.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:_t,"aria-label":"Close search",children:e.jsx(Ft,{size:14})})]})})]})}const oj={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"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!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},cj={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,autoMerge:!0,mergeStrategy:"direct",pushAfterMerge:!1,pushRemote:"origin",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:"",strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,autoCreatePr:!1,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,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,experimentalFeatures:{}},dj=Object.freeze(Object.keys(oj)),uj=Object.freeze(Object.keys(cj));function mj(t){return dj.includes(t)}function hj(t){return uj.includes(t)}function fe(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}const pj=["off","minimal","low","medium","high"],xi=["triage","todo","in-progress","in-review","done","archived"],Jo=["low","normal","high","urgent"],ds="normal",fj=["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"],us={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},gj={triage:"Raw ideas — AI will specify 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"},yo={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo"],done:["todo","triage","archived"],archived:["done"]};function bj(t){const n=t.metadata??{};return!!(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor"||n.type==="spawned"||n.internal===!0||t.role==="executor"&&typeof t.name=="string"&&t.name.startsWith("executor-")&&t.reportsTo==null||t.role==="executor"&&t.name==="verification-agent"&&t.reportsTo==null)}function xj(t,n=1400){const s=a.useRef(null),[i,r]=a.useState(!1),l=a.useRef(null);return a.useEffect(()=>(s.current!==null&&t>s.current&&(r(!0),l.current=setTimeout(()=>r(!1),n)),s.current=t,()=>{l.current!==null&&clearTimeout(l.current)}),[t,n]),i}function vj(t,n){return t==="open"?"card-github-badge--open":n==="completed"?"card-github-badge--completed":n==="not_planned"?"card-github-badge--not-planned":"card-github-badge--closed"}function wh({prInfo:t,issueInfo:n,onIssueRefresh:s}){const i=()=>{t?.url&&window.open(t.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return e.jsxs(e.Fragment,{children:[t&&e.jsxs("span",{className:`card-github-badge card-github-badge--${t.status}`,title:`PR #${t.number}: ${t.title}`,onClick:i,children:[e.jsx(ts,{size:12}),e.jsxs("span",{children:["#",t.number]})]}),n&&e.jsxs("span",{className:`card-github-badge ${vj(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[e.jsx(Vr,{size:12}),e.jsxs("span",{children:["#",n.number]})]})]})}function ar(t,n){return`${t??"default"}:${n}`}class yj{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,l]of this.subscriptionsByTask){const o=r.split(":").slice(1).join(":");for(const d of l)i.push({hookId:d,taskId:o})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:l}of i){const o=ar(this.projectId,l);this.subscriptionsByTask.set(o,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=ar(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,l=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),l&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=ar(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(Ps(i));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const l=new Set;for(const o of this.subscriptionsByTask.keys()){const d=o.split(":").slice(1).join(":");l.add(d)}for(const o of l)this.send({type:"subscribe",taskId:o,projectId:this.projectId})},r.onmessage=l=>{if(this.projectContextVersionRef===n)try{const o=JSON.parse(l.data);if(o.type!=="badge:updated"||o.projectId!==void 0&&o.projectId!==this.projectId)return;const d=ar(this.projectId,o.taskId),m=this.badgeUpdates.get(d);this.badgeUpdates.set(d,{prInfo:gd(o,"prInfo")?o.prInfo??null:m?.prInfo,issueInfo:gd(o,"issueInfo")?o.issueInfo??null:m?.issueInfo,timestamp:o.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 hi=new yj;let kj=0;function gd(t,n){return Object.prototype.hasOwnProperty.call(t,n)}function Nh(t){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${kj++}`);const s=a.useSyncExternalStore(l=>hi.subscribe(l),()=>hi.getSnapshot(),()=>hi.getSnapshot()),i=a.useCallback(l=>{hi.subscribeTask(n.current,l)},[]),r=a.useCallback(l=>{hi.unsubscribeTask(n.current,l)},[]);return a.useEffect(()=>{hi.setProjectId(t??null)},[t]),a.useEffect(()=>()=>{hi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Rr(t,n,s,i){return t===void 0||!n?s:!i||n>=i?t??void 0:s}function jj({taskId:t,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:l}){const{badgeUpdates:o,subscribeToBadge:d,unsubscribeFromBadge:m}=Nh(l),c=!!(n||s);a.useEffect(()=>{if(!c||!r){m(t);return}return d(t),()=>{m(t)}},[c,r,l,d,t,m]);const u=o.get(`${l??"default"}:${t}`),h=Rr(u?.prInfo,u?.timestamp,n,n?.lastCheckedAt??i),g=Rr(u?.issueInfo,u?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:e.jsx(wh,{prInfo:h,issueInfo:g})}const wj=a.memo(jj);wj.displayName="TaskCardBadge";const ys={data:new Map,pendingPromise:null,lastFetchTime:null},Nj=5e3;function wr(t,n){return n?`${n}::${t}`:t}function Sj(t,n){const s=ys.data.get(wr(t,n));if(!(!s||Date.now()-s.timestamp>Nj))return s}function Cj(t){const[n,s]=a.useState(!1),i=a.useRef(null),r=a.useCallback(async d=>{let c=null;for(let u=0;u<3;u++)try{return await fv(d,t)}catch(h){c=h instanceof Error?h:new Error(String(h));const g=fe(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,u),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(c)throw c;return{}},[t]),l=a.useCallback(async d=>{if(d.length===0)return;const c=Date.now()-5e3;if(d.every(g=>{const p=ys.data.get(wr(g,t));return p&&p.timestamp>c})&&ys.lastFetchTime&&ys.lastFetchTime>c)return;if(i.current&&(clearTimeout(i.current),i.current=null),ys.pendingPromise){s(!0);try{await ys.pendingPromise}finally{s(!1)}return}s(!0);const h=r(d);ys.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))ys.data.set(wr(f,t),{result:b,timestamp:p});ys.lastFetchTime=p}catch{}finally{ys.pendingPromise=null,s(!1)}},[r,t]),o=a.useCallback(d=>ys.data.get(wr(d,t)),[t]);return{fetchBatch:l,isLoading:n,lastFetchTime:ys.lastFetchTime,getBatchData:o}}const ko=new Map,Ej=3e4;function Sh(t,n,s,i){return`${t}:${n??""}:${s??""}:${i??""}`}function Mj(t,n,s,i){const r=Sh(t,n,s,i),l=ko.get(r);return l?Date.now()>l.expiresAt?(ko.delete(r),null):l.stats:null}function Aj(t,n,s,i,r){const l=Sh(t,n,s,i);ko.set(l,{stats:r,expiresAt:Date.now()+Ej})}function Pj(t,n,s,i,r={}){const l=r.enabled??!0,o=r.worktree,d=r.stepVersion,m=r.pollIntervalMs,[c,u]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!l){u(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!o;if(!t||!p&&!f){u(null),g(!1);return}const b=f?o:void 0,v=d!==void 0?String(d):void 0;let y=!1;async function k(j=!1){if(!j){const _=Mj(t,i,b,v);if(_){y||(u(_),g(!1));return}}g(!0);try{const _=await gh(t,b,i);y||(u(_.stats),Aj(t,i,b,v,_.stats))}catch{y||u(null)}finally{y||g(!1)}}k();let A;return m&&f&&(A=setInterval(()=>{k(!0)},m)),()=>{y=!0,A&&clearInterval(A)}},[t,n,s,i,l,o,d,m]),{stats:c,loading:h}}const _j=new Set(["failed","stuck-killed"]);function Ir(t,n,s){if(t.column!=="in-progress"||t.status&&_j.has(t.status)||!n||n<=0)return!1;const i=new Date(t.updatedAt).getTime();return(s??Date.now())-i>n}function Tj(t){switch(t){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Rj(t){return t==="done"||t==="skipped"}function Ij(t,n,s){const i=s?.get(t)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||t}function Ch(t,n){const s=(t.steps??[]).map((m,c)=>({id:`step-${c}`,name:m.name,status:m.status,source:"step",phase:"pre-merge"})),i=new Map((t.workflowStepResults??[]).map(m=>[m.workflowStepId,m])),r=(t.enabledWorkflowSteps??[]).map(m=>{const c=i.get(m);return{id:`workflow-${m}`,name:Ij(m,c,n),status:c?Tj(c.status):"pending",source:"workflow",phase:c?.phase??"pre-merge"}}),l=[...s,...r],o=l.length,d=l.filter(m=>Rj(m.status)).length;return{total:o,completed:d,items:l}}const jo=new Map;async function $j(t,n){const s=jo.get(t);if(s)return s;try{const i=await bh(t,n);return jo.set(t,i.title),i.title}catch{return t}}const bd=12;function Dj(t){return t.length<=bd?t:t.slice(0,bd-3)+"..."}const wo=new Map;async function Fj(t,n){const s=wo.get(t);if(s)return s;try{const i=await ph(t,n);return wo.set(t,i.name),i.name}catch{return t}}function Lj(t){return typeof t=="string"&&Jo.includes(t)?t:ds}function zj(t,n){return t.length<=n?t:t.slice(0,n-3)+"..."}const Oj=new Set(["triage","todo"]),xd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Bj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"};function vd(t,n){if(!t&&!n)return!0;if(!t||!n)return!1;const s=Object.keys(t),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>t[r]===n[r])}function Uj(t,n){return t.length!==n.length?!1:t.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Hj(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function qj(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function Vj(t){if(!(t instanceof Error))return null;const n=t.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=t.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Wj(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.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 Kj(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function Gj(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function Jj(t,n){const s=t.task,i=n.task;return t.queued===n.queued&&t.projectId===n.projectId&&t.globalPaused===n.globalPaused&&t.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&t.onOpenDetail===n.onOpenDetail&&t.addToast===n.addToast&&t.onUpdateTask===n.onUpdateTask&&t.onArchiveTask===n.onArchiveTask&&t.onUnarchiveTask===n.onUnarchiveTask&&t.onDeleteTask===n.onDeleteTask&&t.onOpenDetailWithTab===n.onOpenDetailWithTab&&t.onOpenMission===n.onOpenMission&&t.onMoveTask===n.onMoveTask&&t.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&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.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&Kj(s.attachments,i.attachments)&&Gj(s.comments,i.comments)&&Hj(s.dependencies,i.dependencies)&&Uj(s.steps,i.steps)&&qj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Wj(s.workflowStepResults,i.workflowStepResults)&&vd(s.prInfo,i.prInfo)&&vd(s.issueInfo,i.issueInfo)}function Yj({task:t,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:l,onUpdateTask:o,onArchiveTask:d,onUnarchiveTask:m,onDeleteTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:b}){const[v,y]=a.useState(!1),[k,A]=a.useState(!1),[j,_]=a.useState(!1),[N,M]=a.useState(t.description||""),[w,R]=a.useState(!1),[E,I]=a.useState(t.column==="in-progress"||t.column==="triage"&&t.steps.some(be=>be.status==="done"||be.status==="skipped")),[L,ee]=a.useState(null),[$,T]=a.useState(null),[S,Y]=a.useState(!1),K=a.useRef(null),G=a.useRef(!1),P=a.useRef(null),O=a.useRef(null),[X,C]=a.useState(!1),{badgeUpdates:V,subscribeToBadge:de,unsubscribeFromBadge:B}=Nh(n),J=a.useRef(null),D=a.useRef(!1),he=a.useCallback(be=>be instanceof Element?!!be.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{M(t.description||"")},[t.id,t.description]),a.useEffect(()=>{if(!S)return;const be=U=>{O.current&&!O.current.contains(U.target)&&Y(!1)};return document.addEventListener("click",be),()=>document.removeEventListener("click",be)},[S]),a.useEffect(()=>{if(!t.missionId){ee(null);return}const be=jo.get(t.missionId);if(be){ee(be);return}let U=!1;return $j(t.missionId,n).then(we=>{U||ee(we)}),()=>{U=!0}},[t.missionId,n]),a.useEffect(()=>{if(!t.assignedAgentId){T(null);return}const be=wo.get(t.assignedAgentId);if(be){T(be);return}T(null);let U=!1;return Fj(t.assignedAgentId,n).then(we=>{U||T(we)}),()=>{U=!0}},[t.assignedAgentId,n]),a.useEffect(()=>{if(j&&K.current){const be=K.current;be.focus(),be.style.height="auto",be.style.height=be.scrollHeight+"px"}},[j]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){C(!0);return}const be=P.current;if(!be)return;const U=new IntersectionObserver(([we])=>{C(we?.isIntersecting??!0)},{rootMargin:"200px"});return U.observe(be),()=>U.disconnect()},[j,t.id]);const q=a.useCallback(be=>{be.dataTransfer.setData("text/plain",t.id),be.dataTransfer.effectAllowed="move",y(!0)},[t.id]),W=a.useCallback(()=>{y(!1)},[]),me=a.useCallback(be=>be.dataTransfer.types.includes("Files"),[]),Re=a.useCallback(be=>{me(be)&&(be.preventDefault(),be.stopPropagation(),be.dataTransfer.dropEffect="copy",A(!0))},[me]),ve=a.useCallback(be=>{me(be)&&(be.preventDefault(),be.stopPropagation(),A(!1))},[me]),Me=a.useCallback(async be=>{if(!me(be))return;be.preventDefault(),be.stopPropagation(),A(!1);const U=Array.from(be.dataTransfer.files);for(const we of U)try{await Da(t.id,we,n),r(`Attached ${we.name} to ${t.id}`,"success")}catch(rt){r(`Failed to attach ${we.name}: ${fe(rt)}`,"error")}},[t.id,me,r]),_e=a.useCallback(()=>{j||i(t)},[t,i,j]),De=a.useCallback(be=>{if(G.current){G.current=!1;return}he(be.target)||_e()},[_e,he]),Oe=a.useCallback(be=>{const U=be.touches[0];U&&(J.current={x:U.clientX,y:U.clientY,time:Date.now()},D.current=!1)},[]),ze=a.useCallback(be=>{if(!J.current)return;const U=be.touches[0];if(!U)return;const we=Math.abs(U.clientX-J.current.x),rt=Math.abs(U.clientY-J.current.y);(we>yd||rt>yd)&&(D.current=!0)},[]),Be=a.useCallback(be=>{if(he(be.target)||!J.current)return;const we=Date.now()-J.current.time<Qj,rt=!D.current;we&&rt&&(G.current=!0,_e()),J.current=null,D.current=!1},[_e,he]),Ae=a.useCallback(async(be,U)=>{be.stopPropagation();try{const we=await _r(U,n);i(we)}catch{r(`Failed to load dependency ${U}`,"error")}},[i,r]),Ce=t.status==="failed",Ge=t.paused===!0,Te=Lj(t.priority),Xe=Te!==ds,re=Ir(t,h,f),Z=t.column==="triage"&&t.status==="awaiting-approval",ye=t.column==="archived",ie=!l&&!s&&!Ce&&!Ge&&!re&&!Z&&(t.column==="in-progress"||xd.has(t.status)),Ie=!s&&!Ge&&!j&&!ye,pe=Oj.has(t.column)&&!ie&&!Ge&&!s&&o,Ue=!!(t.prInfo||t.issueInfo),dt=!!(t.assignedAgentId&&$===null),ht=a.useMemo(()=>Ch(t,b),[t.steps,t.enabledWorkflowSteps,t.workflowStepResults,b]),ue=ht.total>0&&(t.status==="executing"||t.column==="in-progress");a.useEffect(()=>{if(!Ue||!X){B(t.id);return}return de(t.id),()=>{B(t.id)}},[Ue,X,de,t.id,B]);const te=V.get(`${n??"default"}:${t.id}`),ke=t.column==="in-progress"||t.column==="in-review",Ne=a.useMemo(()=>t.steps.map(be=>`${be.name}:${be.status}`).join("|"),[t.steps]),{stats:Ze}=Pj(t.id,t.column,t.mergeDetails?.commitSha,n,{enabled:X,worktree:t.worktree,stepVersion:ke?Ne:void 0,pollIntervalMs:ke?3e4:void 0}),xe=a.useMemo(()=>Sj(t.id,n),[t.id,n]),st=a.useMemo(()=>{const be=te?.prInfo,U=te?.timestamp,we=xe?.result?.prInfo,rt=xe?.timestamp?new Date(xe.timestamp).toISOString():void 0,xt=t.prInfo,je=t.prInfo?.lastCheckedAt??t.updatedAt;let Ke=Rr(be,U,xt,je);const pt=U&&U>=je?U:je;return we&&rt&&(!pt||rt>pt)&&(Ke=we),Ke},[te,xe,t.prInfo,t.updatedAt]),Ee=a.useMemo(()=>{const be=te?.issueInfo,U=te?.timestamp,we=xe?.result?.issueInfo,rt=xe?.timestamp?new Date(xe.timestamp).toISOString():void 0,xt=t.issueInfo,je=t.issueInfo?.lastCheckedAt??t.updatedAt;let Ke=Rr(be,U,xt,je);const pt=U&&U>=je?U:je;return we&&rt&&(!pt||rt>pt)&&(Ke=we),Ke},[te,xe,t.issueInfo,t.updatedAt]),He=a.useCallback(be=>{be?.stopPropagation(),!(!pe||w)&&(_(!0),M(t.description||""))},[pe,w,t.description]),ce=a.useCallback(()=>{_(!1),M(t.description||"")},[t.description]),qe=a.useCallback(()=>N!==(t.description||""),[N,t.description]),We=a.useCallback(async()=>{if(!(!o||w)){if(!qe()){ce();return}R(!0);try{await o(t.id,{description:N.trim()||void 0}),r(`Updated ${t.id}`,"success"),_(!1)}catch(be){r(`Failed to update ${t.id}: ${fe(be)}`,"error")}finally{R(!1)}}},[o,t.id,N,w,qe,ce,r]),Pe=a.useCallback(be=>{be.key==="Enter"&&!be.shiftKey?(be.preventDefault(),We()):be.key==="Escape"&&(be.preventDefault(),ce())},[We,ce]),nt=a.useCallback(()=>{setTimeout(()=>{const be=document.activeElement;be===K.current||be?.closest(".card-editing-content")||(qe()?We():ce())},0)},[qe,We,ce]),kt=a.useCallback(be=>{pe&&(be.stopPropagation(),He(be))},[pe,He]),yt=a.useCallback(be=>{be.stopPropagation(),He(be)},[He]),Ct=a.useCallback(be=>{M(be.target.value);const U=be.target;U.style.height="auto",U.style.height=U.scrollHeight+"px"},[]),Et=a.useCallback(be=>{be.stopPropagation(),d&&d(t.id).then(()=>{r(`Archived ${t.id}`,"success")}).catch(U=>{r(`Failed to archive ${t.id}: ${fe(U)}`,"error")})},[r,d,t.id]),Pt=a.useCallback(be=>{be.stopPropagation(),m&&m(t.id).then(()=>{r(`Unarchived ${t.id}`,"success")}).catch(U=>{r(`Failed to unarchive ${t.id}: ${fe(U)}`,"error")})},[r,m,t.id]),It=a.useCallback(be=>{be.stopPropagation(),c&&window.confirm(`Delete ${t.id}?`)&&c(t.id).then(()=>{r(`Deleted ${t.id}`,"success")}).catch(U=>{const we=Vj(U);if(!we||we.dependentIds.length===0){r(`Failed to delete ${t.id}: ${fe(U)}`,"error");return}const rt=we.dependentIds.join(", ");window.confirm(`${t.id} is a dependency of ${rt}.
|
|
596
|
+
|
|
597
|
+
Delete anyway by removing these dependency references first?`)&&c(t.id,{removeDependencyReferences:!0}).then(()=>{r(`Deleted ${t.id} after removing dependency references`,"success")}).catch(je=>{r(`Failed to delete ${t.id}: ${fe(je)}`,"error")})})},[r,c,t.id]),bt=a.useCallback(be=>{be.stopPropagation(),u?.(t,"changes")},[t,u]),_t=a.useCallback(be=>{be.stopPropagation(),I(U=>!U)},[]),Ve=a.useCallback(be=>{be.stopPropagation(),t.missionId&&g&&g(t.missionId)},[t.missionId,g]),ft=a.useCallback(be=>{be.stopPropagation(),Y(U=>!U)},[]),Fe=a.useCallback((be,U)=>{be.stopPropagation(),Y(!1),p&&p(t.id,U).then(()=>{r(`Moved ${t.id} to ${us[U]}`,"success")}).catch(we=>{r(`Failed to move ${t.id}: ${fe(we)}`,"error")})},[r,p,t.id]),lt=`card${v?" dragging":""}${s?" queued":""}${ie?" agent-active":""}${Ce?" failed":""}${Ge?" paused":""}${re?" stuck":""}${Z?" awaiting-approval":""}${k?" file-drop-target":""}${j?" card-editing":""}${w?" card-saving":""}`;return j?e.jsx("div",{ref:P,className:lt,"data-id":t.id,onDoubleClick:kt,children:e.jsxs("div",{className:"card-editing-content",children:[e.jsx("textarea",{ref:K,className:"card-edit-desc-textarea",placeholder:"Task description",value:N,onChange:Ct,onKeyDown:Pe,onBlur:nt,disabled:w,rows:4}),w&&e.jsxs("div",{className:"card-edit-loading",children:[e.jsx("span",{className:"card-edit-loading-spinner"}),e.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):e.jsxs("div",{ref:P,className:lt,"data-id":t.id,draggable:Ie,onDragStart:Ie?q:void 0,onDragEnd:Ie?W:void 0,onDragOver:Re,onDragLeave:ve,onDrop:Me,onClick:De,onTouchStart:Oe,onTouchMove:ze,onTouchEnd:Be,onDoubleClick:kt,children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"card-id",children:t.id}),Ge&&e.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Ge&&t.status&&t.status!=="queued"&&e.jsx("span",{className:`card-status-badge card-status-badge--${t.column}${Z?" awaiting-approval":""}${xd.has(t.status)?" pulsing":""}${Ce?" failed":""}${re?" stuck":""}`,children:re?"Stuck":Z?"Awaiting Approval":t.status}),re&&(Ge||!t.status||t.status==="queued")&&e.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Ue&&e.jsx(wh,{prInfo:st,issueInfo:Ee}),Xe&&e.jsx("span",{className:`card-priority-badge card-priority-badge--${Te}`,children:Te}),t.missionId&&e.jsxs("span",{className:"card-mission-badge",onClick:Ve,title:`Mission: ${L??t.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.jsx(ns,{size:11}),Dj(L??t.missionId)]}),e.jsxs("div",{className:"card-header-actions",children:[pe&&e.jsx("button",{className:"card-edit-btn",onClick:yt,title:"Edit task","aria-label":"Edit task",children:e.jsx(Dn,{size:12})}),t.column==="triage"&&c&&e.jsx("button",{className:"card-delete-btn",onClick:It,title:"Delete task","aria-label":"Delete task",children:e.jsx(Ut,{size:12})}),t.column==="done"&&d&&e.jsx("button",{className:"card-archive-btn",onClick:Et,title:"Archive task","aria-label":"Archive task",children:"Archive"}),t.column==="archived"&&m&&e.jsx("button",{className:"card-unarchive-btn",onClick:Pt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),t.column==="in-progress"&&p&&e.jsxs("div",{className:"card-send-back",ref:O,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:ft,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":S,children:["Send back",e.jsx(Lt,{size:10})]}),S&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:yo["in-progress"].filter(be=>be!=="in-review").map(be=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:U=>Fe(U,be),children:us[be]},be))})]}),t.column==="in-review"&&p&&e.jsxs("div",{className:"card-send-back",ref:O,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:ft,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":S,children:["Move",e.jsx(Lt,{size:10})]}),S&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:yo["in-review"].map(be=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:U=>Fe(U,be),children:be==="done"?"Done (no merge)":us[be]},be))})]}),t.size&&e.jsx("span",{className:`card-size-badge size-${t.size.toLowerCase()}`,children:t.size})]})]}),Ce&&t.error&&e.jsxs("div",{className:"card-error",title:t.error,children:[e.jsx("span",{className:"card-error-icon",children:"⚠"}),e.jsx("span",{className:"card-error-text",children:t.error.length>60?t.error.slice(0,60)+"…":t.error})]}),e.jsx("div",{className:"card-title",title:t.title||t.description||void 0,children:jd(t.title,kd)||jd(t.description,kd)||t.id}),ue&&(()=>{const be=ht.completed/ht.total*100;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"card-progress",children:[e.jsx("div",{className:"card-progress-bar",children:e.jsx("div",{className:"card-progress-fill",style:{width:`${be}%`,backgroundColor:Bj[t.column]}})}),e.jsxs("span",{className:"card-progress-label",children:[ht.completed,"/",ht.total]})]}),e.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:_t,"aria-expanded":E,"aria-label":E?"Hide steps":"Show steps",children:[e.jsxs("span",{children:[ht.total," step",ht.total===1?"":"s"]}),e.jsx(Lt,{size:14,className:`card-steps-toggle-icon${E?" expanded":""}`})]}),E&&e.jsx("div",{className:"card-steps-list",children:ht.items.map(U=>e.jsxs("div",{className:"card-step-item",children:[e.jsx("span",{className:`card-step-dot card-step-dot--${U.status}`,"aria-hidden":"true"}),e.jsx("span",{className:`card-step-name${U.status==="done"?" completed":""}`,children:U.name}),U.source==="workflow"&&e.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${U.phase}`,title:"Workflow check",children:"workflow"})]},U.id))})]})})(),t.worktree&&(t.column==="in-progress"||t.column==="in-review")&&(()=>{const be=Ze?.filesChanged;return be==null||be===0?null:e.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!u,children:[e.jsx(Pn,{size:12}),e.jsxs("span",{children:[be," ",be===1?"file":"files"," changed"]})]})})(),t.column==="done"&&(()=>{const be=Ze?.filesChanged,U=t.mergeDetails?.filesChanged,we=be??U;if(we!=null&&we>0)return e.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!u,children:[e.jsx(Pn,{size:12}),e.jsxs("span",{children:[we," ",we===1?"file":"files"," changed"]})]});const rt=t.modifiedFiles?.length;return rt!=null&&rt>0?e.jsxs("button",{type:"button",className:"card-session-files",onClick:bt,disabled:!u,children:[e.jsx(Pn,{size:12}),e.jsxs("span",{children:[rt," ",rt===1?"file":"files"," changed"]})]}):null})(),(t.dependencies&&t.dependencies.length>0||s||t.status==="queued"||t.blockedBy)&&e.jsxs("div",{className:"card-meta",children:[t.dependencies&&t.dependencies.length>0&&e.jsx("div",{className:"card-dep-list",children:t.dependencies.map(be=>e.jsxs("span",{className:"card-dep-badge clickable",onClick:U=>void Ae(U,be),title:`Click to view ${be}`,children:[e.jsx(Vi,{size:12,style:{verticalAlign:"middle"}})," ",be]},be))}),t.blockedBy&&e.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${t.blockedBy} (file overlap)`,children:[e.jsx(ki,{size:12,style:{verticalAlign:"middle"}})," ",t.blockedBy]}),(s||t.status==="queued")&&t.column!=="in-progress"&&e.jsxs("span",{className:"queued-badge",children:[e.jsx(Hi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),t.assignedAgentId&&e.jsx("div",{className:"card-agent-row",children:e.jsxs("span",{className:`card-agent-badge${dt?" card-agent-badge--loading":""}`,title:`Assigned to ${$??t.assignedAgentId}`,children:[e.jsx(sn,{size:11}),e.jsx("span",{className:"card-agent-badge-text",children:zj($??t.assignedAgentId,15)})]})}),e.jsx(Ja,{slotId:"task-card-badge",projectId:n})]})}const yd=10,Qj=300,kd=140;function jd(t,n){return t?t.length>n?t.slice(0,n)+"…":t:""}const $r=a.memo(Yj,Jj);$r.displayName="TaskCard";function Xj({label:t,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g}){return e.jsxs("div",{className:"worktree-group",children:[e.jsxs("div",{className:"worktree-group-header",children:[e.jsx("span",{className:"worktree-icon",children:t==="Up Next"||t==="Unassigned"?e.jsx(ig,{size:14}):e.jsx(Ls,{size:14})}),e.jsx("span",{className:"worktree-label",children:t})]}),n.map(p=>e.jsx($r,{task:p,projectId:i,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id)),s.map(p=>e.jsx($r,{task:p,projectId:i,queued:!0,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id))]})}const Eh=a.memo(Xj);Eh.displayName="WorktreeGroup";function wd(t){return t.toLowerCase().replace(/[-_./]/g,"")}function Zj(t,n){let s=0;for(let i=0;i<n.length&&s<t.length;i++)t[s]===n[i]&&s++;return s===t.length}function ew(t,n,s){const i=t.length,r=n.length;if(i===0)return!0;if(r===0)return!1;let l=new Array(r+1).fill(0),o=new Array(r+1).fill(0);for(let d=1;d<=i;d++){const m=new Array(r+1);m[0]=d;for(let c=1;c<=r;c++){const u=t[d-1]===n[c-1]?0:1;m[c]=Math.min(o[c]+1,m[c-1]+1,o[c-1]+u),d>=2&&c>=2&&t[d-1]===n[c-2]&&t[d-2]===n[c-1]&&(m[c]=Math.min(m[c],l[c-2]+1))}l=o,o=m}for(let d=0;d<=r;d++)if(o[d]<=s)return!0;return!1}function tw(t,n){const s=wd(t),i=wd(n);if(s.length===0||i.includes(s))return!0;const r=i.split(/\s+/).filter(Boolean);for(const l of r)if(s.length>=3&&Zj(s,l)||s.length>=4&&ew(s,l,1))return!0;return!1}function nw(t,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?t:t.filter(i=>{const r=`${i.provider} ${i.id} ${i.name}`;return s.every(l=>tw(l,r))})}const sw={sm:16,md:20,lg:24};function iw({size:t,color:n,label:s="Anthropic"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"anthropic-icon","aria-label":s,children:e.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 Nd({size:t,color:n,label:s="OpenAI"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:e.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 Sd({size:t,color:n,label:s="Google Gemini"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:e.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 aw({size:t,color:n,label:s="Ollama"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"ollama-icon","aria-label":s,children:e.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 rw({size:t,color:n,label:s="MiniMax"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"minimax-icon","aria-label":s,children:e.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 lw({size:t,color:n,label:s="Z.ai"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"zai-icon","aria-label":s,children:e.jsx("path",{d:"M3 5H21V8.5L7 17.5H21V21H3V17.5L17 8.5H3Z",fill:n})})}function Cd({size:t,color:n,label:s="Kimi"}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"kimi-icon","aria-label":s,children:e.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 ow({size:t,color:n,label:s="Anthropic — via Claude CLI"}){return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[e.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:e.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})}),e.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),e.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--bg-primary, #111)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const cw={anthropic:{component:iw,color:"#d4a27f"},"claude-cli":{component:ow,color:"#d4a27f",label:"Anthropic — via Claude CLI"},openai:{component:Nd,color:"#10a37f"},"openai-codex":{component:Nd,color:"#10a37f",label:"OpenAI Codex"},google:{component:Sd,color:"#4285f4"},gemini:{component:Sd,color:"#4285f4"},ollama:{component:aw,color:"#fff"},minimax:{component:rw,color:"#E73562"},zai:{component:lw,color:"#1A6DFF"},kimi:{component:Cd,color:"#6C5CE7"},moonshot:{component:Cd,color:"#6C5CE7"}};function ss({provider:t,size:n="sm"}){const s=t.toLowerCase(),i=cw[s],r=i?.component,l=i?.color??"var(--text-muted)",o=i?.label,d=sw[n];return e.jsx("span",{className:"provider-icon",style:{color:l},"data-provider":s,children:r?e.jsx(r,{size:d,color:l,label:o}):e.jsx(ug,{size:d})})}function Kt({models:t,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:l,label:o,favoriteProviders:d=[],onToggleFavorite:m,favoriteModels:c=[],onToggleModelFavorite:u,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[b,v]=a.useState(""),[y,k]=a.useState(0),[A,j]=a.useState(null),[_,N]=a.useState(null),M=a.useRef(null),w=a.useRef(null),R=a.useRef(null),E=a.useRef(null),I=a.useRef(null),L=a.useMemo(()=>nw(t,b),[t,b]),ee=a.useMemo(()=>L.reduce((W,me)=>((W[me.provider]??=[]).push(me),W),{}),[L]),$=a.useMemo(()=>{const W=[];for(const me of c){const Re=me.indexOf("/");if(Re===-1)continue;const ve=me.slice(0,Re),Me=me.slice(Re+1),_e=L.find(De=>De.provider===ve&&De.id===Me);_e&&W.push({model:_e,fullId:me})}return W},[c,L]),T=a.useMemo(()=>{const W=Object.entries(ee),me=new Set(d);return W.sort(([Re],[ve])=>{const Me=me.has(Re),_e=me.has(ve);if(Me&&!_e)return-1;if(!Me&&_e)return 1;if(Me&&_e){const De=d.indexOf(Re),Oe=d.indexOf(ve);if(De!==Oe)return De-Oe}return Re.localeCompare(ve)})},[ee,d]),S=typeof h=="string"&&h.length>0,Y=a.useMemo(()=>{if(!n||S&&n===h)return null;const W=n.indexOf("/");return W===-1?null:n.slice(0,W)},[S,h,n]),K=a.useMemo(()=>{const W=[];return S&&W.push({type:"no-change",value:h,label:g}),W.push({type:"default",value:"",label:"Use default"}),W},[S,g,h]),G=a.useMemo(()=>{const W=[...K];for(const{model:me,fullId:Re}of $)W.push({type:"favorite",value:Re,label:me.name,provider:me.provider});return T.forEach(([me,Re])=>{W.push({type:"provider",value:`__group_${me}`,label:me,provider:me}),Re.forEach(ve=>{W.push({type:"model",value:`${ve.provider}/${ve.id}`,label:ve.name,provider:ve.provider})})}),W},[$,T,K]),P=a.useMemo(()=>{if(S&&n===h)return g;if(!n)return"Use default";const W=n.indexOf("/");if(W===-1)return n;const me=n.slice(0,W),Re=n.slice(W+1);return t.find(Me=>Me.provider===me&&Me.id===Re)?.name||n},[S,g,h,n,t]),O=a.useMemo(()=>G.findIndex(W=>W.value===n),[G,n]),X=a.useCallback(()=>{const W=window.visualViewport;return W&&W.height>0&&W.width>0?{width:W.width,height:W.height,offsetTop:W.offsetTop,offsetLeft:W.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),C=a.useCallback(()=>{const{height:W}=X(),me=typeof window.matchMedia=="function",Re=me?window.matchMedia("(max-width: 640px)").matches:!1,ve=me?window.matchMedia("(max-width: 768px)").matches:!1;return W<=0?320:Re?Math.min(W*.6,360):ve?Math.min(W*.7,420):320},[X]),V=a.useCallback(()=>{const W=w.current;if(!W)return;const me=W.getBoundingClientRect(),{width:Re,height:ve,offsetTop:Me,offsetLeft:_e}=X(),De=16,Oe=16,ze=4,Be=C(),Ae=me.bottom-Me,Ce=me.top-Me,Ge=me.left-_e,Te=ve-Ae,Xe=Ce,re=Math.max(Te-Oe-ze,160),Z=Math.max(Xe-Oe-ze,160),ye=Te<Be&&Xe>Te,ie=Math.max(Math.min(ye?Z:re,Be),160),Ie=Math.min(me.width,Re-De*2),pe=Math.min(Math.max(Ge,De),Re-De-Ie)+_e,Ue=ye?Math.max(Oe+Me,Ce-ie-ze+Me):Math.min(Ae+ze+Me,ve+Me-Oe-ie);j({top:Ue,left:pe,width:Ie,maxHeight:ie})},[X,C]);a.useEffect(()=>{N(document.body)},[]),a.useEffect(()=>{if(p){const W=G.findIndex((me,Re)=>Re>=(O>=0?O:0)&&me.type!=="provider");k(W>=0?W:0)}},[p,G,O]),a.useEffect(()=>{if(!p)return;V();const W=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(W)},[p,V]),a.useEffect(()=>{if(!p)return;const W=()=>V();window.addEventListener("resize",W),window.addEventListener("scroll",W,!0);const me=window.visualViewport;return me&&(me.addEventListener("resize",W),me.addEventListener("scroll",W)),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),me&&(me.removeEventListener("resize",W),me.removeEventListener("scroll",W))}},[p,V]),a.useEffect(()=>{if(!p)return;const W=me=>{const Re=me.target,ve=M.current?.contains(Re),Me=R.current?.contains(Re);!ve&&!Me&&(f(!1),v(""))};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[p]);const de=a.useCallback(W=>{switch(W.key){case"ArrowDown":if(W.preventDefault(),!p)f(!0);else{let me=y;for(let Re=1;Re<=G.length;Re++){const ve=(y+Re)%G.length;if(G[ve]?.type!=="provider"){me=ve;break}}k(me)}break;case"ArrowUp":if(W.preventDefault(),p){let me=y;for(let Re=1;Re<=G.length;Re++){const ve=(y-Re+G.length)%G.length;if(G[ve]?.type!=="provider"){me=ve;break}}k(me)}break;case"Enter":if(W.preventDefault(),p){const me=G[y];me&&me.type!=="provider"&&me.type!=="favorite"&&(s(me.value),f(!1),v(""))}else f(!0);break;case"Escape":W.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,y,G,s]),B=a.useCallback(W=>{s(W),f(!1),v("")},[s]),J=a.useCallback(()=>{v(""),E.current?.focus()},[]),D=a.useCallback(()=>{r||f(W=>!W)},[r]);a.useEffect(()=>{if(p&&I.current){const W=I.current.querySelector(`[data-index="${y}"]`);W&&typeof W.scrollIntoView=="function"&&W.scrollIntoView({block:"nearest"})}},[y,p]);const he=b.length>0,q=p&&A?e.jsxs("div",{ref:R,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:de,style:{top:`${A.top}px`,left:`${A.left}px`,width:`${A.width}px`,maxHeight:`${A.maxHeight}px`},children:[e.jsxs("div",{className:"model-combobox-search-wrapper",children:[e.jsx("input",{ref:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:W=>v(W.target.value),onClick:W=>W.stopPropagation()}),he&&e.jsx("button",{type:"button",className:"model-combobox-clear",onClick:J,"aria-label":"Clear filter",children:"×"})]}),e.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),e.jsxs("div",{ref:I,className:"model-combobox-list",children:[K.map((W,me)=>e.jsx("div",{"data-index":me,className:`model-combobox-option ${y===me?"model-combobox-option--highlighted":""} ${n===W.value?"model-combobox-option--selected":""}`,onClick:()=>B(W.value),onMouseEnter:()=>k(me),role:"option","aria-selected":n===W.value,children:e.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:W.label})},`${W.type}-${W.value}`)),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-combobox-divider"}),$.map(({model:W,fullId:me},Re)=>{const ve=Re+K.length,Me=y===ve,_e=n===me;return e.jsxs("div",{"data-index":ve,className:`model-combobox-option model-combobox-option--favorite ${Me?"model-combobox-option--highlighted":""} ${_e?"model-combobox-option--selected":""}`,onClick:()=>B(me),onMouseEnter:()=>k(ve),role:"option","aria-selected":_e,children:[e.jsx(ss,{provider:W.provider,size:"sm"}),e.jsx("span",{className:"model-combobox-option-text",children:W.name}),e.jsx("span",{className:"model-combobox-option-id",children:W.id}),u&&e.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:De=>{De.stopPropagation(),u(me)},title:"Remove from favorites","aria-label":`Remove ${W.name} from favorites`,children:"★"})]},me)}),e.jsx("div",{className:"model-combobox-divider"})]}),T.map(([W,me])=>{const Re=G.findIndex(_e=>_e.value===`__group_${W}`),ve=d.includes(W),Me=me.filter(_e=>{const De=`${_e.provider}/${_e.id}`;return!c.includes(De)});return Me.length===0?null:e.jsxs("div",{className:"model-combobox-group",children:[e.jsxs("div",{className:"model-combobox-optgroup","data-index":Re,children:[e.jsx(ss,{provider:W,size:"sm"}),e.jsx("span",{className:"model-combobox-optgroup-text",children:W}),m&&e.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ve?"model-combobox-optgroup-favorite--active":""}`,onClick:_e=>{_e.stopPropagation(),m(W)},title:ve?"Remove from favorites":"Add to favorites","aria-label":ve?`Remove ${W} from favorites`:`Add ${W} to favorites`,children:"★"})]}),Me.map(_e=>{const De=`${_e.provider}/${_e.id}`,Oe=G.findIndex(Ce=>Ce.value===De),ze=y===Oe,Be=n===De,Ae=c.includes(De);return e.jsxs("div",{"data-index":Oe,className:`model-combobox-option ${ze?"model-combobox-option--highlighted":""} ${Be?"model-combobox-option--selected":""}`,onClick:()=>B(De),onMouseEnter:()=>k(Oe),role:"option","aria-selected":Be,children:[e.jsx("span",{className:"model-combobox-option-text",children:_e.name}),e.jsx("span",{className:"model-combobox-option-id",children:_e.id}),u&&e.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ae?"model-combobox-option-favorite--active":""}`,onClick:Ce=>{Ce.stopPropagation(),u(De)},title:Ae?"Remove from favorites":"Add to favorites","aria-label":Ae?`Remove ${_e.name} from favorites`:`Add ${_e.name} to favorites`,children:Ae?"★":"☆"})]},De)})]},W)}),L.length===0&&he&&e.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:M,className:"model-combobox",onKeyDown:de,children:e.jsxs("button",{ref:w,type:"button",id:l,className:"model-combobox-trigger",onClick:D,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":o,children:[Y&&e.jsx("span",{className:"model-combobox-trigger-icon",children:e.jsx(ss,{provider:Y,size:"sm"})}),e.jsx("span",{className:"model-combobox-trigger-text",children:P||i}),e.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),_&&q?Na.createPortal(q,_):null]})}function Yo(t,n){return typeof n!="string"||n.length===0?t:`kb:${n}:${t}`}function In(t,n){return typeof window>"u"?null:window.localStorage.getItem(Yo(t,n))}function ms(t,n,s){typeof window>"u"||window.localStorage.setItem(Yo(t,s),n)}function Fa(t,n){typeof window>"u"||window.localStorage.removeItem(Yo(t,n))}const da="kb-quick-entry-text",dw=["image/png","image/jpeg","image/gif","image/webp"];function bl(t,n){return t&&n?`${t}/${n}`:""}function xl(t){if(!t)return{provider:void 0,modelId:void 0};const n=t.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function Mh({onCreate:t,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:l,projectId:o,autoExpand:d=!0,favoriteProviders:m,favoriteModels:c,onToggleFavorite:u,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&In(da,o)||""),[f,b]=a.useState(!1),[v,y]=a.useState(!1),[k,A]=a.useState(!1),j=a.useRef(null),_=a.useRef(null),N=a.useRef(!1),M=a.useRef(o),[w,R]=a.useState([]),E=a.useRef([]),[I,L]=a.useState([]),[ee,$]=a.useState(!1),[T,S]=a.useState(""),[Y,K]=a.useState(null),[G,P]=a.useState([]),[O,X]=a.useState(void 0),[C,V]=a.useState(!1),[de,B]=a.useState(!1),[J,D]=a.useState(!1),[he,q]=a.useState(null),[W,me]=a.useState(void 0),[Re,ve]=a.useState(void 0),[Me,_e]=a.useState(void 0),[De,Oe]=a.useState(void 0),[ze,Be]=a.useState(void 0),[Ae,Ce]=a.useState(void 0),Ge=a.useRef(null),Te=a.useRef(null),Xe=a.useRef(null),re=a.useRef(null),[Z,ye]=a.useState(null),[ie,Ie]=a.useState(null),pe=a.useRef(null),Ue=a.useRef(null),[dt,ht]=a.useState(null),[ue]=a.useState(()=>typeof document<"u"?document.body:null),[te,ke]=a.useState(!1),[Ne,Ze]=a.useState(null),[xe,st]=a.useState(i??[]),[Ee,He]=a.useState([]),[ce,qe]=a.useState([]),[We,Pe]=a.useState(null),[nt,kt]=a.useState(void 0),[yt,Ct]=a.useState(!1),[Et,Pt]=a.useState(!1),[It,bt]=a.useState(!1),_t=a.useRef(null),Ve=a.useRef(null),[ft,Fe]=a.useState(null),lt=m??Ee,be=c??ce,U=!t;a.useEffect(()=>{if(i)st(i),ke(!1),Ze(null);else{let le=!1;return ke(!0),Ze(null),Kn().then($e=>{le||(st($e.models),m||He($e.favoriteProviders),c||qe($e.favoriteModels))}).catch($e=>{le||Ze(fe($e)||"Failed to load models")}).finally(()=>{le||ke(!1)}),Ki(o).then($e=>{le||Pe($e)}).catch(()=>{}),()=>{le=!0}}},[i,m,c,o]);const we=bl(W,Re),rt=bl(Me,De),xt=bl(ze,Ae),je=!!(W&&Re),Ke=!!(Me&&De),pt=!!(ze&&Ae),Ht=Number(je)+Number(Ke)+Number(pt),fn=nt?We?.modelPresets?.find(le=>le.id===nt)?.name??"Models":Ht>0?`${Ht} model${Ht===1?"":"s"}`:"Models",hn=a.useCallback((le,$e)=>{if(!le||!$e)return"Using default";const ut=xe.find(wt=>wt.provider===le&&wt.id===$e);return ut?`${ut.provider}/${ut.id}`:`${le}/${$e}`},[xe]);a.useEffect(()=>{p(In(da,o)||"")},[o]),a.useEffect(()=>{typeof window<"u"&&ms(da,g,o)},[g,o]),a.useEffect(()=>{M.current!==o&&(M.current=o,P([]),X(void 0),K(null),V(!1),ye(null))},[o]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{E.current=w},[w]),a.useEffect(()=>()=>{E.current.forEach(le=>URL.revokeObjectURL(le.previewUrl))},[]);const Jn=a.useCallback(()=>{const le=j.current;if(!le)return;le.style.height="auto";const $e=Math.min(le.scrollHeight,200);le.style.height=`${$e}px`},[]);a.useEffect(()=>{v&&Jn()},[g,v,Jn]),a.useEffect(()=>{if(!f&&g===""&&j.current){const le=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(le)}},[f,g]),a.useEffect(()=>{ee||S("")},[ee]),a.useEffect(()=>{if(!Et)return;const le=$e=>{const ut=$e.target,wt=_t.current?.contains(ut),St=Ve.current?.contains(ut);!wt&&!St&&Pt(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Et]),a.useEffect(()=>{if(!J)return;const le=$e=>{const ut=$e.target,wt=Ge.current?.contains(ut),St=Te.current?.contains(ut),ln=ut instanceof Element&&ut.closest?.(".model-combobox-dropdown--portal")!=null;!wt&&!St&&!ln&&(D(!1),q(null))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[J]),a.useEffect(()=>{if(!C)return;const le=$e=>{const ut=$e.target;Xe.current?.contains(ut)||re.current?.contains(ut)||(V(!1),ye(null))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[C]);const Ot=a.useCallback(()=>{w.forEach(le=>URL.revokeObjectURL(le.previewUrl)),R([]),_.current&&(_.current.value=""),p(""),L([]),K(null),V(!1),ye(null),me(void 0),ve(void 0),_e(void 0),Oe(void 0),Be(void 0),Ce(void 0),kt(void 0),Ct(!1),$(!1),D(!1),Ie(null),q(null),Pt(!1),bt(!1),y(!1),A(!1),N.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&Fa(da,o)},[w,o]),yn=a.useCallback(le=>{if(!le||le.length===0)return;const $e=[];for(let ut=0;ut<le.length;ut++){const wt=le[ut];dw.includes(wt.type)&&$e.push({file:wt,previewUrl:URL.createObjectURL(wt)})}$e.length>0&&R(ut=>[...ut,...$e])},[]),tn=a.useCallback(le=>{f||yn(le.clipboardData?.files)},[yn,f]),dn=a.useCallback(le=>{R($e=>{const ut=$e[le];return ut&&URL.revokeObjectURL(ut.previewUrl),$e.filter((wt,St)=>St!==le)})},[]),nn=a.useCallback(async()=>{const le=g.trim();if(!(!le||f||!t)){b(!0);try{const $e=await t({description:le,column:"triage",dependencies:I.length?I:void 0,...Y?{assignedAgentId:Y}:{},modelPresetId:nt,modelProvider:je?W:void 0,modelId:je?Re:void 0,validatorModelProvider:Ke?Me:void 0,validatorModelId:Ke?De:void 0,planningModelProvider:pt?ze:void 0,planningModelId:pt?Ae:void 0,...yt?{executionMode:"fast"}:{}});if($e&&w.length>0){const ut=[];for(const wt of w)try{await Da($e.id,wt.file,o)}catch{ut.push(wt.file.name)}ut.length>0&&n(`Failed to upload: ${ut.join(", ")}`,"error")}Ot()}catch($e){n(fe($e)||"Failed to create task","error")}finally{b(!1)}}},[g,f,t,I,Y,je,W,Re,Ke,Me,De,pt,ze,Ae,w,o,n,Ot,yt]),Cn=a.useCallback(le=>{if(le.key==="Enter"){if(le.shiftKey&&v)return;le.preventDefault(),nn()}else if(le.key==="Escape"){if(le.preventDefault(),he){q(null);return}if(J){D(!1),Ie(null);return}if(ee){$(!1);return}if(Et){Pt(!1);return}if(C){V(!1),ye(null);return}g.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&Fa(da,o)),y(!1),A(!1),j.current?.blur()}},[nn,g,v,ee,C,J,he,Et,o,A]),kn=a.useCallback(()=>{N.current&&(N.current=!1)},[]),jn=a.useCallback(()=>{d&&y(!0)},[d]),Yn=a.useCallback(le=>{L($e=>$e.includes(le)?$e.filter(ut=>ut!==le):[...$e,le])},[]),un=a.useCallback(()=>{const le=window.visualViewport;return le&&le.width>0&&le.height>0?{width:le.width,height:le.height,offsetTop:le.offsetTop,offsetLeft:le.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),$t=a.useCallback(()=>{const le=Ge.current;if(!le)return;const $e=le.getBoundingClientRect(),{width:ut,height:wt,offsetTop:St,offsetLeft:ln}=un(),on=16,mn=16,pn=4,gn=ut<=768,En=Math.min(gn?wt*.6:wt*.5,360),ls=gn?Math.min(ut-on*2,360):Math.max($e.width,240),Hn=Math.min(ls,Math.max(ut-on*2,200)),Mn=$e.top-St,Tn=$e.bottom-St,Qn=$e.left-ln,bn=wt-Tn,qn=Mn,fs=Math.max(bn-mn-pn,160),Xn=Math.max(qn-mn-pn,160),gs=bn<En&&qn>bn,$n=Math.max(Math.min(gs?Xn:fs,En),160),se=Math.min(Math.max(Qn,on),ut-on-Hn)+ln,it=gs?Math.max(mn+St,Mn-$n-pn+St):Math.min(Tn+pn+St,wt+St-mn-$n);Ie({top:it,left:se,width:Hn,maxHeight:$n})},[un]),wn=a.useCallback(()=>{const le=_t.current?.querySelector(".refine-button");if(!le)return;const $e=le.getBoundingClientRect(),{width:ut,height:wt,offsetTop:St,offsetLeft:ln}=un(),on=8,mn=12,pn=4,gn=Math.min(200,Math.max(wt-mn*2,160)),En=Math.min(200,ut-on*2),ls=$e.top-St,Hn=$e.bottom-St,Mn=$e.left-ln,Tn=wt-Hn,Qn=ls,bn=Tn<gn&&Qn>Tn,qn=Math.min(Math.max(Mn,on),ut-on-En)+ln,fs=bn?Math.max(mn+St,ls-gn-pn+St):Math.min(Hn+pn+St,wt+St-mn-gn);Fe({top:fs,left:qn})},[un]),On=a.useCallback(()=>{const le=pe.current;if(!le)return;const $e=le.getBoundingClientRect(),{width:ut,height:wt,offsetTop:St,offsetLeft:ln}=un(),on=16,mn=16,pn=4,gn=ut<=768,En=Math.min(gn?wt*.6:wt*.5,320),ls=gn?Math.min(ut-on*2,360):Math.max($e.width,280),Hn=Math.min(ls,Math.max(ut-on*2,240)),Mn=$e.top-St,Tn=$e.bottom-St,Qn=$e.left-ln,bn=wt-Tn,qn=Mn,fs=Math.max(bn-mn-pn,200),Xn=Math.max(qn-mn-pn,200),gs=bn<En&&qn>bn,$n=Math.max(Math.min(gs?Xn:fs,En),200),se=Math.min(Math.max(Qn,on),ut-on-Hn)+ln,it=gs?Math.max(mn+St,Mn-$n-pn+St):Math.min(Tn+pn+St,wt+St-mn-$n);ht({top:it,left:se,width:Hn,maxHeight:$n})},[un]),Nn=a.useCallback(()=>{const le=Xe.current?.querySelector("button");if(!le)return;const $e=le.getBoundingClientRect(),{width:ut,height:wt,offsetTop:St,offsetLeft:ln}=un(),on=16,mn=16,pn=4,gn=ut<=768,En=Math.min(gn?wt*.6:wt*.5,320),ls=gn?Math.min(ut-on*2,280):Math.max($e.width,240),Hn=Math.min(ls,Math.max(ut-on*2,200)),Mn=$e.top-St,Tn=$e.bottom-St,Qn=$e.left-ln,bn=wt-Tn,qn=Mn,fs=Math.max(bn-mn-pn,160),Xn=Math.max(qn-mn-pn,160),gs=bn<En&&qn>bn,$n=Math.max(Math.min(gs?Xn:fs,En),160),se=Math.min(Math.max(Qn,on),ut-on-Hn)+ln,it=gs?Math.max(mn+St,Mn-$n-pn+St):Math.min(Tn+pn+St,wt+St-mn-$n);ye({top:it,left:se,width:Hn,maxHeight:$n})},[un]);a.useEffect(()=>{if(!J)return;const le=()=>$t();window.addEventListener("resize",le),window.addEventListener("scroll",le,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",le),$e.addEventListener("scroll",le)),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0),$e&&($e.removeEventListener("resize",le),$e.removeEventListener("scroll",le))}},[J,$t]),a.useEffect(()=>{if(!Et)return;const le=()=>wn();window.addEventListener("resize",le),window.addEventListener("scroll",le,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",le),$e.addEventListener("scroll",le)),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0),$e&&($e.removeEventListener("resize",le),$e.removeEventListener("scroll",le))}},[Et,wn]),a.useEffect(()=>{if(!ee)return;const le=()=>On();window.addEventListener("resize",le),window.addEventListener("scroll",le,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",le),$e.addEventListener("scroll",le)),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0),$e&&($e.removeEventListener("resize",le),$e.removeEventListener("scroll",le))}},[ee,On]),a.useEffect(()=>{if(!C)return;const le=()=>Nn();window.addEventListener("resize",le),window.addEventListener("scroll",le,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",le),$e.addEventListener("scroll",le)),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0),$e&&($e.removeEventListener("resize",le),$e.removeEventListener("scroll",le))}},[C,Nn]);const Bn=a.useCallback(le=>{const $e=xl(le);Be($e.provider),Ce($e.modelId)},[]),rs=a.useCallback(le=>{const $e=xl(le);me($e.provider),ve($e.modelId)},[]),Vt=a.useCallback(le=>{const $e=xl(le);_e($e.provider),Oe($e.modelId)},[]),_n=a.useCallback(async le=>{if(u){u(le);return}const $e=Ee,wt=$e.includes(le)?$e.filter(St=>St!==le):[le,...$e];He(wt);try{await Wt({favoriteProviders:wt,favoriteModels:ce})}catch{He($e)}},[Ee,ce,u]),x=a.useCallback(async le=>{if(h){h(le);return}const $e=ce,wt=$e.includes(le)?$e.filter(St=>St!==le):[le,...$e];qe(wt);try{await Wt({favoriteProviders:Ee,favoriteModels:wt})}catch{qe($e)}},[ce,Ee,h]),F=a.useCallback(()=>{const le=g.trim();if(!le){n("Enter a description first","error");return}r?.(le),Ot()},[g,r,n,Ot]),ne=a.useCallback(()=>{const le=g.trim();if(!le){n("Enter a description first","error");return}l?.(le),Ot()},[g,l,n,Ot]),ae=a.useCallback(()=>{nn()},[nn]),oe=a.useCallback(async le=>{const $e=g.trim();if(!(!$e||It)){Pt(!1),bt(!0);try{const ut=await uh($e,le,o);p(ut),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(ut){const wt=mh(ut);n(wt,"error")}finally{bt(!1)}}},[g,It,n,o]),ge=(le,$e)=>le.length>$e?le.slice(0,$e)+"…":le,et=a.useCallback(async()=>{if(i){st(i),Ze(null),ke(!1);return}ke(!0),Ze(null);try{const le=await Kn();st(le.models),m||He(le.favoriteProviders),c||qe(le.favoriteModels)}catch(le){Ze(fe(le)||"Failed to load models")}finally{ke(!1)}},[i,m,c]),jt=a.useCallback(async()=>{if(G.length>0&&O===o){V(!0),Nn();return}B(!0);try{const le=await aa(void 0,o);P(le),X(o),V(!0),Nn()}catch(le){const $e=fe(le);n($e?`Failed to load agents: ${$e}`:"Failed to load agents","error"),V(!1)}finally{B(!1)}},[G.length,O,o,n,Nn]),Je=(Y?G.find(le=>le.id===Y):void 0)?.name??Y,ot=k,Un=a.useCallback(()=>{A(le=>{const $e=!le;return y($e),$e})},[]);return e.jsxs("div",{className:`quick-entry-box ${k?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[e.jsx("div",{className:"description-with-refine",children:e.jsxs("div",{className:"quick-entry-main-row",children:[e.jsx("div",{className:"quick-entry-textarea-wrap",children:e.jsx("textarea",{ref:j,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:le=>p(le.target.value),onKeyDown:Cn,onPaste:tn,onFocus:jn,onBlur:kn,disabled:f||U,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":k})}),e.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Un,"aria-expanded":k,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:k?"Collapse":"Expand",children:k?e.jsx(Fs,{size:14}):e.jsx(Lt,{size:14})})]})}),e.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ot,"aria-hidden":!ot,children:[ot&&!f&&e.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:F,onMouseDown:le=>le.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[e.jsx(zs,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ne,onMouseDown:le=>le.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[e.jsx(Wr,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),e.jsxs("div",{className:"refine-trigger-wrap",ref:_t,children:[e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${It?"refine-button--loading":""}`,onClick:()=>{Pt(le=>{const $e=!le;return $e?wn():Fe(null),$e})},disabled:!g.trim()||It,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(Ln,{size:12,style:{verticalAlign:"middle"}}),It?"Refining...":"Refine"]}),Et&&ue&&ft&&Na.createPortal(e.jsxs("div",{ref:Ve,className:"refine-menu refine-menu--portal",onMouseDown:le=>le.preventDefault(),style:{position:"fixed",top:`${ft.top}px`,left:`${ft.left}px`},children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>oe("clarify"),"data-testid":"refine-clarify",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),e.jsxs("div",{className:"refine-menu-item",onClick:()=>oe("add-details"),"data-testid":"refine-add-details",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),e.jsxs("div",{className:"refine-menu-item",onClick:()=>oe("expand"),"data-testid":"refine-expand",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),e.jsxs("div",{className:"refine-menu-item",onClick:()=>oe("simplify"),"data-testid":"refine-simplify",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),ue)]}),e.jsx("div",{className:"dep-trigger-wrap",children:e.jsxs("button",{ref:pe,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(le=>{const $e=!le;return $e?(D(!1),Ie(null),q(null),V(!1),On()):ht(null),$e})},children:[e.jsx(Vi,{size:12,style:{verticalAlign:"middle"}}),I.length>0?`${I.length} deps`:"Deps"]})}),ee&&ue&&dt&&(()=>{const le=T.toLowerCase(),$e=(le?s.filter(ut=>ut.id.toLowerCase().includes(le)||ut.title&&ut.title.toLowerCase().includes(le)||ut.description&&ut.description.toLowerCase().includes(le)):[...s]).sort((ut,wt)=>{const St=wt.createdAt.localeCompare(ut.createdAt);if(St!==0)return St;const ln=parseInt(ut.id.slice(ut.id.lastIndexOf("-")+1),10)||0;return(parseInt(wt.id.slice(wt.id.lastIndexOf("-")+1),10)||0)-ln});return Na.createPortal(e.jsxs("div",{ref:Ue,className:"dep-dropdown dep-dropdown--portal",onMouseDown:ut=>ut.preventDefault(),style:{position:"fixed",top:`${dt.top}px`,left:`${dt.left}px`,width:`${dt.width}px`,maxHeight:dt.maxHeight?`${dt.maxHeight}px`:void 0,overflowY:dt.maxHeight?"auto":void 0},children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:T,onChange:ut=>S(ut.target.value),onClick:ut=>ut.stopPropagation()}),$e.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):$e.map(ut=>e.jsxs("div",{className:`dep-dropdown-item${I.includes(ut.id)?" selected":""}`,onMouseDown:wt=>wt.preventDefault(),onClick:()=>Yn(ut.id),children:[e.jsx("span",{className:"dep-dropdown-id",children:ut.id}),e.jsx("span",{className:"dep-dropdown-title",children:ge(ut.title||ut.description||ut.id,60)})]},ut.id))]}),ue)})(),e.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>_.current?.click(),children:[e.jsx(yb,{size:12,style:{verticalAlign:"middle"}}),w.length>0?`Attach (${w.length})`:"Attach"]}),e.jsxs("button",{ref:Ge,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),V(!1),q(null),D(!0),$t()},children:[e.jsx(Cr,{size:12,style:{verticalAlign:"middle"}}),fn]}),e.jsx("div",{className:"agent-trigger-wrap",ref:Xe,children:e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{C?(V(!1),ye(null)):jt()},"data-testid":"quick-entry-agent-button",children:[e.jsx(sn,{size:12,style:{verticalAlign:"middle"}}),Je?` ${Je}`:" Agent"]})}),C&&ue&&Z&&Na.createPortal(e.jsxs("div",{ref:re,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:le=>le.preventDefault(),style:{position:"fixed",top:`${Z.top}px`,left:`${Z.left}px`,width:`${Z.width}px`,maxHeight:Z.maxHeight?`${Z.maxHeight}px`:void 0,overflowY:Z.maxHeight?"auto":void 0},children:[e.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),de&&e.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!de&&G.filter(le=>le.state!=="terminated").map(le=>e.jsxs("div",{className:`dep-dropdown-item${Y===le.id?" selected":""}`,onMouseDown:$e=>$e.preventDefault(),onClick:()=>{K(le.id===Y?null:le.id),V(!1),ye(null)},children:[e.jsx(sn,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:le.role}),e.jsx("span",{className:"dep-dropdown-title",children:le.name})]},le.id)),!de&&G.filter(le=>le.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Y&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:le=>le.preventDefault(),onClick:()=>{K(null),V(!1),ye(null)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),ue),e.jsx("button",{type:"button",className:`btn btn-sm ${yt?"btn-primary":""}`,onClick:()=>Ct(le=>!le),onMouseDown:le=>le.preventDefault(),"aria-pressed":yt,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),e.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:ae,onMouseDown:le=>le.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[e.jsx(Zm,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),w.length>0&&e.jsx("div",{className:"inline-create-previews",children:w.map((le,$e)=>e.jsxs("div",{className:"inline-create-preview",children:[e.jsx("img",{src:le.previewUrl,alt:le.file.name}),e.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>dn($e),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${$e}`,children:"×"})]},le.previewUrl))}),J&&ue&&ie&&Na.createPortal(e.jsx("div",{ref:Te,className:"model-nested-menu model-nested-menu--portal",onMouseDown:le=>le.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ie.top}px`,left:`${ie.left}px`,width:`${ie.width}px`,maxHeight:ie.maxHeight?`${ie.maxHeight}px`:void 0,overflowY:ie.maxHeight?"auto":void 0},children:he===null?e.jsxs("div",{className:"model-menu-items",children:[e.jsxs("button",{type:"button",className:`model-menu-item ${pt?"model-menu-item--active":""}`,onClick:()=>q("plan"),"data-testid":"model-menu-plan",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(zs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),e.jsx("span",{className:"model-menu-item-value",children:pt?hn(ze,Ae):"Using default"}),e.jsx(rn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${je?"model-menu-item--active":""}`,onClick:()=>q("executor"),"data-testid":"model-menu-executor",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Ln,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),e.jsx("span",{className:"model-menu-item-value",children:je?hn(W,Re):"Using default"}),e.jsx(rn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${Ke?"model-menu-item--active":""}`,onClick:()=>q("validator"),"data-testid":"model-menu-validator",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Cr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Validator"]}),e.jsx("span",{className:"model-menu-item-value",children:Ke?hn(Me,De):"Using default"}),e.jsx(rn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):e.jsxs("div",{className:"model-submenu",children:[e.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>q(null),"data-testid":"model-submenu-back",children:[e.jsx(Lt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),e.jsxs("div",{className:"model-submenu-header",children:[he==="plan"&&"Plan Model",he==="executor"&&"Executor Model",he==="validator"&&"Validator Model"]}),e.jsx(Kt,{models:xe,value:he==="plan"?xt:he==="executor"?we:rt,onChange:he==="plan"?Bn:he==="executor"?rs:Vt,placeholder:"Using default",disabled:te,id:`model-${he}-select`,label:`${he} model`,favoriteProviders:lt,onToggleFavorite:_n,favoriteModels:be,onToggleModelFavorite:x}),Ne&&e.jsxs("div",{className:"model-submenu-error",children:[e.jsx("span",{children:Ne}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:et,children:"Retry"})]})]})}),ue)]}),e.jsx("input",{ref:_,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:le=>{yn(le.target.files),le.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),e.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function uw(t){const n=t.replace(/\/+$/,"").split("/");return n[n.length-1]||t}function mw(t){const n=new Map(t.map(o=>[o.id,o])),s=[],i=new Set,r=new Set;function l(o){if(i.has(o)||r.has(o))return;r.add(o);const d=n.get(o);if(d)for(const m of d.dependencies||[])n.has(m)&&l(m);r.delete(o),i.add(o),s.push(o)}for(const o of t)l(o.id);return s}function hw(t,n,s){const i=t.filter(f=>f.worktree),r=t.filter(f=>!f.worktree),l=new Map;for(const f of i){const b=f.worktree,v=l.get(b)||[];v.push(f),l.set(b,v)}const o=new Map(n.map(f=>[f.id,f])),m=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(b=>{const v=o.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),u=mw(m).map(f=>o.get(f)).filter(f=>f!==void 0&&m.includes(f)),h=[],g=Array.from(l.keys());for(const f of g)h.push({label:uw(f),activeTasks:l.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=u.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Ed=100,vl=50,Md=25;function pw({column:t,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onOpenDetail:l,addToast:o,onQuickCreate:d,onNewTask:m,autoMerge:c,onToggleAutoMerge:u,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onArchiveAllDone:v,collapsed:y,onToggleCollapse:k,allTasks:A,availableModels:j,onPlanningMode:_,onSubtaskBreakdown:N,onOpenDetailWithTab:M,favoriteProviders:w,favoriteModels:R,onToggleFavorite:E,onToggleModelFavorite:I,isSearchActive:L,taskStuckTimeoutMs:ee,onOpenMission:$,lastFetchTimeMs:T,workflowStepNameLookup:S}){const[Y,K]=a.useState(!1),[G,P]=a.useState(vl),[O,X]=a.useState(!1),[C,V]=a.useState(!1),de=a.useRef(null),B=xj(n.length);a.useEffect(()=>{if(!O)return;function ze(Ae){de.current?.contains(Ae.target)||X(!1)}function Be(Ae){Ae.key==="Escape"&&X(!1)}return document.addEventListener("mousedown",ze),document.addEventListener("keydown",Be),()=>{document.removeEventListener("mousedown",ze),document.removeEventListener("keydown",Be)}},[O]);const J=t==="archived",D=J&&y,he=!J&&!L&&t!=="in-progress"&&n.length>Ed;a.useEffect(()=>{P(ze=>t==="in-progress"||J||n.length<=Ed?vl:Math.min(Math.max(ze,vl),n.length))},[t,J,n.length]);const q=a.useCallback(ze=>{J||(ze.preventDefault(),ze.dataTransfer.dropEffect="move",K(!0))},[J]),W=a.useCallback(ze=>{ze.currentTarget.contains(ze.relatedTarget)||K(!1)},[]),me=a.useCallback(async ze=>{ze.preventDefault(),K(!1);const Be=ze.dataTransfer.getData("text/plain");if(!Be)return;const Ae=n.find(Ce=>Ce.id===Be);if(!(Ae&&Ae.column===t))try{await r(Be,t)}catch(Ce){o(fe(Ce),"error")}},[t,r,o,n]),Re=a.useMemo(()=>t!=="in-progress"?[]:hw(n,n,i),[t,n,i]),ve=a.useMemo(()=>he?n.slice(0,G):n,[he,n,G]),Me=Math.max(0,n.length-ve.length),_e=a.useCallback(()=>{P(ze=>Math.min(ze+Md,n.length))},[n.length]),De=a.useCallback(async()=>{if(X(!1),!(n.length===0||!window.confirm(`Move all ${n.length} todo task${n.length===1?"":"s"} back to triage to be respecified?`))){V(!0);try{const Be=await Promise.allSettled(n.map(Ge=>r(Ge.id,"triage"))),Ae=Be.filter(Ge=>Ge.status==="rejected").length,Ce=Be.length-Ae;Ae===0?o(`Moved ${Ce} task${Ce===1?"":"s"} to triage for respec`,"success"):o(`Moved ${Ce} of ${Be.length} tasks; ${Ae} failed`,"error")}finally{V(!1)}}},[n,r,o]),Oe=a.useCallback(async()=>{if(!(!v||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const Be=await v();o(`Archived ${Be.length} tasks`,"success")}catch(Be){o(fe(Be)||"Failed to archive tasks","error")}},[v,n.length,o]);return e.jsxs("div",{className:`column${Y?" drag-over":""}${J?" column-archived":""}${D?" column-collapsed":""}`,"data-column":t,onDragOver:q,onDragLeave:W,onDrop:me,children:[e.jsxs("div",{className:"column-header",children:[e.jsx("div",{className:`column-dot dot-${t}`}),e.jsx("h2",{children:us[t]}),e.jsx("span",{className:`column-count${B?" count-flash":""}`,children:n.length}),t==="in-review"&&u&&e.jsxs("label",{className:"auto-merge-toggle",title:c?"Auto-merge enabled":"Auto-merge disabled",children:[e.jsx("input",{type:"checkbox",checked:!!c,onChange:u}),e.jsx("span",{className:"toggle-slider"}),e.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),m&&e.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}),t==="done"&&v&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:Oe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:e.jsx(qr,{size:16})}),J&&k&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:k,title:y?"Expand archived tasks":"Collapse archived tasks","aria-label":y?"Expand archived tasks":"Collapse archived tasks",children:y?e.jsx(Lt,{size:16}):e.jsx(Fs,{size:16})}),t==="todo"&&e.jsxs("div",{className:"column-menu",ref:de,children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>X(ze=>!ze),"aria-haspopup":"menu","aria-expanded":O,"aria-label":"Todo column actions",title:"Column actions",disabled:C,children:e.jsx(fg,{size:16})}),O&&e.jsx("div",{className:"column-menu-popover",role:"menu",children:e.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void De(),disabled:n.length===0||C,children:["Respecify All",e.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Triage"]})]})})]})]}),!D&&e.jsx("p",{className:"column-desc",children:gj[t]}),!D&&e.jsxs("div",{className:"column-body",children:[t==="triage"&&d&&e.jsx(Mh,{onCreate:d,addToast:o,tasks:A??[],availableModels:j,onPlanningMode:_,onSubtaskBreakdown:N,projectId:s,autoExpand:!1,favoriteProviders:w,favoriteModels:R,onToggleFavorite:E,onToggleModelFavorite:I}),t==="in-progress"?Re.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):Re.map(ze=>e.jsx(Eh,{label:ze.label,activeTasks:ze.activeTasks,queuedTasks:ze.queuedTasks,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onOpenDetailWithTab:M,taskStuckTimeoutMs:ee,onOpenMission:$,lastFetchTimeMs:T,workflowStepNameLookup:S},ze.label)):n.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):e.jsxs(e.Fragment,{children:[ve.map(ze=>e.jsx($r,{task:ze,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onOpenDetailWithTab:M,taskStuckTimeoutMs:ee,onOpenMission:$,onMoveTask:r,lastFetchTimeMs:T,workflowStepNameLookup:S},ze.id)),he&&Me>0&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:_e,children:["Load ",Math.min(Md,Me)," more (",Me," remaining)"]})]}),e.jsx(Ja,{slotId:"board-column-footer",projectId:s})]})]})}const Ah=a.memo(pw);Ah.displayName="Column";function fw(t){return[...t].sort((n,s)=>n.columnMovedAt&&s.columnMovedAt?s.columnMovedAt.localeCompare(n.columnMovedAt):n.columnMovedAt&&!s.columnMovedAt?-1:!n.columnMovedAt&&s.columnMovedAt?1:n.createdAt.localeCompare(s.createdAt))}function gw(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}const Ad=new Map;function bw(t,n){if(t.size!==n.size)return!1;for(const[s,i]of t)if(n.get(s)!==i)return!1;return!0}function xw({tasks:t,projectId:n,maxConcurrent:s,onMoveTask:i,onOpenDetail:r,addToast:l,onQuickCreate:o,onNewTask:d,autoMerge:m,onToggleAutoMerge:c,globalPaused:u,onUpdateTask:h,onArchiveTask:g,onUnarchiveTask:p,onDeleteTask:f,onArchiveAllDone:b,onLoadArchivedTasks:v,searchQuery:y="",availableModels:k,onPlanningMode:A,onSubtaskBreakdown:j,onOpenDetailWithTab:_,favoriteProviders:N,favoriteModels:M,onToggleFavorite:w,onToggleModelFavorite:R,taskStuckTimeoutMs:E,onOpenMission:I,lastFetchTimeMs:L}){const[ee,$]=a.useState(!0),T=a.useRef(!1),{fetchBatch:S}=Cj(n),Y=a.useRef(null),[K,G]=a.useState(Ad),P=y.trim()!=="",O=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),X=a.useCallback(()=>{$(de=>{const B=!de;return!B&&!T.current&&v&&(T.current=!0,v()),B})},[v]),C=a.useMemo(()=>{const de=Object.fromEntries(xi.map(D=>[D,[]]));for(const D of t)de[D.column].push(D);const B=O.current,J={};for(const D of xi){const he=fw(de[D]);J[D]=gw(B[D],he)?B[D]:he}return O.current=J,J},[t]);a.useEffect(()=>{let de=!1;return Yr(n).then(B=>{if(de)return;const J=new Map(B.map(D=>[D.id,D.name]));G(D=>bw(D,J)?D:J)}).catch(()=>{de||G(B=>B.size===0?B:Ad)}),()=>{de=!0}},[n]);const V=a.useMemo(()=>t.filter(de=>de.prInfo||de.issueInfo).map(de=>de.id),[t]);return a.useEffect(()=>{if(V.length!==0)return Y.current&&clearTimeout(Y.current),Y.current=setTimeout(()=>{const de=[];for(let B=0;B<V.length;B+=50)de.push(V.slice(B,B+50));de.forEach(B=>{S(B)})},500),()=>{Y.current&&clearTimeout(Y.current)}},[V,S]),e.jsx(e.Fragment,{children:e.jsx("main",{className:"board",id:"board",children:xi.map(de=>e.jsx(Ah,{column:de,tasks:C[de],projectId:n,maxConcurrent:s,onMoveTask:i,onOpenDetail:r,addToast:l,globalPaused:u,onUpdateTask:h,onArchiveTask:g,onUnarchiveTask:p,onDeleteTask:f,allTasks:t,availableModels:k,onOpenDetailWithTab:_,favoriteProviders:N,favoriteModels:M,onToggleFavorite:w,onToggleModelFavorite:R,isSearchActive:P,taskStuckTimeoutMs:E,onOpenMission:I,lastFetchTimeMs:L,workflowStepNameLookup:K,...de==="triage"?{onQuickCreate:o,onNewTask:d,onPlanningMode:A,onSubtaskBreakdown:j}:{},...de==="in-review"?{autoMerge:m,onToggleAutoMerge:c}:{},...de==="done"?{onArchiveAllDone:b}:{},...de==="archived"?{collapsed:ee,onToggleCollapse:X}:{}},de))})})}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)"},Pd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),No=["id","title","status","column","dependencies","progress"];function _d(t){try{const n=In("kb-dashboard-list-columns",t);if(n){const i=JSON.parse(n).filter(r=>No.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(No)}function Td(t){try{const n=In("kb-dashboard-hide-done",t);if(n!==null)return n==="true"}catch{}return!1}function Rd(t){try{const n=In("kb-dashboard-list-collapsed",t);if(n){const i=JSON.parse(n).filter(r=>xi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Id(t){try{const n=In("kb-dashboard-selected-tasks",t);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function vw(t){return t.status==="executing"||t.column==="in-progress"}function $d(t){const n=Ch(t);return n.total===0||!vw(t)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function yw({tasks:t,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:l,onQuickCreate:o,availableModels:d,favoriteProviders:m=[],favoriteModels:c=[],onToggleFavorite:u,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:b,projectName:v,taskStuckTimeoutMs:y,searchQuery:k="",lastFetchTimeMs:A}){const[j,_]=a.useState("id"),[N,M]=a.useState("desc"),[w,R]=a.useState(null),[E,I]=a.useState(null),[L,ee]=a.useState(null),T=Xr()==="mobile",[S,Y]=a.useState(()=>_d(b)),[K,G]=a.useState(()=>Td(b)),[P,O]=a.useState(()=>Rd(b));a.useEffect(()=>{typeof window<"u"&&ms("kb-dashboard-list-columns",JSON.stringify([...S]),b)},[b,S]),a.useEffect(()=>{typeof window<"u"&&ms("kb-dashboard-hide-done",K.toString(),b)},[K,b]),a.useEffect(()=>{typeof window<"u"&&ms("kb-dashboard-list-collapsed",JSON.stringify([...P]),b)},[P,b]);const[X,C]=a.useState(!1),V=a.useRef(null),[de,B]=a.useState(()=>Id(b));a.useEffect(()=>{Y(_d(b)),G(Td(b)),O(Rd(b)),B(Id(b))},[b]),a.useEffect(()=>{typeof window<"u"&&ms("kb-dashboard-selected-tasks",JSON.stringify([...de]),b)},[b,de]);const J=a.useCallback(te=>{B(ke=>{const Ne=new Set(ke);return Ne.has(te)?Ne.delete(te):Ne.add(te),Ne})},[]),D=a.useCallback(()=>{B(new Set)},[]),he=a.useCallback(te=>{Y(ke=>{const Ne=new Set(ke);return Ne.has(te)?Ne.size>1&&Ne.delete(te):Ne.add(te),Ne})},[]);a.useEffect(()=>{if(!X)return;const te=Ne=>{V.current&&!V.current.contains(Ne.target)&&C(!1)},ke=Ne=>{Ne.key==="Escape"&&C(!1)};return document.addEventListener("mousedown",te),document.addEventListener("keydown",ke),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",ke)}},[X]);const q={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},W=a.useCallback(te=>{j===te?M(ke=>ke==="asc"?"desc":"asc"):(_(te),M("asc"))},[j]),me=a.useCallback(te=>{ee(ke=>ke===te?null:te)},[]),Re=a.useCallback(te=>{O(ke=>{const Ne=new Set(ke);return Ne.has(te)?Ne.delete(te):Ne.add(te),Ne})},[]),ve=a.useCallback(()=>{ee(null)},[]),Me=a.useMemo(()=>{let te=k?t.filter(xe=>xe.id.toLowerCase().includes(k.toLowerCase())||xe.title&&xe.title.toLowerCase().includes(k.toLowerCase())||xe.description.toLowerCase().includes(k.toLowerCase())):[...t];K&&!L&&(te=te.filter(xe=>xe.column!=="done"&&xe.column!=="archived"));const Ne=[...L?te.filter(xe=>xe.column===L):te].sort((xe,st)=>{let Ee=0;switch(j){case"id":Ee=xe.id.localeCompare(st.id);break;case"title":Ee=(xe.title||xe.description).localeCompare(st.title||st.description);break;case"status":Ee=(xe.status||"").localeCompare(st.status||"");break;case"column":Ee=xe.column.localeCompare(st.column);break}return N==="asc"?Ee:-Ee}),Ze={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Ne.forEach(xe=>Ze[xe.column].push(xe)),Ze},[t,k,j,N,K,L]),_e=a.useMemo(()=>Object.values(Me).reduce((te,ke)=>te+ke.length,0),[Me]),De=a.useMemo(()=>t.filter(te=>te.column==="done"||te.column==="archived").length,[t]),Oe=a.useMemo(()=>K?De:0,[K,De]),ze=a.useCallback(()=>{const te=Object.values(Me).flat().filter(ke=>ke.column!=="archived").map(ke=>ke.id);B(ke=>{if(te.every(Ze=>ke.has(Ze))){const Ze=new Set(ke);return te.forEach(xe=>Ze.delete(xe)),Ze}else return new Set([...ke,...te])})},[Me]),Be=a.useMemo(()=>{const te=Object.values(Me).flat().filter(ke=>ke.column!=="archived");return te.length===0?!1:te.every(ke=>de.has(ke.id))},[Me,de]),Ae=a.useMemo(()=>{const te=Object.values(Me).flat().filter(Ne=>Ne.column!=="archived");if(te.length===0)return!1;const ke=te.filter(Ne=>de.has(Ne.id)).length;return ke>0&&ke<te.length},[Me,de]),[Ce,Ge]=a.useState("__no_change__"),[Te,Xe]=a.useState("__no_change__"),[re,Z]=a.useState(!1),ye=a.useCallback(async()=>{if(de.size===0)return;const te=Array.from(de).filter(Ne=>{const Ze=t.find(xe=>xe.id===Ne);return Ze&&Ze.column!=="archived"});if(te.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ke={taskIds:te};if(Ce!=="__no_change__")if(Ce==="")ke.modelProvider=null,ke.modelId=null;else{const Ne=Ce.indexOf("/");Ne!==-1&&(ke.modelProvider=Ce.slice(0,Ne),ke.modelId=Ce.slice(Ne+1))}if(Te!=="__no_change__")if(Te==="")ke.validatorModelProvider=null,ke.validatorModelId=null;else{const Ne=Te.indexOf("/");Ne!==-1&&(ke.validatorModelProvider=Te.slice(0,Ne),ke.validatorModelId=Te.slice(Ne+1))}if(Object.keys(ke).length===1){i("No changes to apply","info");return}Z(!0);try{const Ne=await wx(ke.taskIds,ke.modelProvider,ke.modelId,ke.validatorModelProvider,ke.validatorModelId,void 0,void 0,b);f&&Ne.updated.length>0&&f(Ne.updated),i(`Updated ${Ne.count} task${Ne.count===1?"":"s"}`,"success"),D(),Ge("__no_change__"),Xe("__no_change__")}catch(Ne){i(fe(Ne)||"Failed to update models","error")}finally{Z(!1)}},[de,t,Ce,Te,b,i,D,f]),ie=a.useCallback(te=>{s(te)},[s]),Ie=a.useCallback((te,ke)=>{if(ke.paused){te.preventDefault();return}te.dataTransfer.setData("text/plain",ke.id),te.dataTransfer.effectAllowed="move",R(ke.id)},[]),pe=a.useCallback(()=>{R(null),I(null)},[]),Ue=a.useCallback((te,ke)=>{te.preventDefault(),te.dataTransfer.dropEffect="move",I(ke)},[]),dt=a.useCallback(()=>{I(null)},[]),ht=a.useCallback(async(te,ke)=>{te.preventDefault(),I(null);const Ne=te.dataTransfer.getData("text/plain");if(Ne){if(ke==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Ne,ke)}catch(Ze){i(fe(Ze),"error")}}},[n,i]),ue=te=>j!==te?e.jsx(Bm,{size:14,className:"sort-icon"}):N==="asc"?e.jsx(bi,{size:14,className:"sort-icon active"}):e.jsx(Oa,{size:14,className:"sort-icon active"});return e.jsxs("div",{className:"list-view",children:[e.jsxs("div",{className:"list-toolbar",children:[e.jsxs("div",{className:"list-column-toggle",ref:V,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>C(te=>!te),"aria-expanded":X,"aria-haspopup":"menu",children:[e.jsx(og,{size:14}),"Columns"]}),X&&e.jsx("div",{className:"list-column-dropdown",role:"menu",children:No.map(te=>{const ke=S.has(te),Ne=ke&&S.size===1;return e.jsxs("label",{className:`list-column-dropdown-item${Ne?" disabled":""}`,role:"menuitem",title:Ne?"At least one column must be visible":"",children:[e.jsx("input",{type:"checkbox",checked:ke,onChange:()=>he(te),disabled:Ne}),e.jsx("span",{children:q[te]})]},te)})})]}),e.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>G(te=>!te),"aria-pressed":K,title:K?"Show done tasks":"Hide done tasks",children:[K?e.jsx(qo,{size:14}):e.jsx(yg,{size:14}),K?"Show Done":"Hide Done"]}),e.jsxs("div",{className:"list-stats",children:[L?`${_e} of ${t.length} tasks in ${us[L]}`:`${_e} of ${t.length} tasks`,Oe>0&&!L&&e.jsxs("span",{className:"list-stats-hidden",children:[" (",Oe," hidden)"]}),L&&e.jsx("button",{className:"btn btn-sm",onClick:ve,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),de.size>0&&e.jsxs("div",{className:"list-selection-stats",children:[e.jsxs("span",{className:"selection-count",children:[de.size," selected"]}),e.jsx("button",{className:"btn btn-sm btn-link",onClick:D,children:"Clear"})]}),de.size>0&&d&&d.length>0&&e.jsxs("div",{className:"bulk-edit-toolbar",children:[e.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models:"}),e.jsx("div",{className:"bulk-edit-dropdown",children:e.jsx(Kt,{models:d,value:Ce,onChange:Ge,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:m,onToggleFavorite:u,favoriteModels:c,onToggleModelFavorite:h})}),e.jsx("div",{className:"bulk-edit-dropdown",children:e.jsx(Kt,{models:d,value:Te,onChange:Xe,label:"Validator Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:m,onToggleFavorite:u,favoriteModels:c,onToggleModelFavorite:h})}),e.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ye,disabled:re||Ce==="__no_change__"&&Te==="__no_change__",children:re?"Applying...":"Apply"})]}),l?e.jsx("button",{className:"btn btn-task-create btn-sm",onClick:l,children:"+ New Task"}):null]}),e.jsx("div",{className:"list-drop-zones",children:xi.map(te=>{const ke=t.filter(st=>st.column===te).length,Ne=te==="done"||te==="archived",Ze=K&&Ne?0:ke,xe=K&&Ne&&ke>0;return e.jsxs("div",{className:`list-drop-zone${E===te?" drag-over":""}${L===te?" active":""}`,onClick:()=>me(te),onDragOver:st=>Ue(st,te),onDragLeave:dt,onDrop:st=>ht(st,te),"data-column":te,children:[e.jsx("span",{className:"drop-zone-dot",style:{background:ua[te]}}),e.jsx("span",{className:"drop-zone-label",children:us[te]}),e.jsx("span",{className:"drop-zone-count",children:xe?`${Ze} of ${ke}`:ke})]},te)})}),e.jsxs("div",{className:"list-table-container",children:[e.jsx("div",{className:"list-quick-entry-above-table",children:e.jsx(Mh,{onCreate:o??(async()=>i("Task creation not available","error")),addToast:i,tasks:t,availableModels:d,onPlanningMode:g,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:m,favoriteModels:c,onToggleFavorite:u,onToggleModelFavorite:h})}),_e===0?e.jsx("div",{className:"list-empty",children:k?"No tasks match your filter":"No tasks yet"}):T?e.jsx("div",{className:"list-cards",children:xi.map(te=>{if(L&&te!==L||K&&(te==="done"||te==="archived")&&!L)return null;const ke=Me[te],Ne=ke.length===0;if(k&&Ne)return null;const Ze=P.has(te);return e.jsxs(a.Fragment,{children:[e.jsxs("div",{className:`list-card-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>Re(te),"aria-expanded":!Ze,role:"button",tabIndex:0,onKeyDown:xe=>{(xe.key==="Enter"||xe.key===" ")&&(xe.preventDefault(),Re(te))},children:[e.jsx(rn,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${te}`}),e.jsx("span",{className:"list-section-title",children:us[te]}),e.jsx("span",{className:"list-section-count",children:ke.length})]}),!Ze&&e.jsx(e.Fragment,{children:Ne?e.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ke.map(xe=>{const st=xe.status==="failed",Ee=xe.paused===!0,He=Ir(xe,y,A),ce=!r&&!st&&!Ee&&!He&&(xe.column==="in-progress"||Pd.has(xe.status)),qe=typeof xe.status=="string"&&xe.status.trim().length>0,We=!!(xe.dependencies&&xe.dependencies.length>0),Pe=$d(xe),nt=Pe.hasProgress,kt=de.size>0;return e.jsxs("div",{className:`list-card${ce?" agent-active":""}${kt?" list-card--selectable":""}`,onClick:()=>ie(xe),"data-id":xe.id,children:[kt&&e.jsx("label",{className:"list-card-checkbox",onClick:yt=>yt.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:de.has(xe.id),onChange:yt=>{yt.stopPropagation(),J(xe.id)},onClick:yt=>yt.stopPropagation(),disabled:xe.column==="archived","aria-label":`Select ${xe.id}`})}),e.jsxs("div",{className:"list-card-row",children:[e.jsx("span",{className:"list-card-id",children:xe.id}),e.jsx("span",{className:"list-card-spacer"}),He?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):qe?e.jsx("span",{className:`list-status-badge list-status-badge--${xe.column}${st?" failed":""}${ce?" pulsing":""}`,children:xe.status}):null]}),e.jsx("div",{className:"list-card-row",children:e.jsx("div",{className:"list-card-title",children:xe.title||xe.description})}),(We||nt)&&e.jsxs("div",{className:"list-card-row list-card-meta",children:[We&&e.jsxs("span",{className:"list-dep-badge",title:xe.dependencies.join(", "),children:[e.jsx(Vi,{size:12})," ",xe.dependencies.length]}),nt&&e.jsxs("div",{className:"list-progress",children:[e.jsx("div",{className:"list-progress-bar",children:e.jsx("div",{className:"list-progress-fill",style:{width:`${Pe.percent}%`,backgroundColor:ua[xe.column]}})}),e.jsx("span",{className:"list-progress-label",children:Pe.label})]})]})]},xe.id)})})]},te)})}):e.jsxs("table",{className:"list-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"list-header-cell list-header-checkbox",children:e.jsx("input",{type:"checkbox",checked:Be,ref:te=>{te&&(te.indeterminate=Ae)},onChange:ze,"aria-label":"Select all visible tasks"})}),S.has("id")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("id"),children:["ID ",ue("id")]}),S.has("title")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("title"),children:["Title ",ue("title")]}),S.has("status")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("status"),children:["Status ",ue("status")]}),S.has("column")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("column"),children:["Column ",ue("column")]}),S.has("dependencies")&&e.jsx("th",{className:"list-header-cell",children:"Dependencies"}),S.has("progress")&&e.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),e.jsx("tbody",{children:xi.map(te=>{if(L&&te!==L||K&&(te==="done"||te==="archived")&&!L)return null;const ke=Me[te],Ne=ke.length===0;if(k&&Ne)return null;const Ze=P.has(te);return e.jsxs(a.Fragment,{children:[e.jsx("tr",{className:`list-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>Re(te),"aria-expanded":!Ze,children:e.jsxs("th",{colSpan:S.size+1,className:"list-section-cell",children:[e.jsx(rn,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${te}`}),e.jsx("span",{className:"list-section-title",children:us[te]}),e.jsx("span",{className:"list-section-count",children:ke.length})]})}),!Ze&&e.jsx(e.Fragment,{children:Ne?e.jsx("tr",{className:"list-section-empty",children:e.jsx("td",{colSpan:S.size+1,className:"list-empty-cell",children:"No tasks"})}):ke.map(xe=>{const st=xe.status==="failed",Ee=xe.paused===!0,He=Ir(xe,y,A),ce=!r&&!st&&!Ee&&!He&&(xe.column==="in-progress"||Pd.has(xe.status)),qe=w===xe.id;return e.jsxs("tr",{className:`list-row${st?" failed":""}${Ee?" paused":""}${He?" stuck":""}${ce?" agent-active":""}${qe?" dragging":""}`,onClick:()=>ie(xe),draggable:!Ee,onDragStart:We=>Ie(We,xe),onDragEnd:pe,"data-id":xe.id,children:[e.jsx("td",{className:"list-cell list-cell-checkbox",children:e.jsx("input",{type:"checkbox",checked:de.has(xe.id),onChange:We=>{We.stopPropagation(),J(xe.id)},onClick:We=>We.stopPropagation(),disabled:xe.column==="archived","aria-label":`Select ${xe.id}`})}),S.has("id")&&e.jsx("td",{className:"list-cell list-cell-id",children:xe.id}),S.has("title")&&e.jsx("td",{className:"list-cell list-cell-title",children:xe.title||xe.description}),S.has("status")&&e.jsx("td",{className:"list-cell",children:He?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):xe.status?e.jsx("span",{className:`list-status-badge list-status-badge--${xe.column}${st?" failed":""}${ce?" pulsing":""}`,children:xe.status}):e.jsx("span",{className:"list-status-badge",children:"-"})}),S.has("column")&&e.jsx("td",{className:"list-cell",children:e.jsx("span",{className:"list-column-badge",style:{background:`${ua[xe.column]}20`,color:ua[xe.column]},children:us[xe.column]})}),S.has("dependencies")&&e.jsx("td",{className:"list-cell list-cell-deps",children:xe.dependencies&&xe.dependencies.length>0?e.jsxs("span",{className:"list-dep-badge",title:xe.dependencies.join(", "),children:[e.jsx(Vi,{size:12})," ",xe.dependencies.length]}):"-"}),S.has("progress")&&e.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const We=$d(xe);return We.hasProgress?e.jsxs("div",{className:"list-progress",children:[e.jsx("div",{className:"list-progress-bar",children:e.jsx("div",{className:"list-progress-fill",style:{width:`${We.percent}%`,backgroundColor:ua[xe.column]}})}),e.jsx("span",{className:"list-progress-label",children:We.label})]}):"-"})()})]},xe.id)})})]},te)})})]})]})]})}const kw={active:{label:"Active",color:"var(--success)",icon:an},paused:{label:"Paused",color:"var(--warning)",icon:Ds},errored:{label:"Error",color:"var(--color-error)",icon:is},initializing:{label:"Initializing",color:"var(--info)",icon:ct}};function jw(t){if(!t)return"Never";const n=new Date(t),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),l=Math.floor(i/36e5),o=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:n.toLocaleDateString()}function ww(t,n=40){if(t.length<=n)return t;const s=t.slice(0,Math.floor(n/2)-2),i=t.slice(-Math.floor(n/2)+2);return`${s}...${i}`}function Nw(t,n){if(t.project.id!==n.project.id||t.project.status!==n.project.status||t.project.name!==n.project.name||t.project.path!==n.project.path||t.project.lastActivityAt!==n.project.lastActivityAt||t.isLoading!==n.isLoading)return!1;const s=t.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=t.node,l=n.node;return!r&&!l?t.nodeNameFallback===n.nodeNameFallback:!r||!l?!1:r.id===l.id&&r.name===l.name&&r.status===l.status&&r.type===l.type}function Sw({project:t,health:n,onSelect:s,onPause:i,onResume:r,onRemove:l,node:o,nodeNameFallback:d,isLoading:m=!1}){const[c,u]=a.useState(!1),h=kw[t.status],g=h.icon,p=a.useCallback(()=>{s(t)},[s,t]),f=a.useCallback(j=>{j.stopPropagation(),i(t)},[i,t]),b=a.useCallback(j=>{j.stopPropagation(),r(t)},[r,t]),v=a.useCallback(j=>{if(j.stopPropagation(),!c){u(!0);return}l(t),u(!1)},[c,l,t]),y=t.status==="paused",k=t.status==="errored",A=t.status==="initializing";return e.jsxs("div",{className:`project-card ${m?"project-card-loading":""} ${k?"project-card-errored":""}`,onClick:p,"data-project-id":t.id,role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),p())},children:[e.jsxs("div",{className:"project-card-header",children:[e.jsx("div",{className:"project-card-icon",children:e.jsx(Pn,{size:20})}),e.jsxs("div",{className:"project-card-title-section",children:[e.jsx("h3",{className:"project-card-name",title:t.name,children:t.name}),(o||d)&&e.jsxs("span",{className:"node-badge",title:`Assigned node: ${o?.name??d}`,children:["on: ",o?.name??d]}),e.jsx("span",{className:"project-card-path",title:t.path,children:ww(t.path)})]}),e.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[e.jsx(g,{size:12,className:A?"animate-spin":""}),e.jsx("span",{children:h.label})]})]}),e.jsxs("div",{className:"project-card-health",children:[n&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"project-card-metric",children:[e.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),e.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),e.jsxs("div",{className:"project-card-metric",children:[e.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),e.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),e.jsxs("div",{className:"project-card-metric",children:[e.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),e.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&e.jsx("div",{className:"project-card-metric project-card-metric-empty",children:e.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),e.jsxs("div",{className:"project-card-footer",children:[e.jsxs("div",{className:"project-card-activity",children:[e.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),e.jsx("span",{className:"project-card-activity-time",children:jw(t.lastActivityAt||n?.lastActivityAt)})]}),e.jsxs("div",{className:"project-card-actions",children:[y?e.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:m,title:"Resume project","aria-label":"Resume project",children:[e.jsx(an,{size:14}),e.jsx("span",{children:"Resume"})]}):e.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:m||A,title:A?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[e.jsx(Ds,{size:14}),e.jsx("span",{children:"Pause"})]}),e.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:m,title:"Open project","aria-label":"Open project",children:[e.jsx(Ba,{size:14}),e.jsx("span",{children:"Open"})]}),e.jsxs("button",{className:`project-card-action project-card-action-remove ${c?"is-armed":""}`,onClick:v,disabled:m,title:c?"Confirm remove":"Remove project","aria-label":c?"Confirm remove project":"Remove project",children:[e.jsx(Ut,{size:14}),e.jsx("span",{children:c?"Confirm":""})]})]})]})]})}const Cw=a.memo(Sw,Nw);function Ew(){return e.jsxs("div",{className:"project-overview project-overview--loading",children:[e.jsx("div",{className:"project-overview__header-skeleton",children:e.jsxs("div",{className:"project-overview__stats-row",children:[e.jsxs("div",{className:"project-overview__stat-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon",children:e.jsx(Pn,{size:20,className:"project-skeleton-icon"})}),e.jsx("div",{className:"project-skeleton project-skeleton--value"}),e.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),e.jsxs("div",{className:"project-overview__stat-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon",children:e.jsx(Ns,{size:20,className:"project-skeleton-icon"})}),e.jsx("div",{className:"project-skeleton project-skeleton--value"}),e.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),e.jsxs("div",{className:"project-overview__stat-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon",children:e.jsx(en,{size:20,className:"project-skeleton-icon"})}),e.jsx("div",{className:"project-skeleton project-skeleton--value"}),e.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),e.jsxs("div",{className:"project-overview__stat-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon",children:e.jsx(is,{size:20,className:"project-skeleton-icon"})}),e.jsx("div",{className:"project-skeleton project-skeleton--value"}),e.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),e.jsxs("div",{className:"project-overview__filters-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--tab"}),e.jsx("div",{className:"project-skeleton project-skeleton--tab"}),e.jsx("div",{className:"project-skeleton project-skeleton--tab"}),e.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),e.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((t,n)=>e.jsxs("div",{className:"project-card project-card--skeleton",children:[e.jsxs("div",{className:"project-card-skeleton__header",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),e.jsxs("div",{className:"project-skeleton__text-group",children:[e.jsx("div",{className:"project-skeleton project-skeleton--title"}),e.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),e.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),e.jsxs("div",{className:"project-card-skeleton__health",children:[e.jsx("div",{className:"project-skeleton project-skeleton--metric"}),e.jsx("div",{className:"project-skeleton project-skeleton--metric"}),e.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),e.jsxs("div",{className:"project-card-skeleton__footer",children:[e.jsx("div",{className:"project-skeleton project-skeleton--activity"}),e.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const Mw=1e4,Dd=5;function Aw(t){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[l,o]=a.useState(null),d=a.useRef(null),m=a.useRef(null),c=a.useRef(!1),u=a.useCallback(async()=>{if(t.length===0){s({}),c.current||(c.current=!0),r(!1);return}m.current&&m.current.abort(),m.current=new AbortController,!c.current&&r(!0),o(null);try{const p={};for(let f=0;f<t.length;f+=Dd){const b=t.slice(f,f+Dd),v=await Promise.allSettled(b.map(async y=>{try{return await cd(y)}catch{return null}}));if(b.forEach((y,k)=>{const A=v[k];p[y]=A.status==="fulfilled"?A.value:null}),m.current?.signal.aborted)return}s(p),c.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;o(p instanceof Error?p.message:"Failed to fetch health data"),c.current=!0}finally{r(!1)}},[t]),h=a.useCallback(async g=>{try{const p=await cd(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(c.current=!1,u(),()=>{m.current&&m.current.abort()}),[u]),a.useEffect(()=>{if(t.length!==0)return d.current&&clearInterval(d.current),d.current=setInterval(()=>{u()},Mw),()=>{d.current&&(clearInterval(d.current),d.current=null)}},[u,t.length]),{healthMap:n,loading:i,error:l,refresh:u,refreshProject:h}}function Pw({projects:t,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:l,onRemoveProject:o,nodes:d=[]}){const[m,c]=a.useState("all"),[u,h]=a.useState(null),[g,p]=a.useState("activity"),[f,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const ee=localStorage.getItem("kb-dashboard-recent-projects");if(ee)try{const $=JSON.parse(ee);y($)}catch{}},[]);const[v,y]=a.useState([]),k=a.useMemo(()=>t.map(ee=>ee.id),[t]),{healthMap:A,loading:j}=Aw(k),_=a.useMemo(()=>t.map(ee=>({project:ee,health:A[ee.id]||null})),[t,A]),N=a.useMemo(()=>{let ee=[..._];return m!=="all"&&(ee=ee.filter(({project:$})=>$.status===m)),u!==null&&(ee=ee.filter(({project:$})=>$.nodeId===u)),ee},[_,m,u]),M=a.useMemo(()=>{const ee=[...N];return ee.sort(($,T)=>{let S=0;switch(g){case"name":S=$.project.name.localeCompare(T.project.name);break;case"activity":{const Y=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,K=T.project.lastActivityAt||T.health?.lastActivityAt||T.project.updatedAt;S=new Date(K).getTime()-new Date(Y).getTime();break}case"status":{const Y={errored:0,initializing:1,paused:2,active:3};S=Y[$.project.status]-Y[T.project.status];break}}return f==="asc"?S:-S}),ee},[N,g,f]),w=a.useMemo(()=>{const ee=t.length,$=t.filter(O=>O.status==="active").length,T=t.filter(O=>O.status==="errored").length,S=new Set;t.forEach(O=>{O.nodeId&&S.add(O.nodeId)});const Y=S.size||(ee>0?1:0);let K=0,G=0,P=0;return Object.values(A).forEach(O=>{O&&(K+=O.activeTaskCount,G+=O.totalTasksCompleted,P+=O.inFlightAgentCount)}),{totalProjects:ee,activeProjects:$,erroredProjects:T,totalNodes:Y,totalActiveTasks:K,totalCompletedTasks:G,totalInFlightAgents:P}},[t,A]),R=a.useMemo(()=>({all:t.length,active:t.filter(ee=>ee.status==="active").length,paused:t.filter(ee=>ee.status==="paused").length,errored:t.filter(ee=>ee.status==="errored").length}),[t]),E=a.useMemo(()=>{const ee=new Map;return t.forEach($=>{const T=$.nodeId,S=ee.get(T);if(S)S.count++;else{const K=d.find(G=>G.id===T)?.name??$._sourceNodeName??"Local";ee.set(T,{name:K,count:1})}}),Array.from(ee.entries()).map(([$,{name:T,count:S}])=>({nodeId:$??null,name:T,count:S}))},[t,d]),I=a.useCallback(ee=>{const $=[ee.id,...v.filter(T=>T!==ee.id)].slice(0,3);y($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(ee)},[s,v]);return n||j&&t.length>0&&Object.keys(A).length===0?e.jsx(Ew,{}):t.length===0?e.jsx("div",{className:"project-overview project-overview--empty",children:e.jsxs("div",{className:"project-empty-state",children:[e.jsx("div",{className:"project-empty-state__icon",children:e.jsx(Sa,{size:48})}),e.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),e.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."}),e.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:i,children:[e.jsx(qt,{size:16}),"Add Your First Project"]})]})}):e.jsxs("div",{className:"project-overview",children:[e.jsxs("div",{className:"project-overview__header",children:[e.jsxs("h2",{className:"project-overview__title",children:[e.jsx(ji,{size:20}),"Projects"]}),e.jsxs("div",{className:"project-overview__stats",children:[e.jsxs("div",{className:"project-stat",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(Pn,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:w.totalProjects}),e.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),e.jsxs("div",{className:"project-stat project-stat--active",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(Ns,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:w.totalActiveTasks}),e.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),e.jsxs("div",{className:"project-stat project-stat--completed",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(en,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:w.totalCompletedTasks}),e.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),w.erroredProjects>0&&e.jsxs("div",{className:"project-stat project-stat--error",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(is,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:w.erroredProjects}),e.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),w.totalNodes>1&&e.jsxs("div",{className:"project-stat project-stat--nodes",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(Mr,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:w.totalNodes}),e.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),e.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[e.jsx(qt,{size:16}),"Add Project"]})]}),e.jsxs("div",{className:"project-overview__filters",children:[e.jsxs("div",{className:"project-filter-tabs",children:[e.jsxs("button",{className:`project-filter-tab ${m==="all"?"active":""}`,onClick:()=>c("all"),children:["All",e.jsx("span",{className:"project-filter-count",children:R.all})]}),e.jsxs("button",{className:`project-filter-tab ${m==="active"?"active":""}`,onClick:()=>c("active"),children:["Active",e.jsx("span",{className:"project-filter-count",children:R.active})]}),e.jsxs("button",{className:`project-filter-tab ${m==="paused"?"active":""}`,onClick:()=>c("paused"),children:["Paused",e.jsx("span",{className:"project-filter-count",children:R.paused})]}),e.jsxs("button",{className:`project-filter-tab ${m==="errored"?"active":""} ${R.errored>0?"has-errors":""}`,onClick:()=>c("errored"),children:["Errored",e.jsx("span",{className:"project-filter-count",children:R.errored})]})]}),E.length>1&&e.jsxs("div",{className:"project-node-filter",children:[e.jsx(Mr,{size:14}),e.jsxs("select",{value:u??"",onChange:ee=>{h(ee.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[e.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:ee,name:$,count:T})=>e.jsxs("option",{value:ee??"",children:[$," (",T,")"]},ee??"local"))]})]}),e.jsxs("div",{className:"project-sort",children:[e.jsx(Er,{size:14}),e.jsxs("select",{value:`${g}-${f}`,onChange:ee=>{const[$,T]=ee.target.value.split("-");p($),b(T)},className:"project-sort-select","aria-label":"Sort projects",children:[e.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),e.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),e.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),e.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),e.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),e.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),e.jsx(Bm,{size:14})]})]}),e.jsx("div",{className:"project-grid",children:M.map(({project:ee,health:$})=>{const T=d.find(Y=>Y.id===ee.nodeId),S=T?void 0:ee._sourceNodeName;return e.jsx(Cw,{project:ee,health:$,node:T,nodeNameFallback:S,onSelect:I,onPause:r,onResume:l,onRemove:o},ee.id)})}),M.length===0&&e.jsxs("div",{className:"project-overview__no-results",children:[e.jsx(Er,{size:32}),e.jsx("p",{children:"No projects match the current filter"}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>c("all"),children:"Show All Projects"})]})]})}const _w=45e3,Tw=3e3,Rw=2e3,Iw=1500,Fd="fusion:sse-client-id";let Ti=null;const ti=new Map;function Ld(){const t=typeof globalThis<"u"?globalThis.crypto:void 0;return t&&typeof t.randomUUID=="function"?t.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Ph(){if(!(typeof window>"u")){if(Ti)return Ti;try{const t=window.sessionStorage.getItem(Fd);if(t)return Ti=t,t;const n=Ld();return window.sessionStorage.setItem(Fd,n),Ti=n,n}catch{return Ti=Ld(),Ti}}}function _h(t){if(!(typeof window>"u"))try{return{parsed:new URL(t,window.location.origin),preserveRelativePath:t.startsWith("/")}}catch{return}}function Th(t){return t.origin===window.location.origin&&t.pathname==="/api/events"}function $w(t){const n=Ph();if(!n)return t;const s=_h(t);return!s||!Th(s.parsed)?t:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Qo(t,n){const s=Ph();if(!s)return;const i=_h(t);if(!i||!Th(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const l=i.parsed.searchParams.get("projectId");return l&&r.searchParams.set("projectId",l),Ps(`${r.pathname}${r.search}${r.hash}`)}function Dw(t){if(typeof window>"u")return;const n=Qo(t.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 Zr(t){t.keepaliveTimer&&(clearInterval(t.keepaliveTimer),t.keepaliveTimer=null)}function zd(t){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Qo(t.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),Iw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function Fw(t){Zr(t),Qo(t.url,"keepalive")&&(zd(t),t.keepaliveTimer=window.setInterval(()=>{zd(t)},Rw))}if(typeof window<"u"){const t=()=>{for(const s of Array.from(ti.values()))if(!s.closed){if(Zr(s),Dw(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(ti.values()))i.subscribers.size!==0&&(i.closed=!1,Xo(i))};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t),window.addEventListener("pageshow",n)}function Ea(t){t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),t.heartbeatTimer=setTimeout(()=>{Rh(t)},_w)}function Rh(t){if(t.heartbeatTimer&&(clearTimeout(t.heartbeatTimer),t.heartbeatTimer=null),t.es&&(t.es.close(),t.es=null),Zr(t),t.nativeListeners.clear(),t.closed||t.subscribers.size===0||t.reconnectTimer)return;const n=ti.get(t.url);if(!(!n||n!==t)){for(const s of t.subscribers)s.onReconnect?.();t.reconnectTimer=setTimeout(()=>{if(t.reconnectTimer=null,t.closed)return;const s=ti.get(t.url);s&&s===t&&t.subscribers.size>0&&Xo(t)},Tw)}}function Xo(t){if(t.es||t.closed)return;t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=null);const n=new EventSource(Ps($w(t.url)));t.es=n,Fw(t),n.addEventListener("open",()=>{Ea(t);const s=t.hasOpenedOnce;t.hasOpenedOnce=!0;for(const i of t.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of t.subscribers)i.onError?.(s);Rh(t)}),n.addEventListener("message",()=>Ea(t)),n.addEventListener("heartbeat",()=>Ea(t)),Ih(t),Ea(t)}function Ih(t){if(!t.es)return;const n=new Set;for(const s of t.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(t.nativeListeners.has(s))continue;const i=r=>{Ea(t);const l=r;for(const o of t.subscribers){const d=o.events.get(s);if(d)for(const m of d)m(l)}};t.nativeListeners.set(s,i),t.es.addEventListener(s,i)}}function Lw(t){t.closed=!0,t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),Zr(t),t.reconnectTimer&&clearTimeout(t.reconnectTimer),t.es&&t.es.close(),t.es=null,t.nativeListeners.clear(),ti.delete(t.url)}function Bs(t,n={}){let s=ti.get(t);s||(s={url:t,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ti.set(t,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,o]of Object.entries(n.events)){let d=i.events.get(l);d||(d=new Set,i.events.set(l,d)),d.add(o)}s.subscribers.add(i),Xo(s),Ih(s);let r=!0;return()=>{if(!r)return;r=!1;const l=ti.get(t);l&&(l.subscribers.delete(i),l.subscribers.size===0&&Lw(l))}}const Zo="kb-planning-last-description",ec="kb-subtask-last-description",tc="kb-mission-last-goal";function zw(t,n){ms(Zo,t,n)}function Ow(t){return In(Zo,t)||""}function Ri(t){Fa(Zo,t)}function Bw(t,n){ms(ec,t,n)}function Uw(t){return In(ec,t)||""}function yl(t){Fa(ec,t)}function Hw(t,n){ms(tc,t,n)}function qw(t){return In(tc,t)||""}function Ys(t){Fa(tc,t)}function Vw(t){const{question:n,response:s}=t;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 Ww(t,n){switch(t.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?t.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):t.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 Kw(t){let n=0;const s=[];for(const i of t){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Ss({entries:t,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=Kw(t);return r.length===0?null:e.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((l,o)=>{const d=!!l.question,m=!!l.thinkingOutput,c=s[o]??n,u=d?Vw(l):void 0,h=l.question&&u!==void 0?Ww(l.question,u):"";return e.jsxs("div",{className:"conversation-entry",children:[d?e.jsxs("div",{className:"conversation-entry-question",children:[e.jsxs("span",{className:"conversation-entry-question-label",children:["Q",l.questionNumber]}),e.jsx("p",{children:l.question?.question})]}):e.jsx("div",{className:"conversation-entry-question",children:e.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),d&&e.jsxs("div",{className:"conversation-entry-response",children:[e.jsx("strong",{children:"Your response"}),e.jsx("p",{children:h||"—"})]}),m&&e.jsxs("div",{className:"conversation-entry-thinking",children:[e.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[o]:!c}))},"aria-expanded":c,children:[e.jsx("span",{"aria-hidden":"true",children:c?"▾":"▸"}),c?`Hide ${d?"AI thinking":"AI reasoning"}`:`Show ${d?"AI thinking":"AI reasoning"}`]}),c&&e.jsx("pre",{children:l.thinkingOutput})]})]},`${l.question?.id??"thinking"}-${o}`)})})}const Od="fusion-tab-id";function Gw(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ci(){if(typeof window>"u")return"server-tab";const t=window.sessionStorage.getItem(Od);if(t)return t;const n=Gw();return window.sessionStorage.setItem(Od,n),n}function el(t){const n=a.useMemo(()=>Ci(),[]),[s,i]=a.useState(!1),[r,l]=a.useState(null),[o,d]=a.useState(!1);a.useEffect(()=>{if(!t){i(!1),l(null),d(!1);return}let c=!0;return d(!0),Promise.resolve(Fk(t,n)).then(u=>{if(c){if(u.acquired){i(!1),l(null);return}i(!0),l(u.currentHolder)}}).catch(()=>{c&&(i(!1),l(null))}).finally(()=>{c&&d(!1)}),()=>{c=!1;try{const u=Lk(t,n);u&&typeof u.catch=="function"&&u.catch(()=>{})}catch{}}},[t,n]),a.useEffect(()=>{if(!t||typeof window>"u")return;const c=()=>{if(typeof navigator.sendBeacon!="function")return;const u=Ps(`/api/ai-sessions/${encodeURIComponent(t)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(u)};return window.addEventListener("beforeunload",c),()=>{window.removeEventListener("beforeunload",c)}},[t,n]),a.useEffect(()=>!t||typeof EventSource>"u"?void 0:Bs("/api/events",{events:{"ai_session:updated":u=>{try{const h=JSON.parse(u.data);if(h.id!==t)return;const g=h.lockedByTab??null;l(g),i(!!(g&&g!==n))}catch{}}}}),[t,n]);const m=a.useCallback(async()=>{if(t){d(!0);try{await Promise.resolve(zk(t,n)),i(!1),l(null)}finally{d(!1)}}},[t,n]);return{isLockedByOther:s,currentHolder:r,takeControl:m,isLoading:o}}const Jw="fusion:ai-session-sync",Bd="fusion:ai-session-sync",Yw=3e4,Qw=6e4;function Ts(){return Date.now()}function Xw(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ud(t){if(!t||typeof t!="object")return null;const n=t;return typeof n.type!="string"||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)?null:t}class Zw{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=Xw(),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:Ts()})}broadcastUpdate(n){const s=n.timestamp??Ts();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??Ts();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=Ts();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=Ts();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Ts();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(Jw),this.channel.onmessage=s=>{const i=Ud(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Bd||!s.newValue))try{const i=JSON.parse(s.newValue),r=Ud(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ts();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Yw)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Ts();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(Bd,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(l=>{const o=this.ownershipBySession.get(l.sessionId);return{...l,owningTabId:o?.tabId??l.owningTabId??null}}),i=[...this.ownershipBySession.entries()].map(([l,o])=>({sessionId:l,tabId:o.tabId,timestamp:o.timestamp})),r=[...this.heartbeatByTab.entries()].map(([l,o])=>({tabId:l,timestamp:o}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:i,heartbeats:r,timestamp:Ts()});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 l=this.ownershipBySession.get(n.sessionId),o={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??l?.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,o),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 l=this.ownershipBySession.get(n);if(l&&i<l.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const o=this.sessionStates.get(n);o&&i>=o.lastEventTimestamp&&this.sessionStates.set(n,{...o,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const l=this.ownershipBySession.get(n);if(!l||l.tabId!==s||i<l.timestamp)return;this.ownershipBySession.delete(n);const o=this.sessionStates.get(n);o&&i>=o.lastEventTimestamp&&this.sessionStates.set(n,{...o,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=Ts(),s=new Map;for(const[r,l]of this.sessionStates.entries()){const o=this.ownershipBySession.get(r);s.set(r,{...l,owningTabId:o?.tabId??l.owningTabId??null})}const i=new Map;for(const[r,l]of this.ownershipBySession.entries()){const o=this.heartbeatByTab.get(l.tabId)??l.timestamp,d=n-o>Qw;i.set(r,{sessionId:r,tabId:l.tabId,lastHeartbeatTimestamp:o,lastLockTimestamp:l.timestamp,stale:d})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const Rs=new Zw;function ra(){const t=a.useSyncExternalStore(d=>Rs.subscribe(d),()=>Rs.getSnapshot(),()=>Rs.getSnapshot());a.useEffect(()=>{Rs.requestSync()},[]);const n=a.useCallback(d=>{Rs.broadcastUpdate(d)},[]),s=a.useCallback(d=>{Rs.broadcastCompleted(d)},[]),i=a.useCallback((d,m)=>{Rs.broadcastLock(d,m)},[]),r=a.useCallback((d,m)=>{Rs.broadcastUnlock(d,m)},[]),l=a.useCallback(d=>{Rs.broadcastHeartbeat(d)},[]),o=a.useCallback(()=>{Rs.requestSync()},[]);return{tabId:t.tabId,sessions:t.sessions,activeTabMap:t.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:l,requestSync:o}}function eN(t,n){return t&&n?`${t}/${n}`:""}function tN(t){if(!t)return{provider:void 0,modelId:void 0};const n=t.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:t.slice(0,n),modelId:t.slice(n+1)}}const nN=["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 sN({isOpen:t,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:l}){const[o,d]=a.useState(""),[m,c]=a.useState({type:"initial"}),[u,h]=a.useState(null),[g,p]=a.useState([]),[f,b]=a.useState([]),[v,y]=a.useState(null),[k,A]=a.useState(!1),j=a.useRef(!1),[_,N]=a.useState(""),[M,w]=a.useState(!0),[R,E]=a.useState(!1),[I,L]=a.useState(!1),[ee,$]=a.useState(!1),T=a.useRef(null),S=a.useRef(null),Y=a.useRef(null),K=a.useRef(null),[G,P]=a.useState(l??null),O=a.useMemo(()=>Ci(),[]),{isLockedByOther:X,takeControl:C,isLoading:V}=el(t?G:null),{activeTabMap:de,broadcastUpdate:B,broadcastCompleted:J,broadcastLock:D,broadcastUnlock:he,broadcastHeartbeat:q}=ra(),[W,me]=a.useState(void 0),[Re,ve]=a.useState(void 0),[Me,_e]=a.useState([]),[De,Oe]=a.useState(!0),[ze,Be]=a.useState(null),[Ae,Ce]=a.useState([]),[Ge,Te]=a.useState([]),Xe=eN(W,Re);a.useEffect(()=>{(async()=>{try{Oe(!0);const He=await Kn();_e(He.models),Ce(He.favoriteProviders),Te(He.favoriteModels)}catch(He){Be(fe(He)||"Failed to load models")}finally{Oe(!1)}})()},[]);const re=a.useCallback(Ee=>{Ce(He=>{const ce=He,We=ce.includes(Ee)?ce.filter(Pe=>Pe!==Ee):[Ee,...ce];return Wt({favoriteProviders:We,favoriteModels:Ge}).catch(()=>{Ce(ce)}),We})},[Ge]),Z=a.useCallback(Ee=>{Te(He=>{const ce=He,We=ce.includes(Ee)?ce.filter(Pe=>Pe!==Ee):[Ee,...ce];return Wt({favoriteProviders:Ae,favoriteModels:We}).catch(()=>{Te(ce)}),We})},[Ae]),ye=a.useCallback((Ee,He)=>{if(!Ee||!He)return"Using default";const ce=Me.find(qe=>qe.provider===Ee&&qe.id===He);return ce?`${ce.provider}/${ce.id}`:`${Ee}/${He}`},[Me]),ie=a.useCallback(Ee=>{S.current?.close();const He=Sk(Ee,i,{onThinking:ce=>{N(qe=>qe+ce),B({sessionId:Ee,status:"generating",needsInput:!1,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onQuestion:ce=>{E(!1),L(!1),Ys(i),c({type:"question",sessionId:Ee,question:ce}),N(""),A(!0),B({sessionId:Ee,status:"awaiting_input",needsInput:!0,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onSummary:ce=>{E(!1),L(!1),Ys(i),c({type:"summary",sessionId:Ee,summary:ce}),y(ce),N(""),A(!0),B({sessionId:Ee,status:"complete",needsInput:!1,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onError:ce=>{const qe=ce||"Session failed while contacting the AI.";E(!1),L(!1),h(null),c({type:"error",sessionId:Ee,errorMessage:qe}),N(""),A(!0),Y.current=Ee,B({sessionId:Ee,status:"error",needsInput:!1,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null}),J({sessionId:Ee,status:"error"})},onComplete:()=>{E(!1),L(!1),Y.current=null,J({sessionId:Ee,status:"complete"})},onConnectionStateChange:ce=>{E(ce==="reconnecting")}});S.current=He},[J,B,o,i,O]),Ie=a.useCallback(async Ee=>{const He=Ee??o;if(He.trim()){h(null),N(""),p([]),b([]),E(!1),c({type:"loading"});try{const{sessionId:ce}=await kk(He.trim(),i,W&&Re?{modelProvider:W,modelId:Re}:void 0);Y.current=ce,P(ce),Ys(i),ie(ce),p([])}catch(ce){E(!1),h(fe(ce)||"Failed to start interview session"),c({type:"initial"}),Y.current=null,P(null)}}},[ie,o,W,Re,i]);a.useEffect(()=>{t&&m.type==="initial"&&T.current?.focus()},[t,m.type]),a.useEffect(()=>{if(t&&r&&!j.current&&m.type==="initial"){d(r);const Ee=setTimeout(()=>{j.current=!0,Ie(r)},0);return()=>clearTimeout(Ee)}else if(t&&!r&&!j.current&&m.type==="initial"){const Ee=qw(i);Ee&&d(Ee)}},[t,r,m.type,Ie]),a.useEffect(()=>{t||(j.current=!1,E(!1),L(!1),P(null))},[t]),a.useEffect(()=>{if(!t||!l||m.type!=="initial")return;let Ee=!1;return ni(l).then(He=>{if(Ee||!He)return;const ce=Ji(He.conversationHistory);if(b(ce),P(He.id),p(ce.map(qe=>qe.response).filter(qe=>!!(qe&&typeof qe=="object"&&!Array.isArray(qe)))),He.status==="awaiting_input"&&He.currentQuestion)try{Ys(i);const qe=JSON.parse(He.currentQuestion);Y.current=He.id,A(!0),c({type:"question",sessionId:He.id,question:qe})}catch{h("Failed to restore session question.")}else if(He.status==="complete"&&He.result)try{Ys(i);const qe=JSON.parse(He.result);Y.current=He.id,A(!0),y(qe),c({type:"summary",sessionId:He.id,summary:qe})}catch{h("Failed to restore session result.")}else He.status==="generating"?(Y.current=He.id,A(!0),He.thinkingOutput&&N(He.thinkingOutput),c({type:"loading"}),ie(He.id)):He.status==="error"&&(Y.current=He.id,A(!0),h(null),c({type:"error",sessionId:He.id,errorMessage:He.error??"The session encountered an error."}))}).catch(()=>{Ee||h("Failed to resume session.")}),()=>{Ee=!0}},[ie,t,l,m.type,i]),a.useEffect(()=>{if(!t){K.current&&(he(K.current,O),K.current=null);return}if(G&&K.current!==G){K.current&&he(K.current,O),D(G,O),K.current=G;return}!G&&K.current&&(he(K.current,O),K.current=null)},[D,he,t,G,O]),a.useEffect(()=>{if(!t||!G||K.current!==G)return;q(O);const Ee=setInterval(()=>{q(O)},3e4);return()=>{clearInterval(Ee)}},[q,t,G,O]),a.useEffect(()=>()=>{S.current?.close(),S.current=null,K.current&&(he(K.current,O),K.current=null)},[he,O]),a.useEffect(()=>{if(!t)return;const Ee=He=>{(m.type==="question"||m.type==="summary")&&(He.preventDefault(),He.returnValue=""),S.current?.close()};return window.addEventListener("beforeunload",Ee),()=>window.removeEventListener("beforeunload",Ee)},[t,m]);const pe=a.useCallback(()=>{S.current?.close(),S.current=null,n()},[n]),Ue=a.useCallback(async()=>{if(o&&Hw(o,i),!(k&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(S.current?.close(),S.current=null,m.type==="question"||m.type==="summary"||m.type==="error")try{await xh(m.sessionId,i,O)}catch{}d(""),c({type:"initial"}),h(null),p([]),b([]),y(null),N(""),E(!1),L(!1),A(!1),$(!1),me(void 0),ve(void 0),Y.current=null,P(null),n()}},[o,k,m,n,i,O]);a.useEffect(()=>{if(!t)return;const Ee=He=>{He.key==="Escape"&&(k?confirm("Are you sure you want to close? Your interview progress will be lost.")&&Ue():Ue())};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[t,k,Ue]);const dt=a.useCallback(async Ee=>{if(m.type!=="question")return;const{sessionId:He}=m;h(null),p(ce=>[...ce,Ee]),b(ce=>[...ce,{question:m.question,response:Ee}]),c({type:"loading"}),N("");try{ie(He),await jk(He,Ee,i,O),A(!0)}catch(ce){S.current?.close(),S.current=null,h(fe(ce)||"Failed to submit response"),c({type:"question",sessionId:He,question:m.question})}},[m,i,O,ie]),ht=a.useCallback(async()=>{if(m.type!=="error")return;const Ee=m.sessionId;h(null),L(!0),N(""),c({type:"loading"}),ie(Ee);try{Y.current=Ee,P(Ee),await wk(Ee,i,O)}catch(He){let ce=He;if((fe(He)||"").includes("not in an error state"))try{const We=await ni(Ee);if(!We)throw new Error("Failed to refresh interview session.");const Pe=Ji(We.conversationHistory);if(b(Pe),p(Pe.map(nt=>nt.response).filter(nt=>!!(nt&&typeof nt=="object"&&!Array.isArray(nt)))),Y.current=We.id,P(We.id),A(!0),We.status==="generating")N(We.thinkingOutput??""),c({type:"loading"}),S.current?.isConnected()||ie(We.id);else if(We.status==="awaiting_input"){if(!We.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Ys(i);const nt=JSON.parse(We.currentQuestion);c({type:"question",sessionId:We.id,question:nt}),S.current?.isConnected()||ie(We.id)}else if(We.status==="complete"){if(!We.result)throw new Error("Interview session is complete but has no result.");Ys(i);const nt=JSON.parse(We.result);y(nt),c({type:"summary",sessionId:We.id,summary:nt})}else We.status==="error"&&c({type:"error",sessionId:We.id,errorMessage:We.error??"Retry failed. Please try again."});E(!1);return}catch(We){ce=We}S.current?.close(),S.current=null,c({type:"error",sessionId:Ee,errorMessage:fe(ce)||"Retry failed. Please try again."}),E(!1)}finally{L(!1)}},[ie,i,O,m]),ue=a.useCallback(async()=>{if(m.type==="summary"){h(null),$(!0);try{const Ee=await Nk(m.sessionId,v||void 0,i);s(Ee),Ys(i),S.current?.close(),S.current=null,d(""),c({type:"initial"}),h(null),p([]),b([]),y(null),N(""),E(!1),L(!1),A(!1),$(!1),Y.current=null,P(null),n()}catch(Ee){h(fe(Ee)||"Failed to create mission"),$(!1)}}},[m,v,s,n,i]),te=()=>m.type==="question"?Math.min(g.length+1,6):6,ke=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",Ne=G?de.get(G):null,Ze=Ne&&Ne.tabId!==O,xe=!!(Ze&&!Ne.stale),st=X&&(!Ze||Ne.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:Ee=>Ee.target===Ee.currentTarget&&Ue(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg planning-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx(ns,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Plan Mission with AI"})]}),e.jsxs("div",{className:"modal-header-actions",children:[ke&&e.jsx("button",{className:"modal-send-to-background",onClick:pe,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:Ue,"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[u&&e.jsx("div",{className:"form-error planning-error",children:u}),R&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),xe&&e.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),m.type==="initial"&&e.jsxs("div",{className:"planning-initial",children:[e.jsxs("div",{className:"planning-view-scroll",children:[e.jsxs("div",{className:"planning-intro",children:[e.jsx(Ln,{size:32,className:"icon-triage-lg"}),e.jsx("h4",{children:"Transform your vision into a structured mission"}),e.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."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),e.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:o,onChange:Ee=>d(Ee.target.value),onKeyDown:Ee=>{Ee.key==="Enter"&&!Ee.shiftKey&&o.trim()&&(Ee.preventDefault(),Ie())}})]}),e.jsxs("div",{className:"planning-examples",children:[e.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),e.jsx("div",{className:"planning-example-chips",children:nN.map((Ee,He)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>d(Ee),children:Ee.length>45?Ee.slice(0,45)+"...":Ee},He))})]}),e.jsxs("div",{className:"planning-model-select-group",children:[e.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",De&&e.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),e.jsx(Kt,{id:"mission-interview-modal-model",label:"Planning Model",value:Xe,onChange:Ee=>{const{provider:He,modelId:ce}=tN(Ee);me(He),ve(ce)},models:Me,disabled:De,favoriteProviders:Ae,onToggleFavorite:re,favoriteModels:Ge,onToggleModelFavorite:Z}),ze&&e.jsxs("div",{className:"form-hint form-hint-error",children:[ze," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Oe(!0);const Ee=await Kn();_e(Ee.models),Ce(Ee.favoriteProviders),Te(Ee.favoriteModels),Be(null)}catch(Ee){Be(fe(Ee)||"Failed to load models")}finally{Oe(!1)}})()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${W&&Re?"model-badge-custom":"model-badge-default"}`,children:ye(W,Re)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Ie(),disabled:!o.trim(),children:[e.jsx(ns,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),m.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ct,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:_?"AI is thinking...":"Preparing next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&_&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:_})})]})]}),m.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:f}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:m.errorMessage}),e.jsxs("div",{className:"ai-error-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:I,children:[I?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:Ue,disabled:I,children:"Cancel"})]})]})]})}),m.type==="question"&&e.jsx(iN,{question:m.question,progress:te(),historyEntries:f,onSubmit:dt}),m.type==="summary"&&v&&e.jsx(aN,{summary:v,historyEntries:f,onSummaryChange:y,onApprove:ue,onStartOver:()=>{c({type:"initial"}),A(!1),y(null),p([]),b([]),P(null),S.current?.close(),S.current=null},isCreating:ee}),X&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(Kr,{size:16}),e.jsx("span",{children:st?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),st&&e.jsx("button",{type:"button",onClick:()=>{C()},disabled:V,className:"btn btn-primary session-lock-take-control",children:V?"Taking control...":"Take Control"})]})})]})]})}):null}function iN({question:t,progress:n,historyEntries:s,onSubmit:i}){const[r,l]=a.useState({}),[o,d]=a.useState(""),m=a.useCallback(()=>{t.type==="text"?i({[t.id]:o}):t.type==="confirm"?i({[t.id]:r[t.id]===!0}):i(r)},[t,r,o,i]);a.useEffect(()=>{l({}),d("")},[t.id]);const c=()=>{switch(t.type){case"text":return o.trim().length>0;case"single_select":return r[t.id]!==void 0;case"multi_select":return Array.isArray(r[t.id])&&r[t.id].length>0;case"confirm":return r[t.id]!==void 0;default:return!0}};return e.jsxs("div",{className:"planning-question-form",children:[e.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:s}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-question-panel",children:[e.jsxs("div",{className:"planning-progress",children:[e.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(u=>e.jsx("div",{className:`planning-progress-step ${u<=n?"active":""}`},u))}),e.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),e.jsxs("div",{className:"planning-question-content",children:[e.jsx("h4",{className:"planning-question-text",children:t.question}),t.description&&e.jsx("p",{className:"planning-question-desc",children:t.description}),e.jsxs("div",{className:"planning-options",children:[t.type==="text"&&e.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:o,onChange:u=>d(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&o.trim()&&(u.preventDefault(),m())}}),t.type==="single_select"&&t.options&&e.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:t.options.map(u=>e.jsxs("label",{className:"planning-option planning-option--radio",children:[e.jsx("input",{type:"radio",name:t.id,value:u.id,checked:r[t.id]===u.id,onChange:()=>l({[t.id]:u.id})}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id))}),t.type==="multi_select"&&t.options&&e.jsx("div",{className:"planning-checkbox-group",children:t.options.map(u=>{const h=r[t.id]||[];return e.jsxs("label",{className:"planning-option planning-option--checkbox",children:[e.jsx("input",{type:"checkbox",value:u.id,checked:h.includes(u.id),onChange:g=>{const p=g.target.checked?[...h,u.id]:h.filter(f=>f!==u.id);l({[t.id]:p})}}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id)})}),t.type==="confirm"&&e.jsxs("div",{className:"planning-confirm-group",children:[e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!0?"selected":""}`,onClick:()=>l({[t.id]:!0}),children:[e.jsx(en,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Ft,{size:18}),"No"]})]})]})]})]})]}),e.jsx("div",{className:"planning-actions",children:e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!c(),children:["Continue",e.jsx(Ba,{size:16,className:"icon-ml-4"})]})})]})}function aN({summary:t,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:l}){const[o,d]=a.useState(()=>new Set(t.milestones.map((j,_)=>_))),[m,c]=a.useState(()=>{const j=new Set;return t.milestones.forEach((_,N)=>{_.slices.forEach((M,w)=>j.add(`${N}-${w}`))}),j}),u=j=>{d(_=>{const N=new Set(_);return N.has(j)?N.delete(j):N.add(j),N})},h=j=>{c(_=>{const N=new Set(_);return N.has(j)?N.delete(j):N.add(j),N})},g=(j,_)=>{const N=[...t.milestones];N[j]={...N[j],..._},s({...t,milestones:N})},p=(j,_,N)=>{const M=[...t.milestones],w=[...M[j].slices];w[_]={...w[_],...N},M[j]={...M[j],slices:w},s({...t,milestones:M})},f=(j,_,N,M)=>{const w=[...t.milestones],R=[...w[j].slices],E=[...R[_].features];E[N]={...E[N],...M},R[_]={...R[_],features:E},w[j]={...w[j],slices:R},s({...t,milestones:w})},b=j=>{const _=t.milestones.filter((N,M)=>M!==j);s({...t,milestones:_})},v=(j,_)=>{const N=[...t.milestones];N[j]={...N[j],slices:N[j].slices.filter((M,w)=>w!==_)},s({...t,milestones:N})},y=(j,_,N)=>{const M=[...t.milestones],w=[...M[j].slices];w[_]={...w[_],features:w[_].features.filter((R,E)=>E!==N)},M[j]={...M[j],slices:w},s({...t,milestones:M})},k=(j,_)=>{const N=[...t.milestones],M=[...N[j].slices];M[_]={...M[_],features:[...M[_].features,{title:"New feature",description:""}]},N[j]={...N[j],slices:M},s({...t,milestones:N})},A=t.milestones.reduce((j,_)=>j+_.slices.reduce((N,M)=>N+M.features.length,0),0);return e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(en,{size:24,className:"icon-success"}),e.jsx("h4",{children:"Mission Plan Ready"}),e.jsxs("p",{className:"text-muted",children:[t.milestones.length," milestones, ",A," features. Review and edit before approving."]})]}),e.jsxs("div",{className:"planning-summary-form",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Mission Title"}),e.jsx("input",{type:"text",className:"form-input",value:t.missionTitle||"",onChange:j=>s({...t,missionTitle:j.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Mission Description"}),e.jsx("textarea",{className:"planning-textarea",rows:3,value:t.missionDescription||"",onChange:j=>s({...t,missionDescription:j.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Roadmap"}),e.jsx("div",{className:"roadmap-list",children:t.milestones.map((j,_)=>e.jsxs("div",{className:"roadmap-card",children:[e.jsxs("div",{className:"roadmap-card-header",onClick:()=>u(_),children:[o.has(_)?e.jsx(Lt,{size:16,className:"icon-text-secondary"}):e.jsx(rn,{size:16,className:"icon-text-secondary"}),e.jsx(ki,{size:16,className:"icon-milestone"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:N=>g(_,{title:N.target.value}),onClick:N=>N.stopPropagation()}),t.milestones.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:N=>{N.stopPropagation(),b(_)},title:"Remove milestone",children:e.jsx(Ut,{size:14,className:"icon-text-secondary"})})]}),o.has(_)&&e.jsxs("div",{className:"roadmap-card-body",children:[e.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:N=>g(_,{description:N.target.value})}),e.jsxs("div",{className:"roadmap-field-group",children:[e.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),e.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:j.verification||"",onChange:N=>g(_,{verification:N.target.value})})]}),j.slices.map((N,M)=>{const w=`${_}-${M}`;return e.jsxs("div",{className:"roadmap-slice-card",children:[e.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(w),children:[m.has(w)?e.jsx(Lt,{size:14,className:"icon-text-secondary"}):e.jsx(rn,{size:14,className:"icon-text-secondary"}),e.jsx(go,{size:14,className:"icon-slice"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:N.title,onChange:R=>p(_,M,{title:R.target.value}),onClick:R=>R.stopPropagation()}),j.slices.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:R=>{R.stopPropagation(),v(_,M)},title:"Remove slice",children:e.jsx(Ut,{size:12,className:"icon-text-secondary"})})]}),m.has(w)&&e.jsxs("div",{className:"roadmap-slice-body",children:[e.jsxs("div",{className:"roadmap-slice-field-group",children:[e.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),e.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:N.verification||"",onChange:R=>p(_,M,{verification:R.target.value})})]}),N.features.map((R,E)=>e.jsxs("div",{className:"roadmap-feature-row",children:[e.jsx(uo,{size:12,className:"icon-feature"}),e.jsxs("div",{className:"roadmap-feature-content",children:[e.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:R.title,onChange:I=>f(_,M,E,{title:I.target.value})}),R.description&&e.jsx("p",{className:"roadmap-feature-text",children:R.description}),R.acceptanceCriteria&&e.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",R.acceptanceCriteria]})]}),e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>y(_,M,E),title:"Remove feature",children:e.jsx(Ut,{size:12,className:"icon-text-secondary"})})]},E)),e.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>k(_,M),children:[e.jsx(qt,{size:12}),"Add Feature"]})]})]},M)})]})]},_))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:r,disabled:l,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Start Over"]}),e.jsx("button",{className:"btn btn-primary",onClick:i,disabled:l||t.milestones.length===0,children:l?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function rN({isOpen:t,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:l,missionContext:o,projectId:d,resumeSessionId:m}){const[c,u]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[b,v]=a.useState([]),[y,k]=a.useState(null),[A,j]=a.useState(""),[_,N]=a.useState(!0),[M,w]=a.useState(!1),[R,E]=a.useState(!1),I=a.useRef(null),L=a.useRef(null),ee=a.useRef(null),$=a.useRef(null),[T,S]=a.useState(null),Y=a.useMemo(()=>Ci(),[]);el(t?T:null);const{activeTabMap:K,broadcastUpdate:G,broadcastCompleted:P,broadcastLock:O,broadcastUnlock:X,broadcastHeartbeat:C}=ra(),V=i==="milestone"?Ck:_k,de=i==="milestone"?Ek:Tk,B=i==="milestone"?Mk:Rk,J=i==="milestone"?Ak:Ik,D=i==="milestone"?Pk:$k,he=i==="milestone"?"Milestone":"Slice",q=i==="milestone"?"milestone_interview":"slice_interview",W=a.useCallback(Te=>{L.current?.close();const Xe=B(Te,d,{onThinking:re=>{j(Z=>Z+re),G({sessionId:Te,status:"generating",needsInput:!1,owningTabId:Y,type:q,title:l,projectId:d??null})},onQuestion:re=>{w(!1),me(),u({type:"question",sessionId:Te,question:re}),j(""),G({sessionId:Te,status:"awaiting_input",needsInput:!0,owningTabId:Y,type:q,title:l,projectId:d??null})},onSummary:re=>{w(!1),me(),u({type:"summary",sessionId:Te,summary:re}),k(re),j(""),G({sessionId:Te,status:"complete",needsInput:!1,owningTabId:Y,type:q,title:l,projectId:d??null})},onError:re=>{const Z=re||"Session failed while contacting the AI.";w(!1),g(null),u({type:"error",sessionId:Te,errorMessage:Z}),j(""),ee.current=Te,G({sessionId:Te,status:"error",needsInput:!1,owningTabId:Y,type:q,title:l,projectId:d??null}),P({sessionId:Te,status:"error"})},onComplete:()=>{w(!1),ee.current=null,P({sessionId:Te,status:"complete"})},onConnectionStateChange:re=>{w(re==="reconnecting")}});L.current=Xe},[P,G,B,q,d,Y,l]),me=()=>{k(null),f([]),v([]),j("")},Re=a.useCallback(async()=>{g(null),me(),w(!1),u({type:"loading"});try{const{sessionId:Te}=await V(r,d);ee.current=Te,S(Te),W(Te)}catch(Te){w(!1),g(fe(Te)||`Failed to start ${he.toLowerCase()} interview`),u({type:"initial"}),ee.current=null,S(null)}},[W,d,V,r,he]),ve=a.useCallback(async()=>{g(null),E(!0);try{await D(r,d),s(),u({type:"applied"})}catch(Te){g(fe(Te)||`Failed to skip ${he.toLowerCase()} interview`),E(!1)}},[s,d,D,r,he]);a.useEffect(()=>{t&&c.type==="initial"&&I.current?.focus()},[t,c.type]),a.useEffect(()=>{if(!t||!m||c.type!=="initial")return;let Te=!1;return ni(m).then(Xe=>{if(Te||!Xe)return;const re=Ji(Xe.conversationHistory);if(v(re),S(Xe.id),f(re.map(Z=>Z.response).filter(Z=>!!(Z&&typeof Z=="object"&&!Array.isArray(Z)))),Xe.status==="awaiting_input"&&Xe.currentQuestion)try{const Z=JSON.parse(Xe.currentQuestion);ee.current=Xe.id,u({type:"question",sessionId:Xe.id,question:Z})}catch{g("Failed to restore session question.")}else if(Xe.status==="complete"&&Xe.result)try{const Z=JSON.parse(Xe.result);ee.current=Xe.id,k(Z),u({type:"summary",sessionId:Xe.id,summary:Z})}catch{g("Failed to restore session result.")}else Xe.status==="generating"?(ee.current=Xe.id,Xe.thinkingOutput&&j(Xe.thinkingOutput),u({type:"loading"}),W(Xe.id)):Xe.status==="error"&&(ee.current=Xe.id,g(null),u({type:"error",sessionId:Xe.id,errorMessage:Xe.error??"The session encountered an error."}))}).catch(()=>{Te||g("Failed to resume session.")}),()=>{Te=!0}},[W,t,m,c.type]),a.useEffect(()=>{t||(w(!1),S(null))},[t]),a.useEffect(()=>{if(!(!t||!T)){if($.current!==T){$.current&&X($.current,Y),O(T,Y),$.current=T;return}!T&&$.current&&(X($.current,Y),$.current=null)}},[O,X,t,T,Y]),a.useEffect(()=>{if(!t||!T||$.current!==T)return;C(Y);const Te=setInterval(()=>{C(Y)},3e4);return()=>{clearInterval(Te)}},[C,t,T,Y]),a.useEffect(()=>()=>{L.current?.close(),L.current=null,$.current&&(X($.current,Y),$.current=null)},[X,Y]);const Me=a.useCallback(()=>{L.current?.close(),L.current=null,n()},[n]),_e=a.useCallback(async()=>{L.current?.close(),L.current=null,me(),u({type:"initial"}),g(null),ee.current=null,S(null),n()},[n]),De=a.useCallback(async Te=>{if(c.type!=="question")return;const{sessionId:Xe}=c;g(null),f(re=>[...re,Te]),v(re=>[...re,{question:c.question,response:Te}]),u({type:"loading"}),j("");try{W(Xe),await de(Xe,Te,d,Y)}catch(re){L.current?.close(),L.current=null,g(fe(re)||"Failed to submit response"),u({type:"question",sessionId:Xe,question:c.question})}},[W,d,de,Y,c]),Oe=a.useCallback(async()=>{if(c.type==="summary"){g(null),E(!0);try{await J(c.sessionId,y||void 0,d),s(),u({type:"applied"})}catch(Te){g(fe(Te)||"Failed to apply interview results"),E(!1)}}},[J,y,s,d,c]),ze=()=>c.type==="question"?Math.min(p.length+1,6):6,Be=c.type==="loading"||c.type==="question"||c.type==="summary"||c.type==="error",Ae=T?K.get(T):null,Ge=!!(Ae&&Ae.tabId!==Y&&!Ae.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:Te=>Te.target===Te.currentTarget&&_e(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:e.jsxs("div",{className:"modal modal-lg planning-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx(Ln,{size:20,className:"icon-triage"}),e.jsxs("h3",{children:["Plan ",he,": ",l]})]}),e.jsxs("div",{className:"modal-header-actions",children:[Be&&e.jsx("button",{className:"modal-send-to-background",onClick:Me,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:_e,"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[h&&e.jsx("div",{className:"form-error planning-error",children:h}),M&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ge&&e.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&e.jsxs("div",{className:"planning-initial",children:[e.jsx("div",{className:"planning-view-scroll",children:e.jsxs("div",{className:"planning-intro",children:[e.jsx(Ln,{size:32,className:"icon-triage-lg"}),e.jsxs("h4",{children:["Refine ",he," scope with AI"]}),e.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."]}),o&&e.jsxs("div",{className:"planning-context-info",children:[e.jsx("span",{className:"planning-context-label",children:"Mission context:"}),e.jsx("span",{className:"planning-context-text",children:o})]})]})}),e.jsxs("div",{className:"planning-view-footer",children:[e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void Re(),children:[e.jsx(Ln,{size:16,className:"icon-mr-8"}),"Start Interview"]}),e.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ve(),disabled:R,children:[R?e.jsx(ct,{size:16,className:"spin"}):null,"Use Mission Context"]}),e.jsx("button",{className:"btn",onClick:_e,children:"Cancel"})]})]}),c.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ct,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:A?"AI is thinking...":"Preparing next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&A&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:A})})]})]}),c.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:b}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:c.errorMessage}),e.jsx("div",{className:"ai-error-actions",children:e.jsx("button",{className:"btn",onClick:_e,children:"Cancel"})})]})]})}),c.type==="question"&&e.jsx(lN,{question:c.question,progress:ze(),historyEntries:b,onSubmit:De}),c.type==="summary"&&y&&e.jsx(oN,{summary:y,historyEntries:b,onSummaryChange:k,onApply:Oe,onCancel:_e,isApplying:R}),c.type==="applied"&&e.jsxs("div",{className:"planning-summary planning-applied",children:[e.jsx("div",{className:"planning-view-scroll",children:e.jsxs("div",{className:"planning-applied-content",children:[e.jsx(en,{size:48,className:"icon-success"}),e.jsxs("h4",{children:[he," Updated"]}),e.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",c.type==="applied"?"applied":"updated","."]})]})}),e.jsx("div",{className:"planning-view-footer",children:e.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function lN({question:t,progress:n,historyEntries:s,onSubmit:i}){const[r,l]=a.useState({}),[o,d]=a.useState(""),m=a.useCallback(()=>{t.type==="text"?i({[t.id]:o}):t.type==="confirm"?i({[t.id]:r[t.id]===!0}):i(r)},[t,r,o,i]);a.useEffect(()=>{l({}),d("")},[t.id]);const c=()=>{switch(t.type){case"text":return o.trim().length>0;case"single_select":return r[t.id]!==void 0;case"multi_select":return Array.isArray(r[t.id])&&r[t.id].length>0;case"confirm":return r[t.id]!==void 0;default:return!0}};return e.jsxs("div",{className:"planning-question-form",children:[e.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:s}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-question-panel",children:[e.jsxs("div",{className:"planning-progress",children:[e.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(u=>e.jsx("div",{className:`planning-progress-step ${u<=n?"active":""}`},u))}),e.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),e.jsxs("div",{className:"planning-question-content",children:[e.jsx("h4",{className:"planning-question-text",children:t.question}),t.description&&e.jsx("p",{className:"planning-question-desc",children:t.description}),e.jsxs("div",{className:"planning-options",children:[t.type==="text"&&e.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:o,onChange:u=>d(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&o.trim()&&(u.preventDefault(),m())}}),t.type==="single_select"&&t.options&&e.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:t.options.map(u=>e.jsxs("label",{className:"planning-option planning-option--radio",children:[e.jsx("input",{type:"radio",name:t.id,value:u.id,checked:r[t.id]===u.id,onChange:()=>l({[t.id]:u.id})}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id))}),t.type==="multi_select"&&t.options&&e.jsx("div",{className:"planning-checkbox-group",children:t.options.map(u=>{const h=r[t.id]||[];return e.jsxs("label",{className:"planning-option planning-option--checkbox",children:[e.jsx("input",{type:"checkbox",value:u.id,checked:h.includes(u.id),onChange:g=>{const p=g.target.checked?[...h,u.id]:h.filter(f=>f!==u.id);l({[t.id]:p})}}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id)})}),t.type==="confirm"&&e.jsxs("div",{className:"planning-confirm-group",children:[e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!0?"selected":""}`,onClick:()=>l({[t.id]:!0}),children:[e.jsx(en,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Ft,{size:18}),"No"]})]})]})]})]})]}),e.jsx("div",{className:"planning-actions",children:e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!c(),children:["Continue",e.jsx(Ba,{size:16,className:"icon-ml-4"})]})})]})}function oN({summary:t,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:l}){const[o,d]=a.useState(t),[m,c]=a.useState(!0),u=(h,g)=>{const p={...o,[h]:g};d(p),s(p)};return e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-panel",children:[e.jsx("div",{className:"planning-summary-header",children:e.jsxs("button",{className:"planning-summary-toggle",onClick:()=>c(!m),"aria-expanded":m,children:[m?e.jsx(Lt,{size:16}):e.jsx(rn,{size:16}),e.jsx("span",{children:"Refined Scope"})]})}),m&&e.jsxs("div",{className:"planning-summary-content",children:[o.description&&e.jsxs("div",{className:"planning-summary-field",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{rows:3,value:o.description,onChange:h=>u("description",h.target.value)})]}),o.planningNotes&&e.jsxs("div",{className:"planning-summary-field",children:[e.jsx("label",{children:"Planning Notes"}),e.jsx("textarea",{rows:3,value:o.planningNotes,onChange:h=>u("planningNotes",h.target.value)})]}),o.verification&&e.jsxs("div",{className:"planning-summary-field",children:[e.jsx("label",{children:"Verification Criteria"}),e.jsx("textarea",{rows:2,value:o.verification,onChange:h=>u("verification",h.target.value)})]}),!o.description&&!o.planningNotes&&!o.verification&&e.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),e.jsxs("div",{className:"planning-view-footer",children:[e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:l,children:[l?e.jsx(ct,{size:16,className:"spin"}):null,"Apply"]}),e.jsx("button",{className:"btn",onClick:r,disabled:l,children:"Cancel"})]})]})}const ma={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)"}},Hd={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)"}},qd={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)"}},rr={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)"}},lr={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)"}},or={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)"}},Vd={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)"}},cN=3;function dN(t){return t==="completed"?"planned":t==="needs_update"?"needs_update":"not_started"}function Wd({state:t}){const n=t==="planned"?"mission-plan-state-indicator--planned":t==="needs_update"?"mission-plan-state-indicator--needs-update":"mission-plan-state-indicator--not-started",s=t==="planned"?"Planned":t==="needs_update"?"Needs update":"Not planned";return e.jsx("span",{className:`mission-plan-state-indicator ${n}`,title:s,"aria-label":s})}function Kd(t){return t?t.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const kl={title:"",description:"",status:"planning",autopilotEnabled:!1},jl={title:"",description:"",status:"planning",dependencies:[]},wl={title:"",description:"",status:"pending"},Nl={title:"",description:"",acceptanceCriteria:"",status:"defined"},uN=3600*1e3;function Dr(t){if(!t)return"—";const n=new Date(t).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 mN(t){if(!t)return"healthy";const n=typeof t.lastErrorAt=="string"&&Date.now()-new Date(t.lastErrorAt).getTime()<=uN,s=t.totalTasks>0&&t.tasksFailed>t.totalTasks*.3;return n||s?"error":t.tasksFailed>0?"warning":t.tasksFailed===0&&t.tasksInFlight<=t.totalTasks?"healthy":"warning"}function hN(t){if(!t||typeof t!="object")return!1;const n=t;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 pN(t){if(!t||typeof t!="object")return!1;const n=t;return typeof n.id=="string"&&typeof n.missionId=="string"&&typeof n.eventType=="string"&&typeof n.description=="string"&&typeof n.timestamp=="string"}function Sl(t){if(!t||typeof t!="object")return!1;const n=t;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 $h=["feature_triaged","feature_completed"],Dh=["slice_activated","slice_completed","milestone_completed"],Fh=["mission_started","mission_paused","mission_resumed","mission_completed"],Lh=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Gd(t,n){switch(n){case"errors":return t==="error"||t==="warning";case"state_changes":return Fh.includes(t);case"tasks":return $h.includes(t);case"slices":return Dh.includes(t);case"autopilot":return Lh.includes(t);default:return!0}}function fN(t){return t==="error"||t==="warning"?"mission-event__type--error":Fh.includes(t)?"mission-event__type--state":$h.includes(t)?"mission-event__type--task":Dh.includes(t)?"mission-event__type--slice":Lh.includes(t)?"mission-event__type--autopilot":"mission-event__type--default"}function gN(t){return t.replace(/_/g," ")}function bN(t,n){return n?t==="watching"?`Watching since ${Dr(n)}`:`Last activation ${Dr(n)}`:null}function xN({isOpen:t,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:l,availableTasks:o=[],resumeSessionId:d,targetMissionId:m,milestoneSliceResumeSessionId:c,onMilestoneSliceResumeFetchError:u}){const h=n||t,[g,p]=a.useState([]),[f,b]=a.useState(null),[v,y]=a.useState(!0),[k,A]=a.useState(!1),[j,_]=a.useState(!1),[N,M]=a.useState(null),[w,R]=a.useState(kl),[E,I]=a.useState(!1),[L,ee]=a.useState(new Set),[$,T]=a.useState(new Set),[S,Y]=a.useState(null),[K,G]=a.useState(jl),[P,O]=a.useState(!1),[X,C]=a.useState(null),[V,de]=a.useState(wl),[B,J]=a.useState(!1),[D,he]=a.useState(null),[q,W]=a.useState(null),[me,Re]=a.useState(Nl),[ve,Me]=a.useState(!1),[_e,De]=a.useState(null),[Oe,ze]=a.useState(null),[Be,Ae]=a.useState(""),[Ce,Ge]=a.useState(!1),[Te,Xe]=a.useState([]),[re,Z]=a.useState(void 0),ye=re??d,[ie,Ie]=a.useState(null),[pe,Ue]=a.useState(null),[dt,ht]=a.useState(null);a.useEffect(()=>{h&&ye&&Ge(!0)},[h,ye]),a.useEffect(()=>{if(!h||ye)return;let H=!1;return vh(r).then(Se=>{if(H)return;const Le=Se.filter(gt=>gt.type==="mission_interview"&&(gt.status==="awaiting_input"||gt.status==="error"));Xe(Le)}).catch(Se=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Se)}),()=>{H=!0}},[h,r,ye]),a.useEffect(()=>{if(!h||!c)return;let H=!1;return ni(c).then(Se=>{if(!(H||!Se))try{const Le=JSON.parse(Se.inputPayload||"{}");Le.targetId&&Le.targetType&&Ie({type:Le.targetType,id:Le.targetId,title:Le.targetTitle||Se.title,resumeSessionId:c})}catch{Ie({type:"milestone",id:"",title:Se.title,resumeSessionId:c})}}).catch(Se=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Se),u?.())}),()=>{H=!0}},[h,c,u]);const[ue,te]=a.useState(null),[ke,Ne]=a.useState(new Map),[Ze,xe]=a.useState(null),[st,Ee]=a.useState({title:"",assertion:"",status:"pending"}),[He,ce]=a.useState(!1),[qe,We]=a.useState(null),[Pe,nt]=a.useState(new Map),[kt,yt]=a.useState(new Set),[Ct,Et]=a.useState(new Set),[Pt,It]=a.useState(null),[bt,_t]=a.useState(new Map),[Ve,ft]=a.useState(null),[Fe,lt]=a.useState(null),[be,U]=a.useState(!0),[we,rt]=a.useState(new Set),[xt,je]=a.useState(new Map),[Ke,pt]=a.useState(null),[Ht,fn]=a.useState(new Map),[hn,Jn]=a.useState(null),[Ot,yn]=a.useState(new Map),[tn,dn]=a.useState(new Map),[nn,Cn]=a.useState("structure"),[kn,jn]=a.useState([]),Yn=a.useRef([]),un=a.useRef([]),$t=a.useRef(null),wn=a.useRef(null),On=a.useRef("structure"),Nn=a.useRef("all"),[Bn,rs]=a.useState(!1),[Vt,_n]=a.useState(0),[x,F]=a.useState("all"),[ne,ae]=a.useState(new Set),oe=a.useRef(null),ge=a.useRef(null);un.current=g,$t.current=f,wn.current=Ve,On.current=nn,Nn.current=x;const et=a.useCallback((H="auto")=>{const Se=ge.current;if(Se&&typeof Se.scrollIntoView=="function"){Se.scrollIntoView({block:"end",behavior:H});return}const Le=oe.current;Le&&(Le.scrollTop=Le.scrollHeight)},[]),jt=a.useCallback(()=>{const H=oe.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),Jt=a.useCallback(async H=>{if(H.length===0){dn(new Map);return}const Se=await Gy(r);dn(Le=>{const gt=new Map(Le);for(const[Yt,Mt]of Object.entries(Se))hN(Mt)&>.set(Yt,Mt);return gt})},[r]),Je=a.useCallback(async()=>{try{y(!0);const H=await Hy(r);p(H),Jt(H)}catch(H){i(fe(H)||"Failed to load missions","error")}finally{y(!1)}},[i,r,Jt]),ot=a.useCallback(async H=>{try{A(!0);const Se=await bh(H,r);if(b(Se),Se.milestones.length>0){const Le=Se.milestones[0].id;ft(Le),U(!0),ee(new Set([Le])),fl(Le,r).then(gt=>{Ne(Yt=>{const Mt=new Map(Yt);return Mt.set(Le,gt),Mt})}).catch(()=>{}),gl(Le,r).then(gt=>{_t(Yt=>{const Mt=new Map(Yt);return Mt.set(Le,gt),Mt})}).catch(()=>{}),Se.milestones[0].slices.length>0&&T(new Set([Se.milestones[0].slices[0].id]))}else ft(null),lt(null)}catch(Se){i(fe(Se)||"Failed to load mission details","error")}finally{A(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Ve){lt(null);return}let H=!1;return lt(null),ud(Ve,r).then(Se=>{if(!H){if(!Sl(Se)){lt(null);return}lt(Se),_t(Le=>{const gt=new Map(Le);return gt.set(Ve,Se.rollup),gt})}}).catch(()=>{H||lt(null)}),()=>{H=!0}},[h,Ve,r]),a.useEffect(()=>{U(!0)},[Ve]);const Un=a.useCallback(H=>{!H||H!==wn.current||ud(H,r).then(Se=>{wn.current!==H||!Sl(Se)||(lt(Se),_t(Le=>{const gt=new Map(Le);return gt.set(H,Se.rollup),gt}))}).catch(()=>{})},[r]),le=a.useCallback(async(H,Se)=>{const Le=Se?.append??!1,gt=Le?Yn.current.length:0;Le||(rs(!0),ae(new Set));try{const Yt=await Ky(H,{limit:50,offset:gt,eventType:void 0},r),Mt=Yt.events.filter(Bt=>Gd(Bt.eventType,x));jn(Bt=>{if(!Le)return Mt;const Ye=new Set(Bt.map(vt=>vt.id)),tt=[...Bt];for(const vt of Mt)Ye.has(vt.id)||tt.push(vt);return tt}),_n(Yt.total),Le||requestAnimationFrame(()=>{et("auto")})}catch(Yt){i(fe(Yt)||"Failed to load mission activity","error")}finally{Le||rs(!1)}},[i,x,r,et]);a.useEffect(()=>{Yn.current=kn},[kn]),a.useEffect(()=>{h&&(Je(),b(null),ft(null),lt(null),jn([]),_n(0),Cn("structure"),F("all"),ae(new Set))},[h,Je]);const $e=a.useRef(null);a.useEffect(()=>{h&&m&&$e.current!==m&&g.length>0&&($e.current=m,ot(m))},[h,m,g,ot]),a.useEffect(()=>{h||($e.current=null)},[h]),a.useEffect(()=>{!h||!f||nn!=="activity"||le(f.id)},[nn,h,le,f,x]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const Se=`/api/events${H.size>0?`?${H.toString()}`:""}`,Le=()=>{Jt(un.current)},gt=Rn=>{Le();const cn=Rn;if(cn.data)try{const Tt=JSON.parse(cn.data);Tt?.id&&p(ui=>ui.map(vs=>vs.id===Tt.id?{...vs,...Tt}:vs))}catch{}$t.current&&ot($t.current.id)},Yt=Rn=>{Le(),$t.current&&ot($t.current.id)},Mt=()=>{Le(),$t.current&&ot($t.current.id)},Bt=Rn=>{Le(),$t.current&&ot($t.current.id)},Ye=Rn=>{const cn=Rn;if(cn.data)try{const Tt=JSON.parse(cn.data);Tt&&Tt.featureId&&(ci(Tt.featureId),Mi(Tt.featureId),Tt.milestoneId&&Un(Tt.milestoneId))}catch{}},tt=Rn=>{const cn=Rn;if(cn.data)try{const Tt=JSON.parse(cn.data);Tt&&Tt.featureId&&(ci(Tt.featureId),Mi(Tt.featureId),Tt.milestoneId&&Un(Tt.milestoneId),$t.current&&ot($t.current.id))}catch{}},vt=Rn=>{const cn=Rn;if(cn.data)try{const Tt=JSON.parse(cn.data);Tt&&Tt.milestoneId&&(Js(Tt.milestoneId),Un(Tt.milestoneId))}catch{}},Qt=Rn=>{const cn=Rn;if(cn.data)try{const Tt=JSON.parse(cn.data);Tt&&Tt.milestoneId&&(li(Tt.milestoneId),Js(Tt.milestoneId),Un(Tt.milestoneId))}catch{}};return Bs(Se,{events:{"mission:updated":gt,"slice:updated":Yt,"feature:updated":Mt,"milestone:updated":Bt,"mission:event":Rn=>{Le();const cn=$t.current;if(!cn||On.current!=="activity")return;const Tt=jt(),ui=Rn;if(ui.data)try{const vs=JSON.parse(ui.data);if(!pN(vs)||vs.missionId!==cn.id||!Gd(vs.eventType,Nn.current))return;jn(qs=>{const ml=qs.filter(hl=>hl.id!==vs.id);return[vs,...ml].slice(0,100)}),_n(qs=>qs+1),Tt&&requestAnimationFrame(()=>{const qs=oe.current;qs&&(qs.scrollTop=0)})}catch{}},"validator-run:started":Ye,"validator-run:completed":tt,"milestone:validation:updated":vt,"assertion:created":Qt,"assertion:updated":Qt,"assertion:deleted":Qt,"assertion:linked":Qt,"assertion:unlinked":Qt,"fix-feature:created":Rn=>{const cn=Rn;if(cn.data)try{const Tt=JSON.parse(cn.data);if(Tt&&Tt.sourceFeatureId){ci(Tt.sourceFeatureId);const ui=Tt?.feature?.sliceId,vs=$t.current;if(ui&&vs){const qs=vs.milestones.find(ml=>ml.slices.some(hl=>hl.id===ui));qs&&Un(qs.id)}$t.current&&ot($t.current.id)}}catch{}}}})},[h,jt,ot,Jt,r,Un]);const ut=a.useCallback(()=>{_(!0),M(null),R(kl)},[]),wt=a.useCallback(H=>{M(H.id),_(!1),R({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),St=a.useCallback(()=>{M(null),_(!1),R(kl)},[]),ln=a.useCallback(async()=>{if(!w.title.trim()){i("Mission title is required","error");return}try{if(I(!0),j)await qy({title:w.title.trim(),description:w.description.trim()||void 0,autopilotEnabled:w.autopilotEnabled},r),i("Mission created","success");else if(N){const H={title:w.title.trim(),description:w.description.trim()||void 0,status:w.status,autopilotEnabled:w.autopilotEnabled};w.autopilotEnabled&&(H.autoAdvance=!0),await Vy(N,H,r),i("Mission updated","success"),f?.id===N&&await ot(N)}await Je(),St()}catch(H){i(fe(H)||"Failed to save mission","error")}finally{I(!1)}},[w,j,N,i,Je,ot,f,St,r]),on=a.useCallback(async H=>{try{await Wy(H,r),i("Mission deleted","success"),f?.id===H&&b(null),await Je(),te(null)}catch(Se){i(fe(Se)||"Failed to delete mission","error")}},[i,Je,f,r]),mn=a.useCallback(()=>{O(!0),Y(null),G(jl)},[]),pn=a.useCallback(H=>{Y(H.id),O(!1),G({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),gn=a.useCallback(()=>{Y(null),O(!1),G(jl)},[]),En=a.useCallback(async()=>{if(!K.title.trim()){i("Milestone title is required","error");return}try{I(!0),P&&f?(await Jy(f.id,{title:K.title.trim(),description:K.description.trim()||void 0,dependencies:K.dependencies},r),i("Milestone created","success")):S&&(await Yy(S,{title:K.title.trim(),description:K.description.trim()||void 0,status:K.status,dependencies:K.dependencies},r),i("Milestone updated","success")),await ot(f.id),gn()}catch(H){i(fe(H)||"Failed to save milestone","error")}finally{I(!1)}},[K,P,S,f,i,ot,gn,w.title,r]),ls=a.useCallback(async H=>{try{await Qy(H,r),i("Milestone deleted","success"),await ot(f.id),te(null)}catch(Se){i(fe(Se)||"Failed to delete milestone","error")}},[i,ot,f,r]),Hn=a.useCallback(H=>{ft(H),U(!0),ee(Se=>{const Le=new Set(Se);return!Le.has(H)?(Le.add(H),fl(H,r).then(Yt=>{Ne(Mt=>{const Bt=new Map(Mt);return Bt.set(H,Yt),Bt})}).catch(()=>{}),gl(H,r).then(Yt=>{_t(Mt=>{const Bt=new Map(Mt);return Bt.set(H,Yt),Bt})}).catch(()=>{})):Le.delete(H),Le})},[r]),Mn=a.useCallback(H=>{he(H),J(!0),C(null),de(wl)},[]),Tn=a.useCallback(H=>{C(H.id),J(!1),de({title:H.title,description:H.description||"",status:H.status})},[]),Qn=a.useCallback(()=>{C(null),J(!1),he(null),de(wl)},[]),bn=a.useCallback(async()=>{if(!V.title.trim()){i("Slice title is required","error");return}try{I(!0),B&&D?(await Xy(D,{title:V.title.trim(),description:V.description.trim()||void 0},r),i("Slice created","success")):X&&(await Zy(X,{title:V.title.trim(),description:V.description.trim()||void 0,status:V.status},r),i("Slice updated","success")),await ot(f.id),Qn()}catch(H){i(fe(H)||"Failed to save slice","error")}finally{I(!1)}},[V,B,X,D,f,i,ot,Qn,r]),qn=a.useCallback(async H=>{try{await ek(H,r),i("Slice deleted","success"),await ot(f.id),te(null)}catch(Se){i(fe(Se)||"Failed to delete slice","error")}},[i,ot,f,r]),fs=a.useCallback(async H=>{try{await tk(H,r),i("Slice activated","success"),await ot(f.id)}catch(Se){i(fe(Se)||"Failed to activate slice","error")}},[i,ot,f,r]),Xn=a.useCallback(H=>{T(Se=>{const Le=new Set(Se);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),gs=a.useCallback(H=>{De(H),Me(!0),W(null),Re(Nl)},[]),$n=a.useCallback(H=>{W(H.id),Me(!1),Re({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),se=a.useCallback(()=>{W(null),Me(!1),De(null),Re(Nl)},[]),it=a.useCallback(async()=>{if(!me.title.trim()){i("Feature title is required","error");return}try{I(!0),ve&&_e?(await nk(_e,{title:me.title.trim(),description:me.description.trim()||void 0,acceptanceCriteria:me.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):q&&(await sk(q,{title:me.title.trim(),description:me.description.trim()||void 0,acceptanceCriteria:me.acceptanceCriteria.trim()||void 0,status:me.status},r),i("Feature updated","success")),await ot(f.id),se()}catch(H){i(fe(H)||"Failed to save feature","error")}finally{I(!1)}},[me,ve,q,_e,f,i,ot,se,r]),mt=a.useCallback(async H=>{try{await ik(H,r),i("Feature deleted","success"),await ot(f.id),te(null)}catch(Se){i(fe(Se)||"Failed to delete feature","error")}},[i,ot,f,r]),Rt=a.useCallback(async()=>{if(!Oe||!Be.trim()){i("Task ID is required","error");return}try{await ak(Oe,Be.trim(),r),i("Feature linked to task","success"),await ot(f.id),ze(null),Ae("")}catch(H){i(fe(H)||"Failed to link feature to task","error")}},[Oe,Be,i,ot,f,r]),Cs=a.useCallback(async H=>{try{await rk(H,r),i("Feature unlinked from task","success"),await ot(f.id)}catch(Se){i(fe(Se)||"Failed to unlink feature","error")}},[i,ot,f,r]),bs=a.useCallback(async H=>{try{I(!0),await lk(H,void 0,void 0,r),i("Feature triaged — task created","success"),await ot(f.id)}catch(Se){i(fe(Se)||"Failed to triage feature","error")}finally{I(!1)}},[i,ot,f,r]),rl=a.useCallback(async H=>{ht(H);try{const Se=await Dk(H,r);Ue({featureId:H,enrichedDescription:Se.description})}catch{await bs(H)}finally{ht(null)}},[bs,r]),Za=a.useCallback(async()=>{pe&&(Ue(null),await bs(pe.featureId))},[bs,pe]),ll=a.useCallback(()=>{Ue(null)},[]),ol=a.useCallback(async H=>{try{I(!0);const Se=await ok(H,r);i(`Triaged ${Se.count} feature${Se.count!==1?"s":""}`,"success"),await ot(f.id)}catch(Se){i(fe(Se)||"Failed to triage slice features","error")}finally{I(!1)}},[i,ot,f,r]),li=a.useCallback(async H=>{try{const Se=await fl(H,r);Ne(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch{}},[r]),Js=a.useCallback(async H=>{try{const Se=await gl(H,r);_t(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch{}},[r]),kc=a.useCallback(async H=>{if(!st.title.trim()||!st.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await ck(H,{title:st.title.trim(),assertion:st.assertion.trim(),status:st.status},r),i("Assertion created","success"),await li(H),await Js(H),ce(!1),Ee({title:"",assertion:"",status:"pending"})}catch(Se){i(fe(Se)||"Failed to create assertion","error")}finally{I(!1)}},[st,i,li,Js,r]),Hs=a.useCallback(H=>{xe(H.id),Ee({title:H.title,assertion:H.assertion,status:H.status})},[]),oi=a.useCallback(()=>{xe(null),ce(!1),Ee({title:"",assertion:"",status:"pending"})},[]),cl=a.useCallback(async(H,Se)=>{if(!st.title.trim()||!st.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await dk(H,{title:st.title.trim(),assertion:st.assertion.trim(),status:st.status},r),i("Assertion updated","success"),await li(Se),await Js(Se),oi()}catch(Le){i(fe(Le)||"Failed to update assertion","error")}finally{I(!1)}},[st,i,li,Js,oi,r]),_s=a.useCallback(async H=>{try{const Se=await hk(H,r);nt(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch{}},[r]),jc=a.useCallback(async H=>{const Se=qe!==H;We(Le=>Le===H?null:H),Se&&await _s(H)},[qe,_s]),wc=a.useCallback(H=>{We(H),_s(H),requestAnimationFrame(()=>{const Se=document.querySelector(`[data-mission-assertion-id="${H}"]`);Se instanceof HTMLElement&&typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({behavior:"smooth",block:"center"})})},[_s]),ff=a.useCallback(async(H,Se)=>{try{yt(Le=>new Set(Le).add(Se)),await uk(H,Se,r),i("Feature linked to assertion","success"),await _s(Se),It(null)}catch(Le){i(fe(Le)||"Failed to link feature","error")}finally{yt(Le=>{const gt=new Set(Le);return gt.delete(Se),gt})}},[i,_s,r]),gf=a.useCallback(async(H,Se)=>{const Le=`${H}-${Se}`;try{Et(gt=>new Set(gt).add(Le)),await mk(H,Se,r),i("Feature unlinked from assertion","success"),await _s(Se)}catch(gt){i(fe(gt)||"Failed to unlink feature","error")}finally{Et(gt=>{const Yt=new Set(gt);return Yt.delete(Le),Yt})}},[i,_s,r]),bf=a.useCallback(async H=>{try{rt(Le=>new Set(Le).add(H)),await pk(H,r),i("Validation triggered","success");const Se=await md(H,r);je(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch(Se){i(fe(Se)||"Failed to trigger validation","error")}finally{rt(Se=>{const Le=new Set(Se);return Le.delete(H),Le})}},[i,r]),ci=a.useCallback(async H=>{try{const Se=await md(H,r);je(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch{}},[r]),Mi=a.useCallback(async H=>{try{const Se=await fk(H,{limit:10},r);fn(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch{}},[r]),er=a.useCallback(H=>{const Se=$t.current;if(Se){for(const Le of Se.milestones)for(const gt of Le.slices)if(gt.features.find(Mt=>Mt.id===H)){ee(Mt=>{const Bt=new Set(Mt);return Bt.add(Le.id),Bt}),T(Mt=>{const Bt=new Set(Mt);return Bt.add(gt.id),Bt}),pt(H),ft(Le.id),ci(H),Mi(H),requestAnimationFrame(()=>{const Mt=document.querySelector(`[data-mission-feature-id="${H}"]`);Mt instanceof HTMLElement&&typeof Mt.scrollIntoView=="function"&&Mt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[ci,Mi]),Nc=a.useCallback(async H=>{try{const Se=await gk(H,r);yn(Le=>{const gt=new Map(Le);return gt.set(H,Se),gt})}catch{}},[r]),xf=a.useCallback(async H=>{Ke===H?pt(null):(pt(H),await ci(H),await Mi(H))},[Ke,ci,Mi]),vf=a.useCallback(async H=>{hn===H?Jn(null):(Jn(H),await Nc(H))},[hn,Nc]),Sc=a.useCallback(async H=>{try{await bk(H,r),i("Mission resumed","success"),await ot(H),Je()}catch(Se){i(fe(Se)||"Failed to resume mission","error")}},[i,ot,Je,r]),Cc=a.useCallback(async H=>{try{const Le=(await xk(H,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Le} task${Le!==1?"s":""} paused)`,"success"),await ot(H),Je()}catch(Se){i(fe(Se)||"Failed to stop mission","error")}},[i,ot,Je,r]),Ec=a.useCallback(async H=>{try{await vk(H,r),i("Mission started — first slice activated","success"),await ot(H),Je()}catch(Se){i(fe(Se)||"Failed to start mission","error")}},[i,ot,Je,r]),yf=a.useCallback(async(H,Se)=>{try{await yk(H,{enabled:Se},r),i(Se?"Autopilot enabled":"Autopilot disabled","success"),await ot(H),Je()}catch(Le){i(fe(Le)||"Failed to update autopilot","error")}},[i,ot,Je,r]),Mc=a.useCallback(H=>{Cn("structure"),ft(null),lt(null),jn([]),_n(0),F("all"),ae(new Set),ot(H.id)},[ot]),kf=a.useCallback(()=>{b(null),ft(null),lt(null),Cn("structure"),jn([]),_n(0),F("all"),ae(new Set),Je()},[Je]),dl=kn.length<Vt,Ai=f?.autopilotState??"inactive",Ac=Ai==="watching"||Ai==="activating",Pc=bN(Ai,f?.lastAutopilotActivityAt),tr=a.useMemo(()=>!Fe||!Ve||!Sl(Fe)?null:Fe.rollup.milestoneId===Ve?Fe:null,[Ve,Fe]),jf=a.useMemo(()=>{const H=new Map;for(const Se of tr?.validationTelemetry.validationRounds??[]){const Le=H.get(Se.featureId);(!Le||Se.startedAt>Le.startedAt)&&H.set(Se.featureId,Se)}return H},[tr]),wf=a.useCallback(()=>{!f||Bn||!dl||le(f.id,{append:!0})},[Bn,dl,le,f]),Nf=a.useCallback(H=>{ae(Se=>{const Le=new Set(Se);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),ul=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),ln())},[ln]),_c=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),En())},[En]),Tc=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),bn())},[bn]),Rc=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),it())},[it]),Sf=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const H=Se=>{Se.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const Ic=e.jsxs("div",{ref:Sf,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:[e.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[e.jsxs("div",{className:"mission-manager__header-title",children:[f?e.jsx("button",{className:"mission-manager__back-btn",onClick:kf,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:e.jsx(Ho,{size:18})}):null,e.jsx(ns,{size:18,className:"mission-manager__header-icon"}),e.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&e.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:e.jsx(Ft,{size:18})})]}),e.jsx("div",{className:"mission-manager__body",children:v?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(ct,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading missions..."})]}):k?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(ct,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading mission details..."})]}):f?e.jsxs("div",{className:"mission-detail",children:[e.jsxs("div",{className:"mission-detail__header",children:[e.jsxs("div",{className:"mission-detail__title-row",children:[e.jsxs("div",{className:"mission-detail__title-text",children:[Ac&&e.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),e.jsx("h3",{className:"mission-detail__title",children:f.title})]}),e.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(ma[f.status]||ma.planning).bg,color:(ma[f.status]||ma.planning).text},children:f.status})]}),f.description&&e.jsx("p",{className:"mission-detail__description",children:f.description}),e.jsx("div",{className:"mission-detail__meta",children:e.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),e.jsxs("div",{className:"mission-detail__autopilot",children:[e.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[e.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[e.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:H=>yf(f.id,H.target.checked),"aria-label":"Autopilot"}),e.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:e.jsx("span",{className:"mission-toggle__thumb"})}),e.jsxs("span",{className:"mission-toggle__label",children:[e.jsx(Sn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),e.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(lr[Ai]||lr.inactive).bg,color:(lr[Ai]||lr.inactive).text},"data-testid":"autopilot-state-badge",children:[Ac&&e.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ai]})]}),Pc&&e.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Pc})]}),e.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Cc(f.id),title:"Stop mission","aria-label":"Stop mission",children:e.jsx(cs,{size:14})}),f.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Sc(f.id),title:"Resume mission","aria-label":"Resume mission",children:e.jsx(an,{size:14})}),f.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ec(f.id),title:"Start mission","aria-label":"Start mission",children:e.jsx(an,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>wt(f),title:"Edit mission","aria-label":"Edit mission",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:e.jsx(Ut,{size:14})})]})]}),N===f.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:w.title,onChange:H=>R({...w,title:H.target.value}),onKeyDown:ul,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:w.description,onChange:H=>R({...w,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:w.status,onChange:H=>R({...w,status:H.target.value}),children:[e.jsx("option",{value:"planning",children:"Planning"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"blocked",children:"Blocked"}),e.jsx("option",{value:"complete",children:"Complete"}),e.jsx("option",{value:"archived",children:"Archived"})]}),e.jsxs("label",{className:"mission-checkbox",children:[e.jsx("input",{type:"checkbox",checked:w.autopilotEnabled,onChange:H=>R({...w,autopilotEnabled:H.target.checked})}),e.jsx(Sn,{size:12})," Autopilot"]})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ln,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[e.jsx("button",{className:`mission-btn ${nn==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Cn("structure"),role:"tab","aria-selected":nn==="structure","data-testid":"mission-tab-structure",children:"Structure"}),e.jsxs("button",{className:`mission-btn ${nn==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Cn("activity"),role:"tab","aria-selected":nn==="activity","data-testid":"mission-tab-activity",children:["Activity (",Vt,")"]})]}),nn==="structure"?e.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(H=>{const Se=tr?.rollup.milestoneId===H.id?tr:null,Le=Se?.rollup??bt.get(H.id),gt=Se?.validationTelemetry.validationRounds??[],Yt=Se?.fixFeatures??[],Mt=Vd[Le?.state??"not_started"]??Vd.not_started,Bt=Le&&(Le.state==="blocked"||Le.state==="failed")?Se?.validationTelemetry.validationRounds.find(Ye=>Ye.blockedReason)?.blockedReason:void 0;return e.jsxs("div",{className:"mission-milestone",children:[e.jsxs("div",{className:"mission-milestone__header",onClick:()=>Hn(H.id),children:[e.jsx("button",{className:"mission-milestone__expand",children:L.has(H.id)?e.jsx(Lt,{size:16}):e.jsx(rn,{size:16})}),e.jsx(ki,{size:16,className:"mission-milestone__icon"}),e.jsx("span",{className:"mission-milestone__title",children:H.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Hd[H.status].bg,color:Hd[H.status].text},children:H.status}),e.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),e.jsx(Wd,{state:dN(H.interviewState)}),Le&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Mt.bg,color:Mt.text},title:"Validation state",children:Kd(Le.state)}),Le.totalAssertions>0&&e.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Le.passedAssertions??0} of ${Le.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Le.passedAssertions??0)/Le.totalAssertions*100}%`,backgroundColor:(Le.passedAssertions??0)===Le.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>Ie({type:"milestone",id:H.id,title:H.title}),title:"Plan milestone","aria-label":"Plan milestone",children:e.jsx(vi,{size:14})}),e.jsxs("div",{className:"mission-milestone__actions",onClick:Ye=>Ye.stopPropagation(),children:[e.jsx("button",{className:"mission-icon-btn",onClick:()=>Mn(H.id),title:"Add slice",children:e.jsx(qt,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>pn(H),title:"Edit milestone",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"milestone",id:H.id}),title:"Delete milestone",children:e.jsx(Ut,{size:14})})]})]}),L.has(H.id)&&e.jsxs("div",{className:"mission-milestone__body",children:[(P||S===H.id)&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:Ye=>G({...K,title:Ye.target.value}),onKeyDown:_c,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:Ye=>G({...K,description:Ye.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:En,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),S?"Update":"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gn,children:"Cancel"})]})]}),Se&&e.jsxs("div",{className:"mission-validation-telemetry",children:[e.jsxs("div",{className:"mission-validation-telemetry__header",children:[e.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),e.jsxs("span",{className:"mission-validation-telemetry__meta",children:[Se.validationTelemetry.totalRuns," rounds",Se.validationTelemetry.lastValidatorStatus?` · Last ${Se.validationTelemetry.lastValidatorStatus}`:""]})]}),Bt&&e.jsxs("div",{className:"mission-blocked-reason",children:[e.jsx("strong",{children:"Blocked reason:"})," ",Bt]}),gt.length>0&&e.jsxs("div",{className:"mission-validation-rounds",children:[e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>U(Ye=>!Ye),title:be?"Hide validation rounds":"Show validation rounds",children:[be?e.jsx(Lt,{size:12}):e.jsx(rn,{size:12}),"Validation rounds (",gt.length,")"]}),be&&e.jsx("div",{className:"mission-validation-rounds__list",children:gt.map(Ye=>e.jsxs("div",{className:"mission-validation-round",children:[e.jsxs("div",{className:"mission-validation-round__header",children:[e.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Ye.validatorStatus}`,children:Ye.validatorStatus}),e.jsx("span",{className:"mission-validation-round__feature",children:Ye.featureTitle}),e.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ye.implementationAttempt," · validator #",Ye.validatorAttempt]})]}),e.jsxs("div",{className:"mission-validation-round__links",children:[e.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ye.failedAssertionIds.length>0?e.jsx("div",{className:"mission-validation-round__chip-list",children:Ye.failedAssertionIds.map(tt=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>wc(tt),title:`Jump to assertion ${tt}`,children:tt},`${Ye.roundId}-${tt}`))}):e.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),e.jsxs("div",{className:"mission-validation-round__links",children:[e.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ye.generatedFixFeatureIds.length>0?e.jsx("div",{className:"mission-validation-round__chip-list",children:Ye.generatedFixFeatureIds.map(tt=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>er(tt),title:`Jump to fix feature ${tt}`,children:tt},`${Ye.roundId}-${tt}`))}):e.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ye.blockedReason&&e.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ye.blockedReason})]},Ye.roundId))})]}),Yt.length>0&&e.jsxs("div",{className:"mission-fix-features",children:[e.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),e.jsx("div",{className:"mission-fix-features__list",children:Yt.map(Ye=>e.jsxs("div",{className:"mission-fix-feature",children:[e.jsxs("div",{className:"mission-fix-feature__header",children:[e.jsx("button",{className:"mission-fix-feature__title",onClick:()=>er(Ye.id),title:`Jump to feature ${Ye.id}`,children:Ye.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:rr[Ye.status].bg,color:rr[Ye.status].text},children:Ye.status}),Ye.loopState&&e.jsx("span",{className:`mission-loop-state mission-loop-state--${Ye.loopState}`,children:Ye.loopState})]}),e.jsxs("div",{className:"mission-fix-feature__meta",children:[e.jsx("span",{children:"Source:"}),e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>er(Ye.sourceFeatureId),title:`Jump to source feature ${Ye.sourceFeatureId}`,children:Ye.sourceFeatureId}),e.jsx("span",{children:"Run:"}),e.jsx("span",{className:"mission-fix-feature__run",children:Ye.runId})]}),Ye.failedAssertionIds.length>0&&e.jsxs("div",{className:"mission-fix-feature__assertions",children:[e.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),e.jsx("div",{className:"mission-validation-round__chip-list",children:Ye.failedAssertionIds.map(tt=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>wc(tt),title:`Jump to assertion ${tt}`,children:tt},`${Ye.id}-${tt}`))})]})]},Ye.id))})]})]}),e.jsxs("div",{className:"mission-slices",children:[H.slices.map(Ye=>e.jsxs("div",{className:"mission-slice",children:[e.jsxs("div",{className:"mission-slice__header",onClick:()=>Xn(Ye.id),children:[e.jsx("button",{className:"mission-slice__expand",children:$.has(Ye.id)?e.jsx(Lt,{size:16}):e.jsx(rn,{size:16})}),e.jsx(go,{size:16,className:"mission-slice__icon"}),e.jsx("span",{className:"mission-slice__title",children:Ye.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:qd[Ye.status].bg,color:qd[Ye.status].text},children:Ye.status}),e.jsxs("span",{className:"mission-slice__count",children:[Ye.features?.length||0," features"]}),e.jsx(Wd,{state:Ye.planState??"not_started"}),Ye.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>Ie({type:"slice",id:Ye.id,title:Ye.title}),title:"Plan slice","aria-label":"Plan slice",children:e.jsx(vi,{size:14})}),e.jsxs("div",{className:"mission-slice__actions",onClick:tt=>tt.stopPropagation(),children:[Ye.status==="pending"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>fs(Ye.id),title:"Activate slice",children:e.jsx(an,{size:14})}),Ye.status==="active"&&Ye.features?.some(tt=>tt.status==="defined")&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>ol(Ye.id),title:"Triage all features",disabled:E,children:E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Sn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>gs(Ye.id),title:"Add feature",children:e.jsx(qt,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Tn(Ye),title:"Edit slice",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"slice",id:Ye.id}),title:"Delete slice",children:e.jsx(Ut,{size:14})})]})]}),$.has(Ye.id)&&e.jsxs("div",{className:"mission-slice__body",children:[B&&D===H.id&&!X&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:V.title,onChange:tt=>de({...V,title:tt.target.value}),onKeyDown:Tc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:tt=>de({...V,description:tt.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bn,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),X===Ye.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:V.title,onChange:tt=>de({...V,title:tt.target.value}),onKeyDown:Tc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:tt=>de({...V,description:tt.target.value}),rows:2}),e.jsxs("select",{value:V.status,onChange:tt=>de({...V,status:tt.target.value}),children:[e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"complete",children:"Complete"})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bn,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-features",children:[Ye.features?.map(tt=>e.jsxs("div",{className:"mission-feature","data-mission-feature-id":tt.id,children:[e.jsxs("div",{className:"mission-feature__header",children:[e.jsx("button",{className:"mission-feature__expand",onClick:()=>xf(tt.id),title:Ke===tt.id?"Collapse details":"Expand to show run history",children:Ke===tt.id?e.jsx(Lt,{size:14}):e.jsx(rn,{size:14})}),e.jsx(uo,{size:14,className:"mission-feature__icon"}),e.jsx("span",{className:"mission-feature__title",children:tt.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:rr[tt.status].bg,color:rr[tt.status].text},children:tt.status}),tt.loopState&&tt.loopState!=="idle"&&e.jsxs("span",{className:`mission-loop-state mission-loop-state--${tt.loopState}`,title:`Loop state: ${tt.loopState}`,children:[tt.loopState==="implementing"&&"⏳",tt.loopState==="validating"&&"🔄",tt.loopState==="needs_fix"&&"🔧",tt.loopState==="passed"&&"✅",tt.loopState==="blocked"&&"🚫"]}),tt.generatedFromFeatureId&&e.jsx("button",{className:"mission-feature__lineage",onClick:()=>er(tt.generatedFromFeatureId),title:`Generated from feature: ${tt.generatedFromFeatureId}`,children:"🔗 Fix"}),(tt.loopState==="validating"||tt.loopState==="needs_fix")&&(()=>{const vt=xt.get(tt.id),Qt=jf.get(tt.id),xs=vt?.implementationAttemptCount??Qt?.implementationAttempt??tt.implementationAttemptCount??0,di=vt?.retryBudgetRemaining??Math.max(0,cN-xs);return e.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",xs," · ",di," ",di===1?"retry":"retries"," left"]})})(),tt.loopState==="implementing"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>bf(tt.id),title:"Validate feature",disabled:we.has(tt.id),children:we.has(tt.id)?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Ln,{size:14})}),tt.taskId&&e.jsx("span",{className:"mission-feature__task-link",onClick:()=>l?.(tt.taskId),title:"Click to view task",children:tt.taskId}),e.jsxs("div",{className:"mission-feature__actions",children:[tt.status==="defined"&&!tt.taskId&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>rl(tt.id),title:"Triage — create task",disabled:E||dt===tt.id,children:dt===tt.id?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Sn,{size:14})}),tt.taskId?e.jsx("button",{className:"mission-icon-btn",onClick:()=>Cs(tt.id),title:"Unlink task",children:e.jsx(Bc,{size:14})}):tt.status!=="defined"?e.jsx("button",{className:"mission-icon-btn",onClick:()=>ze(tt.id),title:"Link to task",children:e.jsx(Vi,{size:14})}):null,e.jsx("button",{className:"mission-icon-btn",onClick:()=>$n(tt),title:"Edit feature",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"feature",id:tt.id}),title:"Delete feature",children:e.jsx(Ut,{size:14})})]})]}),tt.description&&e.jsx("p",{className:"mission-feature__description",children:tt.description}),tt.acceptanceCriteria&&e.jsxs("p",{className:"mission-feature__criteria",children:[e.jsx("strong",{children:"Acceptance:"})," ",tt.acceptanceCriteria]}),pe?.featureId===tt.id&&e.jsxs("div",{className:"mission-triage-preview",children:[e.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),e.jsx("div",{className:"mission-triage-preview__content",children:pe.enrichedDescription}),e.jsxs("div",{className:"mission-triage-preview__actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:Za,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):null,"Create Task"]}),e.jsx("button",{className:"btn",onClick:ll,disabled:E,children:"Cancel"})]})]}),q===tt.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:me.title,onChange:vt=>Re({...me,title:vt.target.value}),onKeyDown:Rc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:me.description,onChange:vt=>Re({...me,description:vt.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:me.acceptanceCriteria,onChange:vt=>Re({...me,acceptanceCriteria:vt.target.value}),rows:2}),e.jsxs("select",{value:me.status,onChange:vt=>Re({...me,status:vt.target.value}),children:[e.jsx("option",{value:"defined",children:"Defined"}),e.jsx("option",{value:"triaged",children:"Triaged"}),e.jsx("option",{value:"in-progress",children:"In Progress"}),e.jsx("option",{value:"done",children:"Done"})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:it,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:se,children:"Cancel"})]})]}),Ke===tt.id&&e.jsxs("div",{className:"mission-feature__run-history",children:[e.jsx("div",{className:"mission-feature__run-history-header",children:e.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(Ht.get(tt.id)??[]).map(vt=>e.jsxs("div",{className:"mission-run",children:[e.jsxs("div",{className:"mission-run__header",onClick:()=>vf(vt.id),children:[e.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${vt.status}`,title:vt.status,children:vt.status}),e.jsx("span",{className:"mission-run__time",children:new Date(vt.startedAt).toLocaleString()}),vt.completedAt&&e.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(vt.completedAt).getTime()-new Date(vt.startedAt).getTime())/1e3),"s"]}),vt.triggerType&&e.jsx("span",{className:"mission-run__trigger",children:vt.triggerType}),e.jsx("button",{className:"mission-icon-btn",title:hn===vt.id?"Hide details":"Show details",children:hn===vt.id?e.jsx(Lt,{size:12}):e.jsx(rn,{size:12})})]}),hn===vt.id&&Ot.get(vt.id)&&e.jsxs("div",{className:"mission-run__details",children:[vt.summary&&e.jsx("p",{className:"mission-run__summary",children:vt.summary}),vt.blockedReason&&e.jsxs("p",{className:"mission-run__blocked-reason",children:[e.jsx("strong",{children:"Blocked:"})," ",vt.blockedReason]}),Ot.get(vt.id)?.failures&&Ot.get(vt.id).failures.length>0&&e.jsxs("div",{className:"mission-run__failures",children:[e.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ot.get(vt.id).failures.map(Qt=>e.jsxs("div",{className:"mission-run__failure",children:[e.jsx("span",{className:"mission-run__failure-message",children:Qt.message}),Qt.expected&&e.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Qt.expected]}),Qt.actual&&e.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Qt.actual]})]},Qt.id))]}),(!Ot.get(vt.id)?.failures||Ot.get(vt.id).failures.length===0)&&e.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},vt.id)),(!Ht.get(tt.id)||Ht.get(tt.id).length===0)&&e.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},tt.id)),ve&&_e===Ye.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:me.title,onChange:tt=>Re({...me,title:tt.target.value}),onKeyDown:Rc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:me.description,onChange:tt=>Re({...me,description:tt.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:me.acceptanceCriteria,onChange:tt=>Re({...me,acceptanceCriteria:tt.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:it,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:se,children:"Cancel"})]})]}),!ve&&(!Ye.features||Ye.features.length===0)&&e.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[e.jsx(uo,{size:16}),e.jsx("span",{children:"No fix features generated."})]})]})]})]},Ye.id)),H.slices.length===0&&!B&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(go,{size:16}),e.jsx("span",{children:"No slices yet"})]}),e.jsxs("div",{className:"mission-assertions",children:[e.jsxs("div",{className:"mission-assertions__header",children:[e.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Le&&e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Mt.bg,color:Mt.text},children:Kd(Le.state)}),Le&&Le.totalAssertions>0&&e.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Le.passedAssertions??0} of ${Le.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Le.passedAssertions??0)/Le.totalAssertions*100}%`,backgroundColor:(Le.passedAssertions??0)===Le.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>{ce(!0),xe(null),Ee({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:e.jsx(qt,{size:14})})]}),He&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:st.title,onChange:Ye=>Ee({...st,title:Ye.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:st.assertion,onChange:Ye=>Ee({...st,assertion:Ye.target.value}),rows:2}),e.jsxs("select",{value:st.status,onChange:Ye=>Ee({...st,status:Ye.target.value}),children:[e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"passed",children:"Passed"}),e.jsx("option",{value:"failed",children:"Failed"}),e.jsx("option",{value:"blocked",children:"Blocked"})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>kc(H.id),disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:oi,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(ke.get(H.id))?ke.get(H.id):[]).map(Ye=>e.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ye.id,children:[e.jsx("div",{className:"mission-assertion__header",children:Ze===Ye.id?e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:st.title,onChange:tt=>Ee({...st,title:tt.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text",value:st.assertion,onChange:tt=>Ee({...st,assertion:tt.target.value}),rows:2}),e.jsxs("select",{value:st.status,onChange:tt=>Ee({...st,status:tt.target.value}),children:[e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"passed",children:"Passed"}),e.jsx("option",{value:"failed",children:"Failed"}),e.jsx("option",{value:"blocked",children:"Blocked"})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>cl(Ye.id,H.id),disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Save"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:oi,children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(or[Ye.status]??or.pending).bg,color:(or[Ye.status]??or.pending).text},children:Ye.status}),e.jsx("span",{className:"mission-assertion__title",children:Ye.title}),(()=>{const vt=Pe.get(Ye.id)?.length??0;return vt>0?e.jsxs("span",{className:"mission-assertion__linked-count",title:`${vt} linked feature${vt!==1?"s":""}`,children:["(",vt," linked)"]}):null})(),e.jsx("button",{className:"mission-icon-btn",onClick:()=>jc(Ye.id),title:"Toggle details",children:qe===Ye.id?e.jsx(Lt,{size:14}):e.jsx(rn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Hs(Ye),title:"Edit assertion",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"assertion",id:Ye.id}),title:"Delete assertion",children:e.jsx(Ut,{size:14})})]})}),qe===Ye.id&&e.jsxs("div",{className:"mission-assertion__body",children:[e.jsx("p",{className:"mission-assertion__text",children:Ye.assertion}),e.jsxs("div",{className:"mission-assertion__linked-features",children:[e.jsxs("div",{className:"mission-assertion__linked-features-header",children:[e.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{qe!==Ye.id&&await jc(Ye.id),It(Pt===Ye.id?null:Ye.id)},title:"Link a feature",children:[e.jsx(Vi,{size:12}),"Link Feature"]})]}),Pt===Ye.id&&e.jsx("div",{className:"mission-assertion__feature-picker",children:e.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const tt=new Set((Pe.get(Ye.id)??[]).map(Qt=>Qt.id)),vt=[];return f?.milestones.forEach(Qt=>Qt.slices.forEach(xs=>vt.push(...xs.features.filter(di=>!tt.has(di.id))))),vt.length===0?e.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):vt.map(Qt=>e.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ff(Qt.id,Ye.id),disabled:kt.has(Ye.id),children:[e.jsx("span",{className:"mission-assertion__feature-picker-title",children:Qt.title}),kt.has(Ye.id)&&e.jsx(ct,{size:12,className:"spinner"})]},Qt.id))})()})}),(()=>{const tt=Pe.get(Ye.id)??[];return tt.length===0?e.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):tt.map(vt=>{const Qt=`${vt.id}-${Ye.id}`,xs=Ct.has(Qt);return e.jsxs("div",{className:"mission-assertion__linked-feature",children:[e.jsx("span",{className:"mission-assertion__linked-feature-title",children:vt.title}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>gf(vt.id,Ye.id),disabled:xs,title:"Unlink feature",children:xs?e.jsx(ct,{size:12,className:"spinner"}):e.jsx(Bc,{size:12})})]},vt.id)})})()]})]})]},Ye.id)),(!ke.get(H.id)||ke.get(H.id)?.length===0)&&!He&&e.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:e.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},H.id)}),f&&!P&&S===null&&e.jsxs("button",{className:"mission-add-btn",onClick:mn,children:[e.jsx(qt,{size:16}),"Add Milestone"]}),P&&S===null&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:H=>G({...K,title:H.target.value}),onKeyDown:_c,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:H=>G({...K,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:En,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gn,children:"Cancel"})]})]}),f.milestones.length===0&&!P&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(ki,{size:24}),e.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):e.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[e.jsxs("div",{className:"mission-detail__activity-controls",children:[e.jsxs("label",{className:"mission-detail__activity-filter",children:[e.jsx("span",{children:"Filter"}),e.jsxs("select",{value:x,onChange:H=>F(H.target.value),"data-testid":"mission-activity-filter",children:[e.jsx("option",{value:"all",children:"All events"}),e.jsx("option",{value:"errors",children:"Errors & warnings"}),e.jsx("option",{value:"state_changes",children:"State changes"}),e.jsx("option",{value:"tasks",children:"Task events"}),e.jsx("option",{value:"slices",children:"Slice & milestone events"}),e.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),e.jsxs("span",{className:"mission-detail__activity-count",children:[kn.length," of ",Vt]})]}),!Bn&&dl&&e.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wf,"data-testid":"mission-activity-load-more",children:"Load more"})}),Bn?e.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[e.jsx(ct,{size:18,className:"spinner"}),e.jsx("span",{children:"Loading mission activity..."})]}):kn.length===0?e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(Ns,{size:18}),e.jsx("span",{children:"No events yet."})]}):e.jsxs("div",{ref:oe,className:"mission-events","data-testid":"mission-activity-events",children:[kn.map(H=>{const Se=!!(H.metadata&&Object.keys(H.metadata).length>0),Le=ne.has(H.id);return e.jsxs("div",{className:"mission-event",children:[e.jsxs("div",{className:"mission-event__header",children:[e.jsx("span",{className:`mission-event__type ${fN(H.eventType)}`,children:gN(H.eventType)}),e.jsx("span",{className:"mission-event__time",children:Dr(H.timestamp)})]}),e.jsx("p",{className:"mission-event__description",children:H.description}),e.jsx("span",{className:"mission-event__timestamp",children:new Date(H.timestamp).toLocaleString()}),Se&&e.jsxs("div",{className:"mission-event__metadata",children:[e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Nf(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[Le?"Hide":"Show"," metadata"]}),Le&&e.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),e.jsx("div",{ref:ge})]})]})]}):e.jsxs("div",{className:"mission-list",children:[j&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:w.title,onChange:H=>R({...w,title:H.target.value}),onKeyDown:ul,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:w.description,onChange:H=>R({...w,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ln,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),g.map(H=>{const Se=H,Le=f,gt=Le&&Le.id===Se.id,Yt=ma[Se.status]||{bg:"",text:""},Mt=Se.summary,Bt=tn.get(Se.id),Ye=mN(Bt),tt=!!(Mt&&(Mt.totalMilestones>0||Mt.totalFeatures>0)),vt=Bt?.totalTasks??0,Qt=Bt?.tasksCompleted??0,xs=Bt?.tasksFailed??0,di=Bt?.estimatedCompletionPercent??Mt?.progressPercent??0,Rn=tt||vt>0||xs>0||!!Bt?.lastActivityAt,cn=Se.status==="active"&&(Bt?.currentMilestoneId||Bt?.currentSliceId)?"Current milestone/slice in progress":null;return e.jsxs("div",{className:`mission-list__item ${gt?"mission-list__item--selected":""}`,onClick:()=>Mc(H),children:[e.jsxs("div",{className:"mission-list__item-content",children:[e.jsxs("div",{className:"mission-list__item-header",children:[e.jsx(ns,{size:16,className:"mission-list__item-icon"}),e.jsx("span",{className:"mission-list__item-title",children:Se.title}),H.autopilotEnabled&&e.jsx("span",{title:"Autopilot enabled",children:e.jsx(Sn,{size:12,className:"mission-list__item-autopilot-icon"})}),e.jsx("span",{className:`mission-health-badge mission-health-badge--${Ye}`,"data-testid":`mission-health-badge-${Se.id}`,"aria-label":`Mission health: ${Ye}`}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yt.bg,color:Yt.text},children:Se.status})]}),Se.description&&e.jsx("p",{className:"mission-list__item-description",children:Se.description}),cn&&e.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",cn]}),Rn&&e.jsxs("div",{className:"mission-list__item-summary",children:[tt&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"mission-list__item-stat",children:[Mt.completedMilestones,"/",Mt.totalMilestones," milestones"]}),e.jsxs("span",{className:"mission-list__item-stat",children:[Mt.completedFeatures,"/",Mt.totalFeatures," features"]})]}),e.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Se.id}`,children:[Qt,"/",vt," tasks"]}),xs>0&&e.jsxs("button",{className:"mission-list__item-failed",onClick:Tt=>{Tt.stopPropagation(),Mc(H)},"data-testid":`mission-failed-${Se.id}`,title:"View mission failures",children:[xs," failed"]}),e.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Se.id}`,children:["Activity ",Dr(Bt?.lastActivityAt)]}),e.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Ye}`,children:e.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${di}%`}})})]})]}),e.jsxs("div",{className:"mission-list__item-actions",onClick:Tt=>Tt.stopPropagation(),children:[Se.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Cc(Se.id),title:"Stop mission",children:e.jsx(cs,{size:14})}),Se.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Sc(Se.id),title:"Resume mission",children:e.jsx(an,{size:14})}),Se.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ec(Se.id),title:"Start mission",children:e.jsx(an,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>wt(H),title:"Edit mission",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"mission",id:Se.id}),title:"Delete mission",children:e.jsx(Ut,{size:14})})]})]},Se.id)}),N&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:w.title,onChange:H=>R({...w,title:H.target.value}),onKeyDown:ul,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:w.description,onChange:H=>R({...w,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:w.status,onChange:H=>R({...w,status:H.target.value}),children:[e.jsx("option",{value:"planning",children:"Planning"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"blocked",children:"Blocked"}),e.jsx("option",{value:"complete",children:"Complete"}),e.jsx("option",{value:"archived",children:"Archived"})]}),e.jsxs("label",{className:"mission-checkbox",children:[e.jsx("input",{type:"checkbox",checked:w.autopilotEnabled,onChange:H=>R({...w,autopilotEnabled:H.target.checked})}),e.jsx(Sn,{size:12})," Autopilot"]})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ln,disabled:E,children:[E?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),g.length===0&&!j&&e.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[e.jsx(ns,{size:32}),e.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!j&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Te.length>0&&e.jsxs("div",{className:"mission-resume-prompt",children:[e.jsx(is,{size:16}),e.jsx("span",{children:Te.length===1?`Resume "${Te[0].title}"?`:`${Te.length} interview sessions pending`}),e.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Te.map(H=>e.jsxs("button",{className:"mission-add-btn",onClick:()=>{Z(H.id),Ge(!0),Xe([])},children:[H.status==="error"?e.jsx(vn,{size:14}):e.jsx(Ln,{size:14}),H.status==="error"?"Retry":"Resume"]},H.id))})]}),e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsxs("button",{className:"mission-add-btn",onClick:()=>Ge(!0),children:[e.jsx(Ln,{size:16}),"Plan with AI"]}),e.jsxs("button",{className:"mission-add-btn",onClick:ut,children:[e.jsx(qt,{size:16}),"New Mission"]})]})]})]})}),ue&&e.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:e.jsxs("div",{className:"mission-confirm-panel__content",children:[e.jsxs("p",{children:["Delete this ",ue.type,"? This cannot be undone."]}),e.jsxs("div",{className:"mission-confirm-panel__actions",children:[e.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{ue.type==="mission"?await on(ue.id):ue.type==="milestone"?await ls(ue.id):ue.type==="slice"?await qn(ue.id):ue.type==="feature"&&await mt(ue.id)},children:"Delete"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>te(null),children:"Cancel"})]})]})}),Oe&&e.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:e.jsxs("div",{className:"mission-confirm-panel__content",children:[e.jsx("p",{children:"Link feature to task:"}),e.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:Be,onChange:H=>Ae(H.target.value),autoFocus:!0}),o.length>0&&e.jsxs("div",{className:"mission-task-suggestions",children:[e.jsx("small",{children:"Or select:"}),e.jsx("div",{className:"mission-task-suggestions__list",children:o.slice(0,5).map(H=>e.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ae(H.id),children:[H.id,": ",H.title||"Untitled"]},H.id))})]}),e.jsxs("div",{className:"mission-confirm-panel__actions",children:[e.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Rt,children:"Link"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{ze(null),Ae("")},children:"Cancel"})]})]})})]}),$c=e.jsx(sN,{isOpen:Ce,onClose:()=>Ge(!1),onMissionCreated:()=>{Je(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:ye}),Dc=ie?e.jsx(rN,{isOpen:!0,onClose:()=>Ie(null),onApplied:()=>{Ie(null),f&&ot(f.id)},targetType:ie.type,targetId:ie.id,targetTitle:ie.title,missionContext:f?.title,projectId:r,resumeSessionId:ie.resumeSessionId}):null;return n?e.jsxs(e.Fragment,{children:[Ic,$c,Dc]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mission-manager-overlay open",onClick:H=>H.target===H.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Ic}),$c,Dc]})}const cr=2e3;function vN({recipient:t,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:l,addToast:o,isLoadingAgents:d=!1}){const[m,c]=a.useState(t?.id??""),[u,h]=a.useState(t?.type??"agent"),[g,p]=a.useState(""),[f,b]=a.useState(!1),[v,y]=a.useState(null),k=m.trim()!==""&&g.trim().length>0&&g.length<=cr,A=a.useCallback(async()=>{if(!(!k||f)){b(!0),y(null);try{const _=u==="agent"?"user-to-agent":"system";await qk({toId:m.trim(),toType:u,content:g.trim(),type:_,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(_){const N=fe(_)||"Failed to send message";y(N),o?.(N,"error")}finally{b(!1)}}},[k,f,m,u,g,n,i,r,o]),j=a.useCallback(_=>{c(_),h("agent")},[]);return e.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[e.jsxs("div",{className:"message-composer-header",children:[e.jsx("span",{children:n?"Reply":"New Message"}),e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:e.jsx(Ft,{size:16})})]}),e.jsxs("div",{className:"message-composer-body",children:[!t&&e.jsxs("div",{className:"message-composer-field",children:[e.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),e.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:m,onChange:_=>j(_.target.value),disabled:d||s.length===0,"data-testid":"message-composer-recipient",children:[e.jsx("option",{value:"",children:d?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(_=>e.jsx("option",{value:_.id,children:_.name||_.id},_.id))]})]}),t&&e.jsxs("div",{className:"message-composer-field",children:[e.jsx("span",{className:"message-composer-label",children:"To:"}),e.jsxs("span",{className:"message-composer-recipient-fixed",children:[e.jsx(sn,{size:14}),t.id]})]}),n&&e.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[e.jsx("span",{className:"message-composer-label",children:"Replying to:"}),e.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),e.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[e.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),e.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:_=>p(_.target.value),maxLength:cr,rows:4,"data-testid":"message-composer-content"}),e.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:e.jsxs("span",{className:g.length>cr?"over-limit":"",children:[g.length,"/",cr]})})]}),v&&e.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[e.jsx(is,{size:14}),e.jsx("span",{children:v})]})]}),e.jsxs("div",{className:"message-composer-footer",children:[e.jsx("button",{className:"btn btn-sm btn-secondary",onClick:l,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:A,disabled:!k||f,"data-testid":"message-composer-send",children:f?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:14,className:"spin"}),e.jsx("span",{children:"Sending…"})]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{size:14}),e.jsx("span",{children:"Send"})]})})]})]})}function Ii(t){const n=new Date(t),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),l=Math.floor(i/36e5),o=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function yN(t,n,s){if(n==="user")return t==="dashboard"?"You":`User: ${t}`;if(n==="agent"){const i=s?.get(t)?.trim();return i?i===t?`Agent: ${t}`:`Agent: ${i} (${t})`:`Agent: ${t}`}return"System"}function kN(t){switch(t){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 Jd(t,n=80){return t.length<=n?t:`${t.slice(0,n)}…`}function jN(t){const n=new Map;for(const s of t){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 wN({projectId:t,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[l,o]=a.useState(null),[d,m]=a.useState(null),[c,u]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[b,v]=a.useState([]),[y,k]=a.useState(!1),[A,j]=a.useState(null),[_,N]=a.useState(null),[M,w]=a.useState(null),[R,E]=a.useState("inbox"),[I,L]=a.useState(null),[ee,$]=a.useState([]),T=a.useMemo(()=>new Map(ee.map(q=>[q.id,q.name??""])),[ee]),S=a.useCallback((q,W)=>yN(q,W,T),[T]),Y=a.useCallback(async()=>{g(!0);try{const q=await Uk({limit:50},t);o(q),u(q.unreadCount),s?.(q.unreadCount)}catch{}finally{g(!1)}},[t,s]),K=a.useCallback(async()=>{g(!0);try{const q=await Hk({limit:50},t);m(q)}catch{}finally{g(!1)}},[t]),G=a.useCallback(async q=>{g(!0);try{const W=await Jk(q,t);L(W)}catch{}finally{g(!1)}},[t]),P=a.useCallback(async()=>{try{const q=await aa(void 0,t);$(q)}catch{}},[t]),O=a.useCallback(async()=>{try{const q=await yh(t);u(q.unreadCount),s?.(q.unreadCount)}catch{}},[t,s]);a.useEffect(()=>{i==="inbox"?Y():i==="outbox"?K():i==="agents"&&P()},[i,Y,K,P]),a.useEffect(()=>{M&&G(M)},[M,G]),a.useEffect(()=>{O()},[O]),a.useEffect(()=>{P()},[P]),a.useEffect(()=>{if(typeof EventSource>"u")return;const q=t?`?projectId=${encodeURIComponent(t)}`:"",W=()=>{O(),i==="inbox"?Y():i==="outbox"&&K(),M&&G(M)};return Bs(`/api/events${q}`,{events:{"message:sent":W,"message:received":W,"message:read":W,"message:deleted":W}})},[t,i,M,O,Y,K,G]);const X=a.useCallback(async q=>{if(f(q),!q.read)try{const W=await Vk(q.id,t);W&&o(Re=>Re&&{...Re,messages:Re.messages.map(ve=>ve.id===W.id?W:ve),unreadCount:Math.max(0,Re.unreadCount-1)});const me=Math.max(0,c-1);u(me),s?.(me)}catch{}try{const W=await Gk(q.fromId,q.fromType,t);v(W)}catch{v([q])}},[t,c,s]),C=a.useCallback(()=>{f(null),v([])},[]),V=a.useCallback(async()=>{try{const q=await Wk(t);u(0),s?.(0),o(W=>W&&{...W,messages:W.messages.map(me=>({...me,read:!0})),unreadCount:0}),n?.(`Marked ${q.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[t,n,s]),de=a.useCallback(async q=>{try{await Kk(q,t),f(null),v([]),i==="inbox"?Y():i==="outbox"?K():M&&G(M),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[t,i,M,Y,K,G,n]),B=a.useCallback(q=>{j({id:q.fromId,type:q.fromType}),N({messageId:q.id,preview:Jd(q.content,120)}),k(!0)},[]),J=a.useCallback(()=>{k(!1),j(null),N(null),n?.("Message sent","success"),i==="outbox"?K():i==="agents"&&M&&G(M),O()},[i,K,M,G,n,O]),D=a.useCallback(()=>{j(i==="agents"&&M?{id:M,type:"agent"}:null),N(null),k(!0)},[i,M]),he=a.useCallback(()=>{k(!1),j(null),N(null)},[]);return e.jsxs("div",{className:"mailbox-view","data-testid":"mailbox-view",children:[e.jsxs("div",{className:"mailbox-header",children:[e.jsxs("div",{className:"mailbox-title",children:[e.jsx(Ia,{size:18}),e.jsx("span",{children:"Mailbox"}),c>0&&e.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:c})]}),e.jsxs("div",{className:"mailbox-header-actions",children:[e.jsxs("button",{className:"btn btn-sm btn-primary",onClick:D,title:"Compose message","data-testid":"mailbox-header-compose",children:[e.jsx(ei,{size:14}),e.jsx("span",{children:"Compose"})]}),i==="inbox"&&c>0&&e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:V,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[e.jsx(Wf,{size:14}),e.jsx("span",{children:"Mark all read"})]}),e.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?Y():i==="outbox"?K():M&&G(M)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14})})]})]}),e.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[e.jsx(Sa,{size:14}),e.jsx("span",{children:"Inbox"}),c>0&&e.jsx("span",{className:"mailbox-tab-badge",children:c})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[e.jsx(gi,{size:14}),e.jsx("span",{children:"Outbox"})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[e.jsx(sn,{size:14}),e.jsx("span",{children:"Agents"})]})]}),e.jsxs("div",{className:"mailbox-content","data-testid":"mailbox-content",children:[p&&!y&&e.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[e.jsxs("div",{className:"mailbox-message-detail-header",children:[e.jsx("button",{className:"btn btn-sm btn-secondary",onClick:C,"data-testid":"mailbox-back-to-list",children:"← Back"}),e.jsxs("div",{className:"mailbox-message-detail-meta",children:[e.jsx("span",{className:"mailbox-message-type",children:kN(p.type)}),e.jsx("span",{className:"mailbox-message-time",children:Ii(p.createdAt)})]}),e.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>B(p),"data-testid":"mailbox-reply",children:[e.jsx(ei,{size:14}),e.jsx("span",{children:"Reply"})]}),e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>de(p.id),"data-testid":"mailbox-delete",children:[e.jsx(Ut,{size:14}),e.jsx("span",{children:"Delete"})]})]})]}),e.jsxs("div",{className:"mailbox-message-participants",children:[e.jsxs("div",{className:"mailbox-participant",children:[e.jsx("span",{className:"mailbox-participant-label",children:"From:"}),e.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?e.jsx(sn,{size:14}):e.jsx(Pi,{size:14}),S(p.fromId,p.fromType)]})]}),e.jsxs("div",{className:"mailbox-participant",children:[e.jsx("span",{className:"mailbox-participant-label",children:"To:"}),e.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?e.jsx(sn,{size:14}):e.jsx(Pi,{size:14}),S(p.toId,p.toType)]})]})]}),b.length>1&&e.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[e.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(q=>{const W=q.metadata?.replyTo?.messageId,me=W?b.find(Re=>Re.id===W):void 0;return e.jsxs("div",{className:`mailbox-conversation-msg ${q.id===p.id?"current":""}`,children:[e.jsxs("div",{className:"mailbox-conversation-msg-header",children:[e.jsx("span",{children:S(q.fromId,q.fromType)}),e.jsx("span",{className:"mailbox-message-time",children:Ii(q.createdAt)})]}),W&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${q.id}`,children:["↪ Replying to ",me?Jd(me.content,60):`message ${W}`]}),e.jsx("div",{className:"mailbox-conversation-msg-body",children:q.content})]},q.id)})]}),b.length<=1&&e.jsxs(e.Fragment,{children:[p.metadata?.replyTo?.messageId&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),e.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),y&&e.jsx(vN,{recipient:A,replyContext:_,agents:ee,projectId:t,onSend:J,onCancel:he,addToast:n}),!p&&!y&&e.jsxs(e.Fragment,{children:[i==="inbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!l&&e.jsx(Cl,{}),l&&l.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[e.jsx(Sa,{size:32}),e.jsx("p",{children:"No messages in your inbox"})]}),l&&l.messages.length>0&&e.jsx("div",{className:"mailbox-conversations","data-testid":"mailbox-conversations",children:jN(l.messages).map(q=>e.jsxs("div",{className:`mailbox-conversation-group ${q.unreadCount>0?"unread":""}`,onClick:()=>X(q.latestMessage),"data-testid":`mailbox-conversation-${q.key}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:q.fromType==="agent"?e.jsx(sn,{size:16}):e.jsx(Pi,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsx("span",{className:"mailbox-item-from",children:S(q.fromId,q.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:Ii(q.latestMessage.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[q.latestMessage.content.slice(0,80),q.latestMessage.content.length>80?"…":""]})]}),q.unreadCount>0&&e.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${q.key}`,children:q.unreadCount>9?"9+":q.unreadCount})]},q.key))})]}),i==="outbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!d&&e.jsx(Cl,{}),d&&d.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[e.jsx(gi,{size:32}),e.jsx("p",{children:"No sent messages"})]}),d?.messages.map(q=>e.jsxs("div",{className:"mailbox-item",onClick:()=>X(q),"data-testid":`mailbox-item-${q.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:q.toType==="agent"?e.jsx(sn,{size:16}):e.jsx(Pi,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsxs("span",{className:"mailbox-item-to",children:["To: ",S(q.toId,q.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:Ii(q.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[q.content.slice(0,80),q.content.length>80?"…":""]})]})]},q.id))]}),i==="agents"&&e.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:ee.length===0?e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(sn,{size:32}),e.jsx("p",{children:"No agents found"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mailbox-agents-header",children:[e.jsx("div",{className:"mailbox-agents-dropdown",children:e.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:M??"",onChange:q=>{w(q.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[e.jsx("option",{value:"",children:"Select an agent…"}),ee.map(q=>e.jsx("option",{value:q.id,children:q.name||q.id},q.id))]})}),e.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:D,"data-testid":"mailbox-compose-btn",children:[e.jsx(ei,{size:14}),e.jsx("span",{children:"Compose"})]})]}),M&&e.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${R==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[e.jsx(Sa,{size:12}),e.jsx("span",{children:"Inbox"}),I&&I.unreadCount>0&&e.jsx("span",{className:"mailbox-tab-badge",children:I.unreadCount})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${R==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[e.jsx(gi,{size:12}),e.jsx("span",{children:"Outbox"})]})]}),e.jsxs("div",{className:"mailbox-agents-content",children:[!M&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(sn,{size:32}),e.jsx("p",{children:"Select an agent to view their mailbox"})]}),M&&h&&!I&&e.jsx(Cl,{}),M&&I&&R==="inbox"&&I.inbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(Sa,{size:32}),e.jsx("p",{children:"No received messages for this agent"})]}),M&&I&&R==="outbox"&&I.outbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(gi,{size:32}),e.jsx("p",{children:"No sent messages for this agent"})]}),M&&I&&R==="inbox"&&I.inbox.map(q=>e.jsxs("div",{className:`mailbox-item ${q.read?"":"unread"}`,onClick:()=>X(q),"data-testid":`mailbox-item-${q.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:q.fromType==="agent"?e.jsx(sn,{size:16}):e.jsx(Pi,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsx("span",{className:"mailbox-item-from",children:S(q.fromId,q.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:Ii(q.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[q.content.slice(0,80),q.content.length>80?"…":""]})]})]},q.id)),M&&I&&R==="outbox"&&I.outbox.map(q=>e.jsxs("div",{className:"mailbox-item",onClick:()=>X(q),"data-testid":`mailbox-item-${q.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:q.toType==="agent"?e.jsx(sn,{size:16}):e.jsx(Pi,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsxs("span",{className:"mailbox-item-to",children:["To: ",S(q.toId,q.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:Ii(q.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[q.content.slice(0,80),q.content.length>80?"…":""]})]})]},q.id))]})]})})]})]})]})}function Cl(){return e.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((t,n)=>e.jsxs("div",{className:"mailbox-skeleton-item",children:[e.jsx("div",{className:"mailbox-skeleton-avatar"}),e.jsxs("div",{className:"mailbox-skeleton-content",children:[e.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),e.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}function NN(t,n){const s={};return(t[t.length-1]===""?[...t,""]:t).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const SN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,CN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EN={};function Yd(t,n){return(EN.jsx?CN:SN).test(t)}const MN=/[ \t\n\f\r]/g;function AN(t){return typeof t=="object"?t.type==="text"?Qd(t.value):!1:Qd(t)}function Qd(t){return t.replace(MN,"")===""}class Ya{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Ya.prototype.normal={};Ya.prototype.property={};Ya.prototype.space=void 0;function zh(t,n){const s={},i={};for(const r of t)Object.assign(s,r.property),Object.assign(i,r.normal);return new Ya(s,i,n)}function So(t){return t.toLowerCase()}class as{constructor(n,s){this.attribute=s,this.property=n}}as.prototype.attribute="";as.prototype.booleanish=!1;as.prototype.boolean=!1;as.prototype.commaOrSpaceSeparated=!1;as.prototype.commaSeparated=!1;as.prototype.defined=!1;as.prototype.mustUseProperty=!1;as.prototype.number=!1;as.prototype.overloadedBoolean=!1;as.prototype.property="";as.prototype.spaceSeparated=!1;as.prototype.space=void 0;let PN=0;const At=Ei(),xn=Ei(),Co=Ei(),at=Ei(),Xt=Ei(),Ui=Ei(),os=Ei();function Ei(){return 2**++PN}const Eo=Object.freeze(Object.defineProperty({__proto__:null,boolean:At,booleanish:xn,commaOrSpaceSeparated:os,commaSeparated:Ui,number:at,overloadedBoolean:Co,spaceSeparated:Xt},Symbol.toStringTag,{value:"Module"})),El=Object.keys(Eo);class nc extends as{constructor(n,s,i,r){let l=-1;if(super(n,s),Xd(this,"space",r),typeof i=="number")for(;++l<El.length;){const o=El[l];Xd(this,El[l],(i&Eo[o])===Eo[o])}}}nc.prototype.defined=!0;function Xd(t,n,s){s&&(t[n]=s)}function la(t){const n={},s={};for(const[i,r]of Object.entries(t.properties)){const l=new nc(i,t.transform(t.attributes||{},i),r,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(l.mustUseProperty=!0),n[i]=l,s[So(i)]=i,s[So(l.attribute)]=i}return new Ya(n,s,t.space)}const Oh=la({properties:{ariaActiveDescendant:null,ariaAtomic:xn,ariaAutoComplete:null,ariaBusy:xn,ariaChecked:xn,ariaColCount:at,ariaColIndex:at,ariaColSpan:at,ariaControls:Xt,ariaCurrent:null,ariaDescribedBy:Xt,ariaDetails:null,ariaDisabled:xn,ariaDropEffect:Xt,ariaErrorMessage:null,ariaExpanded:xn,ariaFlowTo:Xt,ariaGrabbed:xn,ariaHasPopup:null,ariaHidden:xn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Xt,ariaLevel:at,ariaLive:null,ariaModal:xn,ariaMultiLine:xn,ariaMultiSelectable:xn,ariaOrientation:null,ariaOwns:Xt,ariaPlaceholder:null,ariaPosInSet:at,ariaPressed:xn,ariaReadOnly:xn,ariaRelevant:null,ariaRequired:xn,ariaRoleDescription:Xt,ariaRowCount:at,ariaRowIndex:at,ariaRowSpan:at,ariaSelected:xn,ariaSetSize:at,ariaSort:null,ariaValueMax:at,ariaValueMin:at,ariaValueNow:at,ariaValueText:null,role:null},transform(t,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Bh(t,n){return n in t?t[n]:n}function Uh(t,n){return Bh(t,n.toLowerCase())}const _N=la({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ui,acceptCharset:Xt,accessKey:Xt,action:null,allow:null,allowFullScreen:At,allowPaymentRequest:At,allowUserMedia:At,alt:null,as:null,async:At,autoCapitalize:null,autoComplete:Xt,autoFocus:At,autoPlay:At,blocking:Xt,capture:null,charSet:null,checked:At,cite:null,className:Xt,cols:at,colSpan:null,content:null,contentEditable:xn,controls:At,controlsList:Xt,coords:at|Ui,crossOrigin:null,data:null,dateTime:null,decoding:null,default:At,defer:At,dir:null,dirName:null,disabled:At,download:Co,draggable:xn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:At,formTarget:null,headers:Xt,height:at,hidden:Co,high:at,href:null,hrefLang:null,htmlFor:Xt,httpEquiv:Xt,id:null,imageSizes:null,imageSrcSet:null,inert:At,inputMode:null,integrity:null,is:null,isMap:At,itemId:null,itemProp:Xt,itemRef:Xt,itemScope:At,itemType:Xt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:At,low:at,manifest:null,max:null,maxLength:at,media:null,method:null,min:null,minLength:at,multiple:At,muted:At,name:null,nonce:null,noModule:At,noValidate:At,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:At,optimum:at,pattern:null,ping:Xt,placeholder:null,playsInline:At,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:At,referrerPolicy:null,rel:Xt,required:At,reversed:At,rows:at,rowSpan:at,sandbox:Xt,scope:null,scoped:At,seamless:At,selected:At,shadowRootClonable:At,shadowRootDelegatesFocus:At,shadowRootMode:null,shape:null,size:at,sizes:null,slot:null,span:at,spellCheck:xn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:at,step:null,style:null,tabIndex:at,target:null,title:null,translate:null,type:null,typeMustMatch:At,useMap:null,value:xn,width:at,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Xt,axis:null,background:null,bgColor:null,border:at,borderColor:null,bottomMargin:at,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:At,declare:At,event:null,face:null,frame:null,frameBorder:null,hSpace:at,leftMargin:at,link:null,longDesc:null,lowSrc:null,marginHeight:at,marginWidth:at,noResize:At,noHref:At,noShade:At,noWrap:At,object:null,profile:null,prompt:null,rev:null,rightMargin:at,rules:null,scheme:null,scrolling:xn,standby:null,summary:null,text:null,topMargin:at,valueType:null,version:null,vAlign:null,vLink:null,vSpace:at,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:At,disableRemotePlayback:At,prefix:null,property:null,results:at,security:null,unselectable:null},space:"html",transform:Uh}),TN=la({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:os,accentHeight:at,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:at,amplitude:at,arabicForm:null,ascent:at,attributeName:null,attributeType:null,azimuth:at,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:at,by:null,calcMode:null,capHeight:at,className:Xt,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:at,diffuseConstant:at,direction:null,display:null,dur:null,divisor:at,dominantBaseline:null,download:At,dx:null,dy:null,edgeMode:null,editable:null,elevation:at,enableBackground:null,end:null,event:null,exponent:at,externalResourcesRequired:null,fill:null,fillOpacity:at,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:Ui,g2:Ui,glyphName:Ui,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:at,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:at,horizOriginX:at,horizOriginY:at,id:null,ideographic:at,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:at,k:at,k1:at,k2:at,k3:at,k4:at,kernelMatrix:os,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:at,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:at,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:at,overlineThickness:at,paintOrder:null,panose1:null,path:null,pathLength:at,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Xt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:at,pointsAtY:at,pointsAtZ:at,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:os,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:os,rev:os,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:os,requiredFeatures:os,requiredFonts:os,requiredFormats:os,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:at,specularExponent:at,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:at,strikethroughThickness:at,string:null,stroke:null,strokeDashArray:os,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:at,strokeOpacity:at,strokeWidth:null,style:null,surfaceScale:at,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:os,tabIndex:at,tableValues:null,target:null,targetX:at,targetY:at,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:os,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:at,underlineThickness:at,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:at,values:null,vAlphabetic:at,vMathematical:at,vectorEffect:null,vHanging:at,vIdeographic:at,version:null,vertAdvY:at,vertOriginX:at,vertOriginY:at,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:at,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Bh}),Hh=la({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,n){return"xlink:"+n.slice(5).toLowerCase()}}),qh=la({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Uh}),Vh=la({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),RN={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"},IN=/[A-Z]/g,Zd=/-[a-z]/g,$N=/^data[-\w.:]+$/i;function DN(t,n){const s=So(n);let i=n,r=as;if(s in t.normal)return t.property[t.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&$N.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(Zd,LN);i="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!Zd.test(l)){let o=l.replace(IN,FN);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}r=nc}return new r(i,n)}function FN(t){return"-"+t.toLowerCase()}function LN(t){return t.charAt(1).toUpperCase()}const zN=zh([Oh,_N,Hh,qh,Vh],"html"),sc=zh([Oh,TN,Hh,qh,Vh],"svg");function ON(t){return t.join(" ").trim()}var $i={},Ml,eu;function BN(){if(eu)return Ml;eu=1;var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,d=/^\s+|\s+$/g,m=`
|
|
598
|
+
`,c="/",u="*",h="",g="comment",p="declaration";function f(v,y){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];y=y||{};var k=1,A=1;function j($){var T=$.match(n);T&&(k+=T.length);var S=$.lastIndexOf(m);A=~S?$.length-S:A+$.length}function _(){var $={line:k,column:A};return function(T){return T.position=new N($),R(),T}}function N($){this.start=$,this.end={line:k,column:A},this.source=y.source}N.prototype.content=v;function M($){var T=new Error(y.source+":"+k+":"+A+": "+$);if(T.reason=$,T.filename=y.source,T.line=k,T.column=A,T.source=v,!y.silent)throw T}function w($){var T=$.exec(v);if(T){var S=T[0];return j(S),v=v.slice(S.length),T}}function R(){w(s)}function E($){var T;for($=$||[];T=I();)T!==!1&&$.push(T);return $}function I(){var $=_();if(!(c!=v.charAt(0)||u!=v.charAt(1))){for(var T=2;h!=v.charAt(T)&&(u!=v.charAt(T)||c!=v.charAt(T+1));)++T;if(T+=2,h===v.charAt(T-1))return M("End of comment missing");var S=v.slice(2,T-2);return A+=2,j(S),v=v.slice(T),A+=2,$({type:g,comment:S})}}function L(){var $=_(),T=w(i);if(T){if(I(),!w(r))return M("property missing ':'");var S=w(l),Y=$({type:p,property:b(T[0].replace(t,h)),value:S?b(S[0].replace(t,h)):h});return w(o),Y}}function ee(){var $=[];E($);for(var T;T=L();)T!==!1&&($.push(T),E($));return $}return R(),ee()}function b(v){return v?v.replace(d,h):h}return Ml=f,Ml}var tu;function UN(){if(tu)return $i;tu=1;var t=$i&&$i.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty($i,"__esModule",{value:!0}),$i.default=s;const n=t(BN());function s(i,r){let l=null;if(!i||typeof i!="string")return l;const o=(0,n.default)(i),d=typeof r=="function";return o.forEach(m=>{if(m.type!=="declaration")return;const{property:c,value:u}=m;d?r(c,u,m):u&&(l=l||{},l[c]=u)}),l}return $i}var ha={},nu;function HN(){if(nu)return ha;nu=1,Object.defineProperty(ha,"__esModule",{value:!0}),ha.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,l=function(c){return!c||s.test(c)||t.test(c)},o=function(c,u){return u.toUpperCase()},d=function(c,u){return"".concat(u,"-")},m=function(c,u){return u===void 0&&(u={}),l(c)?c:(c=c.toLowerCase(),u.reactCompat?c=c.replace(r,d):c=c.replace(i,d),c.replace(n,o))};return ha.camelCase=m,ha}var pa,su;function qN(){if(su)return pa;su=1;var t=pa&&pa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=t(UN()),s=HN();function i(r,l){var o={};return!r||typeof r!="string"||(0,n.default)(r,function(d,m){d&&m&&(o[(0,s.camelCase)(d,l)]=m)}),o}return i.default=i,pa=i,pa}var VN=qN();const WN=Lm(VN),Wh=Kh("end"),ic=Kh("start");function Kh(t){return n;function n(s){const i=s&&s.position&&s.position[t]||{};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 KN(t){const n=ic(t),s=Wh(t);if(n&&s)return{start:n,end:s}}function Aa(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?iu(t.position):"start"in t||"end"in t?iu(t):"line"in t||"column"in t?Mo(t):""}function Mo(t){return au(t&&t.line)+":"+au(t&&t.column)}function iu(t){return Mo(t&&t.start)+"-"+Mo(t&&t.end)}function au(t){return t&&typeof t=="number"?t:1}class zn extends Error{constructor(n,s,i){super(),typeof s=="string"&&(i=s,s=void 0);let r="",l={},o=!1;if(s&&("line"in s&&"column"in s?l={place:s}:"start"in s&&"end"in s?l={place:s}:"type"in s?l={ancestors:[s],place:s.position}:l={...s}),typeof n=="string"?r=n:!l.cause&&n&&(o=!0,r=n.message,l.cause=n),!l.ruleId&&!l.source&&typeof i=="string"){const m=i.indexOf(":");m===-1?l.ruleId=i:(l.source=i.slice(0,m),l.ruleId=i.slice(m+1))}if(!l.place&&l.ancestors&&l.ancestors){const m=l.ancestors[l.ancestors.length-1];m&&(l.place=m.position)}const d=l.place&&"start"in l.place?l.place.start:l.place;this.ancestors=l.ancestors||void 0,this.cause=l.cause||void 0,this.column=d?d.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=d?d.line:void 0,this.name=Aa(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=o&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}zn.prototype.file="";zn.prototype.name="";zn.prototype.reason="";zn.prototype.message="";zn.prototype.stack="";zn.prototype.column=void 0;zn.prototype.line=void 0;zn.prototype.ancestors=void 0;zn.prototype.cause=void 0;zn.prototype.fatal=void 0;zn.prototype.place=void 0;zn.prototype.ruleId=void 0;zn.prototype.source=void 0;const ac={}.hasOwnProperty,GN=new Map,JN=/[A-Z]/g,YN=new Set(["table","tbody","thead","tfoot","tr"]),QN=new Set(["td","th"]),Gh="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function XN(t,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=r1(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=a1(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"?sc:zN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},l=Jh(r,t,void 0);return l&&typeof l!="string"?l:r.create(t,r.Fragment,{children:l||void 0},void 0)}function Jh(t,n,s){if(n.type==="element")return ZN(t,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return e1(t,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return n1(t,n,s);if(n.type==="mdxjsEsm")return t1(t,n);if(n.type==="root")return s1(t,n,s);if(n.type==="text")return i1(t,n)}function ZN(t,n,s){const i=t.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=sc,t.schema=r),t.ancestors.push(n);const l=Qh(t,n.tagName,!1),o=l1(t,n);let d=lc(t,n);return YN.has(n.tagName)&&(d=d.filter(function(m){return typeof m=="string"?!AN(m):!0})),Yh(t,o,l,n),rc(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function e1(t,n){if(n.data&&n.data.estree&&t.evaluater){const i=n.data.estree.body[0];return i.type,t.evaluater.evaluateExpression(i.expression)}La(t,n.position)}function t1(t,n){if(n.data&&n.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(n.data.estree);La(t,n.position)}function n1(t,n,s){const i=t.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=sc,t.schema=r),t.ancestors.push(n);const l=n.name===null?t.Fragment:Qh(t,n.name,!0),o=o1(t,n),d=lc(t,n);return Yh(t,o,l,n),rc(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function s1(t,n,s){const i={};return rc(i,lc(t,n)),t.create(n,t.Fragment,i,s)}function i1(t,n){return n.value}function Yh(t,n,s,i){typeof s!="string"&&s!==t.Fragment&&t.passNode&&(n.node=i)}function rc(t,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(t.children=s)}}function a1(t,n,s){return i;function i(r,l,o,d){const c=Array.isArray(o.children)?s:n;return d?c(l,o,d):c(l,o)}}function r1(t,n){return s;function s(i,r,l,o){const d=Array.isArray(l.children),m=ic(i);return n(r,l,o,d,{columnNumber:m?m.column-1:void 0,fileName:t,lineNumber:m?m.line:void 0},void 0)}}function l1(t,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&ac.call(n.properties,r)){const l=c1(t,r,n.properties[r]);if(l){const[o,d]=l;t.tableCellAlignToStyle&&o==="align"&&typeof d=="string"&&QN.has(n.tagName)?i=d:s[o]=d}}if(i){const l=s.style||(s.style={});l[t.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return s}function o1(t,n){const s={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&t.evaluater){const l=i.data.estree.body[0];l.type;const o=l.expression;o.type;const d=o.properties[0];d.type,Object.assign(s,t.evaluater.evaluateExpression(d.argument))}else La(t,n.position);else{const r=i.name;let l;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&t.evaluater){const d=i.value.data.estree.body[0];d.type,l=t.evaluater.evaluateExpression(d.expression)}else La(t,n.position);else l=i.value===null?!0:i.value;s[r]=l}return s}function lc(t,n){const s=[];let i=-1;const r=t.passKeys?new Map:GN;for(;++i<n.children.length;){const l=n.children[i];let o;if(t.passKeys){const m=l.type==="element"?l.tagName:l.type==="mdxJsxFlowElement"||l.type==="mdxJsxTextElement"?l.name:void 0;if(m){const c=r.get(m)||0;o=m+"-"+c,r.set(m,c+1)}}const d=Jh(t,l,o);d!==void 0&&s.push(d)}return s}function c1(t,n,s){const i=DN(t.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?NN(s):ON(s)),i.property==="style"){let r=typeof s=="object"?s:d1(t,String(s));return t.stylePropertyNameCase==="css"&&(r=u1(r)),["style",r]}return[t.elementAttributeNameCase==="react"&&i.space?RN[i.property]||i.property:i.attribute,s]}}function d1(t,n){try{return WN(n,{reactCompat:!0})}catch(s){if(t.ignoreInvalidStyle)return{};const i=s,r=new zn("Cannot parse `style` attribute",{ancestors:t.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=t.filePath||void 0,r.url=Gh+"#cannot-parse-style-attribute",r}}function Qh(t,n,s){let i;if(!s)i={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let l=-1,o;for(;++l<r.length;){const d=Yd(r[l])?{type:"Identifier",name:r[l]}:{type:"Literal",value:r[l]};o=o?{type:"MemberExpression",object:o,property:d,computed:!!(l&&d.type==="Literal"),optional:!1}:d}i=o}else i=Yd(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return ac.call(t.components,r)?t.components[r]:r}if(t.evaluater)return t.evaluater.evaluateExpression(i);La(t)}function La(t,n){const s=new zn("Cannot handle MDX estrees without `createEvaluater`",{ancestors:t.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=t.filePath||void 0,s.url=Gh+"#cannot-handle-mdx-estrees-without-createevaluater",s}function u1(t){const n={};let s;for(s in t)ac.call(t,s)&&(n[m1(s)]=t[s]);return n}function m1(t){let n=t.replace(JN,h1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function h1(t){return"-"+t.toLowerCase()}const Al={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"]},p1={};function oc(t,n){const s=p1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Xh(t,i,r)}function Xh(t,n,s){if(f1(t)){if("value"in t)return t.type==="html"&&!s?"":t.value;if(n&&"alt"in t&&t.alt)return t.alt;if("children"in t)return ru(t.children,n,s)}return Array.isArray(t)?ru(t,n,s):""}function ru(t,n,s){const i=[];let r=-1;for(;++r<t.length;)i[r]=Xh(t[r],n,s);return i.join("")}function f1(t){return!!(t&&typeof t=="object")}const lu=document.createElement("i");function cc(t){const n="&"+t+";";lu.innerHTML=n;const s=lu.textContent;return s.charCodeAt(s.length-1)===59&&t!=="semi"||s===n?!1:s}function hs(t,n,s,i){const r=t.length;let l=0,o;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,i.length<1e4)o=Array.from(i),o.unshift(n,s),t.splice(...o);else for(s&&t.splice(n,s);l<i.length;)o=i.slice(l,l+1e4),o.unshift(n,0),t.splice(...o),l+=1e4,n+=1e4}function js(t,n){return t.length>0?(hs(t,t.length,0,n),t):n}const ou={}.hasOwnProperty;function Zh(t){const n={};let s=-1;for(;++s<t.length;)g1(n,t[s]);return n}function g1(t,n){let s;for(s in n){const r=(ou.call(t,s)?t[s]:void 0)||(t[s]={}),l=n[s];let o;if(l)for(o in l){ou.call(r,o)||(r[o]=[]);const d=l[o];b1(r[o],Array.isArray(d)?d:d?[d]:[])}}}function b1(t,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?t:i).push(n[s]);hs(t,0,0,i)}function ep(t,n){const s=Number.parseInt(t,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 As(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Wn=ri(/[A-Za-z]/),Fn=ri(/[\dA-Za-z]/),x1=ri(/[#-'*+\--9=?A-Z^-~]/);function Fr(t){return t!==null&&(t<32||t===127)}const Ao=ri(/\d/),v1=ri(/[\dA-Fa-f]/),y1=ri(/[!-/:-@[-`{-~]/);function Nt(t){return t!==null&&t<-2}function Gt(t){return t!==null&&(t<0||t===32)}function Dt(t){return t===-2||t===-1||t===32}const tl=ri(/\p{P}|\p{S}/u),Ni=ri(/\s/);function ri(t){return n;function n(s){return s!==null&&s>-1&&t.test(String.fromCharCode(s))}}function oa(t){const n=[];let s=-1,i=0,r=0;for(;++s<t.length;){const l=t.charCodeAt(s);let o="";if(l===37&&Fn(t.charCodeAt(s+1))&&Fn(t.charCodeAt(s+2)))r=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(o=String.fromCharCode(l));else if(l>55295&&l<57344){const d=t.charCodeAt(s+1);l<56320&&d>56319&&d<57344?(o=String.fromCharCode(l,d),r=1):o="�"}else o=String.fromCharCode(l);o&&(n.push(t.slice(i,s),encodeURIComponent(o)),i=s+r+1,o=""),r&&(s+=r,r=0)}return n.join("")+t.slice(i)}function zt(t,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let l=0;return o;function o(m){return Dt(m)?(t.enter(s),d(m)):n(m)}function d(m){return Dt(m)&&l++<r?(t.consume(m),d):(t.exit(s),n(m))}}const k1={tokenize:j1};function j1(t){const n=t.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(d){if(d===null){t.consume(d);return}return t.enter("lineEnding"),t.consume(d),t.exit("lineEnding"),zt(t,n,"linePrefix")}function r(d){return t.enter("paragraph"),l(d)}function l(d){const m=t.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=m),s=m,o(d)}function o(d){if(d===null){t.exit("chunkText"),t.exit("paragraph"),t.consume(d);return}return Nt(d)?(t.consume(d),t.exit("chunkText"),l):(t.consume(d),o)}}const w1={tokenize:N1},cu={tokenize:S1};function N1(t){const n=this,s=[];let i=0,r,l,o;return d;function d(A){if(i<s.length){const j=s[i];return n.containerState=j[1],t.attempt(j[0].continuation,m,c)(A)}return c(A)}function m(A){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&k();const j=n.events.length;let _=j,N;for(;_--;)if(n.events[_][0]==="exit"&&n.events[_][1].type==="chunkFlow"){N=n.events[_][1].end;break}y(i);let M=j;for(;M<n.events.length;)n.events[M][1].end={...N},M++;return hs(n.events,_+1,0,n.events.slice(j)),n.events.length=M,c(A)}return d(A)}function c(A){if(i===s.length){if(!r)return g(A);if(r.currentConstruct&&r.currentConstruct.concrete)return f(A);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},t.check(cu,u,h)(A)}function u(A){return r&&k(),y(i),g(A)}function h(A){return n.parser.lazy[n.now().line]=i!==s.length,o=n.now().offset,f(A)}function g(A){return n.containerState={},t.attempt(cu,p,f)(A)}function p(A){return i++,s.push([n.currentConstruct,n.containerState]),g(A)}function f(A){if(A===null){r&&k(),y(0),t.consume(A);return}return r=r||n.parser.flow(n.now()),t.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:l}),b(A)}function b(A){if(A===null){v(t.exit("chunkFlow"),!0),y(0),t.consume(A);return}return Nt(A)?(t.consume(A),v(t.exit("chunkFlow")),i=0,n.interrupt=void 0,d):(t.consume(A),b)}function v(A,j){const _=n.sliceStream(A);if(j&&_.push(null),A.previous=l,l&&(l.next=A),l=A,r.defineSkip(A.start),r.write(_),n.parser.lazy[A.start.line]){let N=r.events.length;for(;N--;)if(r.events[N][1].start.offset<o&&(!r.events[N][1].end||r.events[N][1].end.offset>o))return;const M=n.events.length;let w=M,R,E;for(;w--;)if(n.events[w][0]==="exit"&&n.events[w][1].type==="chunkFlow"){if(R){E=n.events[w][1].end;break}R=!0}for(y(i),N=M;N<n.events.length;)n.events[N][1].end={...E},N++;hs(n.events,w+1,0,n.events.slice(M)),n.events.length=N}}function y(A){let j=s.length;for(;j-- >A;){const _=s[j];n.containerState=_[1],_[0].exit.call(n,t)}s.length=A}function k(){r.write([null]),l=void 0,r=void 0,n.containerState._closeFlow=void 0}}function S1(t,n,s){return zt(t,t.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Yi(t){if(t===null||Gt(t)||Ni(t))return 1;if(tl(t))return 2}function nl(t,n,s){const i=[];let r=-1;for(;++r<t.length;){const l=t[r].resolveAll;l&&!i.includes(l)&&(n=l(n,s),i.push(l))}return n}const Po={name:"attention",resolveAll:C1,tokenize:E1};function C1(t,n){let s=-1,i,r,l,o,d,m,c,u;for(;++s<t.length;)if(t[s][0]==="enter"&&t[s][1].type==="attentionSequence"&&t[s][1]._close){for(i=s;i--;)if(t[i][0]==="exit"&&t[i][1].type==="attentionSequence"&&t[i][1]._open&&n.sliceSerialize(t[i][1]).charCodeAt(0)===n.sliceSerialize(t[s][1]).charCodeAt(0)){if((t[i][1]._close||t[s][1]._open)&&(t[s][1].end.offset-t[s][1].start.offset)%3&&!((t[i][1].end.offset-t[i][1].start.offset+t[s][1].end.offset-t[s][1].start.offset)%3))continue;m=t[i][1].end.offset-t[i][1].start.offset>1&&t[s][1].end.offset-t[s][1].start.offset>1?2:1;const h={...t[i][1].end},g={...t[s][1].start};du(h,-m),du(g,m),o={type:m>1?"strongSequence":"emphasisSequence",start:h,end:{...t[i][1].end}},d={type:m>1?"strongSequence":"emphasisSequence",start:{...t[s][1].start},end:g},l={type:m>1?"strongText":"emphasisText",start:{...t[i][1].end},end:{...t[s][1].start}},r={type:m>1?"strong":"emphasis",start:{...o.start},end:{...d.end}},t[i][1].end={...o.start},t[s][1].start={...d.end},c=[],t[i][1].end.offset-t[i][1].start.offset&&(c=js(c,[["enter",t[i][1],n],["exit",t[i][1],n]])),c=js(c,[["enter",r,n],["enter",o,n],["exit",o,n],["enter",l,n]]),c=js(c,nl(n.parser.constructs.insideSpan.null,t.slice(i+1,s),n)),c=js(c,[["exit",l,n],["enter",d,n],["exit",d,n],["exit",r,n]]),t[s][1].end.offset-t[s][1].start.offset?(u=2,c=js(c,[["enter",t[s][1],n],["exit",t[s][1],n]])):u=0,hs(t,i-1,s-i+3,c),s=i+c.length-u-2;break}}for(s=-1;++s<t.length;)t[s][1].type==="attentionSequence"&&(t[s][1].type="data");return t}function E1(t,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Yi(i);let l;return o;function o(m){return l=m,t.enter("attentionSequence"),d(m)}function d(m){if(m===l)return t.consume(m),d;const c=t.exit("attentionSequence"),u=Yi(m),h=!u||u===2&&r||s.includes(m),g=!r||r===2&&u||s.includes(i);return c._open=!!(l===42?h:h&&(r||!g)),c._close=!!(l===42?g:g&&(u||!h)),n(m)}}function du(t,n){t.column+=n,t.offset+=n,t._bufferIndex+=n}const M1={name:"autolink",tokenize:A1};function A1(t,n,s){let i=0;return r;function r(p){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),l}function l(p){return Wn(p)?(t.consume(p),o):p===64?s(p):c(p)}function o(p){return p===43||p===45||p===46||Fn(p)?(i=1,d(p)):c(p)}function d(p){return p===58?(t.consume(p),i=0,m):(p===43||p===45||p===46||Fn(p))&&i++<32?(t.consume(p),d):(i=0,c(p))}function m(p){return p===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),n):p===null||p===32||p===60||Fr(p)?s(p):(t.consume(p),m)}function c(p){return p===64?(t.consume(p),u):x1(p)?(t.consume(p),c):s(p)}function u(p){return Fn(p)?h(p):s(p)}function h(p){return p===46?(t.consume(p),i=0,u):p===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),n):g(p)}function g(p){if((p===45||Fn(p))&&i++<63){const f=p===45?g:h;return t.consume(p),f}return s(p)}}const Qa={partial:!0,tokenize:P1};function P1(t,n,s){return i;function i(l){return Dt(l)?zt(t,r,"linePrefix")(l):r(l)}function r(l){return l===null||Nt(l)?n(l):s(l)}}const tp={continuation:{tokenize:T1},exit:R1,name:"blockQuote",tokenize:_1};function _1(t,n,s){const i=this;return r;function r(o){if(o===62){const d=i.containerState;return d.open||(t.enter("blockQuote",{_container:!0}),d.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(o),t.exit("blockQuoteMarker"),l}return s(o)}function l(o){return Dt(o)?(t.enter("blockQuotePrefixWhitespace"),t.consume(o),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),n):(t.exit("blockQuotePrefix"),n(o))}}function T1(t,n,s){const i=this;return r;function r(o){return Dt(o)?zt(t,l,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):l(o)}function l(o){return t.attempt(tp,n,s)(o)}}function R1(t){t.exit("blockQuote")}const np={name:"characterEscape",tokenize:I1};function I1(t,n,s){return i;function i(l){return t.enter("characterEscape"),t.enter("escapeMarker"),t.consume(l),t.exit("escapeMarker"),r}function r(l){return y1(l)?(t.enter("characterEscapeValue"),t.consume(l),t.exit("characterEscapeValue"),t.exit("characterEscape"),n):s(l)}}const sp={name:"characterReference",tokenize:$1};function $1(t,n,s){const i=this;let r=0,l,o;return d;function d(h){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(h),t.exit("characterReferenceMarker"),m}function m(h){return h===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(h),t.exit("characterReferenceMarkerNumeric"),c):(t.enter("characterReferenceValue"),l=31,o=Fn,u(h))}function c(h){return h===88||h===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(h),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),l=6,o=v1,u):(t.enter("characterReferenceValue"),l=7,o=Ao,u(h))}function u(h){if(h===59&&r){const g=t.exit("characterReferenceValue");return o===Fn&&!cc(i.sliceSerialize(g))?s(h):(t.enter("characterReferenceMarker"),t.consume(h),t.exit("characterReferenceMarker"),t.exit("characterReference"),n)}return o(h)&&r++<l?(t.consume(h),u):s(h)}}const uu={partial:!0,tokenize:F1},mu={concrete:!0,name:"codeFenced",tokenize:D1};function D1(t,n,s){const i=this,r={partial:!0,tokenize:_};let l=0,o=0,d;return m;function m(N){return c(N)}function c(N){const M=i.events[i.events.length-1];return l=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[1],!0).length:0,d=N,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(N)}function u(N){return N===d?(o++,t.consume(N),u):o<3?s(N):(t.exit("codeFencedFenceSequence"),Dt(N)?zt(t,h,"whitespace")(N):h(N))}function h(N){return N===null||Nt(N)?(t.exit("codeFencedFence"),i.interrupt?n(N):t.check(uu,b,j)(N)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),g(N))}function g(N){return N===null||Nt(N)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),h(N)):Dt(N)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),zt(t,p,"whitespace")(N)):N===96&&N===d?s(N):(t.consume(N),g)}function p(N){return N===null||Nt(N)?h(N):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),f(N))}function f(N){return N===null||Nt(N)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),h(N)):N===96&&N===d?s(N):(t.consume(N),f)}function b(N){return t.attempt(r,j,v)(N)}function v(N){return t.enter("lineEnding"),t.consume(N),t.exit("lineEnding"),y}function y(N){return l>0&&Dt(N)?zt(t,k,"linePrefix",l+1)(N):k(N)}function k(N){return N===null||Nt(N)?t.check(uu,b,j)(N):(t.enter("codeFlowValue"),A(N))}function A(N){return N===null||Nt(N)?(t.exit("codeFlowValue"),k(N)):(t.consume(N),A)}function j(N){return t.exit("codeFenced"),n(N)}function _(N,M,w){let R=0;return E;function E(T){return N.enter("lineEnding"),N.consume(T),N.exit("lineEnding"),I}function I(T){return N.enter("codeFencedFence"),Dt(T)?zt(N,L,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):L(T)}function L(T){return T===d?(N.enter("codeFencedFenceSequence"),ee(T)):w(T)}function ee(T){return T===d?(R++,N.consume(T),ee):R>=o?(N.exit("codeFencedFenceSequence"),Dt(T)?zt(N,$,"whitespace")(T):$(T)):w(T)}function $(T){return T===null||Nt(T)?(N.exit("codeFencedFence"),M(T)):w(T)}}}function F1(t,n,s){const i=this;return r;function r(o){return o===null?s(o):(t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),l)}function l(o){return i.parser.lazy[i.now().line]?s(o):n(o)}}const Pl={name:"codeIndented",tokenize:z1},L1={partial:!0,tokenize:O1};function z1(t,n,s){const i=this;return r;function r(c){return t.enter("codeIndented"),zt(t,l,"linePrefix",5)(c)}function l(c){const u=i.events[i.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?o(c):s(c)}function o(c){return c===null?m(c):Nt(c)?t.attempt(L1,o,m)(c):(t.enter("codeFlowValue"),d(c))}function d(c){return c===null||Nt(c)?(t.exit("codeFlowValue"),o(c)):(t.consume(c),d)}function m(c){return t.exit("codeIndented"),n(c)}}function O1(t,n,s){const i=this;return r;function r(o){return i.parser.lazy[i.now().line]?s(o):Nt(o)?(t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),r):zt(t,l,"linePrefix",5)(o)}function l(o){const d=i.events[i.events.length-1];return d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?n(o):Nt(o)?r(o):s(o)}}const B1={name:"codeText",previous:H1,resolve:U1,tokenize:q1};function U1(t){let n=t.length-4,s=3,i,r;if((t[s][1].type==="lineEnding"||t[s][1].type==="space")&&(t[n][1].type==="lineEnding"||t[n][1].type==="space")){for(i=s;++i<n;)if(t[i][1].type==="codeTextData"){t[s][1].type="codeTextPadding",t[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(i=s-1,n++;++i<=n;)r===void 0?i!==n&&t[i][1].type!=="lineEnding"&&(r=i):(i===n||t[i][1].type==="lineEnding")&&(t[r][1].type="codeTextData",i!==r+2&&(t[r][1].end=t[i-1][1].end,t.splice(r+2,i-r-2),n-=i-r-2,i=r+2),r=void 0);return t}function H1(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function q1(t,n,s){let i=0,r,l;return o;function o(h){return t.enter("codeText"),t.enter("codeTextSequence"),d(h)}function d(h){return h===96?(t.consume(h),i++,d):(t.exit("codeTextSequence"),m(h))}function m(h){return h===null?s(h):h===32?(t.enter("space"),t.consume(h),t.exit("space"),m):h===96?(l=t.enter("codeTextSequence"),r=0,u(h)):Nt(h)?(t.enter("lineEnding"),t.consume(h),t.exit("lineEnding"),m):(t.enter("codeTextData"),c(h))}function c(h){return h===null||h===32||h===96||Nt(h)?(t.exit("codeTextData"),m(h)):(t.consume(h),c)}function u(h){return h===96?(t.consume(h),r++,u):r===i?(t.exit("codeTextSequence"),t.exit("codeText"),n(h)):(l.type="codeTextData",c(h))}}class V1{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 l=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&fa(this.left,i),l.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),fa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),fa(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);fa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);fa(this.left,s.reverse())}}}function fa(t,n){let s=0;if(n.length<1e4)t.push(...n);else for(;s<n.length;)t.push(...n.slice(s,s+1e4)),s+=1e4}function ip(t){const n={};let s=-1,i,r,l,o,d,m,c;const u=new V1(t);for(;++s<u.length;){for(;s in n;)s=n[s];if(i=u.get(s),s&&i[1].type==="chunkFlow"&&u.get(s-1)[1].type==="listItemPrefix"&&(m=i[1]._tokenizer.events,l=0,l<m.length&&m[l][1].type==="lineEndingBlank"&&(l+=2),l<m.length&&m[l][1].type==="content"))for(;++l<m.length&&m[l][1].type!=="content";)m[l][1].type==="chunkText"&&(m[l][1]._isInFirstContentOfListItem=!0,l++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,W1(u,s)),s=n[s],c=!0);else if(i[1]._container){for(l=s,r=void 0;l--;)if(o=u.get(l),o[1].type==="lineEnding"||o[1].type==="lineEndingBlank")o[0]==="enter"&&(r&&(u.get(r)[1].type="lineEndingBlank"),o[1].type="lineEnding",r=l);else if(!(o[1].type==="linePrefix"||o[1].type==="listItemIndent"))break;r&&(i[1].end={...u.get(r)[1].start},d=u.slice(r,s),d.unshift(i),u.splice(r,s-r+1,d))}}return hs(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!c}function W1(t,n){const s=t.get(n)[1],i=t.get(n)[2];let r=n-1;const l=[];let o=s._tokenizer;o||(o=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const d=o.events,m=[],c={};let u,h,g=-1,p=s,f=0,b=0;const v=[b];for(;p;){for(;t.get(++r)[1]!==p;);l.push(r),p._tokenizer||(u=i.sliceStream(p),p.next||u.push(null),h&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<d.length;)d[g][0]==="exit"&&d[g-1][0]==="enter"&&d[g][1].type===d[g-1][1].type&&d[g][1].start.line!==d[g][1].end.line&&(b=g+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const y=d.slice(v[g],v[g+1]),k=l.pop();m.push([k,k+y.length-1]),t.splice(k,2,y)}for(m.reverse(),g=-1;++g<m.length;)c[f+m[g][0]]=f+m[g][1],f+=m[g][1]-m[g][0]-1;return c}const K1={resolve:J1,tokenize:Y1},G1={partial:!0,tokenize:Q1};function J1(t){return ip(t),t}function Y1(t,n){let s;return i;function i(d){return t.enter("content"),s=t.enter("chunkContent",{contentType:"content"}),r(d)}function r(d){return d===null?l(d):Nt(d)?t.check(G1,o,l)(d):(t.consume(d),r)}function l(d){return t.exit("chunkContent"),t.exit("content"),n(d)}function o(d){return t.consume(d),t.exit("chunkContent"),s.next=t.enter("chunkContent",{contentType:"content",previous:s}),s=s.next,r}}function Q1(t,n,s){const i=this;return r;function r(o){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),zt(t,l,"linePrefix")}function l(o){if(o===null||Nt(o))return s(o);const d=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&d&&d[1].type==="linePrefix"&&d[2].sliceSerialize(d[1],!0).length>=4?n(o):t.interrupt(i.parser.constructs.flow,s,n)(o)}}function ap(t,n,s,i,r,l,o,d,m){const c=m||Number.POSITIVE_INFINITY;let u=0;return h;function h(y){return y===60?(t.enter(i),t.enter(r),t.enter(l),t.consume(y),t.exit(l),g):y===null||y===32||y===41||Fr(y)?s(y):(t.enter(i),t.enter(o),t.enter(d),t.enter("chunkString",{contentType:"string"}),b(y))}function g(y){return y===62?(t.enter(l),t.consume(y),t.exit(l),t.exit(r),t.exit(i),n):(t.enter(d),t.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(t.exit("chunkString"),t.exit(d),g(y)):y===null||y===60||Nt(y)?s(y):(t.consume(y),y===92?f:p)}function f(y){return y===60||y===62||y===92?(t.consume(y),p):p(y)}function b(y){return!u&&(y===null||y===41||Gt(y))?(t.exit("chunkString"),t.exit(d),t.exit(o),t.exit(i),n(y)):u<c&&y===40?(t.consume(y),u++,b):y===41?(t.consume(y),u--,b):y===null||y===32||y===40||Fr(y)?s(y):(t.consume(y),y===92?v:b)}function v(y){return y===40||y===41||y===92?(t.consume(y),b):b(y)}}function rp(t,n,s,i,r,l){const o=this;let d=0,m;return c;function c(p){return t.enter(i),t.enter(r),t.consume(p),t.exit(r),t.enter(l),u}function u(p){return d>999||p===null||p===91||p===93&&!m||p===94&&!d&&"_hiddenFootnoteSupport"in o.parser.constructs?s(p):p===93?(t.exit(l),t.enter(r),t.consume(p),t.exit(r),t.exit(i),n):Nt(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||Nt(p)||d++>999?(t.exit("chunkString"),u(p)):(t.consume(p),m||(m=!Dt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(t.consume(p),d++,h):h(p)}}function lp(t,n,s,i,r,l){let o;return d;function d(g){return g===34||g===39||g===40?(t.enter(i),t.enter(r),t.consume(g),t.exit(r),o=g===40?41:g,m):s(g)}function m(g){return g===o?(t.enter(r),t.consume(g),t.exit(r),t.exit(i),n):(t.enter(l),c(g))}function c(g){return g===o?(t.exit(l),m(o)):g===null?s(g):Nt(g)?(t.enter("lineEnding"),t.consume(g),t.exit("lineEnding"),zt(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===o||g===null||Nt(g)?(t.exit("chunkString"),c(g)):(t.consume(g),g===92?h:u)}function h(g){return g===o||g===92?(t.consume(g),u):u(g)}}function Pa(t,n){let s;return i;function i(r){return Nt(r)?(t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),s=!0,i):Dt(r)?zt(t,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const X1={name:"definition",tokenize:eS},Z1={partial:!0,tokenize:tS};function eS(t,n,s){const i=this;let r;return l;function l(p){return t.enter("definition"),o(p)}function o(p){return rp.call(i,t,d,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function d(p){return r=As(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),m):s(p)}function m(p){return Gt(p)?Pa(t,c)(p):c(p)}function c(p){return ap(t,u,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(Z1,h,h)(p)}function h(p){return Dt(p)?zt(t,g,"whitespace")(p):g(p)}function g(p){return p===null||Nt(p)?(t.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function tS(t,n,s){return i;function i(d){return Gt(d)?Pa(t,r)(d):s(d)}function r(d){return lp(t,l,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function l(d){return Dt(d)?zt(t,o,"whitespace")(d):o(d)}function o(d){return d===null||Nt(d)?n(d):s(d)}}const nS={name:"hardBreakEscape",tokenize:sS};function sS(t,n,s){return i;function i(l){return t.enter("hardBreakEscape"),t.consume(l),r}function r(l){return Nt(l)?(t.exit("hardBreakEscape"),n(l)):s(l)}}const iS={name:"headingAtx",resolve:aS,tokenize:rS};function aS(t,n){let s=t.length-2,i=3,r,l;return t[i][1].type==="whitespace"&&(i+=2),s-2>i&&t[s][1].type==="whitespace"&&(s-=2),t[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&t[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:t[i][1].start,end:t[s][1].end},l={type:"chunkText",start:t[i][1].start,end:t[s][1].end,contentType:"text"},hs(t,i,s-i+1,[["enter",r,n],["enter",l,n],["exit",l,n],["exit",r,n]])),t}function rS(t,n,s){let i=0;return r;function r(u){return t.enter("atxHeading"),l(u)}function l(u){return t.enter("atxHeadingSequence"),o(u)}function o(u){return u===35&&i++<6?(t.consume(u),o):u===null||Gt(u)?(t.exit("atxHeadingSequence"),d(u)):s(u)}function d(u){return u===35?(t.enter("atxHeadingSequence"),m(u)):u===null||Nt(u)?(t.exit("atxHeading"),n(u)):Dt(u)?zt(t,d,"whitespace")(u):(t.enter("atxHeadingText"),c(u))}function m(u){return u===35?(t.consume(u),m):(t.exit("atxHeadingSequence"),d(u))}function c(u){return u===null||u===35||Gt(u)?(t.exit("atxHeadingText"),d(u)):(t.consume(u),c)}}const lS=["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"],hu=["pre","script","style","textarea"],oS={concrete:!0,name:"htmlFlow",resolveTo:uS,tokenize:mS},cS={partial:!0,tokenize:pS},dS={partial:!0,tokenize:hS};function uS(t){let n=t.length;for(;n--&&!(t[n][0]==="enter"&&t[n][1].type==="htmlFlow"););return n>1&&t[n-2][1].type==="linePrefix"&&(t[n][1].start=t[n-2][1].start,t[n+1][1].start=t[n-2][1].start,t.splice(n-2,2)),t}function mS(t,n,s){const i=this;let r,l,o,d,m;return c;function c(C){return u(C)}function u(C){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(C),h}function h(C){return C===33?(t.consume(C),g):C===47?(t.consume(C),l=!0,b):C===63?(t.consume(C),r=3,i.interrupt?n:P):Wn(C)?(t.consume(C),o=String.fromCharCode(C),v):s(C)}function g(C){return C===45?(t.consume(C),r=2,p):C===91?(t.consume(C),r=5,d=0,f):Wn(C)?(t.consume(C),r=4,i.interrupt?n:P):s(C)}function p(C){return C===45?(t.consume(C),i.interrupt?n:P):s(C)}function f(C){const V="CDATA[";return C===V.charCodeAt(d++)?(t.consume(C),d===V.length?i.interrupt?n:L:f):s(C)}function b(C){return Wn(C)?(t.consume(C),o=String.fromCharCode(C),v):s(C)}function v(C){if(C===null||C===47||C===62||Gt(C)){const V=C===47,de=o.toLowerCase();return!V&&!l&&hu.includes(de)?(r=1,i.interrupt?n(C):L(C)):lS.includes(o.toLowerCase())?(r=6,V?(t.consume(C),y):i.interrupt?n(C):L(C)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(C):l?k(C):A(C))}return C===45||Fn(C)?(t.consume(C),o+=String.fromCharCode(C),v):s(C)}function y(C){return C===62?(t.consume(C),i.interrupt?n:L):s(C)}function k(C){return Dt(C)?(t.consume(C),k):E(C)}function A(C){return C===47?(t.consume(C),E):C===58||C===95||Wn(C)?(t.consume(C),j):Dt(C)?(t.consume(C),A):E(C)}function j(C){return C===45||C===46||C===58||C===95||Fn(C)?(t.consume(C),j):_(C)}function _(C){return C===61?(t.consume(C),N):Dt(C)?(t.consume(C),_):A(C)}function N(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(t.consume(C),m=C,M):Dt(C)?(t.consume(C),N):w(C)}function M(C){return C===m?(t.consume(C),m=null,R):C===null||Nt(C)?s(C):(t.consume(C),M)}function w(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Gt(C)?_(C):(t.consume(C),w)}function R(C){return C===47||C===62||Dt(C)?A(C):s(C)}function E(C){return C===62?(t.consume(C),I):s(C)}function I(C){return C===null||Nt(C)?L(C):Dt(C)?(t.consume(C),I):s(C)}function L(C){return C===45&&r===2?(t.consume(C),S):C===60&&r===1?(t.consume(C),Y):C===62&&r===4?(t.consume(C),O):C===63&&r===3?(t.consume(C),P):C===93&&r===5?(t.consume(C),G):Nt(C)&&(r===6||r===7)?(t.exit("htmlFlowData"),t.check(cS,X,ee)(C)):C===null||Nt(C)?(t.exit("htmlFlowData"),ee(C)):(t.consume(C),L)}function ee(C){return t.check(dS,$,X)(C)}function $(C){return t.enter("lineEnding"),t.consume(C),t.exit("lineEnding"),T}function T(C){return C===null||Nt(C)?ee(C):(t.enter("htmlFlowData"),L(C))}function S(C){return C===45?(t.consume(C),P):L(C)}function Y(C){return C===47?(t.consume(C),o="",K):L(C)}function K(C){if(C===62){const V=o.toLowerCase();return hu.includes(V)?(t.consume(C),O):L(C)}return Wn(C)&&o.length<8?(t.consume(C),o+=String.fromCharCode(C),K):L(C)}function G(C){return C===93?(t.consume(C),P):L(C)}function P(C){return C===62?(t.consume(C),O):C===45&&r===2?(t.consume(C),P):L(C)}function O(C){return C===null||Nt(C)?(t.exit("htmlFlowData"),X(C)):(t.consume(C),O)}function X(C){return t.exit("htmlFlow"),n(C)}}function hS(t,n,s){const i=this;return r;function r(o){return Nt(o)?(t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),l):s(o)}function l(o){return i.parser.lazy[i.now().line]?s(o):n(o)}}function pS(t,n,s){return i;function i(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),t.attempt(Qa,n,s)}}const fS={name:"htmlText",tokenize:gS};function gS(t,n,s){const i=this;let r,l,o;return d;function d(P){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(P),m}function m(P){return P===33?(t.consume(P),c):P===47?(t.consume(P),_):P===63?(t.consume(P),A):Wn(P)?(t.consume(P),w):s(P)}function c(P){return P===45?(t.consume(P),u):P===91?(t.consume(P),l=0,f):Wn(P)?(t.consume(P),k):s(P)}function u(P){return P===45?(t.consume(P),p):s(P)}function h(P){return P===null?s(P):P===45?(t.consume(P),g):Nt(P)?(o=h,Y(P)):(t.consume(P),h)}function g(P){return P===45?(t.consume(P),p):h(P)}function p(P){return P===62?S(P):P===45?g(P):h(P)}function f(P){const O="CDATA[";return P===O.charCodeAt(l++)?(t.consume(P),l===O.length?b:f):s(P)}function b(P){return P===null?s(P):P===93?(t.consume(P),v):Nt(P)?(o=b,Y(P)):(t.consume(P),b)}function v(P){return P===93?(t.consume(P),y):b(P)}function y(P){return P===62?S(P):P===93?(t.consume(P),y):b(P)}function k(P){return P===null||P===62?S(P):Nt(P)?(o=k,Y(P)):(t.consume(P),k)}function A(P){return P===null?s(P):P===63?(t.consume(P),j):Nt(P)?(o=A,Y(P)):(t.consume(P),A)}function j(P){return P===62?S(P):A(P)}function _(P){return Wn(P)?(t.consume(P),N):s(P)}function N(P){return P===45||Fn(P)?(t.consume(P),N):M(P)}function M(P){return Nt(P)?(o=M,Y(P)):Dt(P)?(t.consume(P),M):S(P)}function w(P){return P===45||Fn(P)?(t.consume(P),w):P===47||P===62||Gt(P)?R(P):s(P)}function R(P){return P===47?(t.consume(P),S):P===58||P===95||Wn(P)?(t.consume(P),E):Nt(P)?(o=R,Y(P)):Dt(P)?(t.consume(P),R):S(P)}function E(P){return P===45||P===46||P===58||P===95||Fn(P)?(t.consume(P),E):I(P)}function I(P){return P===61?(t.consume(P),L):Nt(P)?(o=I,Y(P)):Dt(P)?(t.consume(P),I):R(P)}function L(P){return P===null||P===60||P===61||P===62||P===96?s(P):P===34||P===39?(t.consume(P),r=P,ee):Nt(P)?(o=L,Y(P)):Dt(P)?(t.consume(P),L):(t.consume(P),$)}function ee(P){return P===r?(t.consume(P),r=void 0,T):P===null?s(P):Nt(P)?(o=ee,Y(P)):(t.consume(P),ee)}function $(P){return P===null||P===34||P===39||P===60||P===61||P===96?s(P):P===47||P===62||Gt(P)?R(P):(t.consume(P),$)}function T(P){return P===47||P===62||Gt(P)?R(P):s(P)}function S(P){return P===62?(t.consume(P),t.exit("htmlTextData"),t.exit("htmlText"),n):s(P)}function Y(P){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(P),t.exit("lineEnding"),K}function K(P){return Dt(P)?zt(t,G,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):G(P)}function G(P){return t.enter("htmlTextData"),o(P)}}const dc={name:"labelEnd",resolveAll:yS,resolveTo:kS,tokenize:jS},bS={tokenize:wS},xS={tokenize:NS},vS={tokenize:SS};function yS(t){let n=-1;const s=[];for(;++n<t.length;){const i=t[n][1];if(s.push(t[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return t.length!==s.length&&hs(t,0,t.length,s),t}function kS(t,n){let s=t.length,i=0,r,l,o,d;for(;s--;)if(r=t[s][1],l){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;t[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(o){if(t[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(l=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(o=s);const m={type:t[l][1].type==="labelLink"?"link":"image",start:{...t[l][1].start},end:{...t[t.length-1][1].end}},c={type:"label",start:{...t[l][1].start},end:{...t[o][1].end}},u={type:"labelText",start:{...t[l+i+2][1].end},end:{...t[o-2][1].start}};return d=[["enter",m,n],["enter",c,n]],d=js(d,t.slice(l+1,l+i+3)),d=js(d,[["enter",u,n]]),d=js(d,nl(n.parser.constructs.insideSpan.null,t.slice(l+i+4,o-3),n)),d=js(d,[["exit",u,n],t[o-2],t[o-1],["exit",c,n]]),d=js(d,t.slice(o+1)),d=js(d,[["exit",m,n]]),hs(t,l,t.length,d),t}function jS(t,n,s){const i=this;let r=i.events.length,l,o;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){l=i.events[r][1];break}return d;function d(g){return l?l._inactive?h(g):(o=i.parser.defined.includes(As(i.sliceSerialize({start:l.end,end:i.now()}))),t.enter("labelEnd"),t.enter("labelMarker"),t.consume(g),t.exit("labelMarker"),t.exit("labelEnd"),m):s(g)}function m(g){return g===40?t.attempt(bS,u,o?u:h)(g):g===91?t.attempt(xS,u,o?c:h)(g):o?u(g):h(g)}function c(g){return t.attempt(vS,u,h)(g)}function u(g){return n(g)}function h(g){return l._balanced=!0,s(g)}}function wS(t,n,s){return i;function i(h){return t.enter("resource"),t.enter("resourceMarker"),t.consume(h),t.exit("resourceMarker"),r}function r(h){return Gt(h)?Pa(t,l)(h):l(h)}function l(h){return h===41?u(h):ap(t,o,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function o(h){return Gt(h)?Pa(t,m)(h):u(h)}function d(h){return s(h)}function m(h){return h===34||h===39||h===40?lp(t,c,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):u(h)}function c(h){return Gt(h)?Pa(t,u)(h):u(h)}function u(h){return h===41?(t.enter("resourceMarker"),t.consume(h),t.exit("resourceMarker"),t.exit("resource"),n):s(h)}}function NS(t,n,s){const i=this;return r;function r(d){return rp.call(i,t,l,o,"reference","referenceMarker","referenceString")(d)}function l(d){return i.parser.defined.includes(As(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(d):s(d)}function o(d){return s(d)}}function SS(t,n,s){return i;function i(l){return t.enter("reference"),t.enter("referenceMarker"),t.consume(l),t.exit("referenceMarker"),r}function r(l){return l===93?(t.enter("referenceMarker"),t.consume(l),t.exit("referenceMarker"),t.exit("reference"),n):s(l)}}const CS={name:"labelStartImage",resolveAll:dc.resolveAll,tokenize:ES};function ES(t,n,s){const i=this;return r;function r(d){return t.enter("labelImage"),t.enter("labelImageMarker"),t.consume(d),t.exit("labelImageMarker"),l}function l(d){return d===91?(t.enter("labelMarker"),t.consume(d),t.exit("labelMarker"),t.exit("labelImage"),o):s(d)}function o(d){return d===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(d):n(d)}}const MS={name:"labelStartLink",resolveAll:dc.resolveAll,tokenize:AS};function AS(t,n,s){const i=this;return r;function r(o){return t.enter("labelLink"),t.enter("labelMarker"),t.consume(o),t.exit("labelMarker"),t.exit("labelLink"),l}function l(o){return o===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(o):n(o)}}const _l={name:"lineEnding",tokenize:PS};function PS(t,n){return s;function s(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),zt(t,n,"linePrefix")}}const Nr={name:"thematicBreak",tokenize:_S};function _S(t,n,s){let i=0,r;return l;function l(c){return t.enter("thematicBreak"),o(c)}function o(c){return r=c,d(c)}function d(c){return c===r?(t.enter("thematicBreakSequence"),m(c)):i>=3&&(c===null||Nt(c))?(t.exit("thematicBreak"),n(c)):s(c)}function m(c){return c===r?(t.consume(c),i++,m):(t.exit("thematicBreakSequence"),Dt(c)?zt(t,d,"whitespace")(c):d(c))}}const es={continuation:{tokenize:$S},exit:FS,name:"list",tokenize:IS},TS={partial:!0,tokenize:LS},RS={partial:!0,tokenize:DS};function IS(t,n,s){const i=this,r=i.events[i.events.length-1];let l=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,o=0;return d;function d(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Ao(p)){if(i.containerState.type||(i.containerState.type=f,t.enter(f,{_container:!0})),f==="listUnordered")return t.enter("listItemPrefix"),p===42||p===45?t.check(Nr,s,c)(p):c(p);if(!i.interrupt||p===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),m(p)}return s(p)}function m(p){return Ao(p)&&++o<10?(t.consume(p),m):(!i.interrupt||o<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(t.exit("listItemValue"),c(p)):s(p)}function c(p){return t.enter("listItemMarker"),t.consume(p),t.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,t.check(Qa,i.interrupt?s:u,t.attempt(TS,g,h))}function u(p){return i.containerState.initialBlankLine=!0,l++,g(p)}function h(p){return Dt(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=l+i.sliceSerialize(t.exit("listItemPrefix"),!0).length,n(p)}}function $S(t,n,s){const i=this;return i.containerState._closeFlow=void 0,t.check(Qa,r,l);function r(d){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,zt(t,n,"listItemIndent",i.containerState.size+1)(d)}function l(d){return i.containerState.furtherBlankLines||!Dt(d)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,o(d)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,t.attempt(RS,n,o)(d))}function o(d){return i.containerState._closeFlow=!0,i.interrupt=void 0,zt(t,t.attempt(es,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function DS(t,n,s){const i=this;return zt(t,r,"listItemIndent",i.containerState.size+1);function r(l){const o=i.events[i.events.length-1];return o&&o[1].type==="listItemIndent"&&o[2].sliceSerialize(o[1],!0).length===i.containerState.size?n(l):s(l)}}function FS(t){t.exit(this.containerState.type)}function LS(t,n,s){const i=this;return zt(t,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(l){const o=i.events[i.events.length-1];return!Dt(l)&&o&&o[1].type==="listItemPrefixWhitespace"?n(l):s(l)}}const pu={name:"setextUnderline",resolveTo:zS,tokenize:OS};function zS(t,n){let s=t.length,i,r,l;for(;s--;)if(t[s][0]==="enter"){if(t[s][1].type==="content"){i=s;break}t[s][1].type==="paragraph"&&(r=s)}else t[s][1].type==="content"&&t.splice(s,1),!l&&t[s][1].type==="definition"&&(l=s);const o={type:"setextHeading",start:{...t[i][1].start},end:{...t[t.length-1][1].end}};return t[r][1].type="setextHeadingText",l?(t.splice(r,0,["enter",o,n]),t.splice(l+1,0,["exit",t[i][1],n]),t[i][1].end={...t[l][1].end}):t[i][1]=o,t.push(["exit",o,n]),t}function OS(t,n,s){const i=this;let r;return l;function l(c){let u=i.events.length,h;for(;u--;)if(i.events[u][1].type!=="lineEnding"&&i.events[u][1].type!=="linePrefix"&&i.events[u][1].type!=="content"){h=i.events[u][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(t.enter("setextHeadingLine"),r=c,o(c)):s(c)}function o(c){return t.enter("setextHeadingLineSequence"),d(c)}function d(c){return c===r?(t.consume(c),d):(t.exit("setextHeadingLineSequence"),Dt(c)?zt(t,m,"lineSuffix")(c):m(c))}function m(c){return c===null||Nt(c)?(t.exit("setextHeadingLine"),n(c)):s(c)}}const BS={tokenize:US};function US(t){const n=this,s=t.attempt(Qa,i,t.attempt(this.parser.constructs.flowInitial,r,zt(t,t.attempt(this.parser.constructs.flow,r,t.attempt(K1,r)),"linePrefix")));return s;function i(l){if(l===null){t.consume(l);return}return t.enter("lineEndingBlank"),t.consume(l),t.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(l){if(l===null){t.consume(l);return}return t.enter("lineEnding"),t.consume(l),t.exit("lineEnding"),n.currentConstruct=void 0,s}}const HS={resolveAll:cp()},qS=op("string"),VS=op("text");function op(t){return{resolveAll:cp(t==="text"?WS:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[t],l=s.attempt(r,o,d);return o;function o(u){return c(u)?l(u):d(u)}function d(u){if(u===null){s.consume(u);return}return s.enter("data"),s.consume(u),m}function m(u){return c(u)?(s.exit("data"),l(u)):(s.consume(u),m)}function c(u){if(u===null)return!0;const h=r[u];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 cp(t){return n;function n(s,i){let r=-1,l;for(;++r<=s.length;)l===void 0?s[r]&&s[r][1].type==="data"&&(l=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==l+2&&(s[l][1].end=s[r-1][1].end,s.splice(l+2,r-l-2),r=l+2),l=void 0);return t?t(s,i):s}}function WS(t,n){let s=0;for(;++s<=t.length;)if((s===t.length||t[s][1].type==="lineEnding")&&t[s-1][1].type==="data"){const i=t[s-1][1],r=n.sliceStream(i);let l=r.length,o=-1,d=0,m;for(;l--;){const c=r[l];if(typeof c=="string"){for(o=c.length;c.charCodeAt(o-1)===32;)d++,o--;if(o)break;o=-1}else if(c===-2)m=!0,d++;else if(c!==-1){l++;break}}if(n._contentTypeTextTrailing&&s===t.length&&(d=0),d){const c={type:s===t.length||m||d<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:l?o:i.start._bufferIndex+o,_index:i.start._index+l,line:i.end.line,column:i.end.column-d,offset:i.end.offset-d},end:{...i.end}};i.end={...c.start},i.start.offset===i.end.offset?Object.assign(i,c):(t.splice(s,0,["enter",c,n],["exit",c,n]),s+=2)}s++}return t}const KS={42:es,43:es,45:es,48:es,49:es,50:es,51:es,52:es,53:es,54:es,55:es,56:es,57:es,62:tp},GS={91:X1},JS={[-2]:Pl,[-1]:Pl,32:Pl},YS={35:iS,42:Nr,45:[pu,Nr],60:oS,61:pu,95:Nr,96:mu,126:mu},QS={38:sp,92:np},XS={[-5]:_l,[-4]:_l,[-3]:_l,33:CS,38:sp,42:Po,60:[M1,fS],91:MS,92:[nS,np],93:dc,95:Po,96:B1},ZS={null:[Po,HS]},e0={null:[42,95]},t0={null:[]},n0=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:e0,contentInitial:GS,disable:t0,document:KS,flow:YS,flowInitial:JS,insideSpan:ZS,string:QS,text:XS},Symbol.toStringTag,{value:"Module"}));function s0(t,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={},l=[];let o=[],d=[];const m={attempt:M(_),check:M(N),consume:k,enter:A,exit:j,interrupt:M(N,{interrupt:!0})},c={code:null,containerState:{},defineSkip:b,events:[],now:f,parser:t,previous:null,sliceSerialize:g,sliceStream:p,write:h};let u=n.tokenize.call(c,m);return n.resolveAll&&l.push(n),c;function h(I){return o=js(o,I),v(),o[o.length-1]!==null?[]:(w(n,0),c.events=nl(l,c.events,c),c.events)}function g(I,L){return a0(p(I),L)}function p(I){return i0(o,I)}function f(){const{_bufferIndex:I,_index:L,line:ee,column:$,offset:T}=i;return{_bufferIndex:I,_index:L,line:ee,column:$,offset:T}}function b(I){r[I.line]=I.column,E()}function v(){let I;for(;i._index<o.length;){const L=o[i._index];if(typeof L=="string")for(I=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===I&&i._bufferIndex<L.length;)y(L.charCodeAt(i._bufferIndex));else y(L)}}function y(I){u=u(I)}function k(I){Nt(I)?(i.line++,i.column=1,i.offset+=I===-3?2:1,E()):I!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===o[i._index].length&&(i._bufferIndex=-1,i._index++)),c.previous=I}function A(I,L){const ee=L||{};return ee.type=I,ee.start=f(),c.events.push(["enter",ee,c]),d.push(ee),ee}function j(I){const L=d.pop();return L.end=f(),c.events.push(["exit",L,c]),L}function _(I,L){w(I,L.from)}function N(I,L){L.restore()}function M(I,L){return ee;function ee($,T,S){let Y,K,G,P;return Array.isArray($)?X($):"tokenize"in $?X([$]):O($);function O(B){return J;function J(D){const he=D!==null&&B[D],q=D!==null&&B.null,W=[...Array.isArray(he)?he:he?[he]:[],...Array.isArray(q)?q:q?[q]:[]];return X(W)(D)}}function X(B){return Y=B,K=0,B.length===0?S:C(B[K])}function C(B){return J;function J(D){return P=R(),G=B,B.partial||(c.currentConstruct=B),B.name&&c.parser.constructs.disable.null.includes(B.name)?de():B.tokenize.call(L?Object.assign(Object.create(c),L):c,m,V,de)(D)}}function V(B){return I(G,P),T}function de(B){return P.restore(),++K<Y.length?C(Y[K]):S}}}function w(I,L){I.resolveAll&&!l.includes(I)&&l.push(I),I.resolve&&hs(c.events,L,c.events.length-L,I.resolve(c.events.slice(L),c)),I.resolveTo&&(c.events=I.resolveTo(c.events,c))}function R(){const I=f(),L=c.previous,ee=c.currentConstruct,$=c.events.length,T=Array.from(d);return{from:$,restore:S};function S(){i=I,c.previous=L,c.currentConstruct=ee,c.events.length=$,d=T,E()}}function E(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function i0(t,n){const s=n.start._index,i=n.start._bufferIndex,r=n.end._index,l=n.end._bufferIndex;let o;if(s===r)o=[t[s].slice(i,l)];else{if(o=t.slice(s,r),i>-1){const d=o[0];typeof d=="string"?o[0]=d.slice(i):o.shift()}l>0&&o.push(t[r].slice(0,l))}return o}function a0(t,n){let s=-1;const i=[];let r;for(;++s<t.length;){const l=t[s];let o;if(typeof l=="string")o=l;else switch(l){case-5:{o="\r";break}case-4:{o=`
|
|
599
|
+
`;break}case-3:{o=`\r
|
|
600
|
+
`;break}case-2:{o=n?" ":" ";break}case-1:{if(!n&&r)continue;o=" ";break}default:o=String.fromCharCode(l)}r=l===-2,i.push(o)}return i.join("")}function r0(t){const i={constructs:Zh([n0,...(t||{}).extensions||[]]),content:r(k1),defined:[],document:r(w1),flow:r(BS),lazy:{},string:r(qS),text:r(VS)};return i;function r(l){return o;function o(d){return s0(i,l,d)}}}function l0(t){for(;!ip(t););return t}const fu=/[\0\t\n\r]/g;function o0(){let t=1,n="",s=!0,i;return r;function r(l,o,d){const m=[];let c,u,h,g,p;for(l=n+(typeof l=="string"?l.toString():new TextDecoder(o||void 0).decode(l)),h=0,n="",s&&(l.charCodeAt(0)===65279&&h++,s=void 0);h<l.length;){if(fu.lastIndex=h,c=fu.exec(l),g=c&&c.index!==void 0?c.index:l.length,p=l.charCodeAt(g),!c){n=l.slice(h);break}if(p===10&&h===g&&i)m.push(-3),i=void 0;else switch(i&&(m.push(-5),i=void 0),h<g&&(m.push(l.slice(h,g)),t+=g-h),p){case 0:{m.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,m.push(-2);t++<u;)m.push(-1);break}case 10:{m.push(-4),t=1;break}default:i=!0,t=1}h=g+1}return d&&(i&&m.push(-5),n&&m.push(n),m.push(null)),m}}const c0=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function d0(t){return t.replace(c0,u0)}function u0(t,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),l=r===120||r===88;return ep(s.slice(l?2:1),l?16:10)}return cc(s)||t}const dp={}.hasOwnProperty;function m0(t,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),h0(s)(l0(r0(s).document().write(o0()(t,n,!0))))}function h0(t){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(ze),autolinkProtocol:R,autolinkEmail:R,atxHeading:l(Me),blockQuote:l(q),characterEscape:R,characterReference:R,codeFenced:l(W),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:l(W,o),codeText:l(me,o),codeTextData:R,data:R,codeFlowValue:R,definition:l(Re),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:l(ve),hardBreakEscape:l(_e),hardBreakTrailing:l(_e),htmlFlow:l(De,o),htmlFlowData:R,htmlText:l(De,o),htmlTextData:R,image:l(Oe),label:o,link:l(ze),listItem:l(Ae),listItemValue:g,listOrdered:l(Be,h),listUnordered:l(Be),paragraph:l(Ce),reference:C,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:l(Me),strong:l(Ge),thematicBreak:l(Xe)},exit:{atxHeading:m(),atxHeadingSequence:_,autolink:m(),autolinkEmail:he,autolinkProtocol:D,blockQuote:m(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:de,characterReferenceMarkerNumeric:de,characterReferenceValue:B,characterReference:J,codeFenced:m(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:E,codeIndented:m(y),codeText:m(T),codeTextData:E,data:E,definition:m(),definitionDestinationString:j,definitionLabelString:k,definitionTitleString:A,emphasis:m(),hardBreakEscape:m(L),hardBreakTrailing:m(L),htmlFlow:m(ee),htmlFlowData:E,htmlText:m($),htmlTextData:E,image:m(Y),label:G,labelText:K,lineEnding:I,link:m(S),listItem:m(),listOrdered:m(),listUnordered:m(),paragraph:m(),referenceString:V,resourceDestinationString:P,resourceTitleString:O,resource:X,setextHeading:m(w),setextHeadingLineSequence:M,setextHeadingText:N,strong:m(),thematicBreak:m()}};up(n,(t||{}).mdastExtensions||[]);const s={};return i;function i(re){let Z={type:"root",children:[]};const ye={stack:[Z],tokenStack:[],config:n,enter:d,exit:c,buffer:o,resume:u,data:s},ie=[];let Ie=-1;for(;++Ie<re.length;)if(re[Ie][1].type==="listOrdered"||re[Ie][1].type==="listUnordered")if(re[Ie][0]==="enter")ie.push(Ie);else{const pe=ie.pop();Ie=r(re,pe,Ie)}for(Ie=-1;++Ie<re.length;){const pe=n[re[Ie][0]];dp.call(pe,re[Ie][1].type)&&pe[re[Ie][1].type].call(Object.assign({sliceSerialize:re[Ie][2].sliceSerialize},ye),re[Ie][1])}if(ye.tokenStack.length>0){const pe=ye.tokenStack[ye.tokenStack.length-1];(pe[1]||gu).call(ye,void 0,pe[0])}for(Z.position={start:Qs(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:Qs(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Ie=-1;++Ie<n.transforms.length;)Z=n.transforms[Ie](Z)||Z;return Z}function r(re,Z,ye){let ie=Z-1,Ie=-1,pe=!1,Ue,dt,ht,ue;for(;++ie<=ye;){const te=re[ie];switch(te[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{te[0]==="enter"?Ie++:Ie--,ue=void 0;break}case"lineEndingBlank":{te[0]==="enter"&&(Ue&&!ue&&!Ie&&!ht&&(ht=ie),ue=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ue=void 0}if(!Ie&&te[0]==="enter"&&te[1].type==="listItemPrefix"||Ie===-1&&te[0]==="exit"&&(te[1].type==="listUnordered"||te[1].type==="listOrdered")){if(Ue){let ke=ie;for(dt=void 0;ke--;){const Ne=re[ke];if(Ne[1].type==="lineEnding"||Ne[1].type==="lineEndingBlank"){if(Ne[0]==="exit")continue;dt&&(re[dt][1].type="lineEndingBlank",pe=!0),Ne[1].type="lineEnding",dt=ke}else if(!(Ne[1].type==="linePrefix"||Ne[1].type==="blockQuotePrefix"||Ne[1].type==="blockQuotePrefixWhitespace"||Ne[1].type==="blockQuoteMarker"||Ne[1].type==="listItemIndent"))break}ht&&(!dt||ht<dt)&&(Ue._spread=!0),Ue.end=Object.assign({},dt?re[dt][1].start:te[1].end),re.splice(dt||ie,0,["exit",Ue,te[2]]),ie++,ye++}if(te[1].type==="listItemPrefix"){const ke={type:"listItem",_spread:!1,start:Object.assign({},te[1].start),end:void 0};Ue=ke,re.splice(ie,0,["enter",ke,te[2]]),ie++,ye++,ht=void 0,ue=!0}}}return re[Z][1]._spread=pe,ye}function l(re,Z){return ye;function ye(ie){d.call(this,re(ie),ie),Z&&Z.call(this,ie)}}function o(){this.stack.push({type:"fragment",children:[]})}function d(re,Z,ye){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([Z,ye||void 0]),re.position={start:Qs(Z.start),end:void 0}}function m(re){return Z;function Z(ye){re&&re.call(this,ye),c.call(this,ye)}}function c(re,Z){const ye=this.stack.pop(),ie=this.tokenStack.pop();if(ie)ie[0].type!==re.type&&(Z?Z.call(this,re,ie[0]):(ie[1]||gu).call(this,re,ie[0]));else throw new Error("Cannot close `"+re.type+"` ("+Aa({start:re.start,end:re.end})+"): it’s not open");ye.position.end=Qs(re.end)}function u(){return oc(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(re){if(this.data.expectingFirstListItemValue){const Z=this.stack[this.stack.length-2];Z.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.lang=re}function f(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.meta=re}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.value=re.replace(/(\r?\n|\r)$/g,"")}function k(re){const Z=this.resume(),ye=this.stack[this.stack.length-1];ye.label=Z,ye.identifier=As(this.sliceSerialize(re)).toLowerCase()}function A(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.title=re}function j(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.url=re}function _(re){const Z=this.stack[this.stack.length-1];if(!Z.depth){const ye=this.sliceSerialize(re).length;Z.depth=ye}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function M(re){const Z=this.stack[this.stack.length-1];Z.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function w(){this.data.setextHeadingSlurpLineEnding=void 0}function R(re){const ye=this.stack[this.stack.length-1].children;let ie=ye[ye.length-1];(!ie||ie.type!=="text")&&(ie=Te(),ie.position={start:Qs(re.start),end:void 0},ye.push(ie)),this.stack.push(ie)}function E(re){const Z=this.stack.pop();Z.value+=this.sliceSerialize(re),Z.position.end=Qs(re.end)}function I(re){const Z=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ye=Z.children[Z.children.length-1];ye.position.end=Qs(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Z.type)&&(R.call(this,re),E.call(this,re))}function L(){this.data.atHardBreak=!0}function ee(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.value=re}function $(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.value=re}function T(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.value=re}function S(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const Z=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=Z,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Y(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const Z=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=Z,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function K(re){const Z=this.sliceSerialize(re),ye=this.stack[this.stack.length-2];ye.label=d0(Z),ye.identifier=As(Z).toLowerCase()}function G(){const re=this.stack[this.stack.length-1],Z=this.resume(),ye=this.stack[this.stack.length-1];if(this.data.inReference=!0,ye.type==="link"){const ie=re.children;ye.children=ie}else ye.alt=Z}function P(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.url=re}function O(){const re=this.resume(),Z=this.stack[this.stack.length-1];Z.title=re}function X(){this.data.inReference=void 0}function C(){this.data.referenceType="collapsed"}function V(re){const Z=this.resume(),ye=this.stack[this.stack.length-1];ye.label=Z,ye.identifier=As(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function de(re){this.data.characterReferenceType=re.type}function B(re){const Z=this.sliceSerialize(re),ye=this.data.characterReferenceType;let ie;ye?(ie=ep(Z,ye==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ie=cc(Z);const Ie=this.stack[this.stack.length-1];Ie.value+=ie}function J(re){const Z=this.stack.pop();Z.position.end=Qs(re.end)}function D(re){E.call(this,re);const Z=this.stack[this.stack.length-1];Z.url=this.sliceSerialize(re)}function he(re){E.call(this,re);const Z=this.stack[this.stack.length-1];Z.url="mailto:"+this.sliceSerialize(re)}function q(){return{type:"blockquote",children:[]}}function W(){return{type:"code",lang:null,meta:null,value:""}}function me(){return{type:"inlineCode",value:""}}function Re(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ve(){return{type:"emphasis",children:[]}}function Me(){return{type:"heading",depth:0,children:[]}}function _e(){return{type:"break"}}function De(){return{type:"html",value:""}}function Oe(){return{type:"image",title:null,url:"",alt:null}}function ze(){return{type:"link",title:null,url:"",children:[]}}function Be(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function Ae(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function Ce(){return{type:"paragraph",children:[]}}function Ge(){return{type:"strong",children:[]}}function Te(){return{type:"text",value:""}}function Xe(){return{type:"thematicBreak"}}}function Qs(t){return{line:t.line,column:t.column,offset:t.offset}}function up(t,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?up(t,i):p0(t,i)}}function p0(t,n){let s;for(s in n)if(dp.call(n,s))switch(s){case"canContainEols":{const i=n[s];i&&t[s].push(...i);break}case"transforms":{const i=n[s];i&&t[s].push(...i);break}case"enter":case"exit":{const i=n[s];i&&Object.assign(t[s],i);break}}}function gu(t,n){throw t?new Error("Cannot close `"+t.type+"` ("+Aa({start:t.start,end:t.end})+"): a different token (`"+n.type+"`, "+Aa({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Aa({start:n.start,end:n.end})+") is still open")}function f0(t){const n=this;n.parser=s;function s(i){return m0(i,{...n.data("settings"),...t,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function g0(t,n){const s={type:"element",tagName:"blockquote",properties:{},children:t.wrap(t.all(n),!0)};return t.patch(n,s),t.applyData(n,s)}function b0(t,n){const s={type:"element",tagName:"br",properties:{},children:[]};return t.patch(n,s),[t.applyData(n,s),{type:"text",value:`
|
|
601
|
+
`}]}function x0(t,n){const s=n.value?n.value+`
|
|
602
|
+
`:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let l={type:"element",tagName:"code",properties:i,children:[{type:"text",value:s}]};return n.meta&&(l.data={meta:n.meta}),t.patch(n,l),l=t.applyData(n,l),l={type:"element",tagName:"pre",properties:{},children:[l]},t.patch(n,l),l}function v0(t,n){const s={type:"element",tagName:"del",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function y0(t,n){const s={type:"element",tagName:"em",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function k0(t,n){const s=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=oa(i.toLowerCase()),l=t.footnoteOrder.indexOf(i);let o,d=t.footnoteCounts.get(i);d===void 0?(d=0,t.footnoteOrder.push(i),o=t.footnoteOrder.length):o=l+1,d+=1,t.footnoteCounts.set(i,d);const m={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(d>1?"-"+d:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};t.patch(n,m);const c={type:"element",tagName:"sup",properties:{},children:[m]};return t.patch(n,c),t.applyData(n,c)}function j0(t,n){const s={type:"element",tagName:"h"+n.depth,properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function w0(t,n){if(t.options.allowDangerousHtml){const s={type:"raw",value:n.value};return t.patch(n,s),t.applyData(n,s)}}function mp(t,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=t.all(n),l=r[0];l&&l.type==="text"?l.value="["+l.value:r.unshift({type:"text",value:"["});const o=r[r.length-1];return o&&o.type==="text"?o.value+=i:r.push({type:"text",value:i}),r}function N0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return mp(t,n);const r={src:oa(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const l={type:"element",tagName:"img",properties:r,children:[]};return t.patch(n,l),t.applyData(n,l)}function S0(t,n){const s={src:oa(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 t.patch(n,i),t.applyData(n,i)}function C0(t,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};t.patch(n,s);const i={type:"element",tagName:"code",properties:{},children:[s]};return t.patch(n,i),t.applyData(n,i)}function E0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return mp(t,n);const r={href:oa(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const l={type:"element",tagName:"a",properties:r,children:t.all(n)};return t.patch(n,l),t.applyData(n,l)}function M0(t,n){const s={href:oa(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:t.all(n)};return t.patch(n,i),t.applyData(n,i)}function A0(t,n,s){const i=t.all(n),r=s?P0(s):hp(n),l={},o=[];if(typeof n.checked=="boolean"){const u=i[0];let h;u&&u.type==="element"&&u.tagName==="p"?h=u:(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:[]}),l.className=["task-list-item"]}let d=-1;for(;++d<i.length;){const u=i[d];(r||d!==0||u.type!=="element"||u.tagName!=="p")&&o.push({type:"text",value:`
|
|
603
|
+
`}),u.type==="element"&&u.tagName==="p"&&!r?o.push(...u.children):o.push(u)}const m=i[i.length-1];m&&(r||m.type!=="element"||m.tagName!=="p")&&o.push({type:"text",value:`
|
|
604
|
+
`});const c={type:"element",tagName:"li",properties:l,children:o};return t.patch(n,c),t.applyData(n,c)}function P0(t){let n=!1;if(t.type==="list"){n=t.spread||!1;const s=t.children;let i=-1;for(;!n&&++i<s.length;)n=hp(s[i])}return n}function hp(t){const n=t.spread;return n??t.children.length>1}function _0(t,n){const s={},i=t.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<i.length;){const o=i[r];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const l={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:t.wrap(i,!0)};return t.patch(n,l),t.applyData(n,l)}function T0(t,n){const s={type:"element",tagName:"p",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function R0(t,n){const s={type:"root",children:t.wrap(t.all(n))};return t.patch(n,s),t.applyData(n,s)}function I0(t,n){const s={type:"element",tagName:"strong",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function $0(t,n){const s=t.all(n),i=s.shift(),r=[];if(i){const o={type:"element",tagName:"thead",properties:{},children:t.wrap([i],!0)};t.patch(n.children[0],o),r.push(o)}if(s.length>0){const o={type:"element",tagName:"tbody",properties:{},children:t.wrap(s,!0)},d=ic(n.children[1]),m=Wh(n.children[n.children.length-1]);d&&m&&(o.position={start:d,end:m}),r.push(o)}const l={type:"element",tagName:"table",properties:{},children:t.wrap(r,!0)};return t.patch(n,l),t.applyData(n,l)}function D0(t,n,s){const i=s?s.children:void 0,l=(i?i.indexOf(n):1)===0?"th":"td",o=s&&s.type==="table"?s.align:void 0,d=o?o.length:n.children.length;let m=-1;const c=[];for(;++m<d;){const h=n.children[m],g={},p=o?o[m]:void 0;p&&(g.align=p);let f={type:"element",tagName:l,properties:g,children:[]};h&&(f.children=t.all(h),t.patch(h,f),f=t.applyData(h,f)),c.push(f)}const u={type:"element",tagName:"tr",properties:{},children:t.wrap(c,!0)};return t.patch(n,u),t.applyData(n,u)}function F0(t,n){const s={type:"element",tagName:"td",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}const bu=9,xu=32;function L0(t){const n=String(t),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const l=[];for(;i;)l.push(vu(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return l.push(vu(n.slice(r),r>0,!1)),l.join("")}function vu(t,n,s){let i=0,r=t.length;if(n){let l=t.codePointAt(i);for(;l===bu||l===xu;)i++,l=t.codePointAt(i)}if(s){let l=t.codePointAt(r-1);for(;l===bu||l===xu;)r--,l=t.codePointAt(r-1)}return r>i?t.slice(i,r):""}function z0(t,n){const s={type:"text",value:L0(String(n.value))};return t.patch(n,s),t.applyData(n,s)}function O0(t,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(n,s),t.applyData(n,s)}const B0={blockquote:g0,break:b0,code:x0,delete:v0,emphasis:y0,footnoteReference:k0,heading:j0,html:w0,imageReference:N0,image:S0,inlineCode:C0,linkReference:E0,link:M0,listItem:A0,list:_0,paragraph:T0,root:R0,strong:I0,table:$0,tableCell:F0,tableRow:D0,text:z0,thematicBreak:O0,toml:dr,yaml:dr,definition:dr,footnoteDefinition:dr};function dr(){}const pp=-1,sl=0,_a=1,Lr=2,uc=3,mc=4,hc=5,pc=6,fp=7,gp=8,yu=typeof self=="object"?self:globalThis,U0=(t,n)=>{const s=(r,l)=>(t.set(l,r),r),i=r=>{if(t.has(r))return t.get(r);const[l,o]=n[r];switch(l){case sl:case pp:return s(o,r);case _a:{const d=s([],r);for(const m of o)d.push(i(m));return d}case Lr:{const d=s({},r);for(const[m,c]of o)d[i(m)]=i(c);return d}case uc:return s(new Date(o),r);case mc:{const{source:d,flags:m}=o;return s(new RegExp(d,m),r)}case hc:{const d=s(new Map,r);for(const[m,c]of o)d.set(i(m),i(c));return d}case pc:{const d=s(new Set,r);for(const m of o)d.add(i(m));return d}case fp:{const{name:d,message:m}=o;return s(new yu[d](m),r)}case gp:return s(BigInt(o),r);case"BigInt":return s(Object(BigInt(o)),r);case"ArrayBuffer":return s(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:d}=new Uint8Array(o);return s(new DataView(d),o)}}return s(new yu[l](o),r)};return i},ku=t=>U0(new Map,t)(0),Di="",{toString:H0}={},{keys:q0}=Object,ga=t=>{const n=typeof t;if(n!=="object"||!t)return[sl,n];const s=H0.call(t).slice(8,-1);switch(s){case"Array":return[_a,Di];case"Object":return[Lr,Di];case"Date":return[uc,Di];case"RegExp":return[mc,Di];case"Map":return[hc,Di];case"Set":return[pc,Di];case"DataView":return[_a,s]}return s.includes("Array")?[_a,s]:s.includes("Error")?[fp,s]:[Lr,s]},ur=([t,n])=>t===sl&&(n==="function"||n==="symbol"),V0=(t,n,s,i)=>{const r=(o,d)=>{const m=i.push(o)-1;return s.set(d,m),m},l=o=>{if(s.has(o))return s.get(o);let[d,m]=ga(o);switch(d){case sl:{let u=o;switch(m){case"bigint":d=gp,u=o.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+m);u=null;break;case"undefined":return r([pp],o)}return r([d,u],o)}case _a:{if(m){let g=o;return m==="DataView"?g=new Uint8Array(o.buffer):m==="ArrayBuffer"&&(g=new Uint8Array(o)),r([m,[...g]],o)}const u=[],h=r([d,u],o);for(const g of o)u.push(l(g));return h}case Lr:{if(m)switch(m){case"BigInt":return r([m,o.toString()],o);case"Boolean":case"Number":case"String":return r([m,o.valueOf()],o)}if(n&&"toJSON"in o)return l(o.toJSON());const u=[],h=r([d,u],o);for(const g of q0(o))(t||!ur(ga(o[g])))&&u.push([l(g),l(o[g])]);return h}case uc:return r([d,o.toISOString()],o);case mc:{const{source:u,flags:h}=o;return r([d,{source:u,flags:h}],o)}case hc:{const u=[],h=r([d,u],o);for(const[g,p]of o)(t||!(ur(ga(g))||ur(ga(p))))&&u.push([l(g),l(p)]);return h}case pc:{const u=[],h=r([d,u],o);for(const g of o)(t||!ur(ga(g)))&&u.push(l(g));return h}}const{message:c}=o;return r([d,{name:m,message:c}],o)};return l},ju=(t,{json:n,lossy:s}={})=>{const i=[];return V0(!(n||s),!!n,new Map,i)(t),i},zr=typeof structuredClone=="function"?(t,n)=>n&&("json"in n||"lossy"in n)?ku(ju(t,n)):structuredClone(t):(t,n)=>ku(ju(t,n));function W0(t,n){const s=[{type:"text",value:"↩"}];return n>1&&s.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(n)}]}),s}function K0(t,n){return"Back to reference "+(t+1)+(n>1?"-"+n:"")}function G0(t){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",s=t.options.footnoteBackContent||W0,i=t.options.footnoteBackLabel||K0,r=t.options.footnoteLabel||"Footnotes",l=t.options.footnoteLabelTagName||"h2",o=t.options.footnoteLabelProperties||{className:["sr-only"]},d=[];let m=-1;for(;++m<t.footnoteOrder.length;){const c=t.footnoteById.get(t.footnoteOrder[m]);if(!c)continue;const u=t.all(c),h=String(c.identifier).toUpperCase(),g=oa(h.toLowerCase());let p=0;const f=[],b=t.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){f.length>0&&f.push({type:"text",value:" "});let k=typeof s=="string"?s:s(m,p);typeof k=="string"&&(k={type:"text",value:k}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(m,p),className:["data-footnote-backref"]},children:Array.isArray(k)?k:[k]})}const v=u[u.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const k=v.children[v.children.length-1];k&&k.type==="text"?k.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else u.push(...f);const y={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:t.wrap(u,!0)};t.patch(c,y),d.push(y)}if(d.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:l,properties:{...zr(o),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
605
|
+
`},{type:"element",tagName:"ol",properties:{},children:t.wrap(d,!0)},{type:"text",value:`
|
|
606
|
+
`}]}}const il=(function(t){if(t==null)return X0;if(typeof t=="function")return al(t);if(typeof t=="object")return Array.isArray(t)?J0(t):Y0(t);if(typeof t=="string")return Q0(t);throw new Error("Expected function, string, or object as test")});function J0(t){const n=[];let s=-1;for(;++s<t.length;)n[s]=il(t[s]);return al(i);function i(...r){let l=-1;for(;++l<n.length;)if(n[l].apply(this,r))return!0;return!1}}function Y0(t){const n=t;return al(s);function s(i){const r=i;let l;for(l in t)if(r[l]!==n[l])return!1;return!0}}function Q0(t){return al(n);function n(s){return s&&s.type===t}}function al(t){return n;function n(s,i,r){return!!(Z0(s)&&t.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function X0(){return!0}function Z0(t){return t!==null&&typeof t=="object"&&"type"in t}const bp=[],eC=!0,_o=!1,tC="skip";function xp(t,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const l=il(r),o=i?-1:1;d(t,void 0,[])();function d(m,c,u){const h=m&&typeof m=="object"?m:{};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 ("+(m.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=bp,f,b,v;if((!n||l(m,c,u[u.length-1]||void 0))&&(p=nC(s(m,u)),p[0]===_o))return p;if("children"in m&&m.children){const y=m;if(y.children&&p[0]!==tC)for(b=(i?y.children.length:-1)+o,v=u.concat(y);b>-1&&b<y.children.length;){const k=y.children[b];if(f=d(k,b,v)(),f[0]===_o)return f;b=typeof f[1]=="number"?f[1]:b+o}}return p}}}function nC(t){return Array.isArray(t)?t:typeof t=="number"?[eC,t]:t==null?bp:[t]}function fc(t,n,s,i){let r,l,o;typeof n=="function"&&typeof s!="function"?(l=void 0,o=n,r=s):(l=n,o=s,r=i),xp(t,l,d,r);function d(m,c){const u=c[c.length-1],h=u?u.children.indexOf(m):void 0;return o(m,h,u)}}const To={}.hasOwnProperty,sC={};function iC(t,n){const s=n||sC,i=new Map,r=new Map,l=new Map,o={...B0,...s.handlers},d={all:c,applyData:rC,definitionById:i,footnoteById:r,footnoteCounts:l,footnoteOrder:[],handlers:o,one:m,options:s,patch:aC,wrap:oC};return fc(t,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){const h=u.type==="definition"?i:r,g=String(u.identifier).toUpperCase();h.has(g)||h.set(g,u)}}),d;function m(u,h){const g=u.type,p=d.handlers[g];if(To.call(d.handlers,g)&&p)return p(d,u,h);if(d.options.passThrough&&d.options.passThrough.includes(g)){if("children"in u){const{children:b,...v}=u,y=zr(v);return y.children=d.all(u),y}return zr(u)}return(d.options.unknownHandler||lC)(d,u,h)}function c(u){const h=[];if("children"in u){const g=u.children;let p=-1;for(;++p<g.length;){const f=d.one(g[p],u);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=wu(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=wu(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function aC(t,n){t.position&&(n.position=KN(t))}function rC(t,n){let s=n;if(t&&t.data){const i=t.data.hName,r=t.data.hChildren,l=t.data.hProperties;if(typeof i=="string")if(s.type==="element")s.tagName=i;else{const o="children"in s?s.children:[s];s={type:"element",tagName:i,properties:{},children:o}}s.type==="element"&&l&&Object.assign(s.properties,zr(l)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function lC(t,n){const s=n.data||{},i="value"in n&&!(To.call(s,"hProperties")||To.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:t.all(n)};return t.patch(n,i),t.applyData(n,i)}function oC(t,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
607
|
+
`});++i<t.length;)i&&s.push({type:"text",value:`
|
|
608
|
+
`}),s.push(t[i]);return n&&t.length>0&&s.push({type:"text",value:`
|
|
609
|
+
`}),s}function wu(t){let n=0,s=t.charCodeAt(n);for(;s===9||s===32;)n++,s=t.charCodeAt(n);return t.slice(n)}function Nu(t,n){const s=iC(t,n),i=s.one(t,void 0),r=G0(s),l=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&l.children.push({type:"text",value:`
|
|
610
|
+
`},r),l}function cC(t,n){return t&&"run"in t?async function(s,i){const r=Nu(s,{file:i,...n});await t.run(r,i)}:function(s,i){return Nu(s,{file:i,...t||n})}}function Su(t){if(t)throw t}var Tl,Cu;function dC(){if(Cu)return Tl;Cu=1;var t=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(c){return typeof Array.isArray=="function"?Array.isArray(c):n.call(c)==="[object Array]"},l=function(c){if(!c||n.call(c)!=="[object Object]")return!1;var u=t.call(c,"constructor"),h=c.constructor&&c.constructor.prototype&&t.call(c.constructor.prototype,"isPrototypeOf");if(c.constructor&&!u&&!h)return!1;var g;for(g in c);return typeof g>"u"||t.call(c,g)},o=function(c,u){s&&u.name==="__proto__"?s(c,u.name,{enumerable:!0,configurable:!0,value:u.newValue,writable:!0}):c[u.name]=u.newValue},d=function(c,u){if(u==="__proto__")if(t.call(c,u)){if(i)return i(c,u).value}else return;return c[u]};return Tl=function m(){var c,u,h,g,p,f,b=arguments[0],v=1,y=arguments.length,k=!1;for(typeof b=="boolean"&&(k=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<y;++v)if(c=arguments[v],c!=null)for(u in c)h=d(b,u),g=d(c,u),b!==g&&(k&&g&&(l(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&l(h)?h:{},o(b,{name:u,newValue:m(k,f,g)})):typeof g<"u"&&o(b,{name:u,newValue:g}));return b},Tl}var uC=dC();const Rl=Lm(uC);function Ro(t){if(typeof t!="object"||t===null)return!1;const n=Object.getPrototypeOf(t);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)}function mC(){const t=[],n={run:s,use:i};return n;function s(...r){let l=-1;const o=r.pop();if(typeof o!="function")throw new TypeError("Expected function as last argument, not "+o);d(null,...r);function d(m,...c){const u=t[++l];let h=-1;if(m){o(m);return}for(;++h<r.length;)(c[h]===null||c[h]===void 0)&&(c[h]=r[h]);r=c,u?hC(u,d)(...c):o(null,...c)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return t.push(r),n}}function hC(t,n){let s;return i;function i(...o){const d=t.length>o.length;let m;d&&o.push(r);try{m=t.apply(this,o)}catch(c){const u=c;if(d&&s)throw u;return r(u)}d||(m&&m.then&&typeof m.then=="function"?m.then(l,r):m instanceof Error?r(m):l(m))}function r(o,...d){s||(s=!0,n(o,...d))}function l(o){r(null,o)}}const Is={basename:pC,dirname:fC,extname:gC,join:bC,sep:"/"};function pC(t,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Xa(t);let s=0,i=-1,r=t.length,l;if(n===void 0||n.length===0||n.length>t.length){for(;r--;)if(t.codePointAt(r)===47){if(l){s=r+1;break}}else i<0&&(l=!0,i=r+1);return i<0?"":t.slice(s,i)}if(n===t)return"";let o=-1,d=n.length-1;for(;r--;)if(t.codePointAt(r)===47){if(l){s=r+1;break}}else o<0&&(l=!0,o=r+1),d>-1&&(t.codePointAt(r)===n.codePointAt(d--)?d<0&&(i=r):(d=-1,i=o));return s===i?i=o:i<0&&(i=t.length),t.slice(s,i)}function fC(t){if(Xa(t),t.length===0)return".";let n=-1,s=t.length,i;for(;--s;)if(t.codePointAt(s)===47){if(i){n=s;break}}else i||(i=!0);return n<0?t.codePointAt(0)===47?"/":".":n===1&&t.codePointAt(0)===47?"//":t.slice(0,n)}function gC(t){Xa(t);let n=t.length,s=-1,i=0,r=-1,l=0,o;for(;n--;){const d=t.codePointAt(n);if(d===47){if(o){i=n+1;break}continue}s<0&&(o=!0,s=n+1),d===46?r<0?r=n:l!==1&&(l=1):r>-1&&(l=-1)}return r<0||s<0||l===0||l===1&&r===s-1&&r===i+1?"":t.slice(r,s)}function bC(...t){let n=-1,s;for(;++n<t.length;)Xa(t[n]),t[n]&&(s=s===void 0?t[n]:s+"/"+t[n]);return s===void 0?".":xC(s)}function xC(t){Xa(t);const n=t.codePointAt(0)===47;let s=vC(t,!n);return s.length===0&&!n&&(s="."),s.length>0&&t.codePointAt(t.length-1)===47&&(s+="/"),n?"/"+s:s}function vC(t,n){let s="",i=0,r=-1,l=0,o=-1,d,m;for(;++o<=t.length;){if(o<t.length)d=t.codePointAt(o);else{if(d===47)break;d=47}if(d===47){if(!(r===o-1||l===1))if(r!==o-1&&l===2){if(s.length<2||i!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(m=s.lastIndexOf("/"),m!==s.length-1){m<0?(s="",i=0):(s=s.slice(0,m),i=s.length-1-s.lastIndexOf("/")),r=o,l=0;continue}}else if(s.length>0){s="",i=0,r=o,l=0;continue}}n&&(s=s.length>0?s+"/..":"..",i=2)}else s.length>0?s+="/"+t.slice(r+1,o):s=t.slice(r+1,o),i=o-r-1;r=o,l=0}else d===46&&l>-1?l++:l=-1}return s}function Xa(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const yC={cwd:kC};function kC(){return"/"}function Io(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function jC(t){if(typeof t=="string")t=new URL(t);else if(!Io(t)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+t+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(t.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return wC(t)}function wC(t){if(t.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=t.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 Il=["history","path","basename","stem","extname","dirname"];class vp{constructor(n){let s;n?Io(n)?s={path:n}:typeof n=="string"||NC(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":yC.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Il.length;){const l=Il[i];l in s&&s[l]!==void 0&&s[l]!==null&&(this[l]=l==="history"?[...s[l]]:s[l])}let r;for(r in s)Il.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Is.basename(this.path):void 0}set basename(n){Dl(n,"basename"),$l(n,"basename"),this.path=Is.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Is.dirname(this.path):void 0}set dirname(n){Eu(this.basename,"dirname"),this.path=Is.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Is.extname(this.path):void 0}set extname(n){if($l(n,"extname"),Eu(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=Is.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Io(n)&&(n=jC(n)),Dl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Is.basename(this.path,this.extname):void 0}set stem(n){Dl(n,"stem"),$l(n,"stem"),this.path=Is.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 zn(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 $l(t,n){if(t&&t.includes(Is.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Is.sep+"`")}function Dl(t,n){if(!t)throw new Error("`"+n+"` cannot be empty")}function Eu(t,n){if(!t)throw new Error("Setting `"+n+"` requires `path` to be set too")}function NC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const SC=(function(t){const i=this.constructor.prototype,r=i[t],l=function(){return r.apply(l,arguments)};return Object.setPrototypeOf(l,i),l}),CC={}.hasOwnProperty;class gc extends SC{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=mC()}copy(){const n=new gc;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Rl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(zl("data",this.frozen),this.namespace[n]=s,this):CC.call(this.namespace,n)&&this.namespace[n]||void 0:n?(zl("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=mr(n),i=this.parser||this.Parser;return Fl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Fl("process",this.parser||this.Parser),Ll("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(l,o){const d=mr(n),m=i.parse(d);i.run(m,d,function(u,h,g){if(u||!h||!g)return c(u);const p=h,f=i.stringify(p,g);AC(f)?g.value=f:g.result=f,c(u,g)});function c(u,h){u||!h?o(u):l?l(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),Fl("processSync",this.parser||this.Parser),Ll("processSync",this.compiler||this.Compiler),this.process(n,r),Au("processSync","process",s),i;function r(l,o){s=!0,Su(l),i=o}}run(n,s,i){Mu(n),this.freeze();const r=this.transformers;return!i&&typeof s=="function"&&(i=s,s=void 0),i?l(void 0,i):new Promise(l);function l(o,d){const m=mr(s);r.run(n,m,c);function c(u,h,g){const p=h||n;u?d(u):o?o(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,l),Au("runSync","run",i),r;function l(o,d){Su(o),r=d,i=!0}}stringify(n,s){this.freeze();const i=mr(s),r=this.compiler||this.Compiler;return Ll("stringify",r),Mu(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(zl("use",this.frozen),n!=null)if(typeof n=="function")m(n,s);else if(typeof n=="object")Array.isArray(n)?d(n):o(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function l(c){if(typeof c=="function")m(c,[]);else if(typeof c=="object")if(Array.isArray(c)){const[u,...h]=c;m(u,h)}else o(c);else throw new TypeError("Expected usable value, not `"+c+"`")}function o(c){if(!("plugins"in c)&&!("settings"in c))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");d(c.plugins),c.settings&&(r.settings=Rl(!0,r.settings,c.settings))}function d(c){let u=-1;if(c!=null)if(Array.isArray(c))for(;++u<c.length;){const h=c[u];l(h)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function m(c,u){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===c){g=h;break}if(g===-1)i.push([c,...u]);else if(u.length>0){let[p,...f]=u;const b=i[g][1];Ro(b)&&Ro(p)&&(p=Rl(!0,b,p)),i[g]=[c,p,...f]}}}}const EC=new gc().freeze();function Fl(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Ll(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function zl(t,n){if(n)throw new Error("Cannot call `"+t+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Mu(t){if(!Ro(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Au(t,n,s){if(!s)throw new Error("`"+t+"` finished async. Use `"+n+"` instead")}function mr(t){return MC(t)?t:new vp(t)}function MC(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function AC(t){return typeof t=="string"||PC(t)}function PC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const _C="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Pu=[],_u={allowDangerousHtml:!0},TC=/^(https?|ircs?|mailto|xmpp)$/i,RC=[{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 si(t){const n=IC(t),s=$C(t);return DC(n.runSync(n.parse(s),s),t)}function IC(t){const n=t.rehypePlugins||Pu,s=t.remarkPlugins||Pu,i=t.remarkRehypeOptions?{...t.remarkRehypeOptions,..._u}:_u;return EC().use(f0).use(s).use(cC,i).use(n)}function $C(t){const n=t.children||"",s=new vp;return typeof n=="string"&&(s.value=n),s}function DC(t,n){const s=n.allowedElements,i=n.allowElement,r=n.components,l=n.disallowedElements,o=n.skipHtml,d=n.unwrapDisallowed,m=n.urlTransform||FC;for(const u of RC)Object.hasOwn(n,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+_C+u.id,void 0);return fc(t,c),XN(t,{Fragment:e.Fragment,components:r,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function c(u,h,g){if(u.type==="raw"&&g&&typeof h=="number")return o?g.children.splice(h,1):g.children[h]={type:"text",value:u.value},h;if(u.type==="element"){let p;for(p in Al)if(Object.hasOwn(Al,p)&&Object.hasOwn(u.properties,p)){const f=u.properties[p],b=Al[p];(b===null||b.includes(u.tagName))&&(u.properties[p]=m(String(f||""),p,u))}}if(u.type==="element"){let p=s?!s.includes(u.tagName):l?l.includes(u.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(u,h,g)),p&&g&&typeof h=="number")return d&&u.children?g.children.splice(h,1,...u.children):g.children.splice(h,1),h}}}function FC(t){const n=t.indexOf(":"),s=t.indexOf("?"),i=t.indexOf("#"),r=t.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||i!==-1&&n>i||TC.test(t.slice(0,n))?t:""}function Tu(t,n){const s=String(t);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 LC(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function zC(t,n,s){const r=il((s||{}).ignore||[]),l=OC(n);let o=-1;for(;++o<l.length;)xp(t,"text",d);function d(c,u){let h=-1,g;for(;++h<u.length;){const p=u[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return m(c,u)}function m(c,u){const h=u[u.length-1],g=l[o][0],p=l[o][1];let f=0;const v=h.children.indexOf(c);let y=!1,k=[];g.lastIndex=0;let A=g.exec(c.value);for(;A;){const j=A.index,_={index:A.index,input:A.input,stack:[...u,c]};let N=p(...A,_);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?g.lastIndex=j+1:(f!==j&&k.push({type:"text",value:c.value.slice(f,j)}),Array.isArray(N)?k.push(...N):N&&k.push(N),f=j+A[0].length,y=!0),!g.global)break;A=g.exec(c.value)}return y?(f<c.value.length&&k.push({type:"text",value:c.value.slice(f)}),h.children.splice(v,1,...k)):k=[c],v+k.length}}function OC(t){const n=[];if(!Array.isArray(t))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!t[0]||Array.isArray(t[0])?t:[t];let i=-1;for(;++i<s.length;){const r=s[i];n.push([BC(r[0]),UC(r[1])])}return n}function BC(t){return typeof t=="string"?new RegExp(LC(t),"g"):t}function UC(t){return typeof t=="function"?t:function(){return t}}const Ol="phrasing",Bl=["autolink","link","image","label"];function HC(){return{transforms:[YC],enter:{literalAutolink:VC,literalAutolinkEmail:Ul,literalAutolinkHttp:Ul,literalAutolinkWww:Ul},exit:{literalAutolink:JC,literalAutolinkEmail:GC,literalAutolinkHttp:WC,literalAutolinkWww:KC}}}function qC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ol,notInConstruct:Bl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ol,notInConstruct:Bl},{character:":",before:"[ps]",after:"\\/",inConstruct:Ol,notInConstruct:Bl}]}}function VC(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function Ul(t){this.config.enter.autolinkProtocol.call(this,t)}function WC(t){this.config.exit.autolinkProtocol.call(this,t)}function KC(t){this.config.exit.data.call(this,t);const n=this.stack[this.stack.length-1];n.type,n.url="http://"+this.sliceSerialize(t)}function GC(t){this.config.exit.autolinkEmail.call(this,t)}function JC(t){this.exit(t)}function YC(t){zC(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,QC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,XC]],{ignore:["link","linkReference"]})}function QC(t,n,s,i,r){let l="";if(!yp(r)||(/^w/i.test(n)&&(s=n+s,n="",l="http://"),!ZC(s)))return!1;const o=eE(s+i);if(!o[0])return!1;const d={type:"link",title:null,url:l+n+o[0],children:[{type:"text",value:n+o[0]}]};return o[1]?[d,{type:"text",value:o[1]}]:d}function XC(t,n,s,i){return!yp(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function ZC(t){const n=t.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 eE(t){const n=/[!"&'),.:;<>?\]}]+$/.exec(t);if(!n)return[t,void 0];t=t.slice(0,n.index);let s=n[0],i=s.indexOf(")");const r=Tu(t,"(");let l=Tu(t,")");for(;i!==-1&&r>l;)t+=s.slice(0,i+1),s=s.slice(i+1),i=s.indexOf(")"),l++;return[t,s]}function yp(t,n){const s=t.input.charCodeAt(t.index-1);return(t.index===0||Ni(s)||tl(s))&&(!n||s!==47)}kp.peek=cE;function tE(){this.buffer()}function nE(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function sE(){this.buffer()}function iE(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function aE(t){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=As(this.sliceSerialize(t)).toLowerCase(),s.label=n}function rE(t){this.exit(t)}function lE(t){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=As(this.sliceSerialize(t)).toLowerCase(),s.label=n}function oE(t){this.exit(t)}function cE(){return"["}function kp(t,n,s,i){const r=s.createTracker(i);let l=r.move("[^");const o=s.enter("footnoteReference"),d=s.enter("reference");return l+=r.move(s.safe(s.associationId(t),{after:"]",before:l})),d(),o(),l+=r.move("]"),l}function dE(){return{enter:{gfmFootnoteCallString:tE,gfmFootnoteCall:nE,gfmFootnoteDefinitionLabelString:sE,gfmFootnoteDefinition:iE},exit:{gfmFootnoteCallString:aE,gfmFootnoteCall:rE,gfmFootnoteDefinitionLabelString:lE,gfmFootnoteDefinition:oE}}}function uE(t){let n=!1;return t&&t.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:kp},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,l,o){const d=l.createTracker(o);let m=d.move("[^");const c=l.enter("footnoteDefinition"),u=l.enter("label");return m+=d.move(l.safe(l.associationId(i),{before:m,after:"]"})),u(),m+=d.move("]:"),i.children&&i.children.length>0&&(d.shift(4),m+=d.move((n?`
|
|
611
|
+
`:" ")+l.indentLines(l.containerFlow(i,d.current()),n?jp:mE))),c(),m}}function mE(t,n,s){return n===0?t:jp(t,n,s)}function jp(t,n,s){return(s?"":" ")+t}const hE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];wp.peek=xE;function pE(){return{canContainEols:["delete"],enter:{strikethrough:gE},exit:{strikethrough:bE}}}function fE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:hE}],handlers:{delete:wp}}}function gE(t){this.enter({type:"delete",children:[]},t)}function bE(t){this.exit(t)}function wp(t,n,s,i){const r=s.createTracker(i),l=s.enter("strikethrough");let o=r.move("~~");return o+=s.containerPhrasing(t,{...r.current(),before:o,after:"~"}),o+=r.move("~~"),l(),o}function xE(){return"~"}function vE(t){return t.length}function yE(t,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||vE,l=[],o=[],d=[],m=[];let c=0,u=-1;for(;++u<t.length;){const b=[],v=[];let y=-1;for(t[u].length>c&&(c=t[u].length);++y<t[u].length;){const k=kE(t[u][y]);if(s.alignDelimiters!==!1){const A=r(k);v[y]=A,(m[y]===void 0||A>m[y])&&(m[y]=A)}b.push(k)}o[u]=b,d[u]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<c;)l[h]=Ru(i[h]);else{const b=Ru(i);for(;++h<c;)l[h]=b}h=-1;const g=[],p=[];for(;++h<c;){const b=l[h];let v="",y="";b===99?(v=":",y=":"):b===108?v=":":b===114&&(y=":");let k=s.alignDelimiters===!1?1:Math.max(1,m[h]-v.length-y.length);const A=v+"-".repeat(k)+y;s.alignDelimiters!==!1&&(k=v.length+k+y.length,k>m[h]&&(m[h]=k),p[h]=k),g[h]=A}o.splice(1,0,g),d.splice(1,0,p),u=-1;const f=[];for(;++u<o.length;){const b=o[u],v=d[u];h=-1;const y=[];for(;++h<c;){const k=b[h]||"";let A="",j="";if(s.alignDelimiters!==!1){const _=m[h]-(v[h]||0),N=l[h];N===114?A=" ".repeat(_):N===99?_%2?(A=" ".repeat(_/2+.5),j=" ".repeat(_/2-.5)):(A=" ".repeat(_/2),j=A):j=" ".repeat(_)}s.delimiterStart!==!1&&!h&&y.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&k==="")&&(s.delimiterStart!==!1||h)&&y.push(" "),s.alignDelimiters!==!1&&y.push(A),y.push(k),s.alignDelimiters!==!1&&y.push(j),s.padding!==!1&&y.push(" "),(s.delimiterEnd!==!1||h!==c-1)&&y.push("|")}f.push(s.delimiterEnd===!1?y.join("").replace(/ +$/,""):y.join(""))}return f.join(`
|
|
612
|
+
`)}function kE(t){return t==null?"":String(t)}function Ru(t){const n=typeof t=="string"?t.codePointAt(0):0;return n===67||n===99?99:n===76||n===108?108:n===82||n===114?114:0}function jE(t,n,s,i){const r=s.enter("blockquote"),l=s.createTracker(i);l.move("> "),l.shift(2);const o=s.indentLines(s.containerFlow(t,l.current()),wE);return r(),o}function wE(t,n,s){return">"+(s?"":" ")+t}function NE(t,n){return Iu(t,n.inConstruct,!0)&&!Iu(t,n.notInConstruct,!1)}function Iu(t,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let i=-1;for(;++i<n.length;)if(t.includes(n[i]))return!0;return!1}function $u(t,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
613
|
+
`&&NE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
614
|
+
`}function SE(t,n){const s=String(t);let i=s.indexOf(n),r=i,l=0,o=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++l>o&&(o=l):l=1,r=i+n.length,i=s.indexOf(n,r);return o}function CE(t,n){return!!(n.options.fences===!1&&t.value&&!t.lang&&/[^ \r\n]/.test(t.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(t.value))}function EE(t){const n=t.options.fence||"`";if(n!=="`"&&n!=="~")throw new Error("Cannot serialize code with `"+n+"` for `options.fence`, expected `` ` `` or `~`");return n}function ME(t,n,s,i){const r=EE(s),l=t.value||"",o=r==="`"?"GraveAccent":"Tilde";if(CE(t,s)){const h=s.enter("codeIndented"),g=s.indentLines(l,AE);return h(),g}const d=s.createTracker(i),m=r.repeat(Math.max(SE(l,r)+1,3)),c=s.enter("codeFenced");let u=d.move(m);if(t.lang){const h=s.enter(`codeFencedLang${o}`);u+=d.move(s.safe(t.lang,{before:u,after:" ",encode:["`"],...d.current()})),h()}if(t.lang&&t.meta){const h=s.enter(`codeFencedMeta${o}`);u+=d.move(" "),u+=d.move(s.safe(t.meta,{before:u,after:`
|
|
615
|
+
`,encode:["`"],...d.current()})),h()}return u+=d.move(`
|
|
616
|
+
`),l&&(u+=d.move(l+`
|
|
617
|
+
`)),u+=d.move(m),c(),u}function AE(t,n,s){return(s?"":" ")+t}function bc(t){const n=t.options.quote||'"';if(n!=='"'&&n!=="'")throw new Error("Cannot serialize title with `"+n+"` for `options.quote`, expected `\"`, or `'`");return n}function PE(t,n,s,i){const r=bc(s),l=r==='"'?"Quote":"Apostrophe",o=s.enter("definition");let d=s.enter("label");const m=s.createTracker(i);let c=m.move("[");return c+=m.move(s.safe(s.associationId(t),{before:c,after:"]",...m.current()})),c+=m.move("]: "),d(),!t.url||/[\0- \u007F]/.test(t.url)?(d=s.enter("destinationLiteral"),c+=m.move("<"),c+=m.move(s.safe(t.url,{before:c,after:">",...m.current()})),c+=m.move(">")):(d=s.enter("destinationRaw"),c+=m.move(s.safe(t.url,{before:c,after:t.title?" ":`
|
|
618
|
+
`,...m.current()}))),d(),t.title&&(d=s.enter(`title${l}`),c+=m.move(" "+r),c+=m.move(s.safe(t.title,{before:c,after:r,...m.current()})),c+=m.move(r),d()),o(),c}function _E(t){const n=t.options.emphasis||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize emphasis with `"+n+"` for `options.emphasis`, expected `*`, or `_`");return n}function za(t){return"&#x"+t.toString(16).toUpperCase()+";"}function Or(t,n,s){const i=Yi(t),r=Yi(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}}Np.peek=TE;function Np(t,n,s,i){const r=_E(s),l=s.enter("emphasis"),o=s.createTracker(i),d=o.move(r);let m=o.move(s.containerPhrasing(t,{after:r,before:d,...o.current()}));const c=m.charCodeAt(0),u=Or(i.before.charCodeAt(i.before.length-1),c,r);u.inside&&(m=za(c)+m.slice(1));const h=m.charCodeAt(m.length-1),g=Or(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+za(h));const p=o.move(r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+p}function TE(t,n,s){return s.options.emphasis||"*"}function RE(t,n){let s=!1;return fc(t,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,_o}),!!((!t.depth||t.depth<3)&&oc(t)&&(n.options.setext||s))}function IE(t,n,s,i){const r=Math.max(Math.min(6,t.depth||1),1),l=s.createTracker(i);if(RE(t,s)){const u=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(t,{...l.current(),before:`
|
|
619
|
+
`,after:`
|
|
620
|
+
`});return h(),u(),g+`
|
|
621
|
+
`+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
|
|
622
|
+
`))+1))}const o="#".repeat(r),d=s.enter("headingAtx"),m=s.enter("phrasing");l.move(o+" ");let c=s.containerPhrasing(t,{before:"# ",after:`
|
|
623
|
+
`,...l.current()});return/^[\t ]/.test(c)&&(c=za(c.charCodeAt(0))+c.slice(1)),c=c?o+" "+c:o,s.options.closeAtx&&(c+=" "+o),m(),d(),c}Sp.peek=$E;function Sp(t){return t.value||""}function $E(){return"<"}Cp.peek=DE;function Cp(t,n,s,i){const r=bc(s),l=r==='"'?"Quote":"Apostrophe",o=s.enter("image");let d=s.enter("label");const m=s.createTracker(i);let c=m.move("![");return c+=m.move(s.safe(t.alt,{before:c,after:"]",...m.current()})),c+=m.move("]("),d(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(d=s.enter("destinationLiteral"),c+=m.move("<"),c+=m.move(s.safe(t.url,{before:c,after:">",...m.current()})),c+=m.move(">")):(d=s.enter("destinationRaw"),c+=m.move(s.safe(t.url,{before:c,after:t.title?" ":")",...m.current()}))),d(),t.title&&(d=s.enter(`title${l}`),c+=m.move(" "+r),c+=m.move(s.safe(t.title,{before:c,after:r,...m.current()})),c+=m.move(r),d()),c+=m.move(")"),o(),c}function DE(){return"!"}Ep.peek=FE;function Ep(t,n,s,i){const r=t.referenceType,l=s.enter("imageReference");let o=s.enter("label");const d=s.createTracker(i);let m=d.move("![");const c=s.safe(t.alt,{before:m,after:"]",...d.current()});m+=d.move(c+"]["),o();const u=s.stack;s.stack=[],o=s.enter("reference");const h=s.safe(s.associationId(t),{before:m,after:"]",...d.current()});return o(),s.stack=u,l(),r==="full"||!c||c!==h?m+=d.move(h+"]"):r==="shortcut"?m=m.slice(0,-1):m+=d.move("]"),m}function FE(){return"!"}Mp.peek=LE;function Mp(t,n,s){let i=t.value||"",r="`",l=-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+" ");++l<s.unsafe.length;){const o=s.unsafe[l],d=s.compilePattern(o);let m;if(o.atBreak)for(;m=d.exec(i);){let c=m.index;i.charCodeAt(c)===10&&i.charCodeAt(c-1)===13&&c--,i=i.slice(0,c)+" "+i.slice(m.index+1)}}return r+i+r}function LE(){return"`"}function Ap(t,n){const s=oc(t);return!!(!n.options.resourceLink&&t.url&&!t.title&&t.children&&t.children.length===1&&t.children[0].type==="text"&&(s===t.url||"mailto:"+s===t.url)&&/^[a-z][a-z+.-]+:/i.test(t.url)&&!/[\0- <>\u007F]/.test(t.url))}Pp.peek=zE;function Pp(t,n,s,i){const r=bc(s),l=r==='"'?"Quote":"Apostrophe",o=s.createTracker(i);let d,m;if(Ap(t,s)){const u=s.stack;s.stack=[],d=s.enter("autolink");let h=o.move("<");return h+=o.move(s.containerPhrasing(t,{before:h,after:">",...o.current()})),h+=o.move(">"),d(),s.stack=u,h}d=s.enter("link"),m=s.enter("label");let c=o.move("[");return c+=o.move(s.containerPhrasing(t,{before:c,after:"](",...o.current()})),c+=o.move("]("),m(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(m=s.enter("destinationLiteral"),c+=o.move("<"),c+=o.move(s.safe(t.url,{before:c,after:">",...o.current()})),c+=o.move(">")):(m=s.enter("destinationRaw"),c+=o.move(s.safe(t.url,{before:c,after:t.title?" ":")",...o.current()}))),m(),t.title&&(m=s.enter(`title${l}`),c+=o.move(" "+r),c+=o.move(s.safe(t.title,{before:c,after:r,...o.current()})),c+=o.move(r),m()),c+=o.move(")"),d(),c}function zE(t,n,s){return Ap(t,s)?"<":"["}_p.peek=OE;function _p(t,n,s,i){const r=t.referenceType,l=s.enter("linkReference");let o=s.enter("label");const d=s.createTracker(i);let m=d.move("[");const c=s.containerPhrasing(t,{before:m,after:"]",...d.current()});m+=d.move(c+"]["),o();const u=s.stack;s.stack=[],o=s.enter("reference");const h=s.safe(s.associationId(t),{before:m,after:"]",...d.current()});return o(),s.stack=u,l(),r==="full"||!c||c!==h?m+=d.move(h+"]"):r==="shortcut"?m=m.slice(0,-1):m+=d.move("]"),m}function OE(){return"["}function xc(t){const n=t.options.bullet||"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bullet`, expected `*`, `+`, or `-`");return n}function BE(t){const n=xc(t),s=t.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 UE(t){const n=t.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function Tp(t){const n=t.options.rule||"*";if(n!=="*"&&n!=="-"&&n!=="_")throw new Error("Cannot serialize rules with `"+n+"` for `options.rule`, expected `*`, `-`, or `_`");return n}function HE(t,n,s,i){const r=s.enter("list"),l=s.bulletCurrent;let o=t.ordered?UE(s):xc(s);const d=t.ordered?o==="."?")":".":BE(s);let m=n&&s.bulletLastUsed?o===s.bulletLastUsed:!1;if(!t.ordered){const u=t.children?t.children[0]:void 0;if((o==="*"||o==="-")&&u&&(!u.children||!u.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&&(m=!0),Tp(s)===o&&u){let h=-1;for(;++h<t.children.length;){const g=t.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){m=!0;break}}}}m&&(o=d),s.bulletCurrent=o;const c=s.containerFlow(t,i);return s.bulletLastUsed=o,s.bulletCurrent=l,r(),c}function qE(t){const n=t.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 VE(t,n,s,i){const r=qE(s);let l=s.bulletCurrent||xc(s);n&&n.type==="list"&&n.ordered&&(l=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(t))+l);let o=l.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||t.spread))&&(o=Math.ceil(o/4)*4);const d=s.createTracker(i);d.move(l+" ".repeat(o-l.length)),d.shift(o);const m=s.enter("listItem"),c=s.indentLines(s.containerFlow(t,d.current()),u);return m(),c;function u(h,g,p){return g?(p?"":" ".repeat(o))+h:(p?l:l+" ".repeat(o-l.length))+h}}function WE(t,n,s,i){const r=s.enter("paragraph"),l=s.enter("phrasing"),o=s.containerPhrasing(t,i);return l(),r(),o}const KE=il(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function GE(t,n,s,i){return(t.children.some(function(o){return KE(o)})?s.containerPhrasing:s.containerFlow).call(s,t,i)}function JE(t){const n=t.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Rp.peek=YE;function Rp(t,n,s,i){const r=JE(s),l=s.enter("strong"),o=s.createTracker(i),d=o.move(r+r);let m=o.move(s.containerPhrasing(t,{after:r,before:d,...o.current()}));const c=m.charCodeAt(0),u=Or(i.before.charCodeAt(i.before.length-1),c,r);u.inside&&(m=za(c)+m.slice(1));const h=m.charCodeAt(m.length-1),g=Or(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+za(h));const p=o.move(r+r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+p}function YE(t,n,s){return s.options.strong||"*"}function QE(t,n,s,i){return s.safe(t.value,i)}function XE(t){const n=t.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 ZE(t,n,s){const i=(Tp(s)+(s.options.ruleSpaces?" ":"")).repeat(XE(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Ip={blockquote:jE,break:$u,code:ME,definition:PE,emphasis:Np,hardBreak:$u,heading:IE,html:Sp,image:Cp,imageReference:Ep,inlineCode:Mp,link:Pp,linkReference:_p,list:HE,listItem:VE,paragraph:WE,root:GE,strong:Rp,text:QE,thematicBreak:ZE};function e2(){return{enter:{table:t2,tableData:Du,tableHeader:Du,tableRow:s2},exit:{codeText:i2,table:n2,tableData:Hl,tableHeader:Hl,tableRow:Hl}}}function t2(t){const n=t._align;this.enter({type:"table",align:n.map(function(s){return s==="none"?null:s}),children:[]},t),this.data.inTable=!0}function n2(t){this.exit(t),this.data.inTable=void 0}function s2(t){this.enter({type:"tableRow",children:[]},t)}function Hl(t){this.exit(t)}function Du(t){this.enter({type:"tableCell",children:[]},t)}function i2(t){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,a2));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(t)}function a2(t,n){return n==="|"?n:t}function r2(t){const n=t||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,l=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
624
|
+
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:o,tableCell:m,tableRow:d}};function o(p,f,b,v){return c(u(p,b,v),p.align)}function d(p,f,b,v){const y=h(p,b,v),k=c([y]);return k.slice(0,k.indexOf(`
|
|
625
|
+
`))}function m(p,f,b,v){const y=b.enter("tableCell"),k=b.enter("phrasing"),A=b.containerPhrasing(p,{...v,before:l,after:l});return k(),y(),A}function c(p,f){return yE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function u(p,f,b){const v=p.children;let y=-1;const k=[],A=f.enter("table");for(;++y<v.length;)k[y]=h(v[y],f,b);return A(),k}function h(p,f,b){const v=p.children;let y=-1;const k=[],A=f.enter("tableRow");for(;++y<v.length;)k[y]=m(v[y],p,f,b);return A(),k}function g(p,f,b){let v=Ip.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function l2(){return{exit:{taskListCheckValueChecked:Fu,taskListCheckValueUnchecked:Fu,paragraph:c2}}}function o2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:d2}}}function Fu(t){const n=this.stack[this.stack.length-2];n.type,n.checked=t.type==="taskListCheckValueChecked"}function c2(t){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 l=-1,o;for(;++l<r.length;){const d=r[l];if(d.type==="paragraph"){o=d;break}}o===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(t)}function d2(t,n,s,i){const r=t.children[0],l=typeof t.checked=="boolean"&&r&&r.type==="paragraph",o="["+(t.checked?"x":" ")+"] ",d=s.createTracker(i);l&&d.move(o);let m=Ip.listItem(t,n,s,{...i,...d.current()});return l&&(m=m.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,c)),m;function c(u){return u+o}}function u2(){return[HC(),dE(),pE(),e2(),l2()]}function m2(t){return{extensions:[qC(),uE(t),fE(),r2(t),o2()]}}const h2={tokenize:v2,partial:!0},$p={tokenize:y2,partial:!0},Dp={tokenize:k2,partial:!0},Fp={tokenize:j2,partial:!0},p2={tokenize:w2,partial:!0},Lp={name:"wwwAutolink",tokenize:b2,previous:Op},zp={name:"protocolAutolink",tokenize:x2,previous:Bp},Gs={name:"emailAutolink",tokenize:g2,previous:Up},Us={};function f2(){return{text:Us}}let pi=48;for(;pi<123;)Us[pi]=Gs,pi++,pi===58?pi=65:pi===91&&(pi=97);Us[43]=Gs;Us[45]=Gs;Us[46]=Gs;Us[95]=Gs;Us[72]=[Gs,zp];Us[104]=[Gs,zp];Us[87]=[Gs,Lp];Us[119]=[Gs,Lp];function g2(t,n,s){const i=this;let r,l;return o;function o(h){return!$o(h)||!Up.call(i,i.previous)||vc(i.events)?s(h):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),d(h))}function d(h){return $o(h)?(t.consume(h),d):h===64?(t.consume(h),m):s(h)}function m(h){return h===46?t.check(p2,u,c)(h):h===45||h===95||Fn(h)?(l=!0,t.consume(h),m):u(h)}function c(h){return t.consume(h),r=!0,m}function u(h){return l&&r&&Wn(i.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),n(h)):s(h)}}function b2(t,n,s){const i=this;return r;function r(o){return o!==87&&o!==119||!Op.call(i,i.previous)||vc(i.events)?s(o):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(h2,t.attempt($p,t.attempt(Dp,l),s),s)(o))}function l(o){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),n(o)}}function x2(t,n,s){const i=this;let r="",l=!1;return o;function o(h){return(h===72||h===104)&&Bp.call(i,i.previous)&&!vc(i.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),t.consume(h),d):s(h)}function d(h){if(Wn(h)&&r.length<5)return r+=String.fromCodePoint(h),t.consume(h),d;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return t.consume(h),m}return s(h)}function m(h){return h===47?(t.consume(h),l?c:(l=!0,m)):s(h)}function c(h){return h===null||Fr(h)||Gt(h)||Ni(h)||tl(h)?s(h):t.attempt($p,t.attempt(Dp,u),s)(h)}function u(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),n(h)}}function v2(t,n,s){let i=0;return r;function r(o){return(o===87||o===119)&&i<3?(i++,t.consume(o),r):o===46&&i===3?(t.consume(o),l):s(o)}function l(o){return o===null?s(o):n(o)}}function y2(t,n,s){let i,r,l;return o;function o(c){return c===46||c===95?t.check(Fp,m,d)(c):c===null||Gt(c)||Ni(c)||c!==45&&tl(c)?m(c):(l=!0,t.consume(c),o)}function d(c){return c===95?i=!0:(r=i,i=void 0),t.consume(c),o}function m(c){return r||i||!l?s(c):n(c)}}function k2(t,n){let s=0,i=0;return r;function r(o){return o===40?(s++,t.consume(o),r):o===41&&i<s?l(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?t.check(Fp,n,l)(o):o===null||Gt(o)||Ni(o)?n(o):(t.consume(o),r)}function l(o){return o===41&&i++,t.consume(o),r}}function j2(t,n,s){return i;function i(d){return d===33||d===34||d===39||d===41||d===42||d===44||d===46||d===58||d===59||d===63||d===95||d===126?(t.consume(d),i):d===38?(t.consume(d),l):d===93?(t.consume(d),r):d===60||d===null||Gt(d)||Ni(d)?n(d):s(d)}function r(d){return d===null||d===40||d===91||Gt(d)||Ni(d)?n(d):i(d)}function l(d){return Wn(d)?o(d):s(d)}function o(d){return d===59?(t.consume(d),i):Wn(d)?(t.consume(d),o):s(d)}}function w2(t,n,s){return i;function i(l){return t.consume(l),r}function r(l){return Fn(l)?s(l):n(l)}}function Op(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Gt(t)}function Bp(t){return!Wn(t)}function Up(t){return!(t===47||$o(t))}function $o(t){return t===43||t===45||t===46||t===95||Fn(t)}function vc(t){let n=t.length,s=!1;for(;n--;){const i=t[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return t.length>0&&!s&&(t[t.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const N2={tokenize:T2,partial:!0};function S2(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:A2,continuation:{tokenize:P2},exit:_2}},text:{91:{name:"gfmFootnoteCall",tokenize:M2},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:C2,resolveTo:E2}}}}function C2(t,n,s){const i=this;let r=i.events.length;const l=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o;for(;r--;){const m=i.events[r][1];if(m.type==="labelImage"){o=m;break}if(m.type==="gfmFootnoteCall"||m.type==="labelLink"||m.type==="label"||m.type==="image"||m.type==="link")break}return d;function d(m){if(!o||!o._balanced)return s(m);const c=As(i.sliceSerialize({start:o.end,end:i.now()}));return c.codePointAt(0)!==94||!l.includes(c.slice(1))?s(m):(t.enter("gfmFootnoteCallLabelMarker"),t.consume(m),t.exit("gfmFootnoteCallLabelMarker"),n(m))}}function E2(t,n){let s=t.length;for(;s--;)if(t[s][1].type==="labelImage"&&t[s][0]==="enter"){t[s][1];break}t[s+1][1].type="data",t[s+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},t[s+3][1].start),end:Object.assign({},t[t.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},t[s+3][1].end),end:Object.assign({},t[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const l={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},t[t.length-1][1].start)},o={type:"chunkString",contentType:"string",start:Object.assign({},l.start),end:Object.assign({},l.end)},d=[t[s+1],t[s+2],["enter",i,n],t[s+3],t[s+4],["enter",r,n],["exit",r,n],["enter",l,n],["enter",o,n],["exit",o,n],["exit",l,n],t[t.length-2],t[t.length-1],["exit",i,n]];return t.splice(s,t.length-s+1,...d),t}function M2(t,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l=0,o;return d;function d(h){return t.enter("gfmFootnoteCall"),t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),m}function m(h){return h!==94?s(h):(t.enter("gfmFootnoteCallMarker"),t.consume(h),t.exit("gfmFootnoteCallMarker"),t.enter("gfmFootnoteCallString"),t.enter("chunkString").contentType="string",c)}function c(h){if(l>999||h===93&&!o||h===null||h===91||Gt(h))return s(h);if(h===93){t.exit("chunkString");const g=t.exit("gfmFootnoteCallString");return r.includes(As(i.sliceSerialize(g)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),n):s(h)}return Gt(h)||(o=!0),l++,t.consume(h),h===92?u:c}function u(h){return h===91||h===92||h===93?(t.consume(h),l++,c):c(h)}}function A2(t,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l,o=0,d;return m;function m(f){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(f){return f===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",u):s(f)}function u(f){if(o>999||f===93&&!d||f===null||f===91||Gt(f))return s(f);if(f===93){t.exit("chunkString");const b=t.exit("gfmFootnoteDefinitionLabelString");return l=As(i.sliceSerialize(b)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),g}return Gt(f)||(d=!0),o++,t.consume(f),f===92?h:u}function h(f){return f===91||f===92||f===93?(t.consume(f),o++,u):u(f)}function g(f){return f===58?(t.enter("definitionMarker"),t.consume(f),t.exit("definitionMarker"),r.includes(l)||r.push(l),zt(t,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function P2(t,n,s){return t.check(Qa,n,t.attempt(N2,n,s))}function _2(t){t.exit("gfmFootnoteDefinition")}function T2(t,n,s){const i=this;return zt(t,r,"gfmFootnoteDefinitionIndent",5);function r(l){const o=i.events[i.events.length-1];return o&&o[1].type==="gfmFootnoteDefinitionIndent"&&o[2].sliceSerialize(o[1],!0).length===4?n(l):s(l)}}function R2(t){let s=(t||{}).singleTilde;const i={name:"strikethrough",tokenize:l,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(o,d){let m=-1;for(;++m<o.length;)if(o[m][0]==="enter"&&o[m][1].type==="strikethroughSequenceTemporary"&&o[m][1]._close){let c=m;for(;c--;)if(o[c][0]==="exit"&&o[c][1].type==="strikethroughSequenceTemporary"&&o[c][1]._open&&o[m][1].end.offset-o[m][1].start.offset===o[c][1].end.offset-o[c][1].start.offset){o[m][1].type="strikethroughSequence",o[c][1].type="strikethroughSequence";const u={type:"strikethrough",start:Object.assign({},o[c][1].start),end:Object.assign({},o[m][1].end)},h={type:"strikethroughText",start:Object.assign({},o[c][1].end),end:Object.assign({},o[m][1].start)},g=[["enter",u,d],["enter",o[c][1],d],["exit",o[c][1],d],["enter",h,d]],p=d.parser.constructs.insideSpan.null;p&&hs(g,g.length,0,nl(p,o.slice(c+1,m),d)),hs(g,g.length,0,[["exit",h,d],["enter",o[m][1],d],["exit",o[m][1],d],["exit",u,d]]),hs(o,c-1,m-c+3,g),m=c+g.length-2;break}}for(m=-1;++m<o.length;)o[m][1].type==="strikethroughSequenceTemporary"&&(o[m][1].type="data");return o}function l(o,d,m){const c=this.previous,u=this.events;let h=0;return g;function g(f){return c===126&&u[u.length-1][1].type!=="characterEscape"?m(f):(o.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const b=Yi(c);if(f===126)return h>1?m(f):(o.consume(f),h++,p);if(h<2&&!s)return m(f);const v=o.exit("strikethroughSequenceTemporary"),y=Yi(f);return v._open=!y||y===2&&!!b,v._close=!b||b===2&&!!y,d(f)}}}class I2{constructor(){this.map=[]}add(n,s,i){$2(this,n,s,i)}consume(n){if(this.map.sort(function(l,o){return l[0]-o[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 l of r)n.push(l);r=i.pop()}this.map.length=0}}function $2(t,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<t.map.length;){if(t.map[r][0]===n){t.map[r][1]+=s,t.map[r][2].push(...i);return}r+=1}t.map.push([n,s,i])}}function D2(t,n){let s=!1;const i=[];for(;n<t.length;){const r=t[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(t[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(t[n-1][1].type==="tableDelimiterMarker"){const l=i.length-1;i[l]=i[l]==="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 F2(){return{flow:{null:{name:"table",tokenize:L2,resolveAll:z2}}}}function L2(t,n,s){const i=this;let r=0,l=0,o;return d;function d(E){let I=i.events.length-1;for(;I>-1;){const $=i.events[I][1].type;if($==="lineEnding"||$==="linePrefix")I--;else break}const L=I>-1?i.events[I][1].type:null,ee=L==="tableHead"||L==="tableRow"?N:m;return ee===N&&i.parser.lazy[i.now().line]?s(E):ee(E)}function m(E){return t.enter("tableHead"),t.enter("tableRow"),c(E)}function c(E){return E===124||(o=!0,l+=1),u(E)}function u(E){return E===null?s(E):Nt(E)?l>1?(l=0,i.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(E),t.exit("lineEnding"),p):s(E):Dt(E)?zt(t,u,"whitespace")(E):(l+=1,o&&(o=!1,r+=1),E===124?(t.enter("tableCellDivider"),t.consume(E),t.exit("tableCellDivider"),o=!0,u):(t.enter("data"),h(E)))}function h(E){return E===null||E===124||Gt(E)?(t.exit("data"),u(E)):(t.consume(E),E===92?g:h)}function g(E){return E===92||E===124?(t.consume(E),h):h(E)}function p(E){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(E):(t.enter("tableDelimiterRow"),o=!1,Dt(E)?zt(t,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):f(E))}function f(E){return E===45||E===58?v(E):E===124?(o=!0,t.enter("tableCellDivider"),t.consume(E),t.exit("tableCellDivider"),b):_(E)}function b(E){return Dt(E)?zt(t,v,"whitespace")(E):v(E)}function v(E){return E===58?(l+=1,o=!0,t.enter("tableDelimiterMarker"),t.consume(E),t.exit("tableDelimiterMarker"),y):E===45?(l+=1,y(E)):E===null||Nt(E)?j(E):_(E)}function y(E){return E===45?(t.enter("tableDelimiterFiller"),k(E)):_(E)}function k(E){return E===45?(t.consume(E),k):E===58?(o=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(E),t.exit("tableDelimiterMarker"),A):(t.exit("tableDelimiterFiller"),A(E))}function A(E){return Dt(E)?zt(t,j,"whitespace")(E):j(E)}function j(E){return E===124?f(E):E===null||Nt(E)?!o||r!==l?_(E):(t.exit("tableDelimiterRow"),t.exit("tableHead"),n(E)):_(E)}function _(E){return s(E)}function N(E){return t.enter("tableRow"),M(E)}function M(E){return E===124?(t.enter("tableCellDivider"),t.consume(E),t.exit("tableCellDivider"),M):E===null||Nt(E)?(t.exit("tableRow"),n(E)):Dt(E)?zt(t,M,"whitespace")(E):(t.enter("data"),w(E))}function w(E){return E===null||E===124||Gt(E)?(t.exit("data"),M(E)):(t.consume(E),E===92?R:w)}function R(E){return E===92||E===124?(t.consume(E),w):w(E)}}function z2(t,n){let s=-1,i=!0,r=0,l=[0,0,0,0],o=[0,0,0,0],d=!1,m=0,c,u,h;const g=new I2;for(;++s<t.length;){const p=t[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(d=!1,m!==0&&(Lu(g,n,m,c,u),u=void 0,m=0),c={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",c,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,l=[0,0,0,0],o=[0,s+1,0,0],d&&(d=!1,u={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",u,n]])),r=f.type==="tableDelimiterRow"?2:u?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,o[2]===0&&(l[1]!==0&&(o[0]=o[1],h=hr(g,n,l,r,void 0,h),l=[0,0,0,0]),o[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(l[1]!==0&&(o[0]=o[1],h=hr(g,n,l,r,void 0,h)),l=o,o=[l[1],s,0,0])):f.type==="tableHead"?(d=!0,m=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(m=s,l[1]!==0?(o[0]=o[1],h=hr(g,n,l,r,s,h)):o[1]!==0&&(h=hr(g,n,o,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(o[3]=s)}for(m!==0&&Lu(g,n,m,c,u),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=D2(n.events,s))}return t}function hr(t,n,s,i,r,l){const o=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",d="tableContent";s[0]!==0&&(l.end=Object.assign({},Li(n.events,s[0])),t.add(s[0],0,[["exit",l,n]]));const m=Li(n.events,s[1]);if(l={type:o,start:Object.assign({},m),end:Object.assign({},m)},t.add(s[1],0,[["enter",l,n]]),s[2]!==0){const c=Li(n.events,s[2]),u=Li(n.events,s[3]),h={type:d,start:Object.assign({},c),end:Object.assign({},u)};if(t.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,b=s[3]-s[2]-1;t.add(f,b,[])}}t.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(l.end=Object.assign({},Li(n.events,r)),t.add(r,0,[["exit",l,n]]),l=void 0),l}function Lu(t,n,s,i,r){const l=[],o=Li(n.events,s);r&&(r.end=Object.assign({},o),l.push(["exit",r,n])),i.end=Object.assign({},o),l.push(["exit",i,n]),t.add(s+1,0,l)}function Li(t,n){const s=t[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const O2={name:"tasklistCheck",tokenize:U2};function B2(){return{text:{91:O2}}}function U2(t,n,s){const i=this;return r;function r(m){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(m):(t.enter("taskListCheck"),t.enter("taskListCheckMarker"),t.consume(m),t.exit("taskListCheckMarker"),l)}function l(m){return Gt(m)?(t.enter("taskListCheckValueUnchecked"),t.consume(m),t.exit("taskListCheckValueUnchecked"),o):m===88||m===120?(t.enter("taskListCheckValueChecked"),t.consume(m),t.exit("taskListCheckValueChecked"),o):s(m)}function o(m){return m===93?(t.enter("taskListCheckMarker"),t.consume(m),t.exit("taskListCheckMarker"),t.exit("taskListCheck"),d):s(m)}function d(m){return Nt(m)?n(m):Dt(m)?t.check({tokenize:H2},n,s)(m):s(m)}}function H2(t,n,s){return zt(t,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function q2(t){return Zh([f2(),S2(),R2(t),F2(),B2()])}const V2={};function ii(t){const n=this,s=t||V2,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),l=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),o=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(q2(s)),l.push(u2()),o.push(m2(s))}const zu=500,Ou=100;function ql(t){return t.length>zu?t.slice(-zu):t}function Hp(t,n,s){const[i,r]=a.useState([]),[l,o]=a.useState(!1),[d,m]=a.useState(!1),[c,u]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),v=a.useRef(t),y=a.useRef(s),k=a.useRef(n),A=a.useRef(0);(v.current!==t||y.current!==s||k.current!==n)&&(v.current=t,y.current=s,k.current=n,b.current++,f.current=!0,r([]),o(!1),m(!1),u(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!t||!n){p.current&&(p.current(),p.current=null);return}const M=b.current,w=++A.current;f.current=!1;const R=t,E=s;async function I(){if(!R)return;o(!0),g(!1);try{const ee=await Kc(R,E,{limit:Ou});if(f.current||b.current!==M||A.current!==w)return;r(ql(ee.entries)),m(ee.hasMore),u(ee.total)}catch{if(f.current||b.current!==M||A.current!==w)return;r([]),m(!1),u(null)}finally{!f.current&&b.current===M&&A.current===w&&o(!1)}const L=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=Bs(`/api/tasks/${R}/logs/stream${L}`,{events:{"agent:log":ee=>{if(!(f.current||b.current!==M))try{const $=JSON.parse(ee.data);r(T=>ql([...T,$])),u(T=>T!==null?T+1:null)}catch{}}}})}return I(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[t,n,s]);const _=a.useCallback(async()=>{if(!t||h)return;const M=b.current,w=i.length,R=t;g(!0);try{const E=await Kc(R,s,{limit:Ou,offset:w});if(f.current||b.current!==M)return;r(I=>{const L=[...E.entries,...I];return ql(L)}),m(E.hasMore),u(E.total)}catch{}finally{g(!1)}},[t,s,i.length,h]),N=a.useCallback(()=>r([]),[]);return{entries:i,loading:l,clear:N,loadMore:_,hasMore:d,total:c,loadingMore:h}}function W2(t){const n=new Date(t),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),l=Math.floor(r/60),o=Math.floor(l/24);return r<1?"just now":r<60?`${r}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:n.toLocaleDateString()}const Bu={pre:({children:t,...n})=>e.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:t}),table:({children:t,...n})=>e.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:t})},K2=50;function qp(t){return[t.taskId,t.timestamp,t.agent??"",t.type,t.text,t.detail??""].join("|")}function G2(t){const n=new Map;return t.map(s=>{const i=qp(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function J2({entries:t,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:l=!1,onLoadMore:o,loadingMore:d=!1,totalCount:m=null}){const c=a.useRef(null),u=a.useRef(0),h=a.useRef(0),g=a.useRef(null),[p,f]=a.useState(!0),[b,v]=a.useState(!1),y=a.useMemo(()=>G2(t),[t]);a.useLayoutEffect(()=>{const w=c.current;if(!w)return;const R=t.length,E=u.current,I=h.current,L=y[y.length-1]??null,ee=g.current!==L;if(R>E){const $=w.scrollTop<=K2;if(ee)if($)w.scrollTop=0;else{const T=w.scrollHeight-I;T>0&&(w.scrollTop+=T)}}u.current=R,h.current=w.scrollHeight,g.current=L},[t,y]);const k=a.useCallback(w=>{w.key==="Escape"&&b&&v(!1)},[b]);if(a.useEffect(()=>{if(b)return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[b,k]),n&&t.length===0)return e.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:e.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})});if(t.length===0)return e.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:e.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})});const A=[...t].reverse(),j=[...y].reverse(),_=s?.provider&&s?.modelId,N=i?.provider&&i?.modelId,M=r?.provider&&r?.modelId;return e.jsxs("div",{ref:c,className:`agent-log-viewer agent-log-viewer--streaming${b?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[e.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[e.jsxs("div",{className:"agent-log-model-group",children:[e.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),_?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ss,{provider:s.provider,size:"sm"}),e.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):e.jsx("span",{className:"model-badge-default",children:"Using default"})]}),e.jsxs("div",{className:"agent-log-model-group",children:[e.jsx("span",{className:"agent-log-model-label",children:"Validator:"}),N?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ss,{provider:i.provider,size:"sm"}),e.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):e.jsx("span",{className:"model-badge-default",children:"Using default"})]}),e.jsxs("div",{className:"agent-log-model-group",children:[e.jsx("span",{className:"agent-log-model-label",children:"Planning/Triage:"}),M?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ss,{provider:r.provider,size:"sm"}),e.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):e.jsx("span",{className:"model-badge-default",children:"Using default"})]}),e.jsxs("div",{className:"agent-log-model-header-toggle",children:[e.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>f(w=>!w),"aria-label":p?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":p,"data-testid":"agent-log-mode-toggle",title:p?"Show raw text":"Show formatted markdown",children:p?"Markdown":"Plain"}),e.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>v(w=>!w),"aria-label":b?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:b?"Exit full screen":"Expand agent log to full screen",children:b?e.jsx(Ks,{size:14}):e.jsx(Zs,{size:14})})]})]}),m!==null&&e.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",t.length," of ",m," entries"]}),A.map((w,R)=>{const E=j[R]??`${qp(w)}|fallback`,I=A[R-1],L=w.type==="tool"||w.type==="tool_result"||w.type==="tool_error",ee=w.agent?L||R===0||I&&(I.agent!==w.agent||I.type!==w.type):!1,$=ee?e.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:W2(w.timestamp)}):null,T=ee?e.jsxs("span",{className:"agent-log-badge-row",children:[e.jsxs("span",{className:"agent-log-agent-badge",children:["[",w.agent,"]"]}),$]}):null;return w.type==="tool"?e.jsxs("div",{className:"agent-log-tool",children:[T,"⚡ ",w.text,w.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",w.detail]})]},E):w.type==="thinking"?e.jsxs("div",{className:"agent-log-thinking",children:[T,p?e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],components:Bu,children:w.text})}):w.text]},E):w.type==="tool_result"?e.jsxs("div",{className:"agent-log-tool-result",children:[T,"✓ ",w.text,w.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",w.detail]})]},E):w.type==="tool_error"?e.jsxs("div",{className:"agent-log-tool-error",children:[T,"✗ ",w.text,w.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",w.detail]})]},E):e.jsxs("div",{className:"agent-log-text",children:[T,p?e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],components:Bu,children:w.text})}):w.text]},E)}),l&&o&&e.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:e.jsx("button",{className:"agent-log-mode-toggle",onClick:o,disabled:d,"data-testid":"agent-log-load-more-button",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function Qi(t){return t??void 0}function pr(t){return{provider:Qi(t.modelProvider),modelId:Qi(t.modelId)}}function fr(t){return{provider:Qi(t.validatorModelProvider),modelId:Qi(t.validatorModelId)}}function gr(t){return{provider:Qi(t.planningModelProvider),modelId:Qi(t.planningModelId)}}function Y2(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function Q2(t,n){return t.validatorModelProvider&&t.validatorModelId?{provider:t.validatorModelProvider,modelId:t.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function X2(t,n){return t.planningModelProvider&&t.planningModelId?{provider:t.planningModelProvider,modelId:t.planningModelId}:n?.planningProvider&&n.planningModelId?{provider:n.planningProvider,modelId:n.planningModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function Vl(t){if(!t)return{provider:void 0,modelId:void 0};const n=t.indexOf("/");return{provider:t.slice(0,n),modelId:t.slice(n+1)}}function Wl(t){return t.provider&&t.modelId?`${t.provider}/${t.modelId}`:""}function Kl(t,n){return t.provider===n.provider&&t.modelId===n.modelId}function Z2(t,n){const i={executor:"Executor",validator:"Validator",planning:"Planning"}[t]||t;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function eM({task:t,addToast:n,onTaskUpdated:s,settings:i}){const[r,l]=a.useState([]),[o,d]=a.useState([]),[m,c]=a.useState([]),[u,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(()=>pr(t)),[v,y]=a.useState(()=>pr(t)),[k,A]=a.useState(()=>fr(t)),[j,_]=a.useState(()=>fr(t)),[N,M]=a.useState(()=>gr(t)),[w,R]=a.useState(()=>gr(t)),[E,I]=a.useState(()=>t.thinkingLevel??null),[L,ee]=a.useState(()=>t.thinkingLevel??null),[$,T]=a.useState(null),S=a.useRef(t.id);a.useEffect(()=>{h(!0),p(null),Kn().then(ve=>{l(ve.models),d(ve.favoriteProviders),c(ve.favoriteModels)}).catch(ve=>{p(ve.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const Y=a.useCallback(async ve=>{const Me=o,De=Me.includes(ve)?Me.filter(Oe=>Oe!==ve):[ve,...Me];d(De);try{await Wt({favoriteProviders:De,favoriteModels:m})}catch{d(Me),n("Failed to update favorites","error")}},[o,m,n]),K=a.useCallback(async ve=>{const Me=m,De=Me.includes(ve)?Me.filter(Oe=>Oe!==ve):[ve,...Me];c(De);try{await Wt({favoriteProviders:o,favoriteModels:De})}catch{c(Me),n("Failed to update model favorites","error")}},[m,o,n]);a.useEffect(()=>{S.current=t.id;const ve=pr(t),Me=fr(t),_e=gr(t);b(ve),y(ve),A(Me),_(Me),M(_e),R(_e);const De=t.thinkingLevel??null;I(De),ee(De),T(null)},[t.id,t.modelProvider,t.modelId,t.validatorModelProvider,t.validatorModelId,t.planningModelProvider,t.planningModelId,t.thinkingLevel]);const G=a.useMemo(()=>Wl(f),[f]),P=a.useMemo(()=>Wl(k),[k]),O=a.useMemo(()=>Wl(N),[N]),X=a.useMemo(()=>Y2(t,i),[t,i]),C=a.useMemo(()=>Q2(t,i),[t,i]),V=a.useMemo(()=>X2(t,i),[t,i]),de=$!==null,B=a.useCallback(async(ve,Me)=>{const _e=t.id,De=v,Oe=j,ze=w;T(ve);try{const Be=s?ve==="executor"?{modelProvider:Me.provider??null,modelId:Me.modelId??null}:ve==="validator"?{validatorModelProvider:Me.provider??null,validatorModelId:Me.modelId??null}:{planningModelProvider:Me.provider??null,planningModelId:Me.modelId??null}:{modelProvider:(ve==="executor"?Me:v).provider??null,modelId:(ve==="executor"?Me:v).modelId??null,validatorModelProvider:(ve==="validator"?Me:j).provider??null,validatorModelId:(ve==="validator"?Me:j).modelId??null,planningModelProvider:(ve==="planning"?Me:w).provider??null,planningModelId:(ve==="planning"?Me:w).modelId??null},Ae=await Ws(_e,Be);if(S.current!==_e)return;const Ce=pr(Ae),Ge=fr(Ae),Te=gr(Ae);y(Ce),b(Ce),_(Ge),A(Ge),R(Te),M(Te),s?.(Ae),n(Z2(ve,{executor:Ce,validator:Ge,planning:Te}[ve]),"success")}catch(Be){if(S.current!==_e)return;ve==="executor"?b(De):ve==="validator"?A(Oe):M(ze),n(fe(Be)||"Failed to save model settings","error")}finally{S.current===_e&&T(null)}},[t.id,v,j,w,n,s]),J=a.useCallback(ve=>{const Me=Vl(ve);b(Me),!Kl(Me,v)&&B("executor",Me)},[v,B]),D=a.useCallback(ve=>{const Me=Vl(ve);A(Me),!Kl(Me,j)&&B("validator",Me)},[j,B]),he=a.useCallback(ve=>{const Me=Vl(ve);M(Me),!Kl(Me,w)&&B("planning",Me)},[w,B]),q=a.useCallback(async ve=>{const Me=t.id,_e=L,De=ve===""?null:ve;I(De),T("thinking");try{const Oe=await Ws(Me,{thinkingLevel:De});if(S.current!==Me)return;const ze=Oe.thinkingLevel??null;ee(ze),I(ze),s?.(Oe);const Be=i?.defaultThinkingLevel??"off";n(ze===null?`Thinking level set to default (${Be})`:`Thinking level set to ${ze}`,"success")}catch(Oe){if(S.current!==Me)return;I(_e),n(fe(Oe)||"Failed to save thinking level","error")}finally{S.current===Me&&T(null)}},[t.id,L,i,n,s]),W=!v.provider&&!v.modelId,me=!j.provider&&!j.modelId,Re=!w.provider&&!w.modelId;return e.jsxs("div",{className:"model-selector-tab",children:[e.jsx("h4",{children:"Model Configuration"}),e.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, global default settings are used."}),u?e.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):g?e.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,e.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),Kn().then(ve=>{l(ve.models),d(ve.favoriteProviders),c(ve.favoriteModels)}).catch(ve=>p(ve.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?e.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),e.jsx("div",{className:"model-selector-current",children:W?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",X.provider&&X.modelId?` (${X.provider}/${X.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&e.jsx(ss,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),e.jsx(Kt,{id:"executorModel",label:"Executor Model",value:G,onChange:J,models:r,disabled:de,placeholder:"Select executor model…",favoriteProviders:o,onToggleFavorite:Y,favoriteModels:m,onToggleModelFavorite:K}),e.jsx("small",{children:"The AI model used to implement this task."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"validatorModel",children:"Validator Model"}),e.jsx("div",{className:"model-selector-current",children:me?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",C.provider&&C.modelId?` (${C.provider}/${C.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&e.jsx(ss,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),e.jsx(Kt,{id:"validatorModel",label:"Validator Model",value:P,onChange:D,models:r,disabled:de,placeholder:"Select validator model…",favoriteProviders:o,onToggleFavorite:Y,favoriteModels:m,onToggleModelFavorite:K}),e.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),e.jsx("div",{className:"model-selector-current",children:Re?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",V.provider&&V.modelId?` (${V.provider}/${V.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[w.provider&&e.jsx(ss,{provider:w.provider,size:"sm"}),w.provider,"/",w.modelId]})}),e.jsx(Kt,{id:"planningModel",label:"Planning Model",value:O,onChange:he,models:r,disabled:de,placeholder:"Select planning model…",favoriteProviders:o,onToggleFavorite:Y,favoriteModels:m,onToggleModelFavorite:K}),e.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),e.jsx("div",{className:"model-selector-current",children:L===null?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):e.jsx("span",{className:"model-badge model-badge-custom",children:L})}),e.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:ve=>q(ve.target.value),disabled:de,className:"thinking-level-select",children:[e.jsxs("option",{value:"",children:["Default (",i?.defaultThinkingLevel??"off",")"]}),e.jsx("option",{value:"off",children:"Off"}),e.jsx("option",{value:"minimal",children:"Minimal"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]}),e.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),e.jsx("div",{className:"model-selector-status",children:W&&me&&Re&&L===null?"Using global default models.":"Model settings are up to date."})]})]})}const tM={open:e.jsx(Vr,{size:16}),closed:e.jsx(Ua,{size:16}),merged:e.jsx(Gm,{size:16})};function nM({taskId:t,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:l,onPrCreated:o,onPrUpdated:d,addToast:m}){const[c,u]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[b,v]=a.useState(!1),[y,k]=a.useState(!1),[A,j]=a.useState(null),_=a.useCallback(async()=>{if(h.trim()){v(!0);try{const R=await hv(t,{title:h.trim(),body:p.trim()||void 0},n);o(R),u(!1),g(""),f(""),m(`Created PR #${R.number}`,"success")}catch(R){m(fe(R)||"Failed to create PR","error")}finally{v(!1)}}},[t,h,p,n,o,m]),N=a.useCallback(async()=>{if(s){k(!0);try{const R=await pv(t,n);j(R),d(R.prInfo),m("PR status refreshed","success")}catch(R){m(fe(R)||"Failed to refresh PR","error")}finally{k(!1)}}},[t,s,n,d,m]);if(!s)return i==="creating-pr"?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):c?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),e.jsxs("div",{className:"pr-form",children:[e.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:R=>g(R.target.value),disabled:b,className:"pr-input"}),e.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:R=>f(R.target.value),disabled:b,className:"pr-textarea",rows:3}),e.jsxs("div",{className:"pr-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>u(!1),disabled:b,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:_,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u(!0),disabled:!l,title:l?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[e.jsx(qt,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!l&&e.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",e.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const M=tM[s.status]??e.jsx(Vr,{size:16}),w=A?.blockingReasons??[];return e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[e.jsxs("div",{className:"pr-header",children:[e.jsx("span",{className:"pr-status-icon",children:M}),e.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),e.jsxs("span",{className:"pr-number",children:["#",s.number]}),e.jsx("div",{className:"pr-spacer"}),e.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:y,title:"Refresh PR status",children:e.jsx(vn,{size:14,style:{verticalAlign:"middle",opacity:y?.5:1}})})]}),e.jsx("div",{className:"pr-title",children:s.title}),e.jsxs("div",{className:"pr-meta",children:[e.jsx("span",{children:s.headBranch}),e.jsx("span",{className:"pr-meta-arrow",children:"→"}),e.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:w.length>0?`Waiting for: ${w.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),e.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&e.jsxs("span",{className:"pr-comments",children:[e.jsx(ei,{size:14}),s.commentCount]}),e.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[e.jsx(xg,{size:14}),"View on GitHub"]})]})]})]})}const Uu=2e3;function sM(t){const n=t.updatedAt||t.createdAt,s=new Date(n).toLocaleString();return t.updatedAt?`${s} (edited)`:s}function iM(t){return t==="agent"||t==="system"}function aM({task:t,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[l,o]=a.useState(""),[d,m]=a.useState(null),[c,u]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),b=a.useMemo(()=>[...t.comments||[]].sort((M,w)=>new Date(w.createdAt).getTime()-new Date(M.createdAt).getTime()),[t.comments]),v=l.length>Uu;async function y(){const M=l.trim();if(M){g(!0);try{const w=await Qx(t.id,M,r);o(""),n?.(w),s("Comment added","success")}catch(w){s(fe(w)||"Failed to add comment","error")}finally{g(!1)}}}async function k(M){const w=c.trim();if(w){g(!0);try{const R=await Wx(t.id,M,w,r);m(null),u(""),n?.(R),s("Comment updated","success")}catch(R){s(fe(R)||"Failed to update comment","error")}finally{g(!1)}}}async function A(M){f(M);try{const w=await Kx(t.id,M,r);n?.(w),s("Comment deleted","success")}catch(w){s(fe(w)||"Failed to delete comment","error")}finally{f(null)}}function j(M){M.key==="Enter"&&(M.ctrlKey||M.metaKey)&&(M.preventDefault(),y())}return e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Comments"}),b.length===0?e.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):e.jsx("div",{className:"detail-activity-list",children:b.map(M=>{const w=M.author===i,R=d===M.id,E=iM(M.author);return e.jsxs("div",{className:"detail-log-entry",children:[e.jsxs("div",{className:"detail-log-header comments-header-row",children:[e.jsxs("div",{className:"comments-author-row",children:[E?e.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):e.jsx("strong",{children:M.author}),e.jsx("span",{className:"detail-log-timestamp",children:sM(M)})]}),w&&!R?e.jsxs("div",{className:"comments-actions-row",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{m(M.id),u(M.text)},children:"Edit"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void A(M.id),disabled:p===M.id,children:p===M.id?"Deleting…":"Delete"})]}):null]}),R?e.jsxs("div",{className:"comments-edit-form",children:[e.jsx("textarea",{value:c,onChange:I=>u(I.target.value),rows:3,className:"spec-editor-feedback"}),e.jsxs("div",{className:"comments-edit-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{m(null),u("")},disabled:h,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void k(M.id),disabled:h||!c.trim(),children:"Save"})]})]}):e.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:M.text})]},M.id)})}),e.jsxs("div",{className:"comments-compose-form",children:[e.jsx("textarea",{value:l,onChange:M=>o(M.target.value),onKeyDown:j,rows:3,placeholder:"Add a comment",className:"spec-editor-feedback"}),e.jsxs("div",{className:"comments-footer-row",children:[e.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[l.length," / ",Uu]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(),disabled:h||!l.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function rM(t){return t?t.slice(0,7):"Unknown"}function lM({task:t}){if(t.column!=="done"||!t.mergeDetails)return null;const n=t.mergeDetails;return e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Merge Details"}),e.jsxs("div",{className:"pr-card merge-details-card",children:[e.jsx("div",{className:"detail-log-entry",children:e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-action",children:"Status"}),e.jsx("span",{className:"detail-log-outcome",children:n.mergeConfirmed===!1?"Recorded without local merge confirmation":"Merged successfully"})]})}),e.jsx("div",{className:"detail-log-entry",children:e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-action",children:"Commit"}),e.jsx("span",{className:"detail-log-outcome",children:rM(n.commitSha)})]})}),e.jsx("div",{className:"detail-log-entry",children:e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-action",children:"Files changed"}),e.jsx("span",{className:"detail-log-outcome",children:n.filesChanged??0})]})}),e.jsx("div",{className:"detail-log-entry",children:e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-action",children:"Insertions / Deletions"}),e.jsxs("span",{className:"detail-log-outcome",children:["+",n.insertions??0," / -",n.deletions??0]})]})}),n.mergedAt?e.jsx("div",{className:"detail-log-entry",children:e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-action",children:"Merged at"}),e.jsx("span",{className:"detail-log-outcome",children:new Date(n.mergedAt).toLocaleString()})]})}):null,n.prNumber?e.jsx("div",{className:"detail-log-entry",children:e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-action",children:"PR"}),e.jsxs("span",{className:"detail-log-outcome",children:["#",n.prNumber]})]})}):null,n.mergeCommitMessage?e.jsxs("div",{className:"detail-log-entry",children:[e.jsx("div",{className:"detail-log-header",children:e.jsx("span",{className:"detail-log-action",children:"Message"})}),e.jsx("div",{className:"detail-log-outcome",children:n.mergeCommitMessage})]}):null]})]})}function Vp(t){return t.split(`
|
|
626
|
+
`).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?e.jsx("span",{className:r,children:`${s}
|
|
627
|
+
`},i):e.jsx(zm.Fragment,{children:`${s}
|
|
628
|
+
`},i)})}function Hu(t,n=60){if(!t||t.length<=n)return t;if(n<4)return t.slice(0,n);const s="...",i=t.lastIndexOf("/");if(i===-1){const u=Math.max(1,n-s.length);return t.slice(0,u)+s}const r=[];for(let u=1;u<t.length;u++)t[u]==="/"&&r.push(u);const l=n-s.length;let o=null,d=-1;for(let u=r.length-1;u>=0;u--){const h=r[u],g=t.slice(h);if(g.length>l)continue;const p=l-g.length;for(let f=0;f<r.length;f++){const b=r[f],v=t.slice(0,b);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>d&&(d=v.length+g.length,o=v+s+g)}}if(o)return o;const m=t.slice(i);if(s.length+m.length<=n)return s+m;const c=n-s.length;return s+t.slice(t.length-c)}function oM(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function cM({isOpen:t,taskId:n,files:s,stats:i,mergeDetails:r,column:l,onClose:o,onRefresh:d}){const[m,c]=a.useState(null),[u,h]=a.useState(!0);a.useEffect(()=>{s.length>0&&m===null&&c(0)},[s,m]);const g=a.useCallback(()=>{c(v=>v!==null&&v>0?v-1:v)},[]),p=a.useCallback(()=>{c(v=>v!==null&&v<s.length-1?v+1:v)},[]);if(a.useEffect(()=>{if(!t)return;const v=y=>{if(y.key==="Escape"){o();return}y.key==="ArrowUp"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),g()),y.key==="ArrowDown"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),p())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[t,o,g,p]),!t)return null;const f=m!==null?s[m]:null,b=l==="done";return e.jsx("div",{className:"modal-overlay open",onClick:o,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal changes-diff-modal",onClick:v=>v.stopPropagation(),children:[e.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[e.jsxs("div",{className:"changes-diff-header-title",children:[e.jsx(Ms,{size:18}),e.jsxs("span",{children:["Changes — ",n]}),e.jsxs("span",{className:"changes-stat-summary",children:[e.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",e.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),e.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&e.jsxs("div",{className:"changes-nav",children:[e.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:m===null||m<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:e.jsx(Ho,{size:14})}),e.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:m!==null?`${m+1}/${s.length}`:`—/${s.length}`}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:p,disabled:m===null||m>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:e.jsx(rn,{size:14})})]}),e.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:()=>h(v=>!v),title:u?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:e.jsx(Ar,{size:14})}),d&&e.jsxs("button",{className:"btn btn-sm",onClick:d,children:[e.jsx(vn,{size:14}),"Refresh"]}),e.jsx("button",{className:"modal-close",onClick:o,"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsxs("div",{className:"changes-diff-body",children:[e.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Ta,{size:14}),e.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&e.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&e.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),e.jsx("div",{className:"changes-diff-file-list",children:s.map((v,y)=>e.jsxs("button",{className:`changes-diff-file-item ${m===y?"selected":""}`,onClick:()=>c(y),title:v.path,children:[e.jsx("span",{className:`changes-file-status changes-file-status--${v.status}`,children:oM(v.status)}),e.jsx("span",{className:"changes-diff-file-path",children:v.path}),e.jsxs("span",{className:"changes-diff-file-stat",children:["+",v.additions," -",v.deletions]})]},v.path))})]}),e.jsx("div",{className:"changes-diff-content",children:f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"changes-diff-file-header-bar",children:[e.jsx("span",{className:"changes-diff-file-header-name",children:f.path}),e.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",f.additions," -",f.deletions]})]}),f.patch?e.jsx("div",{className:"changes-diff-viewer",children:e.jsx("pre",{className:`changes-diff-patch ${u?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:e.jsx("code",{children:Vp(f.patch)})})}):e.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):e.jsxs("div",{className:"changes-diff-empty",children:[e.jsx(Ms,{size:48,opacity:.3}),e.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function qu(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function dM({taskId:t,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:l}){const[o,d]=a.useState([]),[m,c]=a.useState({filesChanged:0,additions:0,deletions:0}),[u,h]=a.useState(!0),[g,p]=a.useState(null),[f,b]=a.useState(new Set),[v,y]=a.useState(null),[k,A]=a.useState(!0),[j,_]=a.useState(!1),N=i==="done",M=N&&!!r?.commitSha,w=i==="in-progress"||i==="in-review"||M,R=a.useCallback(async()=>{if(!w){h(!1);return}try{h(!0),p(null);const $=await gh(t,void 0,s),T=$.files.map(S=>({path:S.path,status:S.status,additions:S.additions,deletions:S.deletions,patch:S.patch}));d(T),c($.stats),T.length>0&&(b(new Set([T[0].path])),y(0))}catch($){p(fe($)||"Failed to load diff")}finally{h(!1)}},[t,s,w]);a.useEffect(()=>{R()},[R]);const E=$=>{b(T=>{const S=new Set(T);if(S.has($))S.delete($);else{S.add($);const Y=o.findIndex(K=>K.path===$);Y!==-1&&y(Y)}return S})},I=$=>{if($<0||$>=o.length)return;const T=o[$].path;b(new Set([T])),y($)},L=v!==null&&v>0,ee=v!==null&&v<o.length-1;if(u)return e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[e.jsx("div",{className:"loading-spinner"}),e.jsx("span",{children:"Loading changes..."})]})});if(g)return e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[e.jsx(is,{size:16}),e.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!N&&!n)return e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Ms,{size:24}),e.jsx("p",{children:"No worktree available for this task."}),e.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(N&&!M){const $=r?.filesChanged,T=r?.insertions,S=r?.deletions,Y=$!=null||T!=null||S!=null;return e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Ms,{size:24}),e.jsx("p",{children:"Detailed file changes unavailable."}),e.jsx("span",{className:"task-changes-state-hint",children:Y?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${T??0} additions, -${S??0} deletions.`:"No merge commit was recorded for this task."})]})})}return o.length===0?N&&l&&l.length>0?e.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Ta,{size:14}),e.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&e.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Ms,{size:24}),e.jsxs("p",{children:[l.length," file",l.length===1?"":"s"," modified during execution."]}),e.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),e.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>e.jsx("div",{className:"changes-file-item",children:e.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[e.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:qu("unknown")}),e.jsx("span",{className:"changes-file-path",title:$,children:Hu($)})]})},$))})]}):e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Ms,{size:24}),e.jsx("p",{children:"No files modified."}),e.jsx("span",{className:"task-changes-state-hint",children:N?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):e.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Ta,{size:14}),e.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&e.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&e.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),e.jsxs("div",{className:"changes-header",children:[e.jsxs("div",{className:"task-changes-header-title",children:[e.jsxs("h4",{children:[e.jsx(Ms,{size:16}),"Files Changed (",m.filesChanged,")"]}),e.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[e.jsxs("span",{className:"diff-add",children:["+",m.additions]})," ",e.jsxs("span",{className:"diff-del",children:["-",m.deletions]})]})]}),e.jsxs("div",{className:"changes-header-actions-wrapper",children:[e.jsxs("div",{className:"changes-header-actions",children:[o.length>0&&e.jsxs("div",{className:"changes-nav",children:[e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>L&&I(v-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:e.jsx(Ho,{size:14})}),e.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${o.length}`:`—/${o.length}`}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>ee&&I(v+1),disabled:!ee,title:"Next file","aria-label":"Next file",children:e.jsx(rn,{size:14})})]}),e.jsx("button",{className:`btn btn-sm ${k?"btn-primary":""}`,onClick:()=>A($=>!$),title:k?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:e.jsx(Ar,{size:14})})]}),e.jsxs("div",{className:"changes-header-actions-secondary",children:[e.jsx("button",{className:"btn btn-sm",onClick:R,disabled:u,children:"Refresh"}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>_(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:e.jsx(Zs,{size:14})})]})]})]}),e.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>{const T=f.has($.path);return e.jsxs("div",{className:`changes-file-item ${T?"expanded":""}`,children:[e.jsxs("button",{className:"changes-file-header",onClick:()=>E($.path),children:[e.jsx("span",{className:"changes-file-toggle",children:T?e.jsx(Lt,{size:14}):e.jsx(rn,{size:14})}),e.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:qu($.status)}),e.jsx("span",{className:"changes-file-path",title:$.path,children:Hu($.path)}),e.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),T&&$.patch&&e.jsx("div",{className:"changes-file-content",children:e.jsx("pre",{className:`changes-diff-patch ${k?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:e.jsx("code",{children:Vp($.patch)})})})]},$.path)})}),e.jsx(cM,{isOpen:j,taskId:t,files:o,stats:m,mergeDetails:r,column:i,onClose:()=>_(!1),onRefresh:R})]})}function Do(t){return{executorValue:t?.executorProvider&&t?.executorModelId?`${t.executorProvider}/${t.executorModelId}`:"",validatorValue:t?.validatorProvider&&t?.validatorModelId?`${t.validatorProvider}/${t.validatorModelId}`:""}}function uM(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function mM(t,n){const s=uM(t),i=new Set(n.map(d=>d.id));if(!i.has(s))return s;const r=30;let l=s,o=1;for(;i.has(l)&&o<100;){const d=`-${o}`;l=`${s.slice(0,r-d.length)}${d}`,o++}return l}const Vu=["image/png","image/jpeg","image/gif","image/webp"];function hM(t,n,s){const i=t==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return e.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:t==="post-merge"?"Post-merge":"Pre-merge"})}function Wp({mode:t,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:l,onDependenciesChange:o,priority:d,onPriorityChange:m,executorModel:c,onExecutorModelChange:u,validatorModel:h,onValidatorModelChange:g,planningModel:p,onPlanningModelChange:f,thinkingLevel:b,onThinkingLevelChange:v,presetMode:y,onPresetModeChange:k,selectedPresetId:A,onSelectedPresetIdChange:j,selectedWorkflowSteps:_,onWorkflowStepsChange:N,onDefaultOnApplied:M,pendingImages:w,onImagesChange:R,tasks:E,projectId:I,disabled:L=!1,addToast:ee,isActive:$=!0,onAutoSaveDescription:T,onPlanningMode:S,onSubtaskBreakdown:Y,onClose:K,renderBelowPrimary:G,hideDependencies:P,reviewLevel:O,onReviewLevelChange:X}){const C=(P?!1:l.length>0)||w.length>0||_.length>0||y!=="default"||(d??ds)!==ds||c!==""||h!==""||(p||"")!==""||(b||"")!==""||O!==void 0,[V,de]=a.useState(!1),[B,J]=a.useState(C),[D,he]=a.useState(""),[q,W]=a.useState([]),[me,Re]=a.useState([]),[ve,Me]=a.useState([]),[_e,De]=a.useState(!1),[Oe,ze]=a.useState(null),[Be,Ae]=a.useState([]),[Ce,Ge]=a.useState("idle"),[Te,Xe]=a.useState(!1),[re,Z]=a.useState(!1),[ye,ie]=a.useState(!1),Ie=a.useRef(null),pe=a.useRef(null),Ue=a.useRef(null),dt=a.useRef(null),ht=a.useRef(null),ue=a.useRef(null),te=a.useRef(null),ke=a.useRef(!1),Ne=a.useRef(C),Ze=a.useRef(n.trim()),xe=a.useRef(n.trim());a.useEffect(()=>{$&&(De(!0),Kn().then(U=>{W(U.models),Re(U.favoriteProviders),Me(U.favoriteModels)}).catch(()=>{}).finally(()=>De(!1)),Ki(I).then(U=>ze(U)).catch(()=>ze(null)),Yr(I).then(U=>Ae(U.filter(we=>we.enabled))).catch(()=>Ae([])))},[$,I]);const st=Oe?.modelPresets||[],Ee=st.find(U=>U.id===A),He=(P?!1:l.length>0)||w.length>0||_.length>0||y!=="default"||(d??ds)!==ds||c!==""||h!==""||(p||"")!==""||(b||"")!==""||O!==void 0;a.useEffect(()=>{if(t!=="create"||!$||!Oe?.autoSelectModelPreset)return;const U=(Oe.defaultPresetBySize,void 0);if(U){const we=Do(U);j(U.id),k("preset"),u(we.executorValue),g(we.validatorValue)}},[$,Oe,st,t]);const ce=a.useRef(!1);a.useEffect(()=>{if(t!=="create"||!$||ce.current||Be.length===0)return;const U=Be.filter(rt=>rt.defaultOn);if(U.length===0)return;ce.current=!0;const we=U.map(rt=>rt.id);N(we),M?.(we)},[t,$,Be]),a.useEffect(()=>{$||(ce.current=!1)},[$]),a.useEffect(()=>{He&&!Ne.current&&J(!0),Ne.current=He},[He]),a.useEffect(()=>{B||(de(!1),he(""))},[B]),a.useEffect(()=>{t!=="edit"||!$||dt.current&&(dt.current.focus(),dt.current.select())},[t,$]),a.useEffect(()=>{if(!V)return;const U=we=>{pe.current&&!pe.current.contains(we.target)&&de(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[V]),a.useEffect(()=>{(t!=="edit"||L)&&ie(!1)},[t,L]),a.useEffect(()=>{if(t!=="edit"){Ge("idle");return}const U=n.trim();Ze.current=U,xe.current=U,Ge("idle")},[t]),a.useEffect(()=>{if(t!=="edit"||!T||!$)return;const U=n.trim(),we=Ze.current;if(U===we||U===xe.current){ue.current&&(clearTimeout(ue.current),ue.current=null),ke.current||Ge("idle");return}return ue.current&&clearTimeout(ue.current),ue.current=setTimeout(async()=>{if(!ke.current){ke.current=!0,Ge("saving");try{await T(U),xe.current=U,Ge("saved"),te.current&&clearTimeout(te.current),te.current=setTimeout(()=>{Ge("idle"),te.current=null},2e3)}catch{Ge("idle")}finally{ke.current=!1,ue.current=null}}},1500),()=>{ue.current&&(clearTimeout(ue.current),ue.current=null)}},[t,n,T,$]),a.useEffect(()=>()=>{ue.current&&clearTimeout(ue.current),te.current&&clearTimeout(te.current)},[]),a.useEffect(()=>{if(!Te)return;const U=we=>{Ie.current&&!Ie.current.contains(we.target)&&Xe(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[Te]);const qe=a.useCallback(U=>{const we=U.clipboardData?.items;if(we)for(let rt=0;rt<we.length;rt++){const xt=we[rt];if(xt.type.startsWith("image/")){const je=xt.getAsFile();if(je&&Vu.includes(je.type)){U.preventDefault(),R([...w,{file:je,previewUrl:URL.createObjectURL(je)}]);return}}}},[w,R]),We=a.useCallback(U=>{U.preventDefault();const we=U.dataTransfer.files;for(let rt=0;rt<we.length;rt++){const xt=we[rt];if(Vu.includes(xt.type)){R([...w,{file:xt,previewUrl:URL.createObjectURL(xt)}]);return}}},[w,R]),Pe=a.useCallback(U=>{const we=w[U];we&&URL.revokeObjectURL(we.previewUrl),R(w.filter((rt,xt)=>xt!==U))},[w,R]),nt=a.useCallback(U=>{o(l.includes(U)?l.filter(we=>we!==U):[...l,U])},[l,o]),kt=(U,we)=>U.length>we?U.slice(0,we)+"…":U,yt=a.useCallback(U=>{s(U.target.value);const we=U.target;we.style.height="auto",we.style.height=we.scrollHeight+"px"},[s]),Ct=a.useCallback(()=>{ie(U=>!U)},[]),Et=a.useCallback(U=>{!ye||U.key!=="Escape"||(U.preventDefault(),U.stopPropagation(),ie(!1))},[ye]),Pt=a.useCallback(async U=>{const we=n.trim();if(!(!we||re)){Z(!0);try{const rt=await uh(we,U,I);s(rt),Xe(!1),ee("Description refined with AI","success"),Ue.current&&(Ue.current.style.height="auto",Ue.current.style.height=Ue.current.scrollHeight+"px")}catch(rt){const xt=mh(rt);ee(xt,"error")}finally{Z(!1)}}},[n,re,ee,s,I]),It=a.useCallback(async U=>{const we=me,xt=we.includes(U)?we.filter(je=>je!==U):[U,...we];Re(xt);try{await Wt({favoriteProviders:xt,favoriteModels:ve})}catch{Re(we)}},[me,ve]),bt=a.useCallback(async U=>{const we=ve,xt=we.includes(U)?we.filter(je=>je!==U):[U,...we];Me(xt);try{await Wt({favoriteProviders:me,favoriteModels:xt})}catch{Me(we)}},[ve,me]),_t=a.useCallback(U=>{if(U<=0)return;const we=[..._];[we[U-1],we[U]]=[we[U],we[U-1]],N(we)},[_,N]),Ve=a.useCallback(U=>{if(U>=_.length-1)return;const we=[..._];[we[U],we[U+1]]=[we[U+1],we[U]],N(we)},[_,N]),ft=a.useCallback(U=>{N(_.filter(we=>we!==U))},[_,N]),Fe=new Map;for(const U of Be)Fe.set(U.id,{name:U.name,description:U.description});const lt=E.filter(U=>!l.includes(U.id)).sort((U,we)=>{const rt=we.createdAt.localeCompare(U.createdAt);if(rt!==0)return rt;const xt=parseInt(U.id.slice(U.id.lastIndexOf("-")+1),10)||0;return(parseInt(we.id.slice(we.id.lastIndexOf("-")+1),10)||0)-xt}),be=D?lt.filter(U=>U.id.toLowerCase().includes(D.toLowerCase())||U.title&&U.title.toLowerCase().includes(D.toLowerCase())||U.description&&U.description.toLowerCase().includes(D.toLowerCase())):lt;return e.jsxs("div",{className:"task-form",onDrop:We,onDragOver:U=>U.preventDefault(),onPaste:qe,children:[e.jsxs("div",{className:"task-form-primary-section",children:[t==="edit"&&r&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"task-form-title",children:"Title"}),e.jsx("input",{ref:dt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:U=>r(U.target.value),disabled:L})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[e.jsx("span",{children:"Description"}),e.jsx("span",{className:`description-auto-save-status${Ce==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Ce==="saving"?"Saving...":Ce==="saved"?"Saved":""})]}),e.jsxs("div",{className:`description-with-refine${ye?" description--fullscreen":""}`,ref:Ie,onKeyDown:Et,children:[ye&&e.jsxs("div",{className:"description-fullscreen-header",children:[e.jsx("span",{children:"Editing Description"}),e.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Ct,"aria-label":"Collapse description",title:"Collapse description",children:e.jsx(Ks,{size:14})})]}),e.jsx("textarea",{ref:Ue,autoFocus:t==="create",id:"task-form-description",value:n,onChange:yt,placeholder:"What needs to be done?",rows:t==="edit"?8:5,disabled:L||re}),(()=>{const U=!!n.trim()&&!L;return e.jsxs(e.Fragment,{children:[!ye&&e.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${U?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ct,"aria-label":"Expand description",title:"Expand description",children:e.jsx(Zs,{size:14})}),U&&e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${re?"refine-button--loading":""}`,onClick:()=>Xe(we=>!we),disabled:re,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(Ln,{size:12,style:{verticalAlign:"middle"}}),re?"Refining...":"Refine"]})]})})(),Te&&e.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:U=>U.preventDefault(),children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>Pt("clarify"),"data-testid":"refine-clarify",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),e.jsxs("div",{className:"refine-menu-item",onClick:()=>Pt("add-details"),"data-testid":"refine-add-details",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),e.jsxs("div",{className:"refine-menu-item",onClick:()=>Pt("expand"),"data-testid":"refine-expand",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),e.jsxs("div",{className:"refine-menu-item",onClick:()=>Pt("simplify"),"data-testid":"refine-simplify",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),t==="create"&&(S||Y)&&e.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[S&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const U=n.trim();if(!U){ee("Enter a description first","error");return}K?.(),S(U)},disabled:L||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),Y&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const U=n.trim();if(!U){ee("Enter a description first","error");return}K?.(),Y(U)},disabled:L||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),G,e.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>J(U=>!U),"aria-expanded":B,"aria-controls":"task-form-more-options",disabled:L,"data-testid":"task-form-more-options-toggle",children:[e.jsx("span",{children:"More options"}),B?e.jsx(Fs,{size:14}):e.jsx(Lt,{size:14})]}),e.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${B?"":" collapsed"}`,"aria-hidden":!B,"data-testid":"task-form-more-options",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Attachments"}),w.length>0&&e.jsx("div",{className:"inline-create-previews",children:w.map((U,we)=>e.jsxs("div",{className:"inline-create-preview",children:[e.jsx("img",{src:U.previewUrl,alt:U.file.name}),e.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Pe(we),disabled:L,title:"Remove image",children:"×"})]},U.previewUrl))}),e.jsx("input",{ref:ht,type:"file",accept:"image/*",onChange:U=>{const we=U.target.files?.[0];we&&(R([...w,{file:we,previewUrl:URL.createObjectURL(we)}]),U.target.value="")},style:{display:"none"}}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ht.current?.click(),disabled:L,children:"Attach Screenshot"}),e.jsx("small",{children:"You can also paste images or drag & drop"})]}),!P&&e.jsx(e.Fragment,{children:e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Dependencies"}),e.jsxs("div",{className:"dep-trigger-wrap",ref:pe,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(U=>!U),disabled:L,children:l.length>0?`${l.length} selected`:"Add dependencies"}),V&&e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:D,onChange:U=>he(U.target.value),onClick:U=>U.stopPropagation()}),be.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):be.map(U=>e.jsxs("div",{className:`dep-dropdown-item${l.includes(U.id)?" selected":""}`,onClick:()=>nt(U.id),onMouseDown:we=>we.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:U.id}),e.jsx("span",{className:"dep-dropdown-title",children:kt(U.title||U.description||U.id,30)})]},U.id))]})]}),l.length>0&&e.jsx("div",{className:"selected-deps",children:l.map(U=>e.jsxs("span",{className:"dep-chip",children:[U,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>nt(U),disabled:L,children:"×"})]},U))})]})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Model Configuration"}),m&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),e.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:d??ds,onChange:U=>m(U.target.value),disabled:L,children:Jo.map(U=>e.jsx("option",{value:U,children:U[0].toUpperCase()+U.slice(1)},U))})]}),_e?e.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):q.length===0?e.jsx("small",{children:"No models available. Configure authentication in Settings."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),e.jsxs("select",{id:"model-preset",value:y==="preset"?A:y,onChange:U=>{const we=U.target.value;if(we==="default"){k("default"),j(""),u(""),g("");return}if(we==="custom"){k("custom"),j("");return}const rt=st.find(je=>je.id===we),xt=Do(rt);k("preset"),j(we),u(xt.executorValue),g(xt.validatorValue)},disabled:L,children:[e.jsx("option",{value:"default",children:"Use default"}),st.length>0?e.jsx("option",{disabled:!0,children:"──────────"}):null,st.map(U=>e.jsx("option",{value:U.id,children:U.name},U.id)),e.jsx("option",{value:"custom",children:"Custom"})]})]}),y==="preset"&&Ee?e.jsxs("small",{children:["Using preset: ",Ee.name]}):null,y==="preset"?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>k("custom"),disabled:L,children:"Override"}):null,e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),e.jsx(Kt,{id:"executor-model",label:"Executor Model",value:c,onChange:U=>{k("custom"),j(""),u(U)},models:q,disabled:L||y==="preset",favoriteProviders:me,onToggleFavorite:It,favoriteModels:ve,onToggleModelFavorite:bt})]}),e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Validator"}),e.jsx(Kt,{id:"validator-model",label:"Validator Model",value:h,onChange:U=>{k("custom"),j(""),g(U)},models:q,disabled:L||y==="preset",favoriteProviders:me,onToggleFavorite:It,favoriteModels:ve,onToggleModelFavorite:bt})]}),f&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),e.jsx(Kt,{id:"planning-model",label:"Planning Model",value:p||"",onChange:U=>{k("custom"),j(""),f(U)},models:q,disabled:L||y==="preset",favoriteProviders:me,onToggleFavorite:It,favoriteModels:ve,onToggleModelFavorite:bt})]}),v&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),e.jsxs("select",{id:"thinking-level",value:b||"",onChange:U=>v(U.target.value),disabled:L||y==="preset",children:[e.jsxs("option",{value:"",children:["Default (",Oe?.defaultThinkingLevel??"off",")"]}),e.jsx("option",{value:"off",children:"Off"}),e.jsx("option",{value:"minimal",children:"Minimal"}),e.jsx("option",{value:"low",children:"Low"}),e.jsx("option",{value:"medium",children:"Medium"}),e.jsx("option",{value:"high",children:"High"})]})]}),X&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),e.jsxs("select",{id:"review-level",value:O??"",onChange:U=>X(U.target.value===""?0:parseInt(U.target.value,10)),disabled:L,children:[e.jsx("option",{value:"",children:"Default (None)"}),e.jsx("option",{value:"0",children:"0 — None"}),e.jsx("option",{value:"1",children:"1 — Plan Only"}),e.jsx("option",{value:"2",children:"2 — Plan and Code"}),e.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),e.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[e.jsx("label",{children:"Workflow Steps"}),e.jsxs("div",{className:"workflow-steps-section",children:[e.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),e.jsx("div",{className:"workflow-steps-list",children:Be.length>0&&Be.map(U=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${U.id}`,children:[e.jsx("input",{type:"checkbox",checked:_.includes(U.id),onChange:we=>{N(we.target.checked?[..._,U.id]:_.filter(rt=>rt!==U.id))},disabled:L}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[U.name,hM(U.phase||"pre-merge",U.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:U.description})]})]},U.id))})]}),_.length>1&&e.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[e.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),_.map((U,we)=>{const rt=Fe.get(U);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${U}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:we+1}),e.jsx("span",{className:"workflow-step-order-name",children:rt?.name||U}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_t(we),disabled:L||we===0,"data-testid":`workflow-step-move-up-${U}`,title:"Move up",children:e.jsx(Fs,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ve(we),disabled:L||we===_.length-1,"data-testid":`workflow-step-move-down-${U}`,title:"Move down",children:e.jsx(Lt,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ft(U),disabled:L,"data-testid":`workflow-step-remove-${U}`,title:"Remove",children:e.jsx(Ft,{size:14})})]})]},U)})]})]})]})]})}const Wu={pre:({children:t,className:n,...s})=>e.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:t}),table:({children:t,className:n,...s})=>e.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:t})};function pM(t){switch(t){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return t}}function fM(t,n){if(!t||!n)return null;const s=new Date(t).getTime(),r=new Date(n).getTime()-s;if(r<1e3)return`${r}ms`;const l=Math.round(r/1e3);if(l<60)return`${l}s`;const o=Math.floor(l/60),d=l%60;return`${o}m ${d}s`}function gM(t){return t?new Date(t).toLocaleString():null}function bM(t){const n=t.split(`
|
|
629
|
+
`);return n.length<=1?t:`${n.length} lines`}function br(t,n,s){const i=t==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return e.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:t==="post-merge"?"Post-merge":"Pre-merge"})}function xM({entries:t,startedAt:n,stepId:s}){const i=a.useRef(null),r=new Date(n).getTime(),l=t.filter(o=>new Date(o.timestamp).getTime()>=r);return a.useEffect(()=>{const o=i.current;o&&(o.scrollTop=o.scrollHeight)},[l.length]),t.length===0?e.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:e.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):e.jsx("div",{ref:i,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:l.map((o,d)=>o.type==="tool"?e.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",o.text,o.detail&&e.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",o.detail]})]},d):o.type==="tool_result"?e.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",o.text,o.detail&&e.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",o.detail]})]},d):o.type==="tool_error"?e.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",o.text,o.detail&&e.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",o.detail]})]},d):o.type==="thinking"?e.jsx("div",{className:"workflow-live-log-thinking",children:o.text},d):e.jsx("span",{className:"workflow-live-log-text",children:o.text},d))})}function vM({taskId:t,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:l,isTaskInProgress:o,onWorkflowStepsChange:d}){const[m,c]=a.useState({}),[u,h]=a.useState({}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,y]=a.useState(!1),k=n.some(C=>C.status==="pending"),{entries:A}=Hp(t,!!o&&k,l);a.useEffect(()=>{let C=!1;return Yr(l).then(V=>{C||b(V.filter(de=>de.enabled))}).catch(()=>{C||b([])}),()=>{C=!0}},[l]);const j=i??[],_=a.useMemo(()=>[...f.map(V=>({id:V.id,name:V.name,description:V.description,phase:V.phase||"pre-merge"})),{id:"browser-verification",name:"Browser Verification",description:"Verify web application functionality using browser automation (agent-browser)",phase:"pre-merge"}],[f]),N=a.useMemo(()=>new Map(_.map(C=>[C.id,C])),[_]),M=C=>{c(V=>({...V,[C]:!V[C]}))},w=C=>{h(V=>{const de=V[C]??"markdown";return{...V,[C]:de==="markdown"?"plain":"markdown"}})},R=C=>{p(C)},E=()=>{p(null)};a.useEffect(()=>{if(!g)return;const C=V=>{V.key==="Escape"&&E()};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[g]);const I=a.useCallback((C,V)=>{if(d){if(V){if(j.includes(C)){d(j);return}d([...j,C]);return}d(j.filter(de=>de!==C))}},[d,j]),L=a.useCallback(C=>{if(!d||C<=0)return;const V=[...j];[V[C-1],V[C]]=[V[C],V[C-1]],d(V)},[d,j]),ee=a.useCallback(C=>{if(!d||C>=j.length-1)return;const V=[...j];[V[C],V[C+1]]=[V[C+1],V[C]],d(V)},[d,j]),$=a.useCallback(C=>{d&&d(j.filter(V=>V!==C))},[d,j]),T=n.length>0,S=j.length>0;a.useEffect(()=>{r||y(!1)},[r]);const Y=a.useMemo(()=>j.map(C=>{const V=N.get(C);return{id:C,name:V?.name||C,description:V?.description||"Step definition not found.",phase:V?.phase||"pre-merge"}}),[j,N]),K=()=>!r||!v||s?null:e.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[e.jsxs("div",{className:"workflow-steps-section",children:[e.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),e.jsx("div",{className:"workflow-steps-list",children:_.map(C=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":C.id==="browser-verification"?"browser-verification-checkbox":`workflow-step-checkbox-${C.id}`,children:[e.jsx("input",{type:"checkbox",checked:j.includes(C.id),onChange:V=>I(C.id,V.target.checked)}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[C.name,br(C.phase,C.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:C.description})]})]},C.id))})]}),j.length>1&&e.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[e.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((C,V)=>{const de=N.get(C);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${C}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:V+1}),e.jsx("span",{className:"workflow-step-order-name",children:de?.name||C}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>L(V),disabled:V===0,"data-testid":`workflow-step-move-up-${C}`,title:"Move up",children:e.jsx(Fs,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ee(V),disabled:V===j.length-1,"data-testid":`workflow-step-move-down-${C}`,title:"Move down",children:e.jsx(Lt,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(C),"data-testid":`workflow-step-remove-${C}`,title:"Remove",children:e.jsx(Ft,{size:14})})]})]},C)})]})]}),G=()=>{if(s)return e.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[e.jsx("div",{className:"workflow-results-spinner"}),e.jsx("span",{children:"Loading workflow results…"})]});if(!T)return e.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[e.jsx("p",{children:"No workflow steps configured for this task."}),e.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const C=n.filter(D=>D.status==="passed").length,V=n.filter(D=>D.status==="failed").length,de=n.filter(D=>D.status==="skipped").length,B=n.filter(D=>D.status==="pending").length,J=[`${n.length} step${n.length!==1?"s":""}`];return C>0&&J.push(`${C} passed`),V>0&&J.push(`${V} failed`),de>0&&J.push(`${de} skipped`),B>0&&J.push(`${B} running`),e.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[e.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:J.join(" · ")}),n.map((D,he)=>{const q=D.phase||"pre-merge",W=m[D.workflowStepId]??!1;return e.jsxs("div",{className:`workflow-result-item workflow-result-item--${D.status}`,"data-testid":`workflow-result-item-${D.workflowStepId}`,children:[e.jsxs("div",{className:"workflow-result-header",children:[e.jsxs("div",{className:"workflow-result-name",children:[D.workflowStepName,br(q,D.workflowStepId,"workflow-result-phase")]}),e.jsx("span",{className:`workflow-result-badge workflow-result-badge--${D.status}`,"data-testid":`workflow-result-badge-${D.workflowStepId}`,children:pM(D.status)})]}),e.jsxs("div",{className:"workflow-result-meta",children:[D.startedAt&&e.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",gM(D.startedAt)]}),D.completedAt&&e.jsx("span",{className:"workflow-result-duration",children:fM(D.startedAt,D.completedAt)})]}),D.status==="pending"&&D.startedAt?e.jsx(xM,{entries:A,startedAt:D.startedAt,stepId:D.workflowStepId}):D.output?e.jsxs("div",{className:"workflow-result-output-section",children:[e.jsxs("div",{className:"workflow-result-output-header",children:[e.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),e.jsx("button",{className:"workflow-result-toggle",onClick:()=>M(D.workflowStepId),"data-testid":`workflow-result-toggle-${D.workflowStepId}`,children:W?"Hide output":"Show output"}),!W&&e.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${D.workflowStepId}`,children:bM(D.output)}),W&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>w(D.workflowStepId),"data-testid":`workflow-result-mode-toggle-${D.workflowStepId}`,title:(u[D.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(u[D.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),e.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>R(D.workflowStepId),"data-testid":`workflow-result-expand-${D.workflowStepId}`,title:"Expand output",children:e.jsx(Zs,{size:12})})]})]}),W&&e.jsx("div",{className:`workflow-result-output${(u[D.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${D.workflowStepId}`,children:(u[D.workflowStepId]??"markdown")==="markdown"?e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],components:Wu,children:D.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:D.output})})]}):null]},`${D.workflowStepId}-${he}`)})]})},P=r?e.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>y(C=>!C),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?e.jsxs(e.Fragment,{children:[e.jsx(An,{size:14}),"Done"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dn,{size:14}),"Edit"]})}):null,O=!s&&!T&&S,X=r&&T;return e.jsxs("div",{className:"workflow-results-tab","data-task-id":t,children:[O?e.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[e.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[e.jsxs("div",{className:"workflow-configured-title-row",children:[e.jsx("h4",{children:"Configured Workflow Steps"}),e.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[Y.length," step",Y.length===1?"":"s"]})]}),P]}),e.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Y.map(C=>e.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${C.id}`,children:[e.jsxs("div",{className:"workflow-configured-name",children:[C.name,br(C.phase,C.id,"workflow-configured-phase")]}),e.jsx("p",{className:"workflow-configured-description",children:C.description})]},C.id))}),e.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),K()]}):e.jsxs(e.Fragment,{children:[X&&e.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[e.jsx("h4",{children:"Workflow Steps"}),P]}),G(),K()]}),g&&(()=>{const C=n.find(B=>B.workflowStepId===g);if(!C)return null;const V=u[C.workflowStepId]??"markdown",de=C.phase||"pre-merge";return e.jsx("div",{className:"workflow-output-modal-overlay",onClick:B=>{B.target===B.currentTarget&&E()},"data-testid":"workflow-output-modal",children:e.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[e.jsxs("div",{className:"workflow-output-modal-header",children:[e.jsxs("div",{className:"workflow-output-modal-title",children:[e.jsx("span",{className:"workflow-output-modal-name",children:C.workflowStepName}),br(de,C.workflowStepId,"workflow-output-modal-phase")]}),e.jsxs("div",{className:"workflow-output-modal-controls",children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>w(C.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:V==="markdown"?"Switch to plain text":"Switch to markdown",children:V==="markdown"?"Markdown":"Plain"}),e.jsx("button",{className:"workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:e.jsx(Ft,{size:16})})]})]}),e.jsx("div",{className:"workflow-output-modal-body",children:e.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${V==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:V==="markdown"?e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],components:Wu,children:C.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:C.output})})})]})})})()]})}const yM=/^[a-zA-Z0-9_-]{1,64}$/,kM=200;function Ku(t){return t?new Date(t).toLocaleString():""}function jM(t,n=kM){return t.length<=n?t:t.substring(0,n)+"…"}function wM({taskId:t,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[l,o]=a.useState([]),[d,m]=a.useState(!0),[c,u]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[b,v]=a.useState(""),[y,k]=a.useState(null),[A,j]=a.useState([]),[_,N]=a.useState(!1),[M,w]=a.useState(!1),[R,E]=a.useState(""),[I,L]=a.useState(""),[ee,$]=a.useState(!1),[T,S]=a.useState(null),[Y,K]=a.useState(null),[G,P]=a.useState(!1),O=a.useCallback(async()=>{try{const q=await Gx(t,i);o(q)}catch(q){n(fe(q)||"Failed to load documents","error")}finally{m(!1)}},[t,i,n]);a.useEffect(()=>{O()},[O]);async function X(q){c===q.key?(u(null),g(""),f(null),v(""),k(null),j([]),P(!1)):(u(q.key),g(q.content),f(null),v(""),k(null),j([]),P(!1))}async function C(q){if(y===q)k(null),j([]);else{k(q),N(!0);try{const W=await Jx(t,q,i);j(W)}catch(W){n(fe(W)||"Failed to load revisions","error")}finally{N(!1)}}}function V(){c&&(f(c),v(h))}function de(){f(null),v("")}async function B(){if(!(!p||!b.trim())){$(!0);try{await Gc(t,p,b,{},i),f(null),v(""),await O();const q=l.find(W=>W.key===p);q&&g(q.content),n("Document saved","success")}catch(q){n(fe(q)||"Failed to save document","error")}finally{$(!1)}}}async function J(){const q=R.trim(),W=I.trim();if(!q){n("Document key is required","error");return}if(!yM.test(q)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!W){n("Content is required","error");return}$(!0);try{await Gc(t,q,W,{},i),w(!1),E(""),L(""),await O(),n("Document created","success")}catch(me){n(fe(me)||"Failed to create document","error")}finally{$(!1)}}async function D(q){S(q);try{await Yx(t,q,i),K(null),S(null),c===q&&(u(null),g("")),y===q&&(k(null),j([])),await O(),n("Document deleted","success")}catch(W){n(fe(W)||"Failed to delete document","error")}finally{S(null)}}function he(q){g(q.content),f(null),v("")}return d?e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Documents"}),e.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Documents"}),M&&e.jsxs("div",{className:"task-document-create-form",children:[e.jsx("h5",{children:"New Document"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"doc-key",children:"Key"}),e.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:R,onChange:q=>E(q.target.value),placeholder:"e.g., plan, notes, research",disabled:ee}),e.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"doc-content",children:"Content"}),e.jsx("textarea",{id:"doc-content",value:I,onChange:q=>L(q.target.value),rows:6,placeholder:"Enter document content…",disabled:ee})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{w(!1),E(""),L("")},disabled:ee,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void J(),disabled:ee||!R.trim()||!I.trim(),children:ee?"Creating…":"Create"})]})]}),l.length===0&&!M?e.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):e.jsx("div",{className:"task-documents-list",children:l.map(q=>e.jsxs("div",{className:"task-document-card",children:[e.jsxs("div",{className:"task-document-card-header",children:[e.jsxs("div",{className:"task-document-card-title",children:[e.jsx(vi,{size:14}),e.jsx("span",{className:"task-document-key",children:q.key}),e.jsxs("span",{className:"task-document-revision-badge",children:["v",q.revision]})]}),e.jsxs("div",{className:"task-document-meta",children:[e.jsx("span",{className:"task-document-author",children:q.author}),e.jsx("span",{className:"task-document-timestamp",children:Ku(q.updatedAt||q.createdAt)})]})]}),c===q.key&&p!==q.key&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"task-document-content-header",children:e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>P(W=>!W),"aria-label":G?"Switch to plain text":"Switch to markdown","aria-pressed":G,title:G?"Switch to plain text":"Switch to markdown",children:G?"Markdown":"Plain"})}),e.jsx("div",{className:"task-document-content",children:G?e.jsx("div",{className:"task-document-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],children:h})})}):e.jsx("pre",{className:"task-document-content-text",children:h})}),y===q.key&&e.jsxs("div",{className:"task-document-revisions",children:[e.jsx("h5",{children:"Revision History"}),_?e.jsx("div",{className:"detail-log-empty",children:"Loading…"}):A.length<=1?e.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):e.jsx("div",{className:"task-document-revision-list",children:A.filter(W=>W.revision<q.revision).sort((W,me)=>me.revision-W.revision).map(W=>e.jsxs("div",{className:"task-document-revision-item",onClick:()=>he(W),children:[e.jsxs("div",{className:"revision-header",children:[e.jsxs("span",{className:"revision-badge",children:["v",W.revision]}),e.jsx("span",{className:"revision-author",children:W.author}),e.jsx("span",{className:"revision-timestamp",children:Ku(W.createdAt)})]}),e.jsx("div",{className:"revision-preview",children:jM(W.content,100)})]},W.id))})]})]}),p===q.key&&e.jsxs("div",{className:"task-document-edit-form",children:[e.jsx("textarea",{value:b,onChange:W=>v(W.target.value),rows:10,disabled:ee}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:de,disabled:ee,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void B(),disabled:ee||!b.trim(),children:ee?"Saving…":"Save"})]})]}),e.jsxs("div",{className:"task-document-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>void X(q),children:c===q.key?e.jsxs(e.Fragment,{children:[e.jsx(Fs,{size:14})," Collapse"]}):e.jsxs(e.Fragment,{children:[e.jsx(Lt,{size:14})," Expand"]})}),c===q.key&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void C(q.key),children:[e.jsx(Ra,{size:14})," History"]}),r&&p!==q.key&&e.jsx("button",{className:"btn btn-sm",onClick:V,children:"Edit"}),r&&(Y===q.key?e.jsxs("div",{className:"confirm-delete-actions",children:[e.jsx("span",{children:"Delete?"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void D(q.key),disabled:T===q.key,children:T===q.key?"…":"Yes"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>K(null),disabled:T===q.key,children:"No"})]}):e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>K(q.key),children:e.jsx(Ut,{size:14})}))]})]})]},q.key))}),r&&!M&&e.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>w(!0),children:[e.jsx(qt,{size:14})," New Document"]})]})}function xr(t){return t.toLocaleString()}function Gu(t){const n=new Date(t);return Number.isNaN(n.getTime())?t:n.toLocaleString()}function NM({tokenUsage:t,loading:n}){return!t&&n?e.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task token usage",children:[e.jsx("h4",{children:"Token Usage"}),e.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"})]}):t?e.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task token usage",children:[e.jsx("h4",{children:"Token Usage"}),e.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),e.jsx("span",{className:"task-token-stats-panel__value",children:xr(t.inputTokens)})]}),e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),e.jsx("span",{className:"task-token-stats-panel__value",children:xr(t.outputTokens)})]}),e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),e.jsx("span",{className:"task-token-stats-panel__value",children:xr(t.cachedTokens)})]}),e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),e.jsx("span",{className:"task-token-stats-panel__value",children:xr(t.totalTokens)})]})]}),e.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[e.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[e.jsx("dt",{children:"First used"}),e.jsx("dd",{children:e.jsx("time",{dateTime:t.firstUsedAt,children:Gu(t.firstUsedAt)})})]}),e.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[e.jsx("dt",{children:"Last used"}),e.jsx("dd",{children:e.jsx("time",{dateTime:t.lastUsedAt,children:Gu(t.lastUsedAt)})})]})]})]}):e.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task token usage",children:[e.jsx("h4",{children:"Token Usage"}),e.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})}function SM(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function CM(t,n){return t.validatorModelProvider&&t.validatorModelId?{provider:t.validatorModelProvider,modelId:t.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function EM(t){let n=null;for(const s of t){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 MM(t,n,s){if(t.planningModelProvider&&t.planningModelId)return{provider:t.planningModelProvider,modelId:t.planningModelId};const i=EM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function AM(t){switch(t){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 PM(t){const n=new Date(t),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),l=Math.floor(r/60),o=Math.floor(l/24);return r<1?"just now":r<60?`${r}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:n.toLocaleDateString()}function _M(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function TM(t){if(!(t instanceof Error))return null;const n=t.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=t.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Ju(t,n){return t.length>n?t.slice(0,n)+"…":t}function Yu(t=[],n=[]){return t.length===n.length&&t.every((s,i)=>s===n[i])}function Gl(t){const n=t.indexOf("/");return!t||n===-1?null:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function ba(t){return typeof t=="string"&&Jo.includes(t)?t:ds}const Jl=200,RM=new Set(["triage","todo"]);function IM({task:t,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:l,onDeleteTask:o,onMergeTask:d,onRetryTask:m,onDuplicateTask:c,onTaskUpdated:u,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,b]=a.useState(p),[v,y]=a.useState(()=>"prompt"in t?t:null),[k,A]=a.useState(()=>!("prompt"in t));a.useEffect(()=>{if("prompt"in t){y(t),A(!1);return}let se=!1;return A(!0),y(null),_r(t.id,n).then(it=>{se||(y(it),A(!1))}).catch(()=>{se||A(!1)}),()=>{se=!0}},[t.id,n]);const j=v??{...t,prompt:""},_=t.status==="failed"||t.status==="stuck-killed"||t.status==="specifying"||t.status==="needs-respecify"||(t.stuckKillCount??0)>0||(t.recoveryRetryCount??0)>0||!!t.nextRecoveryAt;a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{R(!1)},[t.id]);const[N,M]=a.useState("activity"),[w,R]=a.useState(!1),[E,I]=a.useState(t.attachments||[]),[L,ee]=a.useState(!1),[$,T]=a.useState(t.dependencies||[]),[S,Y]=a.useState(!1),[K,G]=a.useState(""),[P,O]=a.useState(null),[X,C]=a.useState([]),[V,de]=a.useState(!1),[B,J]=a.useState(!1),[D,he]=a.useState(!1),[q,W]=a.useState(!1),[me,Re]=a.useState(!1),[ve,Me]=a.useState(j.prompt||""),[_e,De]=a.useState(""),[Oe,ze]=a.useState(!1),[Be,Ae]=a.useState(""),[Ce,Ge]=a.useState(!1),[Te,Xe]=a.useState(!1),[re,Z]=a.useState(t.title||""),[ye,ie]=a.useState(t.description||""),[Ie,pe]=a.useState(t.dependencies||[]),[Ue,dt]=a.useState(""),[ht,ue]=a.useState(""),[te,ke]=a.useState(""),[Ne,Ze]=a.useState(""),[xe,st]=a.useState("default"),[Ee,He]=a.useState(void 0),[ce,qe]=a.useState(ds),[We,Pe]=a.useState(""),[nt,kt]=a.useState(t.enabledWorkflowSteps||[]),[yt,Ct]=a.useState([]),[Et,Pt]=a.useState(!1),It=a.useRef(!1),[bt,_t]=a.useState(!1),[Ve,ft]=a.useState(!1),Fe=a.useRef(null),lt=a.useRef(null),{getSlotsForId:be}=kh(n),U=be("task-detail-tab");a.useEffect(()=>(It.current=!0,()=>{It.current=!1}),[]);const[we,rt]=a.useState(void 0),[xt,je]=a.useState([]),[Ke,pt]=a.useState(!1),[Ht,fn]=a.useState(t.enabledWorkflowSteps||[]);a.useEffect(()=>{Z(t.title||""),ie(t.description||""),Xe(!1)},[t.id,t.title,t.description]),a.useEffect(()=>{fn(t.enabledWorkflowSteps||[])},[t.id,t.enabledWorkflowSteps]),a.useEffect(()=>{let se=!1;return Ki(n).then(it=>{se||rt(it)}).catch(()=>{}),()=>{se=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let se=!1;return pt(!0),hy(t.id,n).then(it=>{se||je(it)}).catch(it=>{se||h(`Failed to load workflow results: ${fe(it)}`,"error")}).finally(()=>{se||pt(!1)}),()=>{se=!0}},[f,t.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const se=n?`?projectId=${encodeURIComponent(n)}`:"",it=mt=>{try{const Rt=JSON.parse(mt.data);Rt.id===t.id&&Array.isArray(Rt.workflowStepResults)&&je(Rt.workflowStepResults)}catch{}};return Bs(`/api/events${se}`,{events:{"task:updated":it}})},[f,t.id,n]),a.useEffect(()=>{S||G("")},[S]),a.useEffect(()=>{if(!t.assignedAgentId){O(null);return}const se=X.find(mt=>mt.id===t.assignedAgentId);if(se){O(se);return}let it=!1;return ph(t.assignedAgentId,n).then(mt=>{it||O(mt)}).catch(()=>{it||O(null)}),()=>{it=!0}},[t.assignedAgentId,n,X]),a.useEffect(()=>{de(!1)},[t.id]),a.useEffect(()=>{if(!(bt||Ve))return;const it=mt=>{const Rt=mt.target,Cs=Fe.current?.contains(Rt),bs=lt.current?.contains(Rt);!Cs&&bt&&_t(!1),!bs&&Ve&&ft(!1)};return document.addEventListener("mousedown",it),()=>document.removeEventListener("mousedown",it)},[bt,Ve]),a.useEffect(()=>{if(!(bt||Ve))return;const it=mt=>{mt.key==="Escape"&&(mt.stopPropagation(),bt&&_t(!1),Ve&&ft(!1))};return document.addEventListener("keydown",it),()=>document.removeEventListener("keydown",it)},[bt,Ve]),a.useEffect(()=>{Re(!1),Me(j.prompt||""),De("")},[t.id,j.prompt]);const hn=RM.has(t.column)&&!Et,Jn=a.useCallback(()=>{if(!hn)return;Xe(!0),Z(t.title||""),ie(t.description||""),pe(t.dependencies||[]);const se=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"",it=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"",mt=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";dt(se),ue(it),ke(mt),Ze(t.thinkingLevel??""),st(se||it||mt?"custom":"default"),Pe(""),kt(t.enabledWorkflowSteps||[]),Ct([]),He(t.reviewLevel),qe(ba(t.priority))},[hn,t]),Ot=a.useCallback(()=>{Xe(!1),Z(t.title||""),ie(t.description||""),pe(t.dependencies||[]),qe(ba(t.priority)),yt.forEach(se=>URL.revokeObjectURL(se.previewUrl)),Ct([])},[t.title,t.description,t.dependencies,t.priority,yt]),yn=a.useCallback(async()=>{Pt(!0);try{const se={},it=re.trim(),mt=ye.trim();it&&it!==(t.title??"")&&(se.title=it),mt&&mt!==(t.description??"")&&(se.description=mt),Yu(Ie,t.dependencies??[])||(se.dependencies=Ie),Yu(nt,t.enabledWorkflowSteps??[])||(se.enabledWorkflowSteps=nt);const Rt=Gl(Ue),Cs=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"";Ue!==Cs&&(se.modelProvider=Rt?.provider??null,se.modelId=Rt?.modelId??null);const bs=Gl(ht),rl=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"";ht!==rl&&(se.validatorModelProvider=bs?.provider??null,se.validatorModelId=bs?.modelId??null);const Za=Gl(te),ll=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";te!==ll&&(se.planningModelProvider=Za?.provider??null,se.planningModelId=Za?.modelId??null);const ol=t.thinkingLevel??"";Ne!==ol&&(se.thinkingLevel=Ne!==""?Ne:null);const li=t.reviewLevel;Ee!==li&&(se.reviewLevel=Ee);const Js=ba(t.priority);if(ce!==Js&&(se.priority=ce),Object.keys(se).length>0){const Hs=await Ws(t.id,se,n);u?.(Hs)}if(yt.length>0){const Hs=[];for(const oi of yt)try{const cl=await Da(t.id,oi.file,n);I(_s=>[..._s,cl])}catch{Hs.push(oi.file.name)}Hs.length>0&&h(`Failed to upload: ${Hs.join(", ")}`,"error")}yt.forEach(Hs=>URL.revokeObjectURL(Hs.previewUrl)),Ct([]),h(`Updated ${t.id}`,"success"),Xe(!1)}catch(se){h(`Failed to update ${t.id}: ${fe(se)}`,"error")}finally{It.current&&Pt(!1)}},[t,re,ye,Ie,Ue,ht,te,Ne,Ee,ce,nt,yt,h,n,u]),tn=a.useCallback(async se=>{try{await Ws(t.id,{description:se},n),h("Description saved","success")}catch(it){h(`Failed to save: ${fe(it)}`,"error")}},[t.id,h,n]),dn=a.useCallback(se=>{Te&&(se.key==="Escape"?(se.preventDefault(),Ot()):se.key==="Enter"&&(se.ctrlKey||se.metaKey)&&(se.preventDefault(),yn()))},[Te,Ot,yn]);a.useEffect(()=>{if(Te)return document.addEventListener("keydown",dn),()=>document.removeEventListener("keydown",dn)},[Te,dn]);const nn=a.useRef(null),{entries:Cn,loading:kn,loadMore:jn,hasMore:Yn,total:un,loadingMore:$t}=Hp(t.id,f==="logs"&&N==="agent-log",n);a.useEffect(()=>{const se=it=>{it.key==="Escape"&&!Te&&i()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[i,Te]);const wn=a.useCallback(se=>{se.target===se.currentTarget&&i()},[i]),On=a.useCallback(async se=>{try{await l(t.id,se),i(),h(`Moved to ${us[se]}`,"success")}catch(it){h(fe(it),"error")}},[t.id,l,i,h]),Nn=a.useCallback(async()=>{if(confirm(`Delete ${t.id}?`))try{await o(t.id),i(),h(`Deleted ${t.id}`,"info")}catch(se){const it=TM(se);if(!it||it.dependentIds.length===0){h(fe(se),"error");return}const mt=it.dependentIds.join(", ");if(!confirm(`${t.id} is a dependency of ${mt}.
|
|
630
|
+
|
|
631
|
+
Delete anyway by removing these dependency references first?`))return;try{await o(t.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${t.id} after removing dependency references`,"info")}catch(Cs){h(fe(Cs),"error")}}},[t.id,o,i,h]),Bn=a.useCallback(()=>{confirm(`Merge ${t.id} into the current branch?`)&&(i(),h(`Merging ${t.id}...`,"info"),d(t.id).then(se=>{const it=se.merged?`Merged ${t.id} (branch: ${se.branch})`:`Closed ${t.id} (${se.error||"no branch to merge"})`;h(it,"success")}).catch(se=>{h(fe(se),"error")}))},[t.id,d,i,h]),rs=a.useCallback(()=>{m&&(i(),m(t.id).then(()=>{h(`Retried ${t.id}`,"success")}).catch(se=>{h(fe(se),"error")}))},[t.id,m,i,h]),Vt=a.useCallback(async()=>{if(c&&confirm(`Duplicate ${t.id}? This will create a new task in Triage with the same description and prompt.`))try{const se=await c(t.id);i(),h(`Duplicated ${t.id} → ${se.id}`,"success")}catch(se){h(fe(se),"error")}},[t.id,c,i,h]),_n=a.useCallback(async()=>{try{t.paused?(await Px(t.id,n),h(`Unpaused ${t.id}`,"success")):(await Ax(t.id,n),h(`Paused ${t.id}`,"success")),i()}catch(se){h(fe(se),"error")}},[t.id,t.paused,i,h]),x=a.useCallback(async()=>{try{await Ix(t.id,n),h(`Plan approved — ${t.id} moved to Todo`,"success"),i()}catch(se){h(fe(se),"error")}},[t.id,i,h]),F=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await $x(t.id,n),h(`Plan rejected — ${t.id} returned to Triage for re-specification`,"info"),i()}catch(se){h(fe(se),"error")}},[t.id,i,h]),ne=a.useCallback(async()=>{if(confirm("Rebuild the specification for this task? The task will move to triage for re-specification."))try{await Zx(t.id,n),i(),h(`Respecifying ${t.id}...`,"info")}catch(se){h(fe(se),"error")}},[t.id,n,i,h]),ae=a.useCallback(()=>{ze(!0),Ae("")},[]),oe=a.useCallback(()=>{_t(!1),ft(!1)},[]),ge=a.useCallback(se=>{oe(),On(se)},[oe]),et=a.useCallback(se=>{oe(),se()},[oe]),jt=a.useCallback(()=>{oe(),Bn()},[oe]),Jt=a.useCallback(()=>{ze(!1),Ae(""),Ge(!1)},[]),Je=a.useCallback(async()=>{if(!Be.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Be.length>2e3){h("Feedback must be 2000 characters or less","error");return}Ge(!0);try{const se=await ev(t.id,Be.trim(),n);h(`Refinement task created: ${se.id}`,"success"),i()}catch(se){h(fe(se),"error")}finally{Ge(!1)}},[t.id,Be,h,i]),ot=a.useCallback(async se=>{ee(!0);try{const it=await Da(t.id,se,n);I(mt=>[...mt,it]),h("Screenshot attached","success")}catch(it){h(fe(it),"error")}finally{ee(!1)}},[t.id,h]),Un=a.useCallback(async se=>{const it=se.target.files?.[0];it&&(await ot(it),nn.current&&(nn.current.value=""))},[ot]);a.useEffect(()=>{const se=it=>{const mt=it.clipboardData?.items;if(mt)for(let Rt=0;Rt<mt.length;Rt++){const Cs=mt[Rt];if(Cs.type.startsWith("image/")){const bs=Cs.getAsFile();if(bs){it.preventDefault(),ot(bs);return}}}};return document.addEventListener("paste",se),()=>document.removeEventListener("paste",se)},[ot]);const le=a.useCallback(se=>{se.preventDefault()},[]),$e=a.useCallback(se=>{se.preventDefault();const it=se.dataTransfer.files;for(let mt=0;mt<it.length;mt++){const Rt=it[mt];if(Rt.type.startsWith("image/")){ot(Rt);return}}},[ot]),ut=a.useCallback(async se=>{try{await Vx(t.id,se,n),I(it=>it.filter(mt=>mt.filename!==se)),h("Attachment deleted","info")}catch(it){h(fe(it),"error")}},[t.id,h]),wt=a.useCallback(async se=>{const it=Ht;fn(se);try{const mt=await Ws(t.id,{enabledWorkflowSteps:se},n);h("Workflow steps updated","success"),u?.(mt)}catch(mt){fn(it),h(`Failed to update workflow steps: ${fe(mt)}`,"error")}},[t.id,n,Ht,u,h]),St=a.useCallback(async()=>{J(!0);try{const se=await aa(void 0,n);C(se),de(!0)}catch(se){h(`Failed to load agents: ${fe(se)}`,"error"),de(!1)}finally{J(!1)}},[n,h]),ln=a.useCallback(async se=>{try{const it=await ad(t.id,se,n),mt=X.find(Rt=>Rt.id===se)??null;O(mt||(Rt=>Rt?.id===se?Rt:null)),de(!1),u?.(it),h("Assigned agent updated","success")}catch(it){h(`Failed to assign agent: ${fe(it)}`,"error")}},[t.id,n,X,u,h]),on=a.useCallback(async()=>{try{const se=await ad(t.id,null,n);O(null),de(!1),u?.(se),h("Agent unassigned","success")}catch(se){h(`Failed to unassign agent: ${fe(se)}`,"error")}},[t.id,n,u,h]),mn=a.useCallback(async se=>{const it=[...$,se];T(it);try{await Ws(t.id,{dependencies:it},n)}catch(mt){T($),h(fe(mt),"error")}},[t.id,$,h]),pn=a.useCallback(async(se,it)=>{se.stopPropagation();const mt=$.filter(Rt=>Rt!==it);T(mt);try{await Ws(t.id,{dependencies:mt},n)}catch(Rt){T($),h(fe(Rt),"error")}},[t.id,$,h]),gn=a.useCallback(async se=>{try{const it=await _r(se,n);r(it)}catch{h(`Failed to load dependency ${se}`,"error")}},[r,h]),En=a.useCallback(async se=>{he(!0);try{await Ws(j.id,{prompt:se},n),h("Spec updated","success"),v&&(v.prompt=se)}catch(it){throw h(fe(it),"error"),it}finally{he(!1)}},[j,v,h]),ls=a.useCallback(async se=>{W(!0);try{await Xx(t.id,se,n),h("AI revision requested. Task moved to triage.","success"),i()}catch(it){const mt=fe(it);mt.includes("in-review")||mt.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(mt,"error")}finally{W(!1)}},[t.id,h,i]),Hn=a.useCallback(()=>{Re(!0),Me(j.prompt||""),De("")},[j.prompt]),Mn=a.useCallback(()=>{Re(!1),Me(j.prompt||""),De("")},[j.prompt]),Tn=a.useCallback(async()=>{if(ve===(j.prompt||"")){Mn();return}await En(ve),Re(!1)},[ve,j.prompt,En,Mn]),Qn=a.useCallback(async()=>{_e.trim()&&await ls(_e.trim())},[_e,ls]),bn=a.useCallback(se=>{se.key==="Escape"?(se.preventDefault(),Mn()):se.key==="Enter"&&(se.ctrlKey||se.metaKey)&&(se.preventDefault(),Tn())},[Mn,Tn]),qn=s.filter(se=>se.id!==t.id&&!$.includes(se.id)).sort((se,it)=>{const mt=it.createdAt.localeCompare(se.createdAt);if(mt!==0)return mt;const Rt=parseInt(se.id.slice(se.id.lastIndexOf("-")+1),10)||0;return(parseInt(it.id.slice(it.id.lastIndexOf("-")+1),10)||0)-Rt}),fs=P?.name??t.assignedAgentId??null,Xn=yo[t.column]||[],gs={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},$n=t.status?gs[t.status]:void 0;return e.jsx("div",{className:"modal-overlay open",onClick:wn,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg",onDragOver:le,onDrop:$e,children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx("span",{className:"detail-id",children:t.id}),e.jsx("span",{className:`detail-column-badge badge-${t.column}`,children:us[t.column]})]}),e.jsxs("div",{className:"modal-header-actions",children:[!Te&&hn&&e.jsx("button",{className:"modal-edit-btn",onClick:Jn,title:"Edit task","aria-label":"Edit task",children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),e.jsxs("div",{className:`detail-body${f==="logs"&&N==="agent-log"&&!Te?" detail-body--agent-log":""}`,children:[Te?e.jsx("div",{className:"modal-edit-form",children:e.jsx(Wp,{mode:"edit",title:re,onTitleChange:Z,description:ye,onDescriptionChange:ie,dependencies:Ie,onDependenciesChange:pe,executorModel:Ue,onExecutorModelChange:dt,validatorModel:ht,onValidatorModelChange:ue,planningModel:te,onPlanningModelChange:ke,thinkingLevel:Ne,onThinkingLevelChange:Ze,presetMode:xe,onPresetModeChange:st,selectedPresetId:We,onSelectedPresetIdChange:Pe,selectedWorkflowSteps:nt,onWorkflowStepsChange:kt,pendingImages:yt,onImagesChange:Ct,tasks:s.filter(se=>se.id!==t.id),projectId:n,disabled:Et,addToast:h,isActive:Te,onAutoSaveDescription:tn,reviewLevel:Ee,onReviewLevelChange:He,priority:ce,onPriorityChange:qe})}):e.jsxs(e.Fragment,{children:[(()=>{const se=t.title||t.description||t.id,it=!w&&se.length>Jl;return e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"detail-title",children:it?se.slice(0,Jl)+"…":se}),se.length>Jl&&e.jsx("button",{className:"detail-description-toggle",onClick:()=>R(!w),children:w?"Show less":"Show more"})]})})(),e.jsxs("div",{className:"detail-meta",children:["Created ",new Date(t.createdAt).toLocaleDateString()," · Updated"," ",new Date(t.updatedAt).toLocaleDateString()," ·",e.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${ba(t.priority)}`,children:["Priority: ",ba(t.priority)]})]})]}),t.status==="failed"&&t.error&&e.jsxs("div",{className:"detail-error-alert",children:[e.jsx("span",{className:"detail-error-icon",children:"⚠"}),e.jsxs("div",{className:"detail-error-content",children:[e.jsx("div",{className:"detail-error-title",children:"Task Failed"}),e.jsx("div",{className:"detail-error-message",children:t.error})]})]}),!Te&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"detail-tabs",children:[e.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>b("definition"),children:"Definition"}),e.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>b("logs"),children:"Logs"}),(t.column==="in-progress"||t.column==="in-review"||t.column==="done")&&e.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>b("changes"),children:"Changes"}),e.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>b("comments"),children:"Comments"}),e.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>b("documents"),children:"Documents"}),e.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>b("model"),children:"Model"}),e.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>b("workflow"),children:"Workflow"}),e.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>b("stats"),children:"Stats"}),U.map((se,it)=>{const mt=`plugin-${it}`;return e.jsx("button",{className:`detail-tab${f===mt?" detail-tab-active":""}`,onClick:()=>b(mt),children:se.slot.label},`plugin-tab-${se.pluginId}`)})]}),f==="workflow"?e.jsx("div",{className:"detail-section",children:e.jsx(vM,{taskId:t.id,results:xt,loading:Ke,enabledWorkflowSteps:Ht,canEdit:hn,projectId:n,isTaskInProgress:t.column==="in-progress"&&t.status!=="paused",onWorkflowStepsChange:wt})}):f==="model"?e.jsx("div",{className:"detail-section",children:e.jsx(eM,{task:t,addToast:h,onTaskUpdated:u,settings:we})}):f==="logs"?e.jsxs("div",{className:`detail-section${N==="agent-log"?" detail-section--agent-log":""}`,children:[e.jsxs("div",{className:"log-subview-toggle",children:[e.jsx("button",{className:`log-subview-btn${N==="activity"?" log-subview-btn-active":""}`,onClick:()=>M("activity"),children:"Activity"}),e.jsx("button",{className:`log-subview-btn${N==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>M("agent-log"),children:"Agent Log"})]}),N==="agent-log"?e.jsx(J2,{entries:Cn,loading:kn,executorModel:SM(t,we),validatorModel:CM(t,we),planningModel:MM(t,Cn,we),hasMore:Yn,onLoadMore:jn,loadingMore:$t,totalCount:un}):e.jsxs("div",{className:"detail-activity",children:[e.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?e.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?e.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((se,it)=>e.jsxs("div",{className:"detail-log-entry",children:[e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-timestamp",children:PM(se.timestamp)}),e.jsx("span",{className:"detail-log-action",children:se.action})]}),se.outcome&&e.jsx("div",{className:"detail-log-outcome",children:se.outcome})]},it))}):e.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?e.jsx(dM,{taskId:t.id,worktree:t.worktree,projectId:n,column:t.column,mergeDetails:t.mergeDetails,modifiedFiles:t.modifiedFiles}):f==="comments"?e.jsx(aM,{task:t,addToast:h,projectId:n,onTaskUpdated:u}):f==="documents"?e.jsx(wM,{taskId:t.id,addToast:h,projectId:n,onTaskUpdated:u,canEdit:hn}):typeof f=="string"&&f.startsWith("plugin-")?e.jsx("div",{className:"detail-section",children:e.jsx(Ja,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?e.jsx("div",{className:"detail-section",children:e.jsx(NM,{tokenUsage:j.tokenUsage,loading:k})}):e.jsxs(e.Fragment,{children:[t.column==="done"&&t.summary&&e.jsxs("div",{className:"detail-section detail-summary",children:[e.jsx("h4",{children:"Summary"}),e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],children:t.summary})})]}),e.jsx(lM,{task:t}),e.jsx("div",{className:"detail-section detail-agent-section",children:e.jsxs("div",{className:"detail-meta-row",children:[e.jsxs("span",{className:"detail-meta-label",children:[e.jsx(sn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]}),e.jsxs("div",{className:"detail-agent-actions",children:[fs?e.jsxs("span",{className:"detail-agent-chip",children:[e.jsx(sn,{size:14}),fs,e.jsx("button",{className:"detail-agent-clear",onClick:()=>void on(),title:"Unassign agent",children:e.jsx(Ft,{size:12})})]}):e.jsx("button",{className:"btn btn-sm",onClick:()=>{V?de(!1):St()},children:"Assign Agent"}),V&&e.jsxs("div",{className:"agent-picker-dropdown",children:[B&&e.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!B&&X.filter(se=>se.state!=="terminated").map(se=>e.jsxs("button",{className:`agent-picker-item${t.assignedAgentId===se.id?" selected":""}`,onClick:()=>void ln(se.id),children:[e.jsx(sn,{size:14}),e.jsx("span",{className:"agent-picker-name",children:se.name}),e.jsx("span",{className:"agent-picker-role",children:se.role})]},se.id)),!B&&X.filter(se=>se.state!=="terminated").length===0&&e.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),e.jsxs("div",{className:"detail-section detail-step-progress",children:[e.jsx("h4",{children:"Progress"}),j.steps&&j.steps.length>0?e.jsxs("div",{className:"step-progress-wrapper",children:[e.jsx("div",{className:"step-progress-bar",children:j.steps.map((se,it)=>e.jsx("div",{className:`step-progress-segment step-progress-segment--${se.status}`,"data-tooltip":`${se.name} (${se.status})`,style:{backgroundColor:AM(se.status)}},it))}),e.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(se=>se.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):e.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),e.jsxs("div",{className:"detail-section",children:[!me&&e.jsx("div",{className:"detail-spec-edit-trigger",children:e.jsx("button",{className:"btn btn-sm",onClick:Hn,children:"Edit"})}),me?e.jsxs("div",{className:"spec-editor-edit-mode",children:[e.jsx("textarea",{className:"spec-editor-textarea",value:ve,onChange:se=>Me(se.target.value),onKeyDown:bn,disabled:D,placeholder:"Enter task specification in Markdown...",rows:12}),e.jsxs("div",{className:"spec-editor-actions-row",children:[e.jsx("button",{className:"btn btn-sm",onClick:Mn,disabled:D,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Tn(),disabled:ve===(j.prompt||"")||D,children:D?"Saving…":"Save"})]}),e.jsxs("div",{className:"spec-editor-hint",children:[e.jsx("kbd",{children:"Ctrl"}),"+",e.jsx("kbd",{children:"Enter"})," to save · ",e.jsx("kbd",{children:"Escape"})," to cancel"]}),e.jsxs("div",{className:"spec-editor-revision",children:[e.jsx("h4",{children:"Ask AI to Revise"}),e.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to triage for re-specification."}),e.jsx("textarea",{className:"spec-editor-feedback",value:_e,onChange:se=>De(se.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:q,rows:4,maxLength:2e3}),e.jsxs("div",{className:"spec-editor-revision-actions",children:[e.jsxs("span",{className:"spec-editor-char-count",children:[_e.length,"/2000"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Qn(),disabled:!_e.trim()||q,children:q?"Requesting…":"Request AI Revision"})]})]})]}):k?e.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?e.jsx("div",{className:"markdown-body",children:e.jsx(si,{remarkPlugins:[ii],children:j.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):e.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Attachments"}),E.length>0?e.jsx("div",{className:"detail-attachments-grid",children:E.map(se=>{const it=Ps(`/api/tasks/${t.id}/attachments/${se.filename}`);return e.jsxs("div",{className:"detail-attachment-card",children:[e.jsx("a",{className:"detail-attachment-link",href:it,target:"_blank",rel:"noopener noreferrer",children:e.jsx("img",{src:it,alt:se.originalName,className:"detail-attachment-image"})}),e.jsxs("div",{className:"detail-attachment-meta",children:[se.originalName," (",_M(se.size),")"]}),e.jsx("button",{className:"detail-attachment-delete",onClick:()=>ut(se.filename),title:"Delete attachment",children:"×"})]},se.filename)})}):e.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),e.jsx("input",{className:"detail-hidden-file-input",ref:nn,type:"file",accept:"image/*",onChange:Un}),e.jsx("button",{className:"btn btn-sm",onClick:()=>nn.current?.click(),disabled:L,children:L?"Uploading…":"Attach Screenshot"})]}),e.jsxs("div",{className:"detail-deps",children:[e.jsx("h4",{children:"Dependencies"}),$.length>0?e.jsx("ul",{className:"detail-dep-list",children:$.map(se=>{const it=s.find(Rt=>Rt.id===se),mt=it?.title||it?.description||se;return e.jsxs("li",{className:"detail-dep-item",children:[e.jsxs("span",{className:"detail-dep-link",onClick:()=>gn(se),onKeyDown:Rt=>{(Rt.key==="Enter"||Rt.key===" ")&&(Rt.preventDefault(),gn(se))},role:"link",tabIndex:0,title:`Click to view ${se}`,children:[e.jsx("span",{className:"detail-dep-id",children:se}),e.jsx("span",{className:"detail-dep-label",children:Ju(mt,40)})]}),e.jsx("button",{className:"dep-remove-btn",onClick:Rt=>pn(Rt,se),title:`Remove dependency ${se}`,children:"×"})]},se)})}):e.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),e.jsxs("div",{className:"dep-trigger-wrap",children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{S&&G(""),Y(se=>!se)},children:"Add Dependency"}),S&&(()=>{const se=K.toLowerCase(),it=se?qn.filter(mt=>mt.id.toLowerCase().includes(se)||mt.title&&mt.title.toLowerCase().includes(se)||mt.description&&mt.description.toLowerCase().includes(se)):qn;return e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:K,onChange:mt=>G(mt.target.value),onClick:mt=>mt.stopPropagation()}),it.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):it.map(mt=>e.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{mn(mt.id),Y(!1)},children:[e.jsx("span",{className:"dep-dropdown-id",children:mt.id}),e.jsx("span",{className:"dep-dropdown-title",children:Ju(mt.title||mt.description||mt.id,30)})]},mt.id))]})})()]})]}),t.column==="in-review"&&e.jsx(nM,{taskId:t.id,projectId:n,prInfo:t.prInfo,automationStatus:t.status??null,autoMerge:we?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:se=>{t.prInfo=se,h(`PR #${se.number} created`,"success")},onPrUpdated:se=>{t.prInfo=se},addToast:h})]})]})]}),e.jsx("div",{className:"modal-actions",children:Te?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"modal-edit-hint",children:[e.jsx("kbd",{children:"Ctrl+Enter"})," to save · ",e.jsx("kbd",{children:"Escape"})," to cancel"]}),e.jsx("div",{className:"modal-actions-spacer"}),e.jsx("button",{className:"btn btn-sm",onClick:Ot,disabled:Et,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:yn,disabled:Et,children:Et?"Saving…":"Save"})]}):e.jsxs(e.Fragment,{children:[t.column==="triage"&&t.status==="awaiting-approval"&&j.prompt&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-primary btn-sm",onClick:x,children:"Approve Plan"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:F,children:"Reject Plan"})]}),t.column==="triage"&&t.status!=="awaiting-approval"&&!_&&e.jsx("button",{className:"btn btn-sm btn-danger",onClick:Nn,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(t.column!=="triage"||t.status==="awaiting-approval"||_)&&e.jsxs("div",{className:"detail-actions-dropdown",ref:lt,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>{ft(se=>!se),_t(!1)},"aria-haspopup":"menu","aria-expanded":Ve,children:["Actions",e.jsx(Lt,{size:12})]}),Ve&&e.jsxs("div",{className:"detail-actions-menu",role:"menu",children:[e.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>et(Nn),children:"Delete"}),c&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>et(Vt),children:"Duplicate"}),(t.column==="done"||t.column==="in-review")&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>et(ae),children:"Refine"}),e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>et(ne),children:"Respecify"}),_&&m&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>et(rs),children:"Retry"}),t.column!=="done"&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>et(_n),children:t.paused?"Unpause":"Pause"})]})]}),e.jsx("div",{className:"modal-actions-spacer"}),e.jsx("div",{className:"detail-move-dropdown",ref:Fe,children:t.column==="in-review"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"detail-move-actions-in-review",children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>{_t(se=>!se),ft(!1)},"aria-haspopup":"menu","aria-expanded":bt,children:["Move",e.jsx(Lt,{size:12})]}),$n?e.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:$n}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:jt,children:"Merge & Close"})]}),bt&&e.jsxs("div",{className:"detail-move-menu",role:"menu",children:[e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ge("todo"),children:"Move to Todo"}),e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ge("in-progress"),children:"Back to In Progress"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>ge(Xn[0]),disabled:Xn.length===0,children:["Move to ",Xn.length>0?us[Xn[0]]:""]}),Xn.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{_t(se=>!se),ft(!1)},"aria-haspopup":"menu","aria-expanded":bt,children:e.jsx(Lt,{size:12})}),bt&&e.jsx("div",{className:"detail-move-menu",role:"menu",children:Xn.map(se=>e.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ge(se),children:["Move to ",us[se]]},se))})]})]})})]})}),Oe&&e.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Jt,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal detail-refine-modal",onClick:se=>se.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"detail-refine-title",children:"Refine"}),e.jsx("button",{className:"modal-close",onClick:Jt,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"detail-body",children:[e.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),e.jsx("textarea",{className:"detail-refine-textarea",value:Be,onChange:se=>Ae(se.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),e.jsxs("div",{className:"detail-refine-input-group",children:[e.jsxs("div",{className:"detail-refine-char-count",children:[Be.length,"/2000 characters"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Je,disabled:!Be.trim()||Ce,children:Ce?"Creating...":"Create Refinement Task"})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:Jt,disabled:Ce,children:"Cancel"})})]})})]})})}function $M(t={}){const{projectId:n,pollInterval:s=6e4,autoRefresh:i=!1}=t,[r,l]=a.useState(null),[o,d]=a.useState(!0),[m,c]=a.useState(null),[u,h]=a.useState(null),g=a.useRef(null),p=a.useRef(null),f=a.useRef(!0),b=a.useCallback(async(M=!1)=>{g.current&&g.current.abort(),g.current=new AbortController,M&&(d(!0),c(null));try{const w=await Ox(n);if(!f.current)return;l(w),c(null),h(new Date),d(!1)}catch(w){if(w instanceof Error&&w.name==="AbortError"||!f.current)return;const R=w instanceof Error?w.message:"Failed to fetch memory backend status";c(R),d(!1)}},[n]);a.useEffect(()=>(f.current=!0,b(!1),()=>{f.current=!1}),[b]),a.useEffect(()=>{if(i)return p.current=setInterval(()=>{b(!1)},s),()=>{p.current&&(clearInterval(p.current),p.current=null)}},[i,s,b]),a.useEffect(()=>()=>{f.current=!1,g.current&&g.current.abort(),p.current&&(clearInterval(p.current),p.current=null)},[]);const v=a.useCallback(()=>b(!0),[b]),y=r?.currentBackend??null,k=r?.capabilities??null,A=r?.availableBackends??[],j=k?.readable??!1,_=k?.writable??!1,N=k?.supportsAtomicWrite??!1;return{status:r,currentBackend:y,capabilities:k,availableBackends:A,isReadable:j,isWritable:_,supportsAtomicWrite:N,loading:o,error:m,lastUpdated:u,refresh:v}}const DM=[{value:"light",label:"Light",icon:eh},{value:"dark",label:"Dark",icon:Qm},{value:"system",label:"System",icon:Gr}],Qu=[{value:"default",label:"Default",className:"theme-swatch-default"},{value:"ocean",label:"Ocean",className:"theme-swatch-ocean"},{value:"forest",label:"Forest",className:"theme-swatch-forest"},{value:"sunset",label:"Sunset",className:"theme-swatch-sunset"},{value:"zen",label:"Zen",className:"theme-swatch-zen"},{value:"berry",label:"Berry",className:"theme-swatch-berry"},{value:"high-contrast",label:"High Contrast",className:"theme-swatch-high-contrast"},{value:"industrial",label:"Industrial",className:"theme-swatch-industrial"},{value:"monochrome",label:"Mono",className:"theme-swatch-monochrome"},{value:"slate",label:"Slate",className:"theme-swatch-slate"},{value:"ash",label:"Ash",className:"theme-swatch-ash"},{value:"graphite",label:"Graphite",className:"theme-swatch-graphite"},{value:"silver",label:"Silver",className:"theme-swatch-silver"},{value:"solarized",label:"Solarized",className:"theme-swatch-solarized"},{value:"factory",label:"Factory",className:"theme-swatch-factory"},{value:"ayu",label:"Ayu",className:"theme-swatch-ayu"},{value:"one-dark",label:"One Dark",className:"theme-swatch-one-dark"},{value:"nord",label:"Nord",className:"theme-swatch-nord"},{value:"dracula",label:"Dracula",className:"theme-swatch-dracula"},{value:"gruvbox",label:"Gruvbox",className:"theme-swatch-gruvbox"},{value:"tokyo-night",label:"Tokyo Night",className:"theme-swatch-tokyo-night"},{value:"catppuccin-mocha",label:"Catppuccin Mocha",className:"theme-swatch-catppuccin-mocha"},{value:"github-dark",label:"GitHub Dark",className:"theme-swatch-github-dark"},{value:"everforest",label:"Everforest",className:"theme-swatch-everforest"},{value:"rose-pine",label:"Rosé Pine",className:"theme-swatch-rose-pine"},{value:"kanagawa",label:"Kanagawa",className:"theme-swatch-kanagawa"},{value:"night-owl",label:"Night Owl",className:"theme-swatch-night-owl"},{value:"palenight",label:"Palenight",className:"theme-swatch-palenight"},{value:"monokai-pro",label:"Monokai Pro",className:"theme-swatch-monokai-pro"},{value:"slime",label:"Slime",className:"theme-swatch-slime"},{value:"brutalist",label:"Brutalist",className:"theme-swatch-brutalist"},{value:"neon-city",label:"Neon City",className:"theme-swatch-neon-city"},{value:"parchment",label:"Parchment",className:"theme-swatch-parchment"},{value:"terminal",label:"Terminal",className:"theme-swatch-terminal"},{value:"glass",label:"Glass",className:"theme-swatch-glass"},{value:"horizon",label:"Horizon",className:"theme-swatch-horizon"},{value:"vitesse",label:"Vitesse",className:"theme-swatch-vitesse"},{value:"outrun",label:"Outrun",className:"theme-swatch-outrun"},{value:"snazzy",label:"Snazzy",className:"theme-swatch-snazzy"},{value:"porple",label:"Porple",className:"theme-swatch-porple"},{value:"espresso",label:"Espresso",className:"theme-swatch-espresso"},{value:"mars",label:"Mars",className:"theme-swatch-mars"},{value:"poimandres",label:"Poimandres",className:"theme-swatch-poimandres"},{value:"ember",label:"Ember",className:"theme-swatch-ember"},{value:"rust",label:"Rust",className:"theme-swatch-rust"},{value:"copper",label:"Copper",className:"theme-swatch-copper"},{value:"foundry",label:"Foundry",className:"theme-swatch-foundry"},{value:"carbon",label:"Carbon",className:"theme-swatch-carbon"},{value:"sandstone",label:"Sandstone",className:"theme-swatch-sandstone"},{value:"lagoon",label:"Lagoon",className:"theme-swatch-lagoon"},{value:"frost",label:"Frost",className:"theme-swatch-frost"},{value:"lavender",label:"Lavender",className:"theme-swatch-lavender"},{value:"neon-bloom",label:"Neon Bloom",className:"theme-swatch-neon-bloom"},{value:"sepia",label:"Sepia",className:"theme-swatch-sepia"}];function FM({themeMode:t,colorTheme:n,onThemeModeChange:s,onColorThemeChange:i}){const r=a.useCallback(()=>{s("dark"),i("default")},[s,i]);return e.jsxs("div",{className:"theme-selector",children:[e.jsx("div",{className:"theme-mode-toggle",role:"radiogroup","aria-label":"Theme mode",children:DM.map(({value:l,label:o,icon:d})=>e.jsxs("button",{className:`theme-mode-btn${t===l?" active":""}`,onClick:()=>s(l),"aria-pressed":t===l,"aria-label":`${o} mode`,title:`${o} mode`,children:[e.jsx(d,{size:16}),e.jsx("span",{children:o})]},l))}),e.jsxs("div",{className:"theme-current-preview",children:[e.jsx("div",{className:"theme-preview-icon",children:t==="light"?e.jsx(eh,{size:20}):t==="dark"?e.jsx(Qm,{size:20}):e.jsx(Gr,{size:20})}),e.jsxs("div",{className:"theme-preview-info",children:[e.jsx("div",{className:"theme-preview-label",children:"Current theme"}),e.jsxs("div",{className:"theme-preview-value",children:[t==="system"?"System":`${t.charAt(0).toUpperCase()+t.slice(1)}`," / ",Qu.find(l=>l.value===n)?.label]})]})]}),e.jsx("div",{className:"theme-section-title",children:"Color Theme"}),e.jsx("div",{className:"theme-grid",role:"radiogroup","aria-label":"Color theme",children:Qu.map(({value:l,label:o,className:d})=>e.jsxs("button",{className:`theme-option${n===l?" active":""}`,onClick:()=>i(l),"aria-pressed":n===l,"aria-label":`${o} theme`,title:o,children:[e.jsx("div",{className:`theme-option-swatch ${d}`}),e.jsx("span",{className:"theme-option-label",children:o})]},l))}),e.jsx("button",{className:"theme-reset-btn",onClick:r,"aria-label":"Reset to default theme",children:e.jsx("span",{children:"Reset to defaults"})})]})}function LM(t){if(!t)return!1;const n=t.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function Kp({content:t,onChange:n,readOnly:s,filePath:i}){const[r,l]=a.useState(!1),[o,d]=a.useState(!0),m=LM(i),c=m&&(s?!0:r),u=a.useCallback(()=>{l(!1)},[]),h=a.useCallback(()=>{l(!0)},[]),g=a.useCallback(()=>{d(p=>!p)},[]);return e.jsxs("div",{className:"file-editor-container",children:[m?e.jsxs("div",{className:"file-editor-toolbar",children:[e.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:u,disabled:!c,"aria-label":"Edit mode",children:[e.jsx(Wm,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:h,disabled:c,"aria-label":"Preview mode",children:[e.jsx(qo,{size:14}),"Preview"]})]}),!s&&e.jsx("button",{className:`btn btn-sm ${o?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:e.jsx(Ar,{size:14})})]}):!s&&e.jsxs("div",{className:"file-editor-toolbar",children:[e.jsx("div",{className:"file-editor-mode-toggle"}),e.jsx("button",{className:`btn btn-sm ${o?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:e.jsx(Ar,{size:14})})]}),c?e.jsx("div",{className:"file-editor-preview markdown-body",children:e.jsx(si,{remarkPlugins:[ii],children:t})}):e.jsx("textarea",{className:`file-editor-textarea ${o?"file-editor-textarea--wrap":""}`,value:t,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function Gp({authenticated:t,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[l,o]=a.useState(null),[d,m]=a.useState(null),c=a.useRef(!0);a.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const u=a.useCallback(async()=>{try{const y=await nv();return c.current&&r(y),y}catch(y){return c.current&&m({kind:"error",message:y instanceof Error?y.message:String(y)}),null}},[]);a.useEffect(()=>{u()},[u]);const h=a.useCallback(async()=>{o("testing"),m(null),await u(),c.current&&o(null)},[u]),g=a.useCallback(async y=>{o(y?"enabling":"disabling"),m(null);try{const k=await sv(y);c.current&&m({kind:k.enabled?"enabled":"disabled",restartRequired:k.restartRequired}),n?.(k.enabled),await u()}catch(k){c.current&&m({kind:"error",message:k instanceof Error?k.message:String(k)})}finally{c.current&&o(null)}},[n,u]),p=i?.binary.available??!1,f=i?.enabled??t,b=e.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",e.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:l!==null,children:l==="testing"?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:l!==null,children:l==="disabling"?"Disabling…":"Disable"}):e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:l!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:l==="enabling"?"Enabling…":"Enable"})]});return s?e.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${t?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx(ss,{provider:"claude-cli",size:"sm"}),e.jsx("strong",{children:"Anthropic — via Claude CLI"}),e.jsx(zM,{status:i,authenticated:t})]}),e.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),e.jsxs("details",{className:"auth-provider-cli-details",children:[e.jsx("summary",{children:"Details"}),e.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,e.jsx(Xu,{status:i,authenticated:t}),d&&e.jsx(Zu,{action:d})]})]})]}):e.jsxs("div",{className:`onboarding-provider-card${t?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ss,{provider:"claude-cli",size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,e.jsx(Xu,{status:i,authenticated:t})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:v}),d&&e.jsx(Zu,{action:d})]})}function zM({status:t,authenticated:n}){const s=t?.enabled??n,i=t?.binary.available??!1;return s?e.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&t?e.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):e.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function Xu({status:t,authenticated:n}){if(!t)return e.jsxs("small",{className:"settings-muted",children:[e.jsx(ct,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:l}=t;return s.available?i?r&&r.status!=="ok"?e.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):l||n?e.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):e.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):e.jsxs("small",{className:"settings-muted",children:[e.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):e.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function Zu({action:t}){if(t.kind==="error")return e.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:t.message});const n=t.kind==="enabled"?"Enabled":"Disabled";return e.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",t.kind==="enabled"?"Claude-CLI-routed models are now visible in the model picker.":"Claude-CLI-routed models are hidden from the model picker."]})}const zi=[{id:"default-executor",name:"Default Executor",description:"Standard task execution agent with full tooling and review support.",role:"executor",prompt:`You are a task execution agent for "fn", an AI-orchestrated task board.
|
|
632
|
+
|
|
633
|
+
You are working in a git worktree isolated from the main branch. Your job is to implement the task described in the PROMPT.md specification you're given.`,builtIn:!0},{id:"default-triage",name:"Default Triage",description:"Standard task specification agent producing detailed PROMPT.md files.",role:"triage",prompt:`You are a task specification agent for "fn", an AI-orchestrated task board.
|
|
634
|
+
|
|
635
|
+
Your job: take a rough task description and produce a fully specified PROMPT.md that another AI agent can execute autonomously.`,builtIn:!0},{id:"default-reviewer",name:"Default Reviewer",description:"Standard independent code and plan reviewer with balanced criteria.",role:"reviewer",prompt:`You are an independent code and plan reviewer.
|
|
636
|
+
|
|
637
|
+
You provide quality assessment for task implementations with full read access to the codebase.`,builtIn:!0},{id:"default-merger",name:"Default Merger",description:"Standard merge agent for squash merges with conflict resolution.",role:"merger",prompt:`You are a merge agent for "fn", an AI-orchestrated task board.
|
|
638
|
+
|
|
639
|
+
Your job is to finalize a squash merge: resolve any conflicts and write a good commit message.`,builtIn:!0},{id:"senior-engineer",name:"Senior Engineer",description:"Autonomous executor with architectural awareness, performance focus, and minimal hand-holding.",role:"executor",prompt:`You are a senior engineering agent for "fn", an AI-orchestrated task board.
|
|
640
|
+
|
|
641
|
+
You operate with a high degree of autonomy, making architectural decisions and balancing trade-offs independently.`,builtIn:!0},{id:"strict-reviewer",name:"Strict Reviewer",description:"Rigorous reviewer with stricter criteria for security, edge cases, and type safety.",role:"reviewer",prompt:`You are a strict code and plan reviewer with rigorous standards.
|
|
642
|
+
|
|
643
|
+
You hold all submissions to a high bar for correctness, security, and maintainability.`,builtIn:!0},{id:"concise-triage",name:"Concise Triage",description:"Shorter, more focused specification format with minimal prose.",role:"triage",prompt:`You are a task specification agent for "fn". Produce a concise, actionable PROMPT.md from the given task description.
|
|
644
|
+
|
|
645
|
+
Be brief and precise — avoid verbosity.`,builtIn:!0}],OM={"executor-welcome":{key:"executor-welcome",name:"Executor Welcome",roles:["executor"],description:"Introductory section for the executor agent",defaultContent:"You are a task execution agent..."},"executor-guardrails":{key:"executor-guardrails",name:"Executor Guardrails",roles:["executor"],description:"Behavioral guardrails and constraints for the executor",defaultContent:"Treat the File Scope in PROMPT.md..."},"executor-spawning":{key:"executor-spawning",name:"Executor Spawning",roles:["executor"],description:"Instructions for spawning child agents",defaultContent:"You can spawn child agents..."},"executor-completion":{key:"executor-completion",name:"Executor Completion",roles:["executor"],description:"Completion criteria and signaling for executor",defaultContent:"After all steps are done..."},"triage-welcome":{key:"triage-welcome",name:"Triage Welcome",roles:["triage"],description:"Introductory section for the triage/specification agent",defaultContent:"You are a task specification agent..."},"triage-context":{key:"triage-context",name:"Triage Context",roles:["triage"],description:"Context-gathering instructions for triage",defaultContent:"What you receive: A raw task title..."},"reviewer-verdict":{key:"reviewer-verdict",name:"Reviewer Verdict",roles:["reviewer"],description:"Verdict criteria and format for code/review agent",defaultContent:"APPROVE — Step will achieve its stated outcomes..."},"merger-conflicts":{key:"merger-conflicts",name:"Merger Conflicts",roles:["merger"],description:"Merge conflict resolution instructions for merger",defaultContent:"If there are merge conflicts..."},"agent-generation-system":{key:"agent-generation-system",name:"Agent Generation System",roles:["executor"],description:"System prompt for generating agent specifications",defaultContent:"You are an agent specification generator..."},"workflow-step-refine":{key:"workflow-step-refine",name:"Workflow Step Refine",roles:["executor"],description:"System prompt for refining workflow step descriptions",defaultContent:"You are an expert at creating detailed agent prompts..."},"planning-system":{key:"planning-system",name:"Planning System",roles:["triage"],description:"System prompt for the AI planning assistant",defaultContent:"You are a planning assistant for the fn task board system..."},"subtask-breakdown-system":{key:"subtask-breakdown-system",name:"Subtask Breakdown System",roles:["executor"],description:"System prompt for AI subtask decomposition",defaultContent:"You are a task decomposition assistant..."},"mission-interview-system":{key:"mission-interview-system",name:"Mission Interview System",roles:["triage"],description:"System prompt for AI-assisted mission planning",defaultContent:"You are a mission planning assistant..."},"ai-refine-system":{key:"ai-refine-system",name:"AI Refine System",roles:["executor"],description:"System prompt for AI-powered text refinement",defaultContent:"You are a text refinement assistant..."}},em=["executor","triage","reviewer","merger"],xa={executor:"Executor Agent",triage:"Triage Agent",reviewer:"Reviewer Agent",merger:"Merger Agent",scheduler:"Scheduler Agent",engineer:"Engineer Agent",custom:"Custom Agent"},Vs={executor:"#3b82f6",triage:"#f59e0b",reviewer:"#8b5cf6",merger:"#10b981",scheduler:"#06b6d4",engineer:"#ec4899",custom:"#6b7280"},Yl={name:"",description:"",role:"executor",prompt:""};function BM(t,n){const s=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),i=new Set(zi.map(o=>o.id)),r=new Set(n.map(o=>o.id));if(!i.has(s)&&!r.has(s))return s;let l=2;for(;i.has(`${s}-${l}`)||r.has(`${s}-${l}`);)l++;return`${s}-${l}`}function UM({value:t,onChange:n,promptOverrides:s,onPromptOverridesChange:i}){const[r,l]=a.useState("templates"),[o,d]=a.useState(null),[m,c]=a.useState(!1),[u,h]=a.useState(Yl),[g,p]=a.useState(null),[f,b]=a.useState(null),[v,y]=a.useState(new Set),[k,A]=a.useState(null),[j,_]=a.useState(!1),[N,M]=a.useState(null),w=a.useRef(null),R=t?.templates??[],E=t?.roleAssignments??{},I=N===null?null:N.source==="builtin"?zi.find(B=>B.id===N.id):R.find(B=>B.id===N.id),L=a.useCallback(B=>{const J=zi.filter(he=>he.role===B),D=R.filter(he=>he.role===B);return[...J,...D]},[R]);a.useEffect(()=>{N!==null&&w.current?.focus()},[N]);const ee=a.useCallback(()=>{c(!0),d(null),h(Yl),p(null),M(null)},[]),$=a.useCallback(B=>{d(B.id),c(!1),h({name:B.name,description:B.description,role:B.role,prompt:B.prompt}),p(null),M(null)},[]),T=a.useCallback(()=>{d(null),c(!1),h(Yl),p(null),M(null),_(!1)},[]),S=a.useCallback(()=>{const B=u.name.trim();if(!B){p("Template name is required");return}let J;if(m){if(J=BM(B,R),new Set(zi.map(me=>me.id)).has(J)){p(`Template ID "${J}" conflicts with a built-in template. Please use a different name.`);return}}else J=o;const D={id:J,name:B,description:u.description.trim(),role:u.role,prompt:u.prompt,builtIn:!1};let he;m?he=[...R,D]:he=R.map(W=>W.id===J?D:W);const q={...E};for(const[W,me]of Object.entries(q))me===J&&u.role!==W&&delete q[W];n({...t,templates:he,roleAssignments:Object.keys(q).length>0?q:void 0}),T()},[u,m,o,R,E,t,n,T]),Y=a.useCallback(B=>{const J=R.filter(q=>q.id!==B),D={...E};let he=!1;for(const[q,W]of Object.entries(D))W===B&&(delete D[q],he=!0);n({...t,templates:J.length>0?J:void 0,roleAssignments:Object.keys(D).length>0||he?Object.keys(D).length>0?D:void 0:E}),b(null),o===B&&T()},[R,E,t,n,o,T]),K=a.useCallback((B,J)=>{const D={...E};J===""?delete D[B]:D[B]=J,n({...t,roleAssignments:Object.keys(D).length>0?D:void 0})},[E,t,n]),G=a.useCallback((B,J)=>{const D={...s};D[B]=J||null,i(D)},[s,i]),P=a.useCallback(B=>{const J={...s};J[B]=null,i(J)},[s,i]),O=a.useCallback(B=>{y(J=>{const D=new Set(J);return D.has(B)?D.delete(B):D.add(B),D})},[]),X=a.useCallback(B=>{A(J=>J===B?null:B)},[]),C=a.useCallback((B,J)=>{_(!1),M({source:B,id:J})},[]),V=a.useCallback(()=>{M(null),_(B=>!B)},[]),de=B=>zi.some(J=>J.id===B);return e.jsxs("div",{className:"prompt-manager",children:[e.jsxs("div",{className:"prompt-manager-tabs",children:[e.jsxs("button",{className:`prompt-manager-tab ${r==="templates"?"active":""}`,onClick:()=>l("templates"),"data-testid":"tab-templates",children:[e.jsx(Um,{size:14}),"Templates"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="assignments"?"active":""}`,onClick:()=>l("assignments"),"data-testid":"tab-assignments",children:[e.jsx(Xb,{size:14}),"Assignments"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="overrides"?"active":""}`,onClick:()=>l("overrides"),"data-testid":"tab-overrides",children:[e.jsx($b,{size:14}),"Overrides"]})]}),e.jsxs("div",{className:"prompt-manager-content",children:[r==="templates"&&e.jsxs("div",{className:"prompt-manager-templates-tab","data-testid":"templates-tab",children:[(m||o!==null)&&e.jsxs("div",{className:"prompt-template-editor","data-testid":"template-editor",children:[e.jsx("h4",{className:"prompt-template-editor-title",children:m?"New Custom Template":"Edit Custom Template"}),e.jsxs("div",{className:"prompt-template-editor-fields",children:[e.jsxs("div",{className:"prompt-template-field",children:[e.jsx("label",{htmlFor:"template-name",children:"Name"}),e.jsx("input",{id:"template-name",type:"text",value:u.name,onChange:B=>h(J=>({...J,name:B.target.value})),placeholder:"e.g. My Custom Executor","data-testid":"template-name-input"})]}),e.jsxs("div",{className:"prompt-template-field",children:[e.jsx("label",{htmlFor:"template-description",children:"Description"}),e.jsx("input",{id:"template-description",type:"text",value:u.description,onChange:B=>h(J=>({...J,description:B.target.value})),placeholder:"Brief description of this template","data-testid":"template-description-input"})]}),e.jsxs("div",{className:"prompt-template-field",children:[e.jsx("label",{htmlFor:"template-role",children:"Role"}),e.jsx("select",{id:"template-role",value:u.role,onChange:B=>h(J=>({...J,role:B.target.value})),"data-testid":"template-role-select",children:em.map(B=>e.jsx("option",{value:B,children:xa[B]},B))})]}),e.jsxs("div",{className:"prompt-template-field",children:[e.jsxs("div",{className:"prompt-template-prompt-label-row",children:[e.jsx("label",{htmlFor:"template-prompt",children:"Prompt"}),e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:V,"aria-label":"Expand prompt to fullscreen","data-testid":"template-prompt-fullscreen",children:e.jsx(Zs,{size:14})})]}),j?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:B=>{B.key==="Escape"&&(B.preventDefault(),_(!1))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsx("div",{className:"prompt-override-fullscreen-title",children:"Edit Prompt"}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>_(!1),"data-testid":"template-prompt-collapse",children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("textarea",{id:"template-prompt-fullscreen","aria-label":"Template prompt - fullscreen",className:"prompt-template-prompt-textarea",value:u.prompt,onChange:B=>h(J=>({...J,prompt:B.target.value})),placeholder:"Enter the system prompt for this template...",rows:30,autoFocus:!0,"data-testid":"template-prompt-input-fullscreen"}),e.jsx("div",{className:"prompt-override-footer",children:e.jsxs("small",{className:"prompt-override-hint",children:[u.prompt.length," characters"]})})]}):e.jsx("textarea",{id:"template-prompt",value:u.prompt,onChange:B=>h(J=>({...J,prompt:B.target.value})),placeholder:"Enter the system prompt for this template...",rows:8,className:"prompt-template-prompt-textarea","data-testid":"template-prompt-input"})]}),g&&e.jsx("div",{className:"prompt-template-error","data-testid":"template-error",children:g}),e.jsxs("div",{className:"prompt-template-editor-actions",children:[e.jsx("button",{className:"btn btn-secondary",onClick:T,"data-testid":"cancel-template-btn",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:S,"data-testid":"save-template-btn",children:m?"Create":"Save"})]})]})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"builtin-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:"Built-in Templates"}),e.jsx("p",{className:"prompt-template-section-desc",children:"These templates are provided by Fusion and cannot be modified."}),e.jsx("div",{className:"prompt-template-list",children:zi.map(B=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${B.id}`,children:[e.jsxs("div",{className:"prompt-template-card-header",children:[e.jsxs("div",{className:"prompt-template-card-info",children:[e.jsx("span",{className:"prompt-template-card-name",children:B.name}),e.jsx("span",{className:"prompt-template-badge-built-in",style:{borderColor:Vs[B.role]},children:"Built-in"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:Vs[B.role]+"20",color:Vs[B.role]},children:xa[B.role]})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>C("builtin",B.id),title:"View full prompt","aria-label":`View full prompt for ${B.name}`,"data-testid":`expand-view-${B.id}`,children:e.jsx(Zs,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:B.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:B.prompt})})]},B.id))})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"custom-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:"Custom Templates"}),e.jsx("p",{className:"prompt-template-section-desc",children:"Create custom templates to override built-in prompts for specific roles."}),R.length===0&&!m&&e.jsx("div",{className:"prompt-template-empty",children:"No custom templates yet. Create one to get started."}),R.length>0&&e.jsx("div",{className:"prompt-template-list",children:R.map(B=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${B.id}`,children:f===B.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsxs("p",{children:['Delete "',B.name,'"?']}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>Y(B.id),"data-testid":`confirm-delete-${B.id}`,children:"Delete"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>b(null),"data-testid":`cancel-delete-${B.id}`,children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"prompt-template-card-header",children:[e.jsxs("div",{className:"prompt-template-card-info",children:[e.jsx("span",{className:"prompt-template-card-name",children:B.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:"Custom"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:Vs[B.role]+"20",color:Vs[B.role]},children:xa[B.role]}),de(B.id)&&e.jsx("span",{className:"prompt-template-badge-override",children:"Overrides built-in"})]}),e.jsxs("div",{className:"prompt-template-card-actions",children:[e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>C("custom",B.id),title:"View full prompt","aria-label":`View full prompt for ${B.name}`,"data-testid":`expand-view-${B.id}`,children:e.jsx(Zs,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>$(B),title:"Edit","aria-label":`Edit ${B.name}`,"data-testid":`edit-${B.id}`,children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>b(B.id),title:"Delete","aria-label":`Delete ${B.name}`,"data-testid":`delete-${B.id}`,children:e.jsx(Ut,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:B.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:B.prompt})})]})},B.id))}),!m&&o===null&&e.jsxs("button",{className:"btn btn-primary prompt-template-add-btn",onClick:ee,"data-testid":"add-template-btn",children:[e.jsx(qt,{size:14}),"Add Custom Template"]})]}),I&&e.jsxs("div",{ref:w,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:B=>{B.key==="Escape"&&(B.preventDefault(),M(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[I.name,e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:Vs[I.role]+"20",color:Vs[I.role]},children:xa[I.role]})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>M(null),"data-testid":`collapse-view-${I.id}`,children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:I.prompt})]})]}),r==="assignments"&&e.jsxs("div",{className:"prompt-manager-assignments-tab","data-testid":"assignments-tab",children:[e.jsx("p",{className:"prompt-assignments-desc",children:"Assign specific templates to agent roles. When a role has an assignment, that template will be used instead of the default built-in."}),e.jsx("div",{className:"prompt-role-assignment-list",children:em.map(B=>{const J=L(B),D=E[B]??"",he=J.find(W=>W.id===D),q=!!D;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${B}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:"prompt-role-badge",style:{backgroundColor:Vs[B]+"20",color:Vs[B]},children:xa[B]}),q&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[he?.name??"Custom"," (overrides default)"]})]}),e.jsxs("select",{className:"prompt-role-select",value:D,onChange:W=>K(B,W.target.value),"data-testid":`select-${B}`,children:[e.jsx("option",{value:"",children:"Use default"}),J.map(W=>e.jsxs("option",{value:W.id,children:[W.name,de(W.id)?" (built-in)":" (custom)"]},W.id))]})]},B)})}),Object.keys(E).length>0&&e.jsxs("div",{className:"prompt-assignments-note",children:[e.jsx("strong",{children:"Note:"})," Role assignments are stored in the agentPrompts configuration. Custom templates override built-ins by ID."]})]}),r==="overrides"&&e.jsxs("div",{className:"prompt-manager-overrides-tab","data-testid":"overrides-tab",children:[e.jsx("p",{className:"prompt-overrides-desc",children:"Customize specific segments of AI agent prompts. Edits override built-in defaults. Use the Reset button to restore the original default for any prompt."}),e.jsx("div",{className:"prompt-overrides-list",children:Object.values(OM).map(B=>{const J=B.key,D=s?.[J]??"",he=D!=="",q=v.has(J);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${J}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("div",{className:"prompt-override-info",onClick:()=>O(J),role:"button",tabIndex:0,onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&O(J)},children:[e.jsx("span",{className:"prompt-override-name",children:B.name}),e.jsx("code",{className:"prompt-override-key",children:J}),he&&e.jsx("span",{className:"prompt-override-badge",children:"customized"})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[q&&e.jsx("button",{className:"prompt-override-fullscreen-btn",onClick:W=>{W.stopPropagation(),X(J)},"aria-label":"Expand to fullscreen","data-testid":`fullscreen-${J}`,children:e.jsx(Zs,{size:14})}),e.jsx("button",{className:"prompt-override-expand-btn","aria-label":q?"Collapse":"Expand","data-testid":`expand-${J}`,onClick:W=>{W.stopPropagation(),O(J)},children:q?e.jsx(Fs,{size:16}):e.jsx(Lt,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:B.description}),q&&(k===J?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:W=>{W.key==="Escape"&&(W.preventDefault(),A(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[B.name,e.jsx("code",{className:"prompt-override-key",children:J})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>A(null),"data-testid":`collapse-fullscreen-${J}`,children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("textarea",{id:`prompt-${J}-fullscreen`,"aria-label":`${B.name} prompt override (${J}) - fullscreen`,className:"prompt-override-textarea",value:D,onChange:W=>{G(J,W.target.value)},placeholder:`Default: ${B.defaultContent.slice(0,100)}${B.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${J}`}),e.jsxs("div",{className:"prompt-override-footer",children:[he&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>P(J),"data-testid":`reset-fullscreen-${J}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:he?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${B.defaultContent.length} chars).`})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${J}`,"aria-label":`${B.name} prompt override (${J})`,className:"prompt-override-textarea",value:D,onChange:W=>{G(J,W.target.value)},placeholder:`Default: ${B.defaultContent.slice(0,100)}${B.defaultContent.length>100?"...":""}`,rows:4,"data-testid":`override-input-${J}`}),e.jsxs("div",{className:"prompt-override-footer",children:[he&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:W=>{W.stopPropagation(),P(J)},"data-testid":`reset-${J}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:he?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${B.defaultContent.length} chars).`})]})]}))]},J)})})]})]})]})}const HM=a.lazy(()=>Zt(()=>import("./PluginManager-LH02ybSH.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.PluginManager}))),qM=a.lazy(()=>Zt(()=>import("./PiExtensionsManager-wxB-q06A.js"),__vite__mapDeps([7,1,4,5,8])).then(t=>({default:t.PiExtensionsManager}))),tm="(max-width: 768px)",Ql=".fusion/memory/DREAMS.md",vr=[{id:"__account_header",label:"Account",scope:void 0,isGroupHeader:!0},{id:"authentication",label:"Authentication",scope:void 0,icon:yi},{id:"pi-extensions",label:"Pi Extensions",scope:void 0},{id:"__global_header",label:"Global",scope:void 0,isGroupHeader:!0},{id:"appearance",label:"Appearance",scope:"global"},{id:"notifications",label:"Notifications",scope:"global"},{id:"node-sync",label:"Node Sync",scope:"global"},{id:"global-models",label:"Models",scope:"global"},{id:"__project_header",label:"Project",scope:void 0,isGroupHeader:!0},{id:"project-models",label:"Project Models",scope:"project"},{id:"general",label:"General",scope:"project"},{id:"scheduling",label:"Scheduling",scope:"project"},{id:"worktrees",label:"Worktrees",scope:"project"},{id:"commands",label:"Commands",scope:"project"},{id:"merge",label:"Merge",scope:"project"},{id:"memory",label:"Memory",scope:"project"},{id:"experimental",label:"Experimental Features",scope:"project"},{id:"prompts",label:"Prompts",scope:"project"},{id:"backups",label:"Backups",scope:"project"},{id:"plugins",label:"Plugins",scope:"project"}],nm=1440*60*1e3,VM=2,Fi=["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],sm={insights:"Insights",roadmap:"Roadmaps",memoryView:"Memory Editor",skillsView:"Skills View",nodesView:"Nodes View",devServer:"Dev Server",devServerView:"Dev Server View"};function WM({onClose:t,addToast:n,projectId:s,initialSection:i,themeMode:r="dark",colorTheme:l="default",onThemeModeChange:o,onColorThemeChange:d,onReopenOnboarding:m}){const[c,u]=a.useState({maxConcurrent:2,maxTriageConcurrent:2,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,autoMerge:!0,mergeStrategy:"direct",recycleWorktrees:!1,worktreeNaming:"random",includeTaskIdInCommit:!0,worktreeInitCommand:"",ntfyEnabled:!1,ntfyTopic:void 0}),[h,g]=a.useState(!0),[p,f]=a.useState(null),[b,v]=a.useState(null),[y,k]=a.useState(null),A=vr.find(x=>!x.isGroupHeader),[j,_]=a.useState(i??A?.id??"authentication"),[N,M]=a.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(tm)?.matches===!0:!1),[w,R]=a.useState(null),E=vr.find(x=>x.id===j)?.scope,[I,L]=a.useState([]),[ee,$]=a.useState(!1),[T,S]=a.useState(null),[Y,K]=a.useState({}),[G,P]=a.useState({}),[O,X]=a.useState({}),C=a.useRef(null),[V,de]=a.useState([]),[B,J]=a.useState(!1),[D,he]=a.useState([]),[q,W]=a.useState([]),[me,Re]=a.useState(!1),[ve,Me]=a.useState(null),[_e,De]=a.useState(null),[Oe,ze]=a.useState(null),[Be,Ae]=a.useState(!1),[Ce,Ge]=a.useState(""),[Te,Xe]=a.useState(!1),[re,Z]=a.useState(!1),[ye,ie]=a.useState([]),[Ie,pe]=a.useState([]),[Ue,dt]=a.useState(Ql),[ht,ue]=a.useState(""),[te,ke]=a.useState(!1),[Ne,Ze]=a.useState(null),[xe,st]=a.useState(!1),[Ee,He]=a.useState(!1),ce=a.useRef(!1),[qe,We]=a.useState(4),Pe=a.useRef(4),[nt,kt]=a.useState(!1),[,yt]=a.useState(null),[Ct,Et]=a.useState(null),[Pt,It]=a.useState(!1),[bt,_t]=a.useState("both"),[Ve,ft]=a.useState(!0),Fe=a.useRef(null),{status:lt,capabilities:be,loading:U,error:we,refresh:rt}=$M({projectId:s});a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const x=window.matchMedia(tm);if(!x)return;const F=ne=>{M(ne?ne.matches:x.matches)};return F(),typeof x.addEventListener=="function"?(x.addEventListener("change",F),()=>x.removeEventListener("change",F)):(x.addListener(F),()=>x.removeListener(F))},[]),a.useEffect(()=>{Promise.all([Ki(s),Hx(s)]).then(([x,F])=>{u(x),f(x),v(F),k(F),g(!1)}).catch(x=>{n(fe(x),"error"),g(!1)})},[n,s]),a.useEffect(()=>{Oy().then(x=>{We(x.globalMaxConcurrent),Pe.current=x.globalMaxConcurrent}).catch(()=>{})},[]);const xt=a.useCallback(async()=>{try{const{providers:x}=await wi();L(x),K(F=>{const ne={};for(const[ae,oe]of Object.entries(F)){const ge=x.find(et=>et.id===ae);ge&&!ge.authenticated&&(ne[ae]=oe)}return Object.keys(ne).length===Object.keys(F).length?F:ne})}catch{}},[]);a.useEffect(()=>{(j==="global-models"||j==="project-models")&&(J(!0),Kn().then(x=>{de(x.models),he(x.favoriteProviders),W(x.favoriteModels)}).catch(()=>de([])).finally(()=>J(!1)))},[j]),a.useEffect(()=>{j==="backups"&&(Ae(!0),rd(s).then(x=>ze(x)).catch(()=>ze(null)).finally(()=>Ae(!1)))},[j,s]),a.useEffect(()=>{j==="worktrees"&&oh(s).then(x=>ie(x)).catch(()=>ie([]))},[j,s]),a.useEffect(()=>{if(j!=="memory"||re)return;if(ce.current){ce.current=!1;return}let x=!1;return Xe(!0),Wc(s).then(async({files:F})=>{if(x)return;pe(F);const ne=F.some(oe=>oe.path===Ue)?Ue:F.find(oe=>oe.path===Ql)?.path??F.find(oe=>oe.layer==="dreams")?.path??F[0]?.path??Ql;dt(ne);const{content:ae}=await Fx(ne,s);x||(Ge(ae),Z(!1))}).catch(F=>{x||(n(fe(F)||"Failed to load project memory","error"),Ge(""))}).finally(()=>{x||Xe(!1)}),()=>{x=!0}},[j,re,Ue,s,n]),a.useEffect(()=>(j==="authentication"&&($(!0),xt().finally(()=>$(!1))),()=>{C.current&&(clearInterval(C.current),C.current=null)}),[j,xt]);const je=a.useCallback(async x=>{S(x),K(F=>{if(!(x in F))return F;const ne={...F};return delete ne[x],ne});try{const{url:F,instructions:ne}=await ih(x);ne?.trim()&&K(ae=>({...ae,[x]:ne})),window.open(Ps(F),"_blank"),C.current=setInterval(async()=>{try{const{providers:ae}=await wi();L(ae),ae.find(ge=>ge.id===x)?.authenticated&&(C.current&&(clearInterval(C.current),C.current=null),S(null),K(ge=>{if(!(x in ge))return ge;const et={...ge};return delete et[x],et}),n("Login successful","success"))}catch{}},2e3)}catch(F){n(fe(F)||"Login failed","error"),S(null),K(ne=>{if(!(x in ne))return ne;const ae={...ne};return delete ae[x],ae})}},[n]),Ke=a.useCallback(async x=>{S(x);try{await ah(x),await xt(),n("Logged out","success")}catch(F){n(fe(F)||"Logout failed","error")}finally{S(null)}},[n,xt]),pt=a.useCallback(async x=>{const F=G[x]?.trim();if(!F){X(ne=>({...ne,[x]:"API key is required"}));return}S(x),X(ne=>{const ae={...ne};return delete ae[x],ae});try{await rh(x,F),P(ne=>{const ae={...ne};return delete ae[x],ae}),await xt(),n("API key saved","success")}catch(ne){X(ae=>({...ae,[x]:fe(ne)||"Failed to save API key"}))}finally{S(null)}},[G,n,xt]),Ht=a.useCallback(async x=>{S(x);try{await lh(x),P(F=>{const ne={...F};return delete ne[x],ne}),X(F=>{const ne={...F};return delete ne[x],ne}),await xt(),n("API key cleared","success")}catch(F){n(fe(F)||"Failed to clear API key","error")}finally{S(null)}},[n,xt]),fn=a.useCallback(async()=>{if(!(!c.ntfyEnabled||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic))){Re(!0);try{const x=c.ntfyBaseUrl?.trim();(await qx({ntfyEnabled:c.ntfyEnabled,ntfyTopic:c.ntfyTopic,...x?{ntfyBaseUrl:x}:{}},s)).success?n("Test notification sent — check your ntfy app!","success"):n("Failed to send test notification","error")}catch(x){n(fe(x)||"Failed to send test notification","error")}finally{Re(!1)}}},[n,c.ntfyBaseUrl,c.ntfyEnabled,c.ntfyTopic,s]),hn=a.useCallback(async()=>{Ae(!0);try{const x=await Ay(s);if(x.success){n("Backup created successfully","success");const F=await rd(s);ze(F)}else n(x.error||"Failed to create backup","error")}catch(x){n(fe(x)||"Failed to create backup","error")}finally{Ae(!1)}},[n,s]),Jn=a.useCallback(async()=>{try{const x=E==="global"?"global":E==="project"?"project":"both",F=await Py(x,s),ne=new Blob([JSON.stringify(F,null,2)],{type:"application/json"}),ae=URL.createObjectURL(ne),oe=document.createElement("a"),ge=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;oe.href=ae,oe.download=ge,document.body.appendChild(oe),oe.click(),document.body.removeChild(oe),URL.revokeObjectURL(ae),n(`Settings exported (${x==="global"?"global":x==="project"?"project":"all"} scope)`,"success")}catch(x){n(fe(x)||"Failed to export settings","error")}},[n,E,s]),Ot=a.useCallback(async x=>{const F=x.target.files?.[0];if(F){yt(F),It(!0);try{const ne=await F.text(),ae=JSON.parse(ne);Et(ae),kt(!0)}catch(ne){n(`Invalid JSON file: ${fe(ne)}`,"error"),yt(null)}finally{It(!1)}}},[n]),yn=a.useCallback(async()=>{if(Ct){It(!0);try{const x=await _y(Ct,{scope:bt,merge:Ve},s);if(x.success){const F=[];x.globalCount>0&&F.push(`${x.globalCount} global`),x.projectCount>0&&F.push(`${x.projectCount} project`),n(`Imported ${F.join(", ")} setting(s)`,"success"),kt(!1),Et(null),yt(null);const ne=await Ki(s);u(ne)}else n(x.error||"Import failed","error")}catch(x){n(fe(x)||"Failed to import settings","error")}finally{It(!1)}}},[n,Ct,bt,Ve,s]),tn=a.useCallback(async x=>{const F=D,ae=F.includes(x)?F.filter(oe=>oe!==x):[x,...F];he(ae);try{await Wt({favoriteProviders:ae,favoriteModels:q})}catch{he(F)}},[D,q]),dn=a.useCallback(async x=>{const F=q,ae=F.includes(x)?F.filter(oe=>oe!==x):[x,...F];W(ae);try{await Wt({favoriteProviders:D,favoriteModels:ae})}catch{W(F)}},[q,D]);a.useEffect(()=>{const x=F=>{F.key==="Escape"&&t()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t]);const nn=a.useCallback(x=>{x.target===x.currentTarget&&t()},[t]),Cn=[{laneId:"default",label:"Default Model",globalProviderKey:"defaultProvider",globalModelKey:"defaultModelId",projectProviderKey:"defaultProviderOverride",projectModelKey:"defaultModelIdOverride",helperText:"Default AI model used for task execution when no per-task override is set.",fallbackOrder:"Project override → Global default lane → Automatic resolution"},{laneId:"execution",label:"Execution Model",globalProviderKey:"executionGlobalProvider",globalModelKey:"executionGlobalModelId",projectProviderKey:"executionProvider",projectModelKey:"executionModelId",helperText:"AI model used for task implementation (executor agent).",fallbackOrder:"Project override → Global execution lane → Global default lane → Automatic resolution"},{laneId:"planning",label:"Planning Model",globalProviderKey:"planningGlobalProvider",globalModelKey:"planningGlobalModelId",projectProviderKey:"planningProvider",projectModelKey:"planningModelId",helperText:"AI model used for task specification (triage).",fallbackOrder:"Project override → Global planning lane → Global default lane → Automatic resolution"},{laneId:"validator",label:"Validator Model",globalProviderKey:"validatorGlobalProvider",globalModelKey:"validatorGlobalModelId",projectProviderKey:"validatorProvider",projectModelKey:"validatorModelId",helperText:"AI model used for code and specification review.",fallbackOrder:"Project override → Global validator lane → Global default lane → Automatic resolution"},{laneId:"summarization",label:"Title Summarization Model",globalProviderKey:"titleSummarizerGlobalProvider",globalModelKey:"titleSummarizerGlobalModelId",projectProviderKey:"titleSummarizerProvider",projectModelKey:"titleSummarizerModelId",helperText:"AI model used for auto-generating task titles from descriptions.",fallbackOrder:"Project override → Global summarization lane → Global planning lane → Global default lane → Automatic resolution"}];function kn(x){if(!b?.project)return"inherited";const F=b.project[x.projectProviderKey],ne=b.project[x.projectModelKey];return F!==void 0||ne!==void 0?"overridden":"inherited"}function jn(x){const F=c[x.projectProviderKey],ne=c[x.projectModelKey];return F&&ne?`${F}/${ne}`:""}function Yn(x,F){if(F){const ne=F.indexOf("/");u(ae=>({...ae,[x.projectProviderKey]:F.slice(0,ne),[x.projectModelKey]:F.slice(ne+1)}))}else{if(kn(x)==="inherited")return;u(ae=>({...ae,[x.projectProviderKey]:void 0,[x.projectModelKey]:void 0}))}}function un(x){kn(x)!=="inherited"&&u(ne=>({...ne,[x.projectProviderKey]:void 0,[x.projectModelKey]:void 0}))}const $t=a.useCallback(async()=>{if(!(w||_e))try{const x={...c,worktreeInitCommand:c.worktreeInitCommand?.trim()||void 0,taskPrefix:c.taskPrefix?.trim()||void 0},F={};for(const[ae,oe]of Object.entries(x))if(mj(ae)){const ge=p?.[ae];oe===void 0&&ge!==void 0?F[ae]=null:F[ae]=oe}const ne={};for(const[ae,oe]of Object.entries(x)){if(ae==="githubTokenConfigured"||ae==="prAuthAvailable"||!hj(ae))continue;const ge=y?.project?.[ae];["planningProvider","planningModelId","validatorProvider","validatorModelId","executionProvider","executionModelId","titleSummarizerProvider","titleSummarizerModelId","defaultProviderOverride","defaultModelIdOverride","planningFallbackProvider","planningFallbackModelId","validatorFallbackProvider","validatorFallbackModelId","titleSummarizerFallbackProvider","titleSummarizerFallbackModelId"].includes(ae)?oe!==ge&&(oe==null&&ge!==void 0&&ge!==null?ne[ae]=null:oe!==void 0&&(ne[ae]=oe)):ne[ae]=oe}await Promise.all([Object.keys(F).length>0?Wt(F):Promise.resolve(),Object.keys(ne).length>0?Ca(ne,s):Promise.resolve(),qe!==Pe.current?By({globalMaxConcurrent:qe??4}):Promise.resolve()]),n("Settings saved","success"),t()}catch(x){n(fe(x),"error")}},[c,qe,w,_e,p,y,t,n,s]),wn=a.useCallback(async()=>{try{await Lx(Ue,Ce,s),Z(!1),n("Memory saved","success")}catch(x){n(fe(x)||"Failed to save memory","error")}},[Ue,Ce,s,n]),On=a.useCallback(async()=>{st(!0);try{const{path:x,content:F}=await zx(Ue,s),ne=x??Ue;Ue!==ne&&(ce.current=!0),dt(ne),Ge(F),Z(!1);const{files:ae}=await Wc(s);pe(ae),n("Memory file compacted","success")}catch(x){n(fe(x)||"Failed to compact memory","error")}finally{st(!1)}},[Ue,s,n]),Nn=a.useCallback(async()=>{ke(!0),Ze(null);try{const x=await Ux(ht,s);Ze(x),n(x.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",x.qmdAvailable?"success":"warning")}catch(x){n(fe(x)||"Failed to test memory retrieval","error")}finally{ke(!1)}},[ht,s,n]),Bn=a.useCallback(async()=>{He(!0);try{const x=await Bx(s);await rt(),n(x.qmdAvailable?"qmd installed successfully":"qmd install finished, but qmd is still unavailable",x.qmdAvailable?"success":"warning")}catch(x){n(fe(x)||"Failed to install qmd","error")}finally{He(!1)}},[s,rt,n]),rs=()=>{if(!_e)return;const x=_e.name.trim();if(!x){n("Preset name is required","error");return}const F=c.modelPresets||[];let ne;ve?ne=ve:ne=mM(x,F);const ae={id:ne,name:x,executorProvider:_e.executorProvider,executorModelId:_e.executorModelId,validatorProvider:_e.validatorProvider,validatorModelId:_e.validatorModelId};u(oe=>{const ge=oe.modelPresets||[],et=ve?ge.map(jt=>jt.id===ve?ae:jt):[...ge,ae];return{...oe,modelPresets:et}}),Me(null),De(null)},Vt=()=>E==="global"?e.jsxs("div",{className:"settings-scope-banner settings-scope-global",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(yi,{size:14})}),e.jsx("span",{children:"These settings are shared across all your Fusion projects."})]}):E==="project"?e.jsxs("div",{className:"settings-scope-banner settings-scope-project",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(Pn,{size:14})}),e.jsx("span",{children:"These settings only affect this project."})]}):null,_n=()=>{switch(j){case"general":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"General"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskPrefix",children:"Task Prefix"}),e.jsx("input",{id:"taskPrefix",type:"text",placeholder:"FN",value:c.taskPrefix||"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,taskPrefix:F||void 0})),F&&!/^[A-Z]{1,10}$/.test(F)?R("Prefix must be 1–10 uppercase letters"):R(null)}}),w&&e.jsx("small",{className:"field-error",children:w}),!w&&e.jsx("small",{children:"Prefix for new task IDs (e.g. KB, PROJ)"})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"requirePlanApproval",className:"checkbox-label",children:[e.jsx("input",{id:"requirePlanApproval",type:"checkbox",checked:c.requirePlanApproval||!1,onChange:x=>u(F=>({...F,requirePlanApproval:x.target.checked}))}),"Require plan approval"]}),e.jsx("small",{children:"When enabled, AI-generated task specifications require manual approval before moving to Todo"})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"showQuickChatFAB",className:"checkbox-label",children:[e.jsx("input",{id:"showQuickChatFAB",type:"checkbox",checked:c.showQuickChatFAB===!0,onChange:x=>u(F=>({...F,showQuickChatFAB:x.target.checked}))}),"Show quick chat button"]}),e.jsx("small",{children:"Show the floating chat button in the dashboard. Chat is still accessible from the Chat tab in the mobile navigation."})]})]});case"global-models":{const x=c.defaultProvider&&c.defaultModelId?`${c.defaultProvider}/${c.defaultModelId}`:"",F=Cn.filter(ne=>ne.laneId!=="default");return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Default Model"}),B?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):V.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No models available. Configure authentication first."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultModel",children:"Default Model"}),e.jsx(Kt,{id:"defaultModel",label:"Default Model",models:V,value:x,onChange:ne=>{if(!ne)u(ae=>({...ae,defaultProvider:void 0,defaultModelId:void 0}));else{const ae=ne.indexOf("/");u(oe=>({...oe,defaultProvider:ne.slice(0,ae),defaultModelId:ne.slice(ae+1)}))}},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn}),e.jsx("small",{children:'Default AI model used for task execution when no per-task override is set. "Use default" lets the engine choose automatically.'})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"fallbackModel",children:"Fallback Model"}),e.jsx(Kt,{id:"fallbackModel",label:"Fallback Model",models:V,value:c.fallbackProvider&&c.fallbackModelId?`${c.fallbackProvider}/${c.fallbackModelId}`:"",onChange:ne=>{if(!ne)u(ae=>({...ae,fallbackProvider:void 0,fallbackModelId:void 0}));else{const ae=ne.indexOf("/");u(oe=>({...oe,fallbackProvider:ne.slice(0,ae),fallbackModelId:ne.slice(ae+1)}))}},placeholder:"No fallback",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn}),e.jsx("small",{children:"Used automatically if the primary default model hits a retryable provider error like rate limiting or overload."})]})]}),(()=>{const ne=V.find(ae=>ae.provider===c.defaultProvider&&ae.id===c.defaultModelId);return ne&&!ne.reasoning?null:e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultThinkingLevel",children:"Thinking Effort"}),e.jsxs("select",{id:"defaultThinkingLevel",value:c.defaultThinkingLevel||"",onChange:ae=>{const oe=ae.target.value;u(ge=>({...ge,defaultThinkingLevel:oe||void 0}))},children:[e.jsx("option",{value:"",children:"Default"}),pj.map(ae=>e.jsx("option",{value:ae,children:ae.charAt(0).toUpperCase()+ae.slice(1)},ae))]}),e.jsx("small",{children:"Controls how much reasoning effort the AI model uses. Higher levels produce better results but cost more."})]})})(),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Model Lanes"}),e.jsx("p",{className:"settings-description",children:"Global baseline models for each AI role. Project settings can override these per-project."}),F.map(ne=>{const ae=c[ne.globalProviderKey],oe=c[ne.globalModelKey],ge=ae&&oe?`${ae}/${oe}`:"";return e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`global-${ne.laneId}-model`,children:ne.label}),e.jsx(Kt,{id:`global-${ne.laneId}-model`,label:ne.label,models:V,value:ge,onChange:et=>{if(!et){u(Jt=>({...Jt,[ne.globalProviderKey]:void 0,[ne.globalModelKey]:void 0}));return}const jt=et.indexOf("/");u(Jt=>({...Jt,[ne.globalProviderKey]:et.slice(0,jt),[ne.globalModelKey]:et.slice(jt+1)}))},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn}),e.jsx("small",{children:ne.helperText})]},`global-${ne.laneId}`)})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"OpenRouter Models"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"openrouterModelSync",className:"checkbox-label",children:[e.jsx("input",{id:"openrouterModelSync",type:"checkbox",checked:c.openrouterModelSync!==!1,onChange:ne=>u(ae=>({...ae,openrouterModelSync:ne.target.checked}))}),"Sync OpenRouter model list at dashboard startup"]}),e.jsx("small",{children:"When enabled, the dashboard fetches the latest available models from the OpenRouter API on startup, so the model picker always shows the most up-to-date catalog. Disable to skip the initial API call and use only the built-in model list."})]})]})}case"project-models":{const x=c.modelPresets||[],F=x.map(oe=>({id:oe.id,name:oe.name})),ne=new Set(Object.values(c.defaultPresetBySize||{}).filter(Boolean)),ae=Cn.filter(oe=>oe.laneId==="execution"||oe.laneId==="planning"||oe.laneId==="validator"||oe.laneId==="summarization");return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Token Cap"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"tokenCap",children:"Token Cap"}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[e.jsx("input",{id:"tokenCap",type:"number",placeholder:"No cap",value:c.tokenCap??"",onChange:oe=>{const ge=oe.target.value;u(et=>({...et,tokenCap:ge?parseInt(ge,10):null}))}}),c.tokenCap!=null&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to default (no cap)",onClick:()=>u(oe=>({...oe,tokenCap:null})),style:{whiteSpace:"nowrap"},children:"Reset"})]}),e.jsx("small",{children:"Automatically compact context when approaching this token count. Leave empty for no cap (compact only on overflow errors). Set a number to proactively compact when reaching this token count."})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Model Lanes"}),e.jsx("p",{className:"settings-description",children:"Override global model settings at the project level. Each lane controls a specific AI usage context. Unset lanes inherit from the corresponding global lane."}),B?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):V.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No models available. Configure authentication first."}):e.jsx(e.Fragment,{children:ae.map(oe=>{const ge=kn(oe),et=jn(oe),jt=ge==="overridden";return e.jsxs("div",{className:"form-group",children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",marginBottom:"0.25rem"},children:[e.jsx("label",{htmlFor:`${oe.laneId}Model`,children:oe.label}),e.jsx("span",{className:`settings-lane-badge ${jt?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:jt?"Explicitly set for this project":"Inherited from global settings",children:jt?"Override (Project)":"Inherited (Global)"})]}),e.jsxs("div",{style:{display:"flex",gap:"0.5rem",alignItems:"center"},children:[e.jsx("div",{style:{flex:1},children:e.jsx(Kt,{id:`${oe.laneId}Model`,label:oe.label,models:V,value:et,onChange:Jt=>Yn(oe,Jt),placeholder:"Use global",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn})}),jt&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to inherit from global",onClick:()=>un(oe),style:{whiteSpace:"nowrap"},children:"Reset"})]}),e.jsxs("small",{children:[oe.helperText," Falls back to: ",oe.fallbackOrder,"."]})]},oe.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Fallback Models"}),B?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):V.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No models available."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"planningFallbackModel",children:"Planning Fallback Model"}),e.jsx(Kt,{id:"planningFallbackModel",label:"Planning Fallback Model",models:V,value:c.planningFallbackProvider&&c.planningFallbackModelId?`${c.planningFallbackProvider}/${c.planningFallbackModelId}`:"",onChange:oe=>{if(!oe)u(ge=>({...ge,planningFallbackProvider:void 0,planningFallbackModelId:void 0}));else{const ge=oe.indexOf("/");u(et=>({...et,planningFallbackProvider:oe.slice(0,ge),planningFallbackModelId:oe.slice(ge+1)}))}},placeholder:"Use global fallback",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn}),e.jsx("small",{children:"Used if the planning model fails due to rate limits or provider overload. Defaults to the global fallback model."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"validatorFallbackModel",children:"Validator Fallback Model"}),e.jsx(Kt,{id:"validatorFallbackModel",label:"Validator Fallback Model",models:V,value:c.validatorFallbackProvider&&c.validatorFallbackModelId?`${c.validatorFallbackProvider}/${c.validatorFallbackModelId}`:"",onChange:oe=>{if(!oe)u(ge=>({...ge,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0}));else{const ge=oe.indexOf("/");u(et=>({...et,validatorFallbackProvider:oe.slice(0,ge),validatorFallbackModelId:oe.slice(ge+1)}))}},placeholder:"Use global fallback",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn}),e.jsx("small",{children:"Used if the validator model fails due to rate limits or provider overload. Defaults to the global fallback model."})]})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Model Presets"}),e.jsxs("div",{className:"form-group settings-model-presets",children:[e.jsx("label",{children:"Configured presets"}),x.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No presets configured yet."}):e.jsx("div",{className:"settings-preset-list",children:x.map(oe=>{const ge=Do(oe),et=`${ge.executorValue||"default"} / ${ge.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:oe.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:et})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Me(oe.id),De({...oe})},children:"Edit"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{ne.has(oe.id)&&!confirm(`Preset "${oe.name}" is used in auto-selection. Delete it anyway?`)||(u(jt=>({...jt,modelPresets:(jt.modelPresets||[]).filter(Jt=>Jt.id!==oe.id),defaultPresetBySize:Object.fromEntries(Object.entries(jt.defaultPresetBySize||{}).filter(([,Jt])=>Jt!==oe.id))})),ve===oe.id&&(Me(null),De(null)))},children:"Delete"})]})]},oe.id)})}),_e?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Me(null),De({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:"Add Preset"})})]}),_e?e.jsxs("div",{className:"form-group settings-preset-editor",children:[e.jsx("label",{children:"Preset editor"}),e.jsxs("div",{className:"settings-preset-editor-fields",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-name",children:"Name"}),e.jsx("input",{id:"preset-name",type:"text",value:_e.name,onChange:oe=>{const ge=oe.target.value;De(et=>et&&{...et,name:ge})}})]}),V.length===0?e.jsx("small",{children:"No models available. Configure authentication first."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-executor-model",children:"Executor model"}),e.jsx(Kt,{id:"preset-executor-model",label:"Preset executor model",models:V,value:_e.executorProvider&&_e.executorModelId?`${_e.executorProvider}/${_e.executorModelId}`:"",onChange:oe=>{if(!oe){De(et=>et&&{...et,executorProvider:void 0,executorModelId:void 0});return}const ge=oe.indexOf("/");De(et=>et&&{...et,executorProvider:oe.slice(0,ge),executorModelId:oe.slice(ge+1)})},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:"Validator model"}),e.jsx(Kt,{id:"preset-validator-model",label:"Preset validator model",models:V,value:_e.validatorProvider&&_e.validatorModelId?`${_e.validatorProvider}/${_e.validatorModelId}`:"",onChange:oe=>{if(!oe){De(et=>et&&{...et,validatorProvider:void 0,validatorModelId:void 0});return}const ge=oe.indexOf("/");De(et=>et&&{...et,validatorProvider:oe.slice(0,ge),validatorModelId:oe.slice(ge+1)})},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:rs,children:"Save preset"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Me(null),De(null)},children:"Cancel"})]})]}):null,e.jsx("div",{className:"form-group settings-preset-auto-select",children:e.jsxs("label",{htmlFor:"autoSelectModelPreset",className:"checkbox-label",children:[e.jsx("input",{id:"autoSelectModelPreset",type:"checkbox",checked:c.autoSelectModelPreset||!1,onChange:oe=>u(ge=>({...ge,autoSelectModelPreset:oe.target.checked}))}),"Auto-select preset based on task size"]})}),c.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(oe=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${oe}`,children:oe==="S"?"Small tasks (S):":oe==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${oe}`,value:c.defaultPresetBySize?.[oe]||"",onChange:ge=>{const et=ge.target.value||void 0;u(jt=>({...jt,defaultPresetBySize:{...jt.defaultPresetBySize||{},[oe]:et}}))},children:[e.jsx("option",{value:"",children:"No preset"}),F.map(ge=>e.jsx("option",{value:ge.id,children:ge.name},ge.id))]})]},oe))}):null,e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"AI Summarization"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoSummarizeTitles",className:"checkbox-label",children:[e.jsx("input",{id:"autoSummarizeTitles",type:"checkbox",checked:c.autoSummarizeTitles||!1,onChange:oe=>u(ge=>({...ge,autoSummarizeTitles:oe.target.checked}))}),"Auto-summarize long descriptions as titles"]}),e.jsx("small",{children:"When enabled, tasks created without a title but with descriptions over 200 characters will automatically get an AI-generated title (max 60 characters)."})]}),(c.autoSummarizeTitles||!1)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title summarization model"}),B?e.jsx("small",{children:"Loading available models..."}):V.length===0?e.jsx("small",{children:"No models available. Configure authentication first."}):e.jsx(Kt,{id:"titleSummarizerModel",label:"Title summarization model",models:V,value:c.titleSummarizerProvider&&c.titleSummarizerModelId?`${c.titleSummarizerProvider}/${c.titleSummarizerModelId}`:"",onChange:oe=>{if(!oe){u(et=>({...et,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0}));return}const ge=oe.indexOf("/");u(et=>({...et,titleSummarizerProvider:oe.slice(0,ge),titleSummarizerModelId:oe.slice(ge+1)}))},placeholder:"Use fallback model",favoriteProviders:D,onToggleFavorite:tn,favoriteModels:q,onToggleModelFavorite:dn}),e.jsx("small",{children:c.titleSummarizerProvider&&c.titleSummarizerModelId?"Using explicitly configured model":c.planningProvider&&c.planningModelId?"(using planning model)":c.defaultProvider&&c.defaultModelId?"(using default model)":"(using automatic model selection)"})]}),e.jsx("div",{className:"form-group",children:e.jsxs("div",{className:"modal-actions",style:{justifyContent:"flex-start"},children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>u(oe=>({...oe,titleSummarizerProvider:oe.planningProvider,titleSummarizerModelId:oe.planningModelId})),disabled:!c.planningProvider||!c.planningModelId,children:"Use planning model"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>u(oe=>({...oe,titleSummarizerProvider:oe.defaultProvider,titleSummarizerModelId:oe.defaultModelId})),disabled:!c.defaultProvider||!c.defaultModelId,children:"Use default model"})]})})]})]})}case"appearance":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Appearance"}),e.jsx(FM,{themeMode:r,colorTheme:l,onThemeModeChange:x=>{u(F=>({...F,themeMode:x})),o?.(x)},onColorThemeChange:x=>{u(F=>({...F,colorTheme:x})),d?.(x)}})]});case"scheduling":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Scheduling"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"globalMaxConcurrent",children:"Global Max Concurrent"}),e.jsx("input",{id:"globalMaxConcurrent",type:"number",min:0,max:1e4,value:qe??"",onChange:x=>{const F=x.target.value;We(F===""?void 0:Number(F))}}),e.jsx("small",{className:"form-text text-muted",children:"Maximum concurrent agents across all projects"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxConcurrent",children:"Max Concurrent Tasks"}),e.jsx("input",{id:"maxConcurrent",type:"number",min:1,max:10,value:c.maxConcurrent??"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,maxConcurrent:F===""?void 0:Number(F)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxTriageConcurrent",children:"Max Triage Concurrent"}),e.jsx("input",{id:"maxTriageConcurrent",type:"number",min:1,max:10,value:c.maxTriageConcurrent??"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,maxTriageConcurrent:F===""?void 0:Number(F)}))}}),e.jsx("small",{children:"Maximum concurrent triage/specification agents"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pollIntervalMs",children:"Poll Interval (ms)"}),e.jsx("input",{id:"pollIntervalMs",type:"number",min:5e3,step:1e3,value:c.pollIntervalMs??"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,pollIntervalMs:F===""?void 0:Number(F)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskStuckTimeoutMs",children:"Stuck Task Timeout (minutes)"}),e.jsx("input",{id:"taskStuckTimeoutMs",type:"number",min:1,step:1,value:c.taskStuckTimeoutMs?Math.round(c.taskStuckTimeoutMs/6e4):"",onChange:x=>{const F=x.target.value,ne=Number(F);u(ae=>({...ae,taskStuckTimeoutMs:F&&ne>0?ne*6e4:void 0}))}}),e.jsx("small",{children:"Timeout in minutes for detecting stuck tasks. When a task's agent session shows no activity for longer than this duration, the task is terminated and retried. Leave empty to disable. Suggested: 10."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"specStalenessEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"specStalenessEnabled",type:"checkbox",checked:c.specStalenessEnabled||!1,onChange:x=>u(F=>({...F,specStalenessEnabled:x.target.checked}))}),"Enable specification staleness enforcement"]}),e.jsx("small",{children:"When enabled, tasks with stale specifications (PROMPT.md older than the threshold) are automatically sent back to triage for re-specification"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"specStalenessMaxAgeMs",children:"Stale Spec Threshold (hours)"}),e.jsx("input",{id:"specStalenessMaxAgeMs",type:"number",min:0,step:1,value:c.specStalenessMaxAgeMs!==void 0?Math.round(c.specStalenessMaxAgeMs/36e5):"",onChange:x=>{const F=x.target.value,ne=Number(F);u(ae=>({...ae,specStalenessMaxAgeMs:F!==""?ne*36e5:void 0}))},disabled:!c.specStalenessEnabled}),e.jsx("small",{children:"Maximum age in hours before a specification is considered stale. Default: 6 hours."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoArchiveDoneTasksEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoArchiveDoneTasksEnabled",type:"checkbox",checked:c.autoArchiveDoneTasksEnabled??!0,onChange:x=>u(F=>({...F,autoArchiveDoneTasksEnabled:x.target.checked}))}),"Enable automatic task archiving"]}),e.jsx("small",{children:"Completed tasks older than the threshold are moved out of the active task database."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoArchiveDoneAfterMs",children:"Archive Completed Tasks After (days)"}),e.jsx("input",{id:"autoArchiveDoneAfterMs",type:"number",min:1,step:1,value:c.autoArchiveDoneAfterMs!==void 0?Math.round(c.autoArchiveDoneAfterMs/nm):VM,onChange:x=>{const F=x.target.value,ne=Number(F);u(ae=>({...ae,autoArchiveDoneAfterMs:F===""?void 0:ne*nm}))},disabled:c.autoArchiveDoneTasksEnabled===!1}),e.jsx("small",{children:"Number of days a task can stay in Done before it is archived. Default: 2 days (48 hours)."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"archiveAgentLogMode",children:"Archive Agent Log"}),e.jsxs("select",{id:"archiveAgentLogMode",value:c.archiveAgentLogMode??"compact",onChange:x=>u(F=>({...F,archiveAgentLogMode:x.target.value})),disabled:c.autoArchiveDoneTasksEnabled===!1,children:[e.jsx("option",{value:"compact",children:"Compact summary and recent entries"}),e.jsx("option",{value:"none",children:"Do not archive agent logs"}),e.jsx("option",{value:"full",children:"Full agent log"})]}),e.jsx("small",{children:"Compact mode keeps archive size low while preserving recent agent activity for context."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxStuckKills",children:"Max Stuck Retries"}),e.jsx("input",{id:"maxStuckKills",type:"number",min:1,step:1,value:c.maxStuckKills??"",onChange:x=>{const F=x.target.value,ne=Number(F);u(ae=>({...ae,maxStuckKills:F&&ne>0?ne:void 0}))}}),e.jsx("small",{children:"Maximum stuck-detector retries before a task is marked failed. Default: 6."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"groupOverlappingFiles",className:"checkbox-label",children:[e.jsx("input",{id:"groupOverlappingFiles",type:"checkbox",checked:c.groupOverlappingFiles,onChange:x=>u(F=>({...F,groupOverlappingFiles:x.target.checked}))}),"Serialize tasks with overlapping files"]}),e.jsx("small",{children:"When enabled, tasks that modify the same files are queued serially to avoid merge conflicts"})]}),e.jsx("div",{style:{borderTop:"1px solid var(--border)",margin:"var(--space-lg) 0"}}),e.jsx("h5",{className:"settings-section-heading",children:"Step Execution"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"runStepsInNewSessions",className:"checkbox-label",children:[e.jsx("input",{id:"runStepsInNewSessions",type:"checkbox",checked:c.runStepsInNewSessions||!1,onChange:x=>u(F=>({...F,runStepsInNewSessions:x.target.checked}))}),"Run each step in a new session"]}),e.jsx("small",{children:"Run each task step in its own fresh agent session for better isolation and error recovery. Failed steps can be retried individually."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxParallelSteps",children:"Maximum parallel steps"}),e.jsx("input",{id:"maxParallelSteps",type:"number",min:1,max:4,value:c.maxParallelSteps??"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,maxParallelSteps:F===""?void 0:Number(F)}))},disabled:!c.runStepsInNewSessions}),e.jsx("small",{children:"Maximum number of steps to run in parallel when file scopes don't overlap (1-4)"})]})]});case"worktrees":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Worktrees"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxWorktrees",children:"Max Worktrees"}),e.jsx("input",{id:"maxWorktrees",type:"number",min:1,max:20,value:c.maxWorktrees??"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,maxWorktrees:F===""?void 0:Number(F)}))}}),e.jsx("small",{children:"Limits total git worktrees including in-review tasks"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeInitCommand",children:"Worktree Init Command"}),e.jsx("input",{id:"worktreeInitCommand",type:"text",placeholder:"pnpm install --frozen-lockfile",value:c.worktreeInitCommand||"",onChange:x=>u(F=>({...F,worktreeInitCommand:x.target.value}))}),e.jsx("small",{children:"Shell command to run in each new worktree after creation"})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"recycleWorktrees",className:"checkbox-label",children:[e.jsx("input",{id:"recycleWorktrees",type:"checkbox",checked:c.recycleWorktrees,onChange:x=>u(F=>({...F,recycleWorktrees:x.target.checked}))}),"Recycle worktrees"]}),e.jsx("small",{children:"When enabled, completed task worktrees are returned to an idle pool instead of being deleted, preserving build caches for faster startup"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeNaming",children:"Worktree Naming Style"}),e.jsxs("select",{id:"worktreeNaming",value:c.worktreeNaming||"random",onChange:x=>u(F=>({...F,worktreeNaming:x.target.value})),disabled:c.recycleWorktrees,children:[e.jsx("option",{value:"random",children:"Random names (e.g., swift-falcon)"}),e.jsx("option",{value:"task-id",children:"Task ID (e.g., FN-042)"}),e.jsx("option",{value:"task-title",children:"Task title (e.g., fix-login-bug)"})]}),e.jsx("small",{children:c.recycleWorktrees?"Naming style is not applicable when recycling worktrees — pooled worktrees retain their existing names":"How to name fresh worktree directories. Only applies when recycling is off."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"worktreeRebaseBeforeMerge",className:"checkbox-label",children:[e.jsx("input",{id:"worktreeRebaseBeforeMerge",type:"checkbox",checked:c.worktreeRebaseBeforeMerge!==!1,onChange:x=>u(F=>({...F,worktreeRebaseBeforeMerge:x.target.checked}))}),"Rebase from remote before merge"]}),e.jsx("small",{children:"When enabled, the merger fetches from the configured remote and rebases the task branch onto the latest default-branch tip before merging — catching concurrent pushes from other collaborators or fusion workers. Any conflicts the rebase surfaces flow into the existing smart/AI resolve pipeline."})]}),c.worktreeRebaseBeforeMerge!==!1&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeRebaseRemote",children:"Rebase Remote"}),e.jsxs("select",{id:"worktreeRebaseRemote",value:c.worktreeRebaseRemote??"",onChange:x=>u(F=>({...F,worktreeRebaseRemote:x.target.value||void 0})),children:[e.jsx("option",{value:"",children:"Use git default"}),ye.map(x=>e.jsxs("option",{value:x.name,children:[x.name," (",x.fetchUrl,")"]},x.name))]}),e.jsxs("small",{children:['Which remote to fetch for the pre-merge rebase. "Use git default" falls back to the remote configured for the default branch (typically ',e.jsx("code",{children:"origin"}),")."]})]})]});case"commands":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Commands"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"testCommand",children:"Test Command"}),e.jsx("input",{id:"testCommand",type:"text",placeholder:"e.g. pnpm test",value:c.testCommand||"",onChange:x=>u(F=>({...F,testCommand:x.target.value||void 0}))}),e.jsx("small",{children:"Command used to run tests — injected into generated task specs"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"buildCommand",children:"Build Command"}),e.jsx("input",{id:"buildCommand",type:"text",placeholder:"e.g. pnpm build",value:c.buildCommand||"",onChange:x=>u(F=>({...F,buildCommand:x.target.value||void 0}))}),e.jsx("small",{children:"Command used to build the project — injected into generated task specs"})]})]});case"merge":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Merge"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoMerge",className:"checkbox-label",children:[e.jsx("input",{id:"autoMerge",type:"checkbox",checked:c.autoMerge,onChange:x=>u(F=>({...F,autoMerge:x.target.checked}))}),"Auto-merge completed tasks"]}),e.jsx("small",{children:"When enabled, tasks that pass review are automatically merged into the main branch"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"mergeStrategy",children:"Auto-completion mode"}),e.jsxs("select",{id:"mergeStrategy",value:c.mergeStrategy||"direct",onChange:x=>u(F=>({...F,mergeStrategy:x.target.value})),children:[e.jsx("option",{value:"direct",children:"Direct merge into the current branch"}),e.jsx("option",{value:"pull-request",children:"Create, monitor, and merge a GitHub pull request"})]}),e.jsx("small",{children:"Controls what happens after a task reaches In Review. Direct mode preserves Fusion's current local squash-merge behavior. Pull request mode keeps the task in In Review while Fusion waits for GitHub reviews and required checks before merging the PR."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"includeTaskIdInCommit",className:"checkbox-label",children:[e.jsx("input",{id:"includeTaskIdInCommit",type:"checkbox",checked:c.includeTaskIdInCommit!==!1,onChange:x=>u(F=>({...F,includeTaskIdInCommit:x.target.checked}))}),"Include task ID in commit scope"]}),e.jsxs("small",{children:["When disabled, merge commit messages omit the task ID from the scope (e.g. ",e.jsx("code",{children:"feat: ..."})," instead of ",e.jsx("code",{children:"feat(KB-001): ..."}),")"]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"commitAuthorEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"commitAuthorEnabled",type:"checkbox",checked:c.commitAuthorEnabled!==!1,onChange:x=>u(F=>({...F,commitAuthorEnabled:x.target.checked}))}),"Add author attribution to commits"]}),e.jsxs("small",{children:["When enabled, all commits made by Fusion include ",e.jsx("code",{children:"--author"})," ","attribution identifying them as AI-generated"]})]}),c.commitAuthorEnabled!==!1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorName",children:"Author Name"}),e.jsx("input",{id:"commitAuthorName",type:"text",value:c.commitAuthorName??"",placeholder:"Fusion",onChange:x=>u(F=>({...F,commitAuthorName:x.target.value||void 0}))}),e.jsx("small",{children:"Name used in commit author attribution"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"commitAuthorEmail",children:"Author Email"}),e.jsx("input",{id:"commitAuthorEmail",type:"email",value:c.commitAuthorEmail??"",placeholder:"noreply@runfusion.ai",onChange:x=>u(F=>({...F,commitAuthorEmail:x.target.value||void 0}))}),e.jsx("small",{children:"Email used in commit author attribution"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoResolveConflicts",className:"checkbox-label",children:[e.jsx("input",{id:"autoResolveConflicts",type:"checkbox",checked:c.autoResolveConflicts!==!1,onChange:x=>u(F=>({...F,autoResolveConflicts:x.target.checked}))}),"Auto-resolve conflicts in lock files and generated files"]}),e.jsx("small",{children:"When enabled, lock files (package-lock.json, pnpm-lock.yaml, etc.), generated files (dist/*, *.gen.ts), and trivial whitespace conflicts are resolved automatically without AI intervention. Complex code conflicts still require AI review."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"smartConflictResolution",className:"checkbox-label",children:[e.jsx("input",{id:"smartConflictResolution",type:"checkbox",checked:c.smartConflictResolution!==!1,onChange:x=>u(F=>({...F,smartConflictResolution:x.target.checked}))}),"Smart conflict resolution"]}),e.jsx("small",{children:"When enabled, lock files (package-lock.json, pnpm-lock.yaml, etc.) are resolved using 'ours' strategy, generated files (dist/*, *.gen.ts) using 'theirs' strategy, and trivial whitespace conflicts are auto-resolved without spawning an AI agent. Complex code conflicts still require AI review."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"pushAfterMerge",className:"checkbox-label",children:[e.jsx("input",{id:"pushAfterMerge",type:"checkbox",checked:c.pushAfterMerge===!0,onChange:x=>u(F=>({...F,pushAfterMerge:x.target.checked}))}),"Push to remote after merge"]}),e.jsx("small",{children:"When enabled, the merged result is automatically pushed to the configured git remote. This includes pulling the latest from the remote first (rebase) and resolving any conflicts with AI if needed."})]}),c.pushAfterMerge&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pushRemote",children:"Push Remote"}),e.jsx("input",{id:"pushRemote",type:"text",placeholder:"origin",value:c.pushRemote||"",onChange:x=>u(F=>({...F,pushRemote:x.target.value||void 0}))}),e.jsx("small",{children:'Git remote to push to (e.g. "origin"). Can include branch name (e.g. "origin main"). Default: "origin".'})]})]});case"memory":{const{capabilities:x,status:F,loading:ne,error:ae}={capabilities:be,status:lt,loading:U,error:we},oe=c.memoryEnabled!==!1,ge=x?.writable??!0,et=oe&&ge,jt=Ie.find(Je=>Je.path===Ue),Jt={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Memory"}),e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"settings-muted",children:["Memory lives in ",e.jsx("code",{children:".fusion/memory/"}),". Agents search with qmd first, fall back to local files when qmd is missing, and open exact line windows only when needed."]})}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryEnabled",type:"checkbox",checked:c.memoryEnabled!==!1,onChange:Je=>u(ot=>({...ot,memoryEnabled:Je.target.checked}))}),"Enable memory tools"]}),e.jsx("small",{children:"Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback."})]}),ne?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:"Checking memory write access..."})}):ae?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Failed to load backend status: ",ae]})}):null,F?.qmdAvailable===!1&&e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:["qmd is not installed. Search will use local files. Install indexed retrieval: ",e.jsx("code",{children:F.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Bn,disabled:Ee,children:Ee?"Installing…":"Install qmd"})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:c.memoryAutoSummarizeEnabled||!1,onChange:Je=>u(ot=>({...ot,memoryAutoSummarizeEnabled:Je.target.checked}))}),"Auto-Summarize Memory"]}),e.jsx("small",{children:"Automatically compact memory when it exceeds the threshold on a schedule"})]}),(c.memoryAutoSummarizeEnabled||!1)&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:"Compaction Threshold (chars)"}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:c.memoryAutoSummarizeThresholdChars??5e4,onChange:Je=>u(ot=>({...ot,memoryAutoSummarizeThresholdChars:parseInt(Je.target.value,10)||5e4})),min:1e3}),e.jsx("small",{children:"Memory will be compacted when it exceeds this character count"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:"Schedule (cron)"}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:c.memoryAutoSummarizeSchedule??"0 3 * * *",onChange:Je=>u(ot=>({...ot,memoryAutoSummarizeSchedule:Je.target.value})),placeholder:"0 3 * * *"}),e.jsx("small",{children:"Cron expression for auto-summarize schedule (default: daily at 3 AM)"})]})]}),e.jsx("div",{style:{borderTop:"1px solid var(--border)",margin:"var(--space-lg) 0"}}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:c.memoryDreamsEnabled===!0,onChange:Je=>u(ot=>({...ot,memoryDreamsEnabled:Je.target.checked})),disabled:!oe}),"Process dreams from daily memory"]}),e.jsx("small",{children:"Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md."})]}),oe&&c.memoryDreamsEnabled===!0&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:"Dream Schedule"}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",value:c.memoryDreamsSchedule??"0 4 * * *",onChange:Je=>u(ot=>({...ot,memoryDreamsSchedule:Je.target.value}))}),e.jsx("small",{children:"Cron expression for dream processing."})]}),e.jsxs("div",{className:"memory-retrieval-test",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryRetrievalQuery",children:"Test Retrieval"}),e.jsx("input",{id:"memoryRetrievalQuery",type:"text",value:ht,onChange:Je=>ue(Je.target.value),placeholder:"Search memory with qmd"}),e.jsx("small",{children:"Runs the same qmd-backed memory_search path agents use."})]}),e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Nn,disabled:te,children:te?"Testing…":"Test Retrieval"})}),Ne&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[Ne.results.length," result",Ne.results.length===1?"":"s"," ",'for "',Ne.query,'"']}),e.jsxs("small",{children:["qmd ",Ne.qmdAvailable?"available":"missing"," · ",Ne.usedFallback?"local fallback used":"qmd path used"]}),Ne.results.length>0?e.jsx("ul",{children:Ne.results.map((Je,ot)=>e.jsxs("li",{children:[e.jsxs("span",{children:[Je.path,":",Je.lineStart]}),e.jsx("p",{children:Je.snippet})]},`${Je.path}-${Je.lineStart}-${ot}`))}):e.jsx("small",{children:"No matching memory found."})]})]}),!oe&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:"Memory is currently disabled. You can view the file, but editing is read-only until memory is re-enabled."}),oe&&!ge&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:"Memory is configured with a read-only backend. You can view the file, but saving is disabled."}),Te?e.jsx("div",{className:"settings-empty-state",children:"Loading memory…"}):e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryFilePath",children:"Memory File"}),e.jsx("select",{id:"memoryFilePath",value:Ue,onChange:Je=>{dt(Je.target.value),Z(!1)},disabled:re,children:Ie.map(Je=>e.jsxs("option",{value:Je.path,children:[Je.label," - ",Je.path]},Je.path))}),e.jsx("small",{children:re?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),jt&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:Jt[jt.layer]}),e.jsx("strong",{children:jt.path}),e.jsxs("small",{children:[jt.size.toLocaleString()," bytes · updated ",new Date(jt.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:jt?.label||"Memory Editor"}),e.jsxs("small",{children:[jt?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",jt?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",jt?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!jt&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(Kp,{content:Ce,onChange:Je=>{Ge(Je),Z(!0)},readOnly:!et,filePath:Ue})})]})]}),!Te&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:On,disabled:!et||re||xe,children:xe?"Compacting…":"Compact Selected File"}),e.jsx("small",{children:re?"Save or discard edits before compacting this file.":`Compacts ${Ue} and writes the result back to the same file.`})]}),re&&et&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:wn,children:"Save Memory"})}),re&&!et&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Cannot save: ",oe?"Backend is read-only":"Memory is disabled"]})})]})}case"experimental":{const x=c.experimentalFeatures??{},ne=Array.from(new Set([...Object.keys(sm),...Object.keys(x)])).sort((ae,oe)=>ae.localeCompare(oe)).map(ae=>[ae,x[ae]===!0]);return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Experimental Features"}),e.jsx("div",{className:"form-group",children:e.jsx("small",{children:"Experimental features are early capabilities that are not yet fully stable. Enable them to test new functionality, but be aware they may change or be removed."})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Feature Flags"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:ne.map(([ae,oe])=>e.jsxs("label",{htmlFor:`experimental-${ae}`,className:"checkbox-label",children:[e.jsx("input",{id:`experimental-${ae}`,type:"checkbox",checked:oe,onChange:ge=>{u(et=>({...et,experimentalFeatures:{...et.experimentalFeatures??{},[ae]:ge.target.checked}}))}}),e.jsx("span",{children:sm[ae]??ae})]},ae))})]})]})}case"backups":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Database Backups"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoBackupEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoBackupEnabled",type:"checkbox",checked:c.autoBackupEnabled||!1,onChange:x=>u(F=>({...F,autoBackupEnabled:x.target.checked}))}),"Enable automatic database backups"]}),e.jsx("small",{children:"When enabled, the database is backed up automatically on a schedule"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupSchedule",children:"Backup Schedule (Cron)"}),e.jsx("input",{id:"autoBackupSchedule",type:"text",placeholder:"0 2 * * *",value:c.autoBackupSchedule||"0 2 * * *",onChange:x=>u(F=>({...F,autoBackupSchedule:x.target.value})),disabled:!c.autoBackupEnabled}),e.jsx("small",{children:"Cron expression for backup timing. Default: 0 2 * * * (daily at 2 AM). Examples: 0 * * * * (hourly), 0 0 * * 0 (weekly), */15 * * * * (every 15 min)"}),c.autoBackupSchedule&&!/^[\s\d*,/-]+$/.test(c.autoBackupSchedule)&&e.jsx("small",{className:"field-error",children:"Invalid cron expression format"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupRetention",children:"Retention Count"}),e.jsx("input",{id:"autoBackupRetention",type:"number",min:1,max:100,value:c.autoBackupRetention??"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,autoBackupRetention:F===""?void 0:Number(F)}))},disabled:!c.autoBackupEnabled}),e.jsx("small",{children:"Number of backup files to keep (oldest are deleted first). Range: 1-100."}),c.autoBackupRetention!==void 0&&(c.autoBackupRetention<1||c.autoBackupRetention>100)&&e.jsx("small",{className:"field-error",children:"Must be between 1 and 100"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupDir",children:"Backup Directory"}),e.jsx("input",{id:"autoBackupDir",type:"text",placeholder:".fusion/backups",value:c.autoBackupDir||".fusion/backups",onChange:x=>u(F=>({...F,autoBackupDir:x.target.value})),disabled:!c.autoBackupEnabled}),e.jsx("small",{children:"Directory for backup files, relative to project root"}),c.autoBackupDir&&c.autoBackupDir.includes("..")&&e.jsx("small",{className:"field-error",children:"Path cannot contain parent directory traversal (..)"})]}),Be?e.jsx("div",{className:"settings-empty-state",children:"Loading backup info…"}):Oe?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Current Backups"}),e.jsxs("div",{className:"backup-stats",children:[e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:Oe.count}),e.jsx("span",{className:"backup-stat-label",children:"backups"})]}),e.jsxs("div",{className:"backup-stat",children:[e.jsx("span",{className:"backup-stat-value",children:Oe.totalSize>1024*1024?`${(Oe.totalSize/(1024*1024)).toFixed(1)} MB`:`${(Oe.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:"total size"})]})]}),Oe.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:["View ",Oe.backups.length," backup(s)"]}),e.jsxs("ul",{children:[Oe.backups.slice(0,10).map(x=>e.jsxs("li",{children:[e.jsx("code",{children:x.filename}),e.jsx("span",{className:"backup-size",children:x.size>1024*1024?`${(x.size/(1024*1024)).toFixed(1)} MB`:`${(x.size/1024).toFixed(1)} KB`})]},x.filename)),Oe.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:["...and ",Oe.backups.length-10," more"]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:hn,disabled:Be,children:Be?"Creating…":"Backup Now"})})]});case"notifications":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Notifications"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"ntfyEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"ntfyEnabled",type:"checkbox",checked:c.ntfyEnabled||!1,onChange:x=>u(F=>({...F,ntfyEnabled:x.target.checked}))}),"Enable ntfy.sh notifications"]}),e.jsx("small",{children:"Receive push notifications when tasks complete or fail via ntfy.sh"})]}),c.ntfyEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"ntfyTopic",children:"ntfy Topic"}),e.jsx("input",{id:"ntfyTopic",type:"text",placeholder:"my-topic-name",value:c.ntfyTopic||"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,ntfyTopic:F||void 0}))}}),e.jsxs("small",{children:["Your ntfy.sh topic name (1–64 alphanumeric/hyphen/underscore characters)."," ",e.jsx("a",{href:"https://ntfy.sh",target:"_blank",rel:"noopener noreferrer",children:"Learn more about ntfy.sh"})]}),c.ntfyTopic&&!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic)&&e.jsx("small",{className:"field-error",children:"Topic must be 1–64 alphanumeric, hyphen, or underscore characters"}),e.jsxs("details",{className:"ntfy-advanced-disclosure",children:[e.jsx("summary",{children:"Advanced"}),e.jsxs("div",{className:"ntfy-advanced-content",children:[e.jsx("label",{htmlFor:"ntfyBaseUrl",children:"Custom ntfy server URL (optional)"}),e.jsx("input",{id:"ntfyBaseUrl",type:"url",placeholder:"https://ntfy.sh",value:c.ntfyBaseUrl||"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,ntfyBaseUrl:F||void 0}))}}),e.jsx("small",{children:"Leave blank to keep the default server: https://ntfy.sh. Custom servers must use http:// or https://."})]})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:fn,disabled:me||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic),children:me?"Sending…":"Test notification"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Notify on events"}),e.jsxs("div",{className:"ntfy-events-list",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("in-review")??!0,onChange:x=>{const F=c.ntfyEvents??[...Fi],ne=x.target.checked?F.includes("in-review")?F:[...F,"in-review"]:F.filter(ae=>ae!=="in-review");u(ae=>({...ae,ntfyEvents:ne.length>0?ne:void 0}))}}),"Task completed (in-review)"]}),e.jsx("small",{children:"When a task moves to In Review (ready for review)"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("merged")??!0,onChange:x=>{const F=c.ntfyEvents??[...Fi],ne=x.target.checked?F.includes("merged")?F:[...F,"merged"]:F.filter(ae=>ae!=="merged");u(ae=>({...ae,ntfyEvents:ne.length>0?ne:void 0}))}}),"Task merged"]}),e.jsx("small",{children:"When a task is successfully merged to main"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("failed")??!0,onChange:x=>{const F=c.ntfyEvents??[...Fi],ne=x.target.checked?F.includes("failed")?F:[...F,"failed"]:F.filter(ae=>ae!=="failed");u(ae=>({...ae,ntfyEvents:ne.length>0?ne:void 0}))}}),"Task failed"]}),e.jsx("small",{children:"When a task fails during execution (high priority)"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("awaiting-approval")??!0,onChange:x=>{const F=c.ntfyEvents??[...Fi],ne=x.target.checked?F.includes("awaiting-approval")?F:[...F,"awaiting-approval"]:F.filter(ae=>ae!=="awaiting-approval");u(ae=>({...ae,ntfyEvents:ne.length>0?ne:void 0}))}}),"Plan needs approval"]}),e.jsx("small",{children:"When a task specification needs manual approval before execution"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("awaiting-user-review")??!0,onChange:x=>{const F=c.ntfyEvents??[...Fi],ne=x.target.checked?F.includes("awaiting-user-review")?F:[...F,"awaiting-user-review"]:F.filter(ae=>ae!=="awaiting-user-review");u(ae=>({...ae,ntfyEvents:ne.length>0?ne:void 0}))}}),"User review needed"]}),e.jsx("small",{children:"When an agent hands off a task for human review (high priority)"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("planning-awaiting-input")??!0,onChange:x=>{const F=c.ntfyEvents??[...Fi],ne=x.target.checked?F.includes("planning-awaiting-input")?F:[...F,"planning-awaiting-input"]:F.filter(ae=>ae!=="planning-awaiting-input");u(ae=>({...ae,ntfyEvents:ne.length>0?ne:void 0}))}}),"Planning needs input"]}),e.jsx("small",{children:"When planning mode is waiting for your response to continue"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"ntfyDashboardHost",children:"Dashboard Hostname"}),e.jsx("input",{id:"ntfyDashboardHost",type:"text",placeholder:"http://localhost:3000",value:c.ntfyDashboardHost||"",onChange:x=>{const F=x.target.value;u(ne=>({...ne,ntfyDashboardHost:F||void 0}))}}),e.jsx("small",{children:"Base URL for deep links in notifications. When set, clicking a notification opens the dashboard directly to the task."}),c.ntfyDashboardHost&&!/^https?:\/\/.+/.test(c.ntfyDashboardHost)&&e.jsx("small",{className:"field-error",children:"Must be a valid URL starting with http:// or https://"})]})]})]});case"node-sync":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Node Sync"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"settingsSyncEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"settingsSyncEnabled",type:"checkbox",checked:c.settingsSyncEnabled||!1,onChange:x=>u(F=>({...F,settingsSyncEnabled:x.target.checked}))}),"Enable automatic settings sync"]}),e.jsx("small",{children:"Automatically synchronize settings between this node and connected remote nodes"})]}),c.settingsSyncEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"settingsSyncAuth",className:"checkbox-label",children:[e.jsx("input",{id:"settingsSyncAuth",type:"checkbox",checked:c.settingsSyncAuth||!1,onChange:x=>u(F=>({...F,settingsSyncAuth:x.target.checked}))}),"Sync model auth credentials"]}),e.jsx("small",{children:"Include API keys and OAuth tokens in sync operations"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"settingsSyncInterval",children:"Sync interval"}),e.jsxs("select",{id:"settingsSyncInterval",className:"select",value:c.settingsSyncInterval||9e5,onChange:x=>u(F=>({...F,settingsSyncInterval:parseInt(x.target.value,10)})),children:[e.jsx("option",{value:3e5,children:"Every 5 minutes"}),e.jsx("option",{value:9e5,children:"Every 15 minutes"}),e.jsx("option",{value:18e5,children:"Every 30 minutes"}),e.jsx("option",{value:36e5,children:"Every 1 hour"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"settingsSyncConflictResolution",children:"Conflict resolution"}),e.jsxs("select",{id:"settingsSyncConflictResolution",className:"select",value:c.settingsSyncConflictResolution||"last-write-wins",onChange:x=>u(F=>({...F,settingsSyncConflictResolution:x.target.value})),children:[e.jsx("option",{value:"last-write-wins",children:"Last write wins"}),e.jsx("option",{value:"always-ask",children:"Always ask"}),e.jsx("option",{value:"keep-local",children:"Keep local"}),e.jsx("option",{value:"keep-remote",children:"Keep remote"})]})]})]})]});case"prompts":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Prompts"}),e.jsx(UM,{value:c.agentPrompts,onChange:x=>{u(F=>({...F,agentPrompts:x}))},promptOverrides:c.promptOverrides,onPromptOverridesChange:x=>{u(F=>({...F,promptOverrides:x}))}})]});case"plugins":return e.jsxs(e.Fragment,{children:[Vt(),e.jsx("h4",{className:"settings-section-heading",children:"Plugins"}),e.jsx(a.Suspense,{fallback:null,children:e.jsx(HM,{addToast:n,projectId:s})}),e.jsx(Ja,{slotId:"settings-section",projectId:s})]});case"pi-extensions":return e.jsx(a.Suspense,{fallback:null,children:e.jsx(qM,{addToast:n,projectId:s})});case"authentication":{const x=I.filter(ge=>ge.type==="cli"),ne=[...I.filter(ge=>ge.type!=="cli")].sort((ge,et)=>ge.authenticated!==et.authenticated?ge.authenticated?-1:1:ge.name.localeCompare(et.name)),ae=ne.filter(ge=>ge.authenticated),oe=ne.filter(ge=>!ge.authenticated);return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:"Authentication"}),ee?e.jsx("div",{className:"settings-empty-state",children:"Loading authentication status…"}):I.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No providers available"}):e.jsxs(e.Fragment,{children:[x.some(ge=>ge.id==="claude-cli")&&e.jsx(Gp,{compact:!0,authenticated:x.find(ge=>ge.id==="claude-cli")?.authenticated??!1,onToggled:()=>{xt()}}),ae.length===0&&e.jsx("div",{className:"auth-section-hint",children:"Sign in to at least one provider to get started with AI models."}),ae.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Authenticated"}),ae.map(ge=>e.jsx("div",{className:"auth-provider-card auth-provider-card--authenticated",children:e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx("strong",{children:ge.name}),e.jsx("span",{"data-testid":`auth-status-${ge.id}`,className:`auth-status-badge ${ge.authenticated?"authenticated":"not-authenticated"}`,children:"✓ Active"}),ge.authenticated&&ge.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",ge.keyHint]})]}),ge.type==="api_key"?e.jsxs("div",{className:"auth-apikey-section",children:[e.jsxs("div",{className:"auth-apikey-input-row",children:[e.jsx("input",{type:"password",className:"auth-apikey-input",placeholder:"Enter API key",value:G[ge.id]??"",onChange:et=>P(jt=>({...jt,[ge.id]:et.target.value})),disabled:T===ge.id}),ge.authenticated&&!G[ge.id]?e.jsx("button",{className:"btn btn-sm",onClick:()=>Ht(ge.id),disabled:T===ge.id,children:"Clear"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>pt(ge.id),disabled:T===ge.id,children:"Save"})]}),T===ge.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),O[ge.id]&&e.jsx("small",{className:"auth-apikey-error",children:O[ge.id]})]}):e.jsx("div",{children:T===ge.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>Ke(ge.id),children:"Logout"})})]})},ge.id))]}),oe.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Available"}),oe.map(ge=>e.jsx("div",{className:"auth-provider-card",children:e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx("strong",{children:ge.name}),e.jsx("span",{"data-testid":`auth-status-${ge.id}`,className:`auth-status-badge ${ge.authenticated?"authenticated":"not-authenticated"}`,children:"✗ Not connected"})]}),ge.type==="api_key"?e.jsxs("div",{className:"auth-apikey-section",children:[e.jsxs("div",{className:"auth-apikey-input-row",children:[e.jsx("input",{type:"password",className:"auth-apikey-input",placeholder:"Enter API key",value:G[ge.id]??"",onChange:et=>P(jt=>({...jt,[ge.id]:et.target.value})),disabled:T===ge.id}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>pt(ge.id),disabled:T===ge.id,children:"Save"})]}),T===ge.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),O[ge.id]&&e.jsx("small",{className:"auth-apikey-error",children:O[ge.id]})]}):e.jsxs("div",{children:[T===ge.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>je(ge.id),children:"Login"}),Y[ge.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`auth-login-instructions-${ge.id}`,children:Y[ge.id]})]})]})},ge.id))]})]}),e.jsx("small",{className:"auth-hint",children:"Authentication changes take effect immediately — no need to save."}),m&&e.jsxs("div",{className:"form-group",style:{marginTop:"var(--space-md)"},children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:m,children:"Reopen onboarding guide"}),e.jsx("small",{className:"settings-muted",children:"Re-run the setup wizard to review or update your AI provider and model configuration."})]})]})}}};return e.jsxs("div",{className:"modal-overlay open",onClick:nn,role:"dialog","aria-modal":"true",children:[e.jsxs("div",{className:"modal modal-lg",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"Settings"}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:"×"})]}),h?e.jsx("div",{className:"settings-empty-state settings-loading",children:"Loading…"}):e.jsxs("div",{className:"settings-layout",children:[N&&e.jsxs("div",{className:"settings-mobile-section-picker",children:[e.jsx("label",{htmlFor:"settings-mobile-section",children:"Settings Section"}),e.jsx("select",{id:"settings-mobile-section",className:"select touch-target",value:j,onChange:x=>_(x.target.value),children:vr.filter(x=>!x.isGroupHeader).map(x=>e.jsx("option",{value:x.id,children:x.label},x.id))})]}),e.jsx("nav",{className:"settings-sidebar",children:vr.map(x=>x.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:x.label},x.id):e.jsxs("button",{className:`settings-nav-item${j===x.id?" active":""}`,onClick:()=>_(x.id),title:x.scope==="global"?"Shared across all projects":x.scope==="project"?"Specific to this project":void 0,children:[x.scope==="global"&&e.jsx(yi,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),x.scope==="project"&&e.jsx(Pn,{className:"settings-scope-icon","aria-label":"Project setting",size:16}),x.icon&&!x.scope&&e.jsx(x.icon,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),x.label]},x.id))}),e.jsx("div",{className:"settings-content",children:_n()})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"modal-actions-left",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Jn,title:"Export settings to JSON file",children:"Export"}),e.jsx("input",{type:"file",ref:Fe,accept:".json,application/json",style:{display:"none"},onChange:Ot}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Fe.current?.click(),disabled:Pt,title:"Import settings from JSON file",children:Pt?"Loading…":"Import"})]}),e.jsxs("div",{className:"modal-actions-right",children:[e.jsx("button",{className:"btn btn-sm",onClick:t,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:$t,disabled:h,children:"Save"})]})]})]}),nt&&Ct&&e.jsx("div",{className:"modal-overlay open",onClick:x=>x.target===x.currentTarget&&kt(!1),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-md",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"Import Settings"}),e.jsx("button",{className:"modal-close",onClick:()=>kt(!1),"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:"Review the settings to be imported:"}),Ct.global&&Object.keys(Ct.global).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:"Global Settings:"}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(Ct.global).filter(([,x])=>x!==void 0).map(([x])=>e.jsx("li",{children:x},x))})]}),Ct.project&&Object.keys(Ct.project).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:"Project Settings:"}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(Ct.project).filter(([,x])=>x!==void 0).map(([x])=>e.jsx("li",{children:x},x))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:"Import Scope:"}),e.jsxs("select",{id:"import-scope",value:bt,onChange:x=>_t(x.target.value),children:[e.jsx("option",{value:"both",children:"Both global and project settings"}),e.jsx("option",{value:"global",children:"Global settings only"}),e.jsx("option",{value:"project",children:"Project settings only"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"import-merge",className:"checkbox-label",children:[e.jsx("input",{id:"import-merge",type:"checkbox",checked:Ve,onChange:x=>ft(x.target.checked)}),"Merge with existing settings (recommended)"]}),e.jsx("small",{children:"If unchecked, existing settings will be replaced with imported values."})]})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>kt(!1),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:yn,disabled:Pt,children:Pt?"Importing…":"Confirm Import"})]})]})})]})}const KM=640;function GM({isOpen:t,onClose:n,onImport:s,tasks:i,projectId:r}){const[l,o]=a.useState(""),[d,m]=a.useState(""),[c,u]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[b,v]=a.useState([]),[y,k]=a.useState(null),[A,j]=a.useState([]),[_,N]=a.useState(null),[M,w]=a.useState(null),[R,E]=a.useState(!1),[I,L]=a.useState([]),[ee,$]=a.useState(!1),[T,S]=a.useState(""),Y=a.useRef(!1),[K,G]=a.useState(!1),[P,O]=a.useState("list"),X=a.useRef(null),C=new Set;for(const ie of i){const Ie=ie.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Ie&&C.add(Ie[1]);const pe=ie.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);pe&&C.add(pe[1])}a.useEffect(()=>{if(t)return o(""),m(""),u(""),v([]),k(null),j([]),N(null),f("issues"),w(null),E(!1),L([]),$(!0),S(""),X.current=null,Y.current=!0,ov().then(ie=>{if(Y.current)if(L(ie),$(!1),ie.length===1){const Ie=ie[0];o(Ie.owner),m(Ie.repo),S(Ie.name)}else ie.length>1&&(o(""),m(""),S(""))}).catch(()=>{Y.current&&$(!1)}),()=>{Y.current=!1}},[t]);const V=a.useCallback(ie=>{if(S(ie),ie==="")o(""),m("");else{const Ie=I.find(pe=>pe.name===ie);Ie&&(o(Ie.owner),m(Ie.repo))}},[I]),de=a.useCallback(async()=>{if(!l.trim()||!d.trim()){w("Repository must be selected");return}g(!0),w(null),v([]),k(null);try{const ie=c.split(",").map(pe=>pe.trim()).filter(Boolean),Ie=await iv(l.trim(),d.trim(),30,ie.length>0?ie:void 0);v(Ie),Ie.length===0&&w("No open issues found")}catch(ie){w(fe(ie)||"Failed to fetch issues")}finally{g(!1)}},[l,d,c]),B=a.useCallback(async()=>{if(!l.trim()||!d.trim()){w("Repository must be selected");return}g(!0),w(null),j([]),N(null);try{const ie=await rv(l.trim(),d.trim(),30);j(ie),ie.length===0&&w("No open pull requests found")}catch(ie){w(fe(ie)||"Failed to fetch pull requests")}finally{g(!1)}},[l,d]);a.useEffect(()=>{if(!t||!l.trim()||!d.trim()||h||R)return;const ie={owner:l.trim(),repo:d.trim(),labels:c.trim(),tab:p};X.current?.owner===ie.owner&&X.current?.repo===ie.repo&&X.current?.labels===ie.labels&&X.current?.tab===ie.tab||(X.current=ie,p==="issues"?de():B())},[l,d,c,p,t,h,R,de,B]),a.useEffect(()=>{if(!t)return;const ie=Ie=>{Ie.key==="Escape"&&n()};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[t,n]),a.useEffect(()=>{if(!t)return;const ie=()=>{G(window.innerWidth<=KM)};return ie(),window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[t]);const J=a.useCallback(ie=>{k(ie),K&&O("preview")},[K]),D=a.useCallback(ie=>{N(ie),K&&O("preview")},[K]),he=a.useCallback(()=>{O("list")},[]),q=a.useCallback(async()=>{if(p==="issues"){if(y===null)return;E(!0),w(null);try{const ie=await av(l.trim(),d.trim(),y,r);s(ie),n()}catch(ie){const Ie=fe(ie);Ie?.includes("already imported")?w(Ie):w(Ie||"Failed to import issue")}finally{E(!1)}}else{if(_===null)return;E(!0),w(null);try{const ie=await lv(l.trim(),d.trim(),_,r);s(ie),n()}catch(ie){const Ie=fe(ie);Ie?.includes("already imported")?w(Ie):w(Ie||"Failed to import pull request")}finally{E(!1)}}},[p,y,_,l,d,s,n]),W=b.find(ie=>ie.number===y),me=A.find(ie=>ie.number===_);if(!t)return null;const Re=I.length>0,ve=I.length===1,Me=b.filter(ie=>C.has(ie.html_url)).length,_e=A.filter(ie=>C.has(ie.html_url)).length,De=M==="No open issues found",Oe=M==="No open pull requests found",ze=p==="issues"?De:Oe,Be=!!M&&!De&&b.length===0&&!h,Ae=!!M&&!Oe&&A.length===0&&!h,Ce=p==="issues"?Be:Ae,Ge=h||b.length>0||De||Be,Te=h||A.length>0||Oe||Ae,Xe=p==="issues"?Ge:Te,re=!!M&&b.length>0&&!De,Z=!!M&&A.length>0&&!Oe,ye=p==="issues"?re:Z;return e.jsx("div",{className:"modal-overlay open",onClick:ie=>ie.target===ie.currentTarget&&n(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg github-import-modal",children:[e.jsxs("div",{className:"modal-header github-import-modal__header",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Import from GitHub"}),e.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),e.jsxs("div",{className:"modal-body github-import-modal__body",children:[e.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[e.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{f("issues"),N(null)},disabled:h||R,children:[e.jsx(Vr,{size:16}),e.jsx("span",{children:"Issues"})]}),e.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),k(null)},disabled:h||R,children:[e.jsx(ts,{size:16}),e.jsx("span",{children:"Pull Requests"})]})]}),e.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[e.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:ee?e.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[e.jsx(ct,{size:16,className:"spin"}),e.jsx("span",{children:"Detecting…"})]}):Re?ve?e.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[e.jsx("span",{className:"github-import-remote-pill__name",children:I[0].name}),e.jsxs("span",{className:"github-import-remote-pill__repo",children:[I[0].owner,"/",I[0].repo]})]}):e.jsxs("div",{className:"github-import-remote-select",children:[e.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),e.jsxs("select",{id:"gh-remote",value:T,onChange:ie=>V(ie.target.value),disabled:h||R,"aria-label":"Select Git remote",children:[e.jsx("option",{value:"",children:"Select remote…"}),I.map(ie=>e.jsxs("option",{value:ie.name,children:[ie.name," (",ie.owner,"/",ie.repo,")"]},ie.name))]})]}):e.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),e.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),e.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:c,onChange:ie=>u(ie.target.value),onKeyDown:ie=>ie.key==="Enter"&&de(),disabled:h||R||!Re,"aria-label":"Filter issues by labels"})]}):e.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",l||"selected remote"]})}),e.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:e.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?de:B,disabled:h||R||!l.trim()||!d.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!ee&&!Re&&e.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"No GitHub remotes detected"}),e.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),e.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),ye&&e.jsx("div",{className:"form-error github-import-banner",role:"alert",children:M}),e.jsxs("div",{className:"github-import-workspace",children:[e.jsxs("section",{className:`github-import-list-pane ${K?"mobile":""} ${P==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[e.jsxs("div",{className:"github-import-pane-header",children:[e.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&e.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[e.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),e.jsxs("span",{children:[Me," imported"]})]}),p==="pulls"&&A.length>0&&e.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[e.jsxs("span",{children:[A.length," pull request",A.length===1?"":"s"]}),e.jsxs("span",{children:[_e," imported"]})]})]}),e.jsxs("div",{className:"github-import-pane-content",children:[!Xe&&e.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:e.jsxs("div",{children:[e.jsx("strong",{children:"Nothing loaded yet"}),e.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&e.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[e.jsx(ct,{size:16,className:"spin"}),e.jsxs("div",{children:[e.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),e.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),Ce&&e.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:e.jsxs("div",{children:[e.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),e.jsx("span",{children:M})]})}),ze&&e.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:e.jsxs("div",{children:[e.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),e.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(ie=>{const Ie=C.has(ie.html_url);return e.jsxs("div",{className:`issue-item ${y===ie.number?"selected":""} ${Ie?"imported":""}`,onClick:()=>!Ie&&J(ie.number),children:[e.jsx("input",{type:"radio",name:"issue",checked:y===ie.number,onChange:()=>J(ie.number),disabled:Ie,"aria-label":`Select issue #${ie.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",ie.number]}),e.jsx("span",{className:"issue-title",children:ie.title})]}),ie.labels.length>0&&e.jsx("span",{className:"issue-labels",children:ie.labels.map(pe=>e.jsx("span",{className:"label-chip",children:pe.name},pe.name))})]}),Ie&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},ie.number)})}),p==="pulls"&&A.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:A.map(ie=>{const Ie=C.has(ie.html_url);return e.jsxs("div",{className:`issue-item ${_===ie.number?"selected":""} ${Ie?"imported":""}`,onClick:()=>!Ie&&D(ie.number),children:[e.jsx("input",{type:"radio",name:"pull",checked:_===ie.number,onChange:()=>D(ie.number),disabled:Ie,"aria-label":`Select pull request #${ie.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",ie.number]}),e.jsx("span",{className:"issue-title",children:ie.title})]}),e.jsxs("span",{className:"pull-branch-info",children:[ie.headBranch," → ",ie.baseBranch]})]}),Ie&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},ie.number)})})]})]}),e.jsxs("section",{className:`github-import-preview-pane ${K?"mobile":""} ${P==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[e.jsxs("div",{className:"github-import-pane-header",children:[K&&e.jsxs("button",{className:"github-import-back-button",onClick:he,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[e.jsx(sa,{size:16}),e.jsx("span",{children:"Back"})]}),e.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),e.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&W?e.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[e.jsxs("div",{className:"preview-meta",children:["Issue #",W.number]}),e.jsx("div",{className:"preview-title",children:W.title}),e.jsx("div",{className:"preview-body",children:W.body?W.body.slice(0,200)+(W.body.length>200?"…":""):"(no description)"})]}):p==="issues"?e.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:e.jsxs("div",{children:[e.jsx("strong",{children:"No issue selected"}),e.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&me?e.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[e.jsxs("div",{className:"preview-meta",children:["Pull Request #",me.number]}),e.jsx("div",{className:"preview-title",children:me.title}),e.jsxs("div",{className:"preview-branch",children:[e.jsx("strong",{children:"Branch:"})," ",me.headBranch," → ",me.baseBranch]}),e.jsx("div",{className:"preview-body",children:me.body?me.body.slice(0,200)+(me.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?e.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:e.jsxs("div",{children:[e.jsx("strong",{children:"No pull request selected"}),e.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),e.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[e.jsx("button",{className:"btn",onClick:n,disabled:R,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:q,disabled:(p==="issues"?y===null:_===null)||R,children:R?e.jsx(ct,{size:14,className:"spin"}):"Import"})]})]})})}const JM=["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 YM(t,n){return t&&n?`${t}/${n}`:""}function QM(t){if(!t)return{provider:void 0,modelId:void 0};const n=t.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function XM({isOpen:t,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:l,projectId:o,resumeSessionId:d}){const[m,c]=a.useState(""),[u,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,y]=a.useState([]),[k,A]=a.useState(null),j=a.useRef(!1),[_,N]=a.useState(""),[M,w]=a.useState(!0),[R,E]=a.useState(!1),[I,L]=a.useState(!1),ee=a.useRef(null),$=a.useRef(null),T=a.useRef(null),[S,Y]=a.useState(d??null),K=a.useMemo(()=>Ci(),[]),{isLockedByOther:G,takeControl:P,isLoading:O}=el(t?S:null),{activeTabMap:X,broadcastUpdate:C,broadcastCompleted:V,broadcastLock:de,broadcastUnlock:B,broadcastHeartbeat:J}=ra(),[D,he]=a.useState(void 0),[q,W]=a.useState(void 0),[me,Re]=a.useState([]),[ve,Me]=a.useState(!1),[_e,De]=a.useState(null),[Oe,ze]=a.useState([]),[Be,Ae]=a.useState([]),Ce=a.useRef(null),Ge=YM(D,q),Te=a.useCallback((ce,qe)=>{if(!ce||!qe)return"Using default";const We=me.find(Pe=>Pe.provider===ce&&Pe.id===qe);return We?`${We.provider}/${We.id}`:`${ce}/${qe}`},[me]),Xe=a.useCallback(async()=>{Me(!0),De(null);try{const ce=await Kn();Re(ce.models),ze(ce.favoriteProviders),Ae(ce.favoriteModels)}catch(ce){De(fe(ce)||"Failed to load models")}finally{Me(!1)}},[]),re=a.useCallback(ce=>{ze(qe=>{const We=qe,nt=We.includes(ce)?We.filter(kt=>kt!==ce):[ce,...We];return Wt({favoriteProviders:nt,favoriteModels:Be}).catch(()=>{ze(We)}),nt})},[Be]),Z=a.useCallback(ce=>{Ae(qe=>{const We=qe,nt=We.includes(ce)?We.filter(kt=>kt!==ce):[ce,...We];return Wt({favoriteProviders:Oe,favoriteModels:nt}).catch(()=>{Ae(We)}),nt})},[Oe]),ye=a.useCallback(ce=>{$.current?.close();const qe=ay(ce,o,{onThinking:We=>{N(Pe=>Pe+We),C({sessionId:ce,status:"generating",needsInput:!1,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onQuestion:We=>{E(!1),L(!1),Ri(o),h({type:"question",session:{sessionId:ce,currentQuestion:We,summary:null}}),N(""),C({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onSummary:We=>{E(!1),L(!1),Ri(o),h({type:"summary",session:{sessionId:ce,currentQuestion:null,summary:We},summary:We}),A(We),N(""),C({sessionId:ce,status:"complete",needsInput:!1,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onError:We=>{const Pe=We||"Session failed while contacting the AI.";E(!1),L(!1),p(null),h(nt=>nt.type==="question"||nt.type==="summary"||nt.type==="error"?{type:"error",session:nt.session,errorMessage:Pe}:{type:"error",session:{sessionId:ce,currentQuestion:null,summary:null},errorMessage:Pe}),N(""),T.current=ce,C({sessionId:ce,status:"error",needsInput:!1,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null}),V({sessionId:ce,status:"error"})},onComplete:()=>{E(!1),L(!1),T.current=null,V({sessionId:ce,status:"complete"})},onConnectionStateChange:We=>{E(We==="reconnecting")}});$.current=qe},[V,C,m,o,K]),ie=a.useCallback(async ce=>{const qe=ce??m;if(qe.trim()){p(null),N(""),y([]),b([]),E(!1),h({type:"loading"});try{const We=D&&q?{planningModelProvider:D,planningModelId:q}:void 0,{sessionId:Pe}=await Hv(qe.trim(),o,We);T.current=Pe,Y(Pe),ye(Pe),b([])}catch(We){E(!1),p(fe(We)||"Failed to start planning session"),h({type:"initial"}),T.current=null,Y(null)}}},[ye,m,q,D,o]);a.useEffect(()=>{t&&u.type==="initial"&&ee.current?.focus()},[t,u.type]),a.useEffect(()=>{t&&Xe()},[t,Xe]),a.useEffect(()=>{if(t&&l&&!j.current&&u.type==="initial"){c(l);const ce=setTimeout(()=>{j.current=!0,ie(l)},0);return()=>clearTimeout(ce)}else if(t&&!l&&!j.current&&u.type==="initial"){const ce=Ow(o);ce&&c(ce)}},[t,l,u.type,ie]),a.useEffect(()=>{if(!t||!d||u.type!=="initial")return;let ce=!1;return(async()=>{try{const qe=await ni(d);if(ce||!qe)return;T.current=d,Y(d);const We=Ji(qe.conversationHistory);if(y(We),b(We.map(Pe=>Pe.response).filter(Pe=>!!(Pe&&typeof Pe=="object"&&!Array.isArray(Pe)))),qe.status==="awaiting_input"&&qe.currentQuestion){Ri(o);const Pe=JSON.parse(qe.currentQuestion);h({type:"question",session:{sessionId:d,currentQuestion:Pe,summary:null}}),qe.thinkingOutput&&N(qe.thinkingOutput),ye(d)}else if(qe.status==="complete"&&qe.result){Ri(o);const Pe=JSON.parse(qe.result);h({type:"summary",session:{sessionId:d,currentQuestion:null,summary:Pe},summary:Pe}),A(Pe)}else qe.status==="generating"?(h({type:"loading"}),qe.thinkingOutput&&N(qe.thinkingOutput),ye(d)):qe.status==="error"&&(p(null),h({type:"error",session:{sessionId:d,currentQuestion:null,summary:null},errorMessage:qe.error||"Session failed"}))}catch{p("Failed to resume session")}})(),()=>{ce=!0}},[ye,t,d,u.type,o]),a.useEffect(()=>{t||(j.current=!1,E(!1),L(!1),Y(null))},[t]),a.useEffect(()=>{if(!t){Ce.current&&(B(Ce.current,K),Ce.current=null);return}if(S&&Ce.current!==S){Ce.current&&B(Ce.current,K),de(S,K),Ce.current=S;return}!S&&Ce.current&&(B(Ce.current,K),Ce.current=null)},[de,B,t,S,K]),a.useEffect(()=>{if(!t||!S||Ce.current!==S)return;J(K);const ce=setInterval(()=>{J(K)},3e4);return()=>{clearInterval(ce)}},[J,t,S,K]),a.useEffect(()=>()=>{$.current?.close(),$.current=null,Ce.current&&(B(Ce.current,K),Ce.current=null)},[B,K]),a.useEffect(()=>{if(!t)return;const ce=()=>{$.current?.close(),$.current=null};return window.addEventListener("beforeunload",ce),()=>window.removeEventListener("beforeunload",ce)},[t]);const Ie=a.useCallback(()=>{$.current?.close(),$.current=null,n()},[n]),pe=a.useCallback(()=>{let ce=null;u.type==="question"||u.type==="summary"||u.type==="error"?ce=u.session.sessionId:u.type==="breakdown"?ce=u.sessionId:u.type==="loading"&&(ce=T.current),m&&zw(m,o),$.current?.close(),$.current=null,ce&&dh(ce,o,K).catch(()=>{}),c(""),h({type:"initial"}),p(null),b([]),y([]),A(null),N(""),E(!1),L(!1),he(void 0),W(void 0),T.current=null,Y(null),n()},[m,n,o,K,u]);a.useEffect(()=>{if(!t)return;const ce=qe=>{qe.key==="Escape"&&pe()};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[t,pe]);const Ue=a.useCallback(async ce=>{if(u.type!=="question")return;const{session:qe}=u,We=qe.sessionId,Pe=qe.currentQuestion;if(!Pe){p("No active question in session");return}p(null),b(nt=>[...nt,ce]),y(nt=>[...nt,{question:Pe,response:ce}]),h({type:"loading"}),N("");try{await qv(We,ce,o,K)}catch(nt){p(fe(nt)||"Failed to submit response"),h({type:"question",session:qe})}},[o,K,u]),dt=a.useCallback(async()=>{if(u.type!=="error")return;const ce=u.session;p(null),L(!0),N(""),h({type:"loading"}),ye(ce.sessionId);try{T.current=ce.sessionId,Y(ce.sessionId),await Vv(ce.sessionId,o,K)}catch(qe){let We=qe;if((fe(qe)||"").includes("not in an error state"))try{const nt=await ni(ce.sessionId);if(!nt)throw new Error("Failed to refresh planning session.");if(T.current=nt.id,Y(nt.id),nt.status==="generating")N(nt.thinkingOutput??""),h({type:"loading"});else if(nt.status==="awaiting_input"){if(!nt.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const kt=JSON.parse(nt.currentQuestion);Ri(o),h({type:"question",session:{sessionId:nt.id,currentQuestion:kt,summary:null}}),$.current?.isConnected()||ye(nt.id)}else if(nt.status==="complete"){if(!nt.result)throw new Error("Planning session is complete but has no result.");const kt=JSON.parse(nt.result);Ri(o),h({type:"summary",session:{sessionId:nt.id,currentQuestion:null,summary:kt},summary:kt}),A(kt)}else nt.status==="error"&&h({type:"error",session:{sessionId:nt.id,currentQuestion:null,summary:null},errorMessage:nt.error||"Retry failed. Please try again."});E(!1);return}catch(nt){We=nt}$.current?.close(),$.current=null,h({type:"error",session:ce,errorMessage:fe(We)||"Retry failed. Please try again."}),E(!1)}finally{L(!1)}},[ye,o,K,u]),ht=a.useCallback(async()=>{if(u.type==="summary"){p(null),h({type:"loading"});try{const ce=await Wv(u.session.sessionId,k??void 0,o);s(ce),pe()}catch(ce){p(fe(ce)||"Failed to create task"),h({type:"summary",session:u.session,summary:u.summary})}}},[k,u,o,s,pe]),ue=a.useCallback(async()=>{if(u.type==="summary"){p(null),h({type:"loading"});try{const ce=await Kv(u.session.sessionId,k??void 0,o);Y(ce.sessionId),h({type:"breakdown",sessionId:ce.sessionId,subtasks:ce.subtasks,dirty:!1})}catch(ce){p(fe(ce)||"Failed to start breakdown"),h({type:"summary",session:u.session,summary:u.summary})}}},[k,u,o]),te=a.useCallback(async()=>{if(u.type==="breakdown"){p(null),h({type:"creating"});try{const ce=await Gv(u.sessionId,u.subtasks,o);i(ce.tasks),c(""),h({type:"initial"}),p(null),b([]),y([]),A(null),N(""),he(void 0),W(void 0),T.current=null,Y(null),n()}catch(ce){p(fe(ce)||"Failed to create tasks"),h({type:"breakdown",sessionId:u.sessionId,subtasks:u.subtasks,dirty:u.dirty})}}},[u,i,n,o]),ke=a.useCallback(()=>{if(u.type==="question"&&f.length>0){const ce=f.slice(0,-1);b(ce),h({type:"question",session:u.session})}},[u,f]),Ne=()=>u.type==="question"?Math.min(f.length+1,3):3,Ze=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",xe=S?X.get(S):null,st=xe&&xe.tabId!==K,Ee=!!(st&&!xe.stale),He=G&&(!st||xe.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&pe(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg planning-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx(zs,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Planning Mode"})]}),e.jsxs("div",{className:"modal-header-actions",children:[Ze&&e.jsx("button",{className:"modal-send-to-background",onClick:Ie,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:pe,"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[g&&e.jsx("div",{className:"form-error planning-error",children:g}),R&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ee&&e.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&e.jsxs("div",{className:"planning-initial",children:[e.jsxs("div",{className:"planning-view-scroll",children:[e.jsxs("div",{className:"planning-intro",children:[e.jsx(Ln,{size:32,className:"icon-triage-lg"}),e.jsx("h4",{children:"Transform your idea into a detailed task"}),e.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."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),e.jsx("textarea",{ref:ee,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:m,onChange:ce=>c(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&!ce.shiftKey&&m.trim()&&(ce.preventDefault(),ie())}})]}),e.jsxs("div",{className:"planning-examples",children:[e.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),e.jsx("div",{className:"planning-example-chips",children:JM.map((ce,qe)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>c(ce),children:ce.length>40?ce.slice(0,40)+"...":ce},qe))})]}),e.jsxs("div",{className:"planning-model-select-group",children:[e.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",ve&&e.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),e.jsx(Kt,{id:"planning-modal-model",label:"Planning Model",value:Ge,onChange:ce=>{const{provider:qe,modelId:We}=QM(ce);he(qe),W(We)},models:me,disabled:ve,favoriteProviders:Oe,onToggleFavorite:re,favoriteModels:Be,onToggleModelFavorite:Z}),_e&&e.jsxs("div",{className:"form-hint form-hint-error",children:[_e," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{Xe()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${D&&q?"model-badge-custom":"model-badge-default"}`,children:Te(D,q)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ie(),disabled:!m.trim(),children:[e.jsx(zs,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),u.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ct,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:_?"AI is thinking...":"Generating next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&_&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:_})})]})]}),u.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:v}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:u.errorMessage}),e.jsxs("div",{className:"ai-error-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:()=>void dt(),disabled:I,children:[I?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:pe,disabled:I,children:"Dismiss"})]})]})]})}),u.type==="creating"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ct,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:"Creating tasks..."})]}),u.type==="question"&&u.session.currentQuestion&&e.jsx("div",{className:"planning-question",children:e.jsx(ZM,{question:u.session.currentQuestion,progress:Ne(),historyEntries:v,onSubmit:Ue,onBack:f.length>0?ke:void 0})}),u.type==="summary"&&k&&e.jsx(eA,{summary:k,historyEntries:v,onSummaryChange:A,tasks:r,onCreateTask:ht,onBreakIntoTasks:ue,onRefine:()=>{h({type:"question",session:u.session})},isLoading:!1}),u.type==="breakdown"&&e.jsx(nA,{subtasks:u.subtasks,dirty:u.dirty,isLoading:!1,onUpdateSubtasks:ce=>h({...u,subtasks:ce,dirty:!0}),onCreateTasks:te,onBack:()=>{const qe={sessionId:u.sessionId,currentQuestion:null,summary:k??null};k&&h({type:"summary",session:qe,summary:k})}}),G&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(Kr,{size:16}),e.jsx("span",{children:He?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),He&&e.jsx("button",{type:"button",onClick:()=>{P()},disabled:O,className:"btn btn-primary session-lock-take-control",children:O?"Taking control...":"Take Control"})]})})]})]})}):null}function ZM({question:t,progress:n,historyEntries:s,onSubmit:i,onBack:r}){const[l,o]=a.useState({}),[d,m]=a.useState(""),c=a.useCallback(()=>{t.type==="text"?i({[t.id]:d}):t.type==="confirm"?i({[t.id]:l[t.id]===!0}):i(l)},[t,l,d,i]);a.useEffect(()=>{o({}),m("")},[t.id]);const u=()=>{switch(t.type){case"text":return d.trim().length>0;case"single_select":return l[t.id]!==void 0;case"multi_select":return Array.isArray(l[t.id])&&l[t.id].length>0;case"confirm":return l[t.id]!==void 0;default:return!0}};return e.jsxs("div",{className:"planning-question-form",children:[e.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:s}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-question-panel",children:[e.jsxs("div",{className:"planning-progress",children:[e.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>e.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),e.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),e.jsxs("div",{className:"planning-question-content",children:[e.jsx("h4",{className:"planning-question-text",children:t.question}),t.description&&e.jsx("p",{className:"planning-question-desc",children:t.description}),e.jsxs("div",{className:"planning-options",children:[t.type==="text"&&e.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:d,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&d.trim()&&(h.preventDefault(),c())}}),t.type==="single_select"&&t.options&&e.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:t.options.map(h=>e.jsxs("label",{className:"planning-option planning-option--radio",children:[e.jsx("input",{type:"radio",name:t.id,value:h.id,checked:l[t.id]===h.id,onChange:()=>o({[t.id]:h.id})}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&e.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),t.type==="multi_select"&&t.options&&e.jsx("div",{className:"planning-checkbox-group",children:t.options.map(h=>{const g=l[t.id]||[];return e.jsxs("label",{className:"planning-option planning-option--checkbox",children:[e.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(b=>b!==h.id);o({[t.id]:f})}}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&e.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),t.type==="confirm"&&e.jsxs("div",{className:"planning-confirm-group",children:[e.jsxs("button",{className:`planning-confirm-btn ${l[t.id]===!0?"selected":""}`,onClick:()=>o({[t.id]:!0}),children:[e.jsx(en,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${l[t.id]===!1?"selected":""}`,onClick:()=>o({[t.id]:!1}),children:[e.jsx(Ft,{size:18}),"No"]})]})]})]})]})]}),e.jsxs("div",{className:"planning-actions",children:[r&&e.jsxs("button",{className:"btn",onClick:r,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Back"]}),e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:c,disabled:!u(),children:["Continue",e.jsx(Ba,{size:16,className:"icon-ml-4"})]})]})]})}function eA({summary:t,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:l,onRefine:o,isLoading:d}){const[m,c]=a.useState(!1),[u,h]=a.useState(t.suggestedDependencies),g=p=>{const f=u.includes(p)?u.filter(b=>b!==p):[...u,p];h(f),s({...t,suggestedDependencies:f})};return e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(en,{size:24,className:"icon-success"}),e.jsx("h4",{children:"Planning Complete!"}),e.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),e.jsxs("div",{className:"planning-summary-form",children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{children:["Description",e.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>c(!m),children:m?"Collapse":"Expand"})]}),e.jsx("textarea",{className:`planning-textarea ${m?"expanded":""}`,rows:m?10:4,value:t.description,onChange:p=>s({...t,description:p.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Suggested Size"}),e.jsxs("select",{className:"planning-size-select",value:t.suggestedSize,onChange:p=>s({...t,suggestedSize:p.target.value}),disabled:d,children:[e.jsx("option",{value:"S",children:"S (Small)"}),e.jsx("option",{value:"M",children:"M (Medium)"}),e.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Suggested Dependencies"}),e.jsx("div",{className:"planning-deps-list",children:i.map(p=>e.jsxs("label",{className:`planning-dep-chip ${u.includes(p.id)?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:u.includes(p.id),onChange:()=>g(p.id)}),e.jsx("span",{className:"planning-dep-id",children:p.id}),e.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Key Deliverables"}),e.jsx("ul",{className:"planning-deliverables",children:t.keyDeliverables.map((p,f)=>e.jsx("li",{children:p},f))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:o,disabled:d,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Refine Further"]}),e.jsxs("div",{className:"planning-summary-actions-right",children:[e.jsx("button",{className:"btn",onClick:l,disabled:d,title:"Break the plan into multiple tasks with dependencies",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),e.jsx("button",{className:"btn btn-primary",onClick:r,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function im(t){const n=new Map(t.map(l=>[l.id,l.dependsOn])),s=new Set,i=new Set,r=l=>{if(s.has(l))return!0;if(i.has(l))return!1;s.add(l);for(const o of n.get(l)??[])if(n.has(o)&&r(o))return!0;return s.delete(l),i.add(l),!1};return t.some(l=>r(l.id))}function tA(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function nA({subtasks:t,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:l}){const[o,d]=a.useState(null),[m,c]=a.useState(null),[u,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>t.length===0||t.some(M=>!M.title.trim())?!0:im(t),[t]),f=a.useCallback((M,w)=>{i(t.map(R=>R.id===M?{...R,...w}:R))},[t,i]),b=a.useCallback(()=>{i([...t,tA(t.length+1)])},[t,i]),v=a.useCallback(M=>{i(t.filter(w=>w.id!==M).map(w=>({...w,dependsOn:w.dependsOn.filter(R=>R!==M)})))},[t,i]),y=a.useCallback((M,w)=>{if(w<0||w>=t.length)return;const R=[...t],[E]=R.splice(M,1);R.splice(w,0,E),i(R)},[t,i]),k=a.useCallback(M=>w=>{d(M),w.dataTransfer.setData("text/plain",M),w.dataTransfer.effectAllowed="move"},[]),A=a.useCallback(()=>{d(null),c(null),h(null)},[]),j=a.useCallback(M=>w=>{if(w.preventDefault(),M===o)return;const R=w.currentTarget.getBoundingClientRect(),E=R.top+R.height/2,I=w.clientY<E?"before":"after";c(M),h(I)},[o]),_=a.useCallback(M=>w=>{w.preventDefault();const R=w.dataTransfer.getData("text/plain");if(!R||R===M){A();return}const E=t.findIndex(T=>T.id===R),I=t.findIndex(T=>T.id===M);if(E===-1||I===-1){A();return}const L=[...t],[ee]=L.splice(E,1);let $=I;u==="after"&&E<I&&$--,u==="after"&&$++,L.splice($,0,ee),i(L),A()},[t,u,i,A]),N=a.useCallback(M=>{const w=M.currentTarget.getBoundingClientRect(),R=M.clientX,E=M.clientY;(R<w.left||R>w.right||E<w.top||E>w.bottom)&&(c(null),h(null))},[]);return e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(Wr,{size:24,className:"icon-triage"}),e.jsx("h4",{children:"Break into Tasks"}),e.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, and dependencies before creating."})]}),e.jsxs("div",{className:"planning-summary-form",children:[t.map((M,w)=>{const R=o===M.id,E=m===M.id,I=["task-detail-section","subtask-item",R?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&u==="before"?"subtask-item-drop-before":"",E&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:I,"data-testid":`subtask-item-${w}`,draggable:!s,onDragStart:k(M.id),onDragEnd:A,onDragOver:j(M.id),onDrop:_(M.id),onDragLeave:N,children:[e.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[e.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[e.jsx(Vo,{size:16}),e.jsx("strong",{children:M.id})]}),e.jsxs("div",{className:"subtask-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>y(w,w-1),disabled:s||w===0,title:"Move up","aria-label":"Move subtask up",children:e.jsx(bi,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>y(w,w+1),disabled:s||w===t.length-1,title:"Move down","aria-label":"Move subtask down",children:e.jsx(Oa,{size:14})}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(M.id),disabled:s,children:[e.jsx(Ut,{size:14})," Remove"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title"}),e.jsx("input",{ref:L=>{g.current[w]=L},value:M.title,onChange:L=>f(M.id,{title:L.target.value}),onKeyDown:L=>{L.key==="Enter"&&(L.preventDefault(),w<t.length-1&&g.current[w+1]?.focus())},disabled:s})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{rows:3,value:M.description,onChange:L=>f(M.id,{description:L.target.value}),disabled:s})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Size"}),e.jsxs("select",{className:"planning-size-select",value:M.suggestedSize,onChange:L=>f(M.id,{suggestedSize:L.target.value}),disabled:s,children:[e.jsx("option",{value:"S",children:"S"}),e.jsx("option",{value:"M",children:"M"}),e.jsx("option",{value:"L",children:"L"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Dependencies"}),e.jsxs("div",{className:"planning-deps-list",children:[t.slice(0,w).filter(L=>L.id!==M.id).map(L=>{const ee=M.dependsOn.includes(L.id);return e.jsxs("label",{className:`planning-dep-chip ${ee?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:ee,onChange:()=>{const $=ee?M.dependsOn.filter(T=>T!==L.id):[...M.dependsOn,L.id];f(M.id,{dependsOn:$})},disabled:s}),e.jsx("span",{className:"planning-dep-id",children:L.id}),e.jsx("span",{className:"planning-dep-title",children:L.title||"Untitled"})]},L.id)}),w===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),w>0&&t.slice(0,w).filter(L=>L.id!==M.id).length===0&&e.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},M.id)}),e.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[e.jsx(qt,{size:16,className:"icon-mr-6"})," Add subtask"]}),im(t)&&e.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:l,disabled:s,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),e.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):e.jsx(e.Fragment,{children:"Create Tasks"})})]})]})}function sA(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function am(t){const n=new Map(t.map(l=>[l.id,l.dependsOn])),s=new Set,i=new Set,r=l=>{if(s.has(l))return!0;if(i.has(l))return!1;s.add(l);for(const o of n.get(l)??[])if(n.has(o)&&r(o))return!0;return s.delete(l),i.add(l),!1};return t.some(l=>r(l.id))}function iA({isOpen:t,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:l,resumeSessionId:o}){const[d,m]=a.useState({type:"initial"}),[c,u]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[b,v]=a.useState(!0),[y,k]=a.useState(!1),[A,j]=a.useState(!1),[_,N]=a.useState(s),[M,w]=a.useState(null),[R,E]=a.useState(!1),[I,L]=a.useState(null),[ee,$]=a.useState(null),[T,S]=a.useState(null),Y=a.useRef(null),K=a.useRef([]),G=a.useRef(!1),P=a.useRef(null),O=d.type==="generating"||d.type==="editing"||d.type==="creating"||d.type==="error"?d.sessionId:null,X=a.useMemo(()=>Ci(),[]),{isLockedByOther:C,takeControl:V,isLoading:de}=el(t?O:null),{activeTabMap:B,broadcastUpdate:J,broadcastCompleted:D,broadcastLock:he,broadcastUnlock:q,broadcastHeartbeat:W}=ra(),me=a.useMemo(()=>c.length===0||c.some(ue=>!ue.title.trim())?!0:am(c),[c]),Re=d.type==="generating"||d.type==="editing"||d.type==="error",ve=O?B.get(O):null,Me=ve&&ve.tabId!==X,_e=!!(Me&&!ve.stale),De=C&&(!Me||ve.stale),Oe=a.useCallback(()=>{_&&Bw(_,l),Y.current?.close(),Y.current=null,m({type:"initial"}),u([]),g([]),f(""),v(!0),k(!1),j(!1),w(null),E(!1),G.current=!1},[_,l]),ze=a.useCallback(()=>{Y.current?.close(),Y.current=null,n()},[n]),Be=a.useCallback(async()=>{if(!((R||d.type==="editing"||d.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(O)try{await hh(O,l,X)}catch{}Oe(),n()}},[R,n,Oe,O,X,d.type,l]),Ae=a.useCallback(ue=>{Y.current?.close(),Y.current=ky(ue,l,{onThinking:te=>{f(ke=>ke+te),J({sessionId:ue,status:"generating",needsInput:!1,owningTabId:X,type:"subtask",title:_.trim()||"Subtask breakdown",projectId:l??null})},onSubtasks:te=>{k(!1),j(!1),yl(l),u(te),m({type:"editing",sessionId:ue}),E(!1),J({sessionId:ue,status:"awaiting_input",needsInput:!0,owningTabId:X,type:"subtask",title:_.trim()||"Subtask breakdown",projectId:l??null})},onError:te=>{const ke=te||"Session failed while contacting the AI.";k(!1),j(!1),w(null),m({type:"error",sessionId:ue,errorMessage:ke}),J({sessionId:ue,status:"error",needsInput:!1,owningTabId:X,type:"subtask",title:_.trim()||"Subtask breakdown",projectId:l??null}),D({sessionId:ue,status:"error"})},onComplete:()=>{D({sessionId:ue,status:"complete"})},onConnectionStateChange:te=>{k(te==="reconnecting")}})},[D,J,_,l,X]),Ce=a.useCallback(async()=>{if(_.trim()){w(null),g([]),f(""),k(!1);try{const{sessionId:ue}=await xy(_.trim(),l);m({type:"generating",sessionId:ue}),Ae(ue)}catch(ue){w(fe(ue)||"Failed to start subtask breakdown"),m({type:"initial"})}}},[Ae,_,l]);a.useEffect(()=>{if(!t){Oe();return}if(t&&s&&!G.current)N(s),G.current=!0,Ce();else if(t&&!s&&!G.current){const ue=Uw(l);ue&&N(ue)}},[t,s,Ce,Oe]),a.useEffect(()=>{!t||!o||d.type!=="initial"||(async()=>{try{const ue=await ni(o);if(!ue)return;const te=Ji(ue.conversationHistory);if(g(te),ue.status==="generating"||ue.status==="awaiting_input")f(ue.thinkingOutput??""),m({type:"generating",sessionId:o}),Ae(o);else if(ue.status==="complete"&&ue.result){yl(l);const ke=JSON.parse(ue.result);u(ke),m({type:"editing",sessionId:o})}else ue.status==="error"&&(w(null),m({type:"error",sessionId:o,errorMessage:ue.error??"Session encountered an error"}))}catch(ue){w(fe(ue)||"Failed to resume session")}})()},[Ae,t,o,d.type,l]),a.useEffect(()=>{if(!t){P.current&&(q(P.current,X),P.current=null);return}if(O&&P.current!==O){P.current&&q(P.current,X),he(O,X),P.current=O;return}!O&&P.current&&(q(P.current,X),P.current=null)},[he,q,t,O,X]),a.useEffect(()=>{if(!t||!O||P.current!==O)return;W(X);const ue=setInterval(()=>{W(X)},3e4);return()=>{clearInterval(ue)}},[W,t,O,X]),a.useEffect(()=>()=>{Y.current?.close(),P.current&&(q(P.current,X),P.current=null)},[q,X]),a.useEffect(()=>{if(!t)return;const ue=te=>{te.key==="Escape"&&(te.preventDefault(),Be())};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[t,Be]);const Ge=a.useCallback((ue,te)=>{u(ke=>ke.map(Ne=>Ne.id===ue?{...Ne,...te}:Ne)),E(!0)},[]),Te=a.useCallback(()=>{u(ue=>[...ue,sA(ue.length+1)]),E(!0)},[]),Xe=a.useCallback(ue=>{u(te=>te.filter(ke=>ke.id!==ue).map(ke=>({...ke,dependsOn:ke.dependsOn.filter(Ne=>Ne!==ue)}))),E(!0)},[]),re=a.useCallback(ue=>te=>{L(ue),te.dataTransfer.setData("text/plain",ue),te.dataTransfer.effectAllowed="move"},[]),Z=a.useCallback(()=>{L(null),$(null),S(null)},[]),ye=a.useCallback(ue=>te=>{if(te.preventDefault(),ue===I)return;const ke=te.currentTarget.getBoundingClientRect(),Ne=ke.top+ke.height/2,Ze=te.clientY<Ne?"before":"after";$(ue),S(Ze)},[I]),ie=a.useCallback(ue=>te=>{te.preventDefault();const ke=te.dataTransfer.getData("text/plain");if(!ke||ke===ue){L(null),$(null),S(null);return}u(Ne=>{const Ze=Ne.findIndex(ce=>ce.id===ke),xe=Ne.findIndex(ce=>ce.id===ue);if(Ze===-1||xe===-1)return Ne;const st=[...Ne],[Ee]=st.splice(Ze,1);let He=xe;return T==="after"&&Ze<xe&&He--,T==="after"&&He++,st.splice(He,0,Ee),st}),E(!0),L(null),$(null),S(null)},[T]),Ie=a.useCallback(ue=>{const te=ue.currentTarget.getBoundingClientRect(),ke=ue.clientX,Ne=ue.clientY;(ke<te.left||ke>te.right||Ne<te.top||Ne>te.bottom)&&($(null),S(null))},[]),pe=a.useCallback((ue,te)=>{te<0||te>=c.length||(u(ke=>{const Ne=[...ke],[Ze]=Ne.splice(ue,1);return Ne.splice(te,0,Ze),Ne}),E(!0))},[c.length]),Ue=a.useCallback(ue=>{K.current[ue+1]?.focus()},[]),dt=a.useCallback(async()=>{if(!(!O||me)){w(null),m({type:"creating",sessionId:O});try{const ue=await jy(O,c,r,l);i(ue.tasks),Oe(),n()}catch(ue){w(fe(ue)||"Failed to create tasks"),m({type:"editing",sessionId:O})}}},[me,n,i,r,l,Oe,O,c]),ht=a.useCallback(async()=>{if(d.type!=="error")return;const ue=d.sessionId;w(null),j(!0),f(""),m({type:"generating",sessionId:ue}),Ae(ue);try{await vy(ue,l,X)}catch(te){let ke=te;if((fe(te)||"").includes("not in an error state"))try{const Ze=await ni(ue);if(!Ze)throw new Error("Failed to refresh subtask session.");if(g(Ji(Ze.conversationHistory)),Ze.status==="generating"||Ze.status==="awaiting_input")f(Ze.thinkingOutput??""),m({type:"generating",sessionId:Ze.id}),Y.current?.isConnected()||Ae(Ze.id);else if(Ze.status==="complete"){if(!Ze.result)throw new Error("Subtask session is complete but has no result.");yl(l);const xe=JSON.parse(Ze.result);u(xe),m({type:"editing",sessionId:Ze.id}),E(!1)}else Ze.status==="error"&&m({type:"error",sessionId:Ze.id,errorMessage:Ze.error??"Retry failed. Please try again."});k(!1);return}catch(Ze){ke=Ze}Y.current?.close(),Y.current=null,m({type:"error",sessionId:ue,errorMessage:fe(ke)||"Retry failed. Please try again."}),k(!1)}finally{j(!1)}},[Ae,l,X,d]);return t?e.jsx("div",{className:"modal-overlay open",onClick:ue=>ue.target===ue.currentTarget&&void Be(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg planning-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx(Wr,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Subtask Breakdown"})]}),e.jsxs("div",{className:"modal-header-actions",children:[Re&&e.jsx("button",{className:"modal-send-to-background",onClick:ze,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:()=>void Be(),"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[M&&e.jsx("div",{className:"form-error planning-error",children:M}),y&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),_e&&e.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&e.jsx("div",{className:"planning-initial",children:e.jsxs("div",{className:"planning-view-scroll",children:[e.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),e.jsx("pre",{className:"planning-thinking-output",children:_})]})}),d.type==="generating"&&e.jsxs("div",{className:"planning-loading",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:h,defaultShowThinking:!0}),e.jsx("div",{className:"conversation-separator"})]}),e.jsx(ct,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:"AI is generating subtasks..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:p})})]})]}),d.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:h,defaultShowThinking:!0}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:d.errorMessage}),e.jsxs("div",{className:"ai-error-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:A,children:[A?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:A?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:()=>void Be(),disabled:A,children:"Cancel"})]})]})]})}),(d.type==="editing"||d.type==="creating")&&e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:h}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(en,{size:24,className:"icon-success"}),e.jsx("h4",{children:"Review your subtasks"}),e.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),e.jsxs("div",{className:"planning-summary-form",children:[c.map((ue,te)=>{const ke=I===ue.id,Ne=ee===ue.id,Ze=["task-detail-section","subtask-item",ke?"subtask-item-dragging":"",Ne?"subtask-item-drop-target":"",Ne&&T==="before"?"subtask-item-drop-before":"",Ne&&T==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:Ze,"data-testid":`subtask-item-${te}`,draggable:d.type!=="creating",onDragStart:re(ue.id),onDragEnd:Z,onDragOver:ye(ue.id),onDrop:ie(ue.id),onDragLeave:Ie,children:[e.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[e.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[e.jsx(Vo,{size:16}),e.jsx("strong",{children:ue.id})]}),e.jsxs("div",{className:"subtask-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pe(te,te-1),disabled:d.type==="creating"||te===0,title:"Move up","aria-label":"Move subtask up",children:e.jsx(bi,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pe(te,te+1),disabled:d.type==="creating"||te===c.length-1,title:"Move down","aria-label":"Move subtask down",children:e.jsx(Oa,{size:14})}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Xe(ue.id),disabled:d.type==="creating",children:[e.jsx(Ut,{size:14})," Remove"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title"}),e.jsx("input",{ref:xe=>{K.current[te]=xe},value:ue.title,onChange:xe=>Ge(ue.id,{title:xe.target.value}),onKeyDown:xe=>{xe.key==="Enter"&&(xe.preventDefault(),Ue(te))},disabled:d.type==="creating"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{rows:8,value:ue.description,onChange:xe=>Ge(ue.id,{description:xe.target.value}),disabled:d.type==="creating"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Size"}),e.jsxs("select",{className:"planning-size-select",value:ue.suggestedSize,onChange:xe=>Ge(ue.id,{suggestedSize:xe.target.value}),disabled:d.type==="creating",children:[e.jsx("option",{value:"S",children:"S"}),e.jsx("option",{value:"M",children:"M"}),e.jsx("option",{value:"L",children:"L"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Dependencies"}),e.jsxs("div",{className:"planning-deps-list",children:[c.slice(0,te).filter(xe=>xe.id!==ue.id).map(xe=>{const st=ue.dependsOn.includes(xe.id);return e.jsxs("label",{className:`planning-dep-chip ${st?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:st,onChange:()=>{const Ee=st?ue.dependsOn.filter(He=>He!==xe.id):[...ue.dependsOn,xe.id];Ge(ue.id,{dependsOn:Ee})},disabled:d.type==="creating"}),e.jsx("span",{className:"planning-dep-id",children:xe.id}),e.jsx("span",{className:"planning-dep-title",children:xe.title||"Untitled"})]},xe.id)}),te===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),te>0&&c.slice(0,te).filter(xe=>xe.id!==ue.id).length===0&&e.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ue.id)}),e.jsxs("button",{type:"button",className:"btn",onClick:Te,disabled:d.type==="creating",children:[e.jsx(qt,{size:16,className:"icon-mr-6"})," Add subtask"]}),am(c)&&e.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsx("button",{className:"btn",onClick:()=>void Be(),disabled:d.type==="creating",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void dt(),disabled:d.type==="creating"||me,children:d.type==="creating"?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):e.jsx(e.Fragment,{children:"Create Tasks"})})]})]}),C&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(Kr,{size:16}),e.jsx("span",{children:De?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),De&&e.jsx("button",{type:"button",onClick:()=>{V()},disabled:de,className:"btn btn-primary session-lock-take-control",children:de?"Taking control...":"Take Control"})]})})]})]})}):null}const aA=5,rA=1e3,lA=45e3;function yr(){return{scrollback:null,connected:null,data:[]}}function oA(t,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),l=a.useRef(t),o=a.useRef(n),d=l.current!==t||o.current!==n;d&&(l.current=t,o.current=n,r.current++);const m=a.useRef(null),c=a.useRef(0),u=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),y=a.useRef(new Set),k=a.useRef(yr()),A=a.useCallback($=>{p.current.add($);const T=k.current;return T.data.length>0&&(T.data.forEach(S=>$(S)),T.data=[]),()=>p.current.delete($)},[]),j=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),_=a.useCallback($=>{b.current.add($);const T=k.current;return T.connected&&($(T.connected),T.connected=null),()=>b.current.delete($)},[]),N=a.useCallback($=>{v.current.add($);const T=k.current;return T.scrollback&&($(T.scrollback),T.scrollback=null),()=>v.current.delete($)},[]),M=a.useCallback($=>(y.current.add($),()=>y.current.delete($)),[]),w=a.useCallback($=>{const T=m.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:$}))},[]),R=a.useCallback(($,T)=>{const S=m.current;S?.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"resize",cols:$,rows:T}))},[]),E=a.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null),h.current&&(clearInterval(h.current),h.current=null),m.current&&(m.current.onopen=null,m.current.onmessage=null,m.current.onclose=null,m.current.onerror=null,m.current.close(),m.current=null),k.current=yr()},[]),I=a.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null),h.current&&(clearInterval(h.current),h.current=null),m.current&&(g.current=!0,m.current.close(),m.current=null),k.current=yr()},[]),L=a.useCallback(()=>{if(!t){i("disconnected");return}if(m.current?.readyState===WebSocket.OPEN)return;m.current&&(g.current=!0,m.current.close()),g.current=!1,i("connecting");const $=r.current;let S=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(t)}`;n&&(S+=`&projectId=${encodeURIComponent(n)}`);const Y=new WebSocket(Ps(S));m.current=Y,Y.onopen=()=>{if(r.current!==$){Y.close();return}k.current=yr(),i("connected"),c.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&Y.readyState===WebSocket.OPEN&&Y.send(JSON.stringify({type:"ping"}))},lA)},Y.onmessage=K=>{if(r.current===$)try{const G=JSON.parse(K.data),P=k.current;switch(G.type){case"data":G.data&&(p.current.size===0&&P.data.push(G.data),p.current.forEach(O=>O(G.data)));break;case"scrollback":G.data&&(P.scrollback=G.data,v.current.forEach(O=>O(G.data)));break;case"connected":G.shell&&G.cwd&&(P.connected={shell:G.shell,cwd:G.cwd},b.current.forEach(O=>O({shell:G.shell,cwd:G.cwd})));break;case"exit":G.exitCode!==void 0&&f.current.forEach(O=>O(G.exitCode));break;case"ping":Y.readyState===WebSocket.OPEN&&Y.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Y.onclose=K=>{if(r.current!==$)return;if(m.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(K.code===4e3||K.code===4004){i("disconnected"),K.code===4004&&y.current.forEach(O=>O());return}if(c.current++,c.current>aA){i("disconnected");return}const G=rA*Math.pow(2,c.current-1);i("reconnecting");const P=r.current;u.current=setTimeout(()=>{r.current===P&&(g.current||L())},Math.min(G,16e3))},Y.onerror=()=>{}},[t,n]),ee=a.useCallback(()=>{c.current=0,I(),L()},[I,L]);return a.useEffect(()=>(d&&(E(),c.current=0,i("disconnected")),t?L():i("disconnected"),I),[t,n,d,L,I,E]),{connectionStatus:s,sendInput:w,resize:R,onData:A,onExit:j,onConnect:_,onScrollback:N,reconnect:ee,onSessionInvalid:M}}const Jp="kb-terminal-tabs",cA=15e3,dA=15e3;function rm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function lm(t){if(typeof window>"u")return[];try{const n=In(Jp,t);if(n)return JSON.parse(n)}catch{}return[]}function Xl(t){const n=t instanceof Error?t.message:typeof t=="string"?t:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function om(t,n,s){let i;const r=new Promise((l,o)=>{i=setTimeout(()=>o(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([t,r]).finally(()=>clearTimeout(i))}function uA(t){const[n,s]=a.useState(()=>lm(t)),[i,r]=a.useState(!1),[l,o]=a.useState(!0),[d,m]=a.useState(null),[c,u]=a.useState(0),h=a.useRef(0);a.useEffect(()=>{h.current+=1,s(lm(t)),r(!1),o(!0),m(null)},[t]),a.useEffect(()=>{try{ms(Jp,JSON.stringify(n),t)}catch{}},[t,n]),a.useEffect(()=>{let _=!1;const N=h.current;return(async()=>{if(!_)try{const w=await om(gv(t),cA,"listTerminalSessions");if(_||N!==h.current)return;const R=new Set(w.map(E=>E.id));o(!0),s(E=>{if(_||N!==h.current)return E;const L=E.map(T=>({...T,_verified:R.has(T.sessionId)})).filter(T=>T._verified);if(L.length===0)return[];const ee=L.map(({_verified:T,...S})=>S);return ee.find(T=>T.isActive)?ee:ee.map((T,S)=>({...T,isActive:S===0}))}),r(!0)}catch(w){if(_||N!==h.current)return;const R=Xl(w);R||console.warn("Failed to validate terminal sessions with server:",w),o(!R),r(!0)}})(),()=>{_=!0}},[t]),a.useEffect(()=>{if(n.length===0&&i&&l){const _=h.current,N=setTimeout(()=>{om(nr(void 0,void 0,void 0,t),dA,"createTerminalSession").then(M=>{if(_!==h.current)return;const w={id:rm(),sessionId:M.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(R=>R.length>0?R:[...R.map(I=>({...I,isActive:!1})),w]),m(null)}).catch(M=>{if(_!==h.current)return;Xl(M)||console.error(M);const w=M instanceof Error?M.message:typeof M=="string"?M:"Failed to create terminal session";m(w)})},0);return()=>clearTimeout(N)}},[i,l,n.length,c]);const g=a.useCallback(async()=>{const _=await nr(void 0,void 0,void 0,t),N={id:rm(),sessionId:_.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(M=>[...M.map(R=>({...R,isActive:!1})),N]),N},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(_=>{s(N=>{const M=N.find(I=>I.id===_);if(!M)return N;Jc(M.sessionId,t).catch(I=>{console.warn(`Failed to kill terminal session ${M.sessionId}:`,I)});const w=N.findIndex(I=>I.id===_),R=M.isActive,E=N.filter(I=>I.id!==_);if(E.length===0)return[];if(R){const I=Math.min(w,E.length-1);return E.map((L,ee)=>({...L,isActive:ee===I}))}return E})},[]),b=a.useCallback(_=>{s(N=>{let M=!1;const w=N.map(R=>R.id===_?(M=!0,{...R,isActive:!0}):{...R,isActive:!1});return M?w:N})},[]),v=a.useCallback((_,N)=>{s(M=>M.map(w=>w.id===_?{...w,title:N}:w))},[]),y=a.useCallback(async()=>{s(M=>{const w=M.find(R=>R.isActive);return w&&Jc(w.sessionId,t).catch(R=>{console.warn(`Failed to kill old session ${w.sessionId}:`,R)}),M});const _=n.find(M=>M.isActive);if(!_)return;const N=await nr(void 0,void 0,void 0,t);s(M=>M.map(w=>w.id===_.id?{...w,sessionId:N.sessionId}:w))},[n]),k=a.useCallback(async()=>{const _=n.find(N=>N.isActive);if(_)try{const N=await nr(void 0,void 0,void 0,t);s(M=>M.map(w=>w.id===_.id?{...w,sessionId:N.sessionId}:w)),m(null)}catch(N){Xl(N)||console.error(N);const M=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";m(M)}},[n]),A=n.find(_=>_.isActive)??null,j=a.useCallback(()=>{m(null),h.current+=1,u(_=>_+1)},[]);return{tabs:n,activeTab:A,isReady:i,bootstrapError:d,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:v,restartActiveTab:y,retryBootstrap:j,replaceActiveTabSession:k}}const mA=1e4,hA=[500,1500,3e3];function pA(t){const n=typeof t=="string"?t:t instanceof Error?t.message:String(t);return n.includes("MIME type")||n.includes("Failed to fetch dynamically imported module")}function fA(t){return new Promise(n=>setTimeout(n,t))}async function gA(t,n=hA){let s;for(let i=0;i<=n.length;i+=1)try{return await t()}catch(r){if(!pA(r))throw r;s===void 0&&(s=r);const l=n[i];if(l===void 0)throw s??r;const o=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${i+1}/${n.length+1}). Retrying in ${l}ms...`,o),await fA(l)}throw s??new Error("Dynamic import failed")}function cm(){if(typeof window>"u")return!1;const t="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return t&&n}function bA(){if(typeof window>"u"||!window.visualViewport)return 0;const t=window.visualViewport,n=Math.max(0,window.innerHeight-t.offsetTop-t.height);if(n>0)return n;const i=xA()-t.offsetTop-t.height;return i>=30&&i>80?i:0}let Zl=null;function xA(){return Zl===null&&(Zl=window.innerHeight),Zl}function vA({isOpen:t,onClose:n,initialCommand:s,projectId:i}){const[r,l]=a.useState(null),[o,d]=a.useState(null),[m,c]=a.useState(!1),[u,h]=a.useState(null),[g,p]=a.useState(0),[f,b]=a.useState(0),[v,y]=a.useState(null),k=a.useRef(null),A=a.useRef(null),j=a.useRef(null),_=a.useRef(null),N=a.useRef(!1),M=a.useRef(!1),w=a.useRef(null),R=a.useRef(0),E=a.useRef(null),I=a.useRef(i);R.current=f;const L=a.useCallback(Ae=>{if(Ae&&M.current!==Ae)return;const Ce=_.current,Ge=j.current,Te=w.current;if(!(!Ce||!Ge)&&!(Ae&&M.current!==Ae))try{Ce.fit(),Te&&Te(Ge.cols,Ge.rows)}catch{}},[]);a.useEffect(()=>{t&&p(Ae=>Ae+1)},[t]),a.useEffect(()=>{if(!t||!cm())return;const Ae=window.visualViewport;if(!Ae)return;const Ce=()=>{const Ge=bA();b(Ge),y(Ae.height),Ge>0&&A.current?.scrollIntoView&&A.current.scrollIntoView({block:"end",behavior:"smooth"}),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const Te=typeof M.current=="string"?M.current:void 0;E.current=requestAnimationFrame(()=>{E.current=null,L(Te)})};return Ce(),Ae.addEventListener("resize",Ce),Ae.addEventListener("scroll",Ce),()=>{Ae.removeEventListener("resize",Ce),Ae.removeEventListener("scroll",Ce),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),b(0),y(null)}},[L,t]);const{tabs:ee,activeTab:$,isReady:T,bootstrapError:S,createTab:Y,closeTab:K,setActiveTab:G,updateTabTitle:P,restartActiveTab:O,retryBootstrap:X,replaceActiveTabSession:C}=uA(i),{connectionStatus:V,sendInput:de,resize:B,onData:J,onConnect:D,onExit:he,onScrollback:q,reconnect:W,onSessionInvalid:me}=oA($?.sessionId??null,i);w.current=B,a.useEffect(()=>{if(!t||!T||!$)return;const Ae=$.sessionId,Ce=I.current!==i;if(Ce&&(I.current=i),M.current===Ae&&j.current&&!Ce)return;j.current&&(M.current!==Ae||Ce)&&(j.current.dispose(),j.current=null,_.current=null,M.current=!1,c(!1),h(null));let Ge=!0,Te;const re=(async()=>{const Z=gA(()=>Promise.all([Zt(()=>import("./vendor-xterm-DzcZoU0P.js").then(pe=>pe.x),__vite__mapDeps([4,1,5])),Zt(()=>import("./addon-fit-C7jRorKK.js").then(pe=>pe.a),__vite__mapDeps([9,1])),Zt(()=>import("./addon-web-links-CkJwd4cQ.js").then(pe=>pe.a),__vite__mapDeps([10,1]))])),ye=new Promise((pe,Ue)=>{Te=setTimeout(()=>{Ue(new Error("xterm initialization timed out"))},mA)});let ie,Ie;try{const[{Terminal:pe},{FitAddon:Ue},{WebLinksAddon:dt}]=await Promise.race([Z,ye]);if(!Ge||!k.current||j.current)return;ie=new pe({cursorBlink:!0,cursorStyle:"block",fontSize:14,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}),Ie=new Ue,ie.loadAddon(Ie);const ht=new dt;if(ie.loadAddon(ht),!cm())try{const{WebglAddon:Ne}=await Zt(async()=>{const{WebglAddon:xe}=await import("./addon-webgl-BjvOw43o.js").then(st=>st.a);return{WebglAddon:xe}},__vite__mapDeps([11,1])),Ze=new Ne;Ze.onContextLoss(()=>{Ze.dispose()}),ie.loadAddon(Ze)}catch{}ie.open(k.current),clearTimeout(Te);const ue=k.current?.querySelector(".xterm-helper-textarea");if(ue&&ue.focus(),k.current)try{k.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Ie.fit();const Ne=k.current?.querySelector(".xterm-helper-textarea");Ne&&Ne.focus()},50),j.current=ie,_.current=Ie,M.current=Ae,R.current>0&&(E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),E.current=requestAnimationFrame(()=>{E.current=null,L(Ae)})),c(!0),h(null);const te=ie.onData(Ne=>{de(Ne)}),ke=()=>{if(_.current&&j.current)try{_.current.fit();const{cols:Ne,rows:Ze}=j.current;B(Ne,Ze)}catch{}};return window.addEventListener("resize",ke),()=>{te.dispose(),window.removeEventListener("resize",ke)}}catch(pe){if(clearTimeout(Te),!Ge)return;const Ue=pe instanceof Error?pe.message:"xterm initialization failed";h(Ue)}})();return()=>{Ge=!1,clearTimeout(Te),re.then(Z=>Z?.())}},[L,t,T,$,$?.sessionId,de,B]),a.useEffect(()=>{t||(j.current&&(j.current.dispose(),j.current=null),_.current=null,M.current=!1,c(!1),h(null),N.current=!1,l(null),d(null))},[t]),a.useEffect(()=>{if(!m||!j.current||!$)return;const Ae=$.sessionId,Ce=Z=>{M.current===Ae&&j.current?.write(Z)},Ge=J(Z=>{Ce(Z)}),Te=q(Z=>{Ce(Z)}),Xe=D(Z=>{P($.id,Z.shell.split("/").pop()||Z.shell)}),re=he(Z=>{M.current===Ae&&(d(Z),j.current?.write(`\r
|
|
646
|
+
\x1B[33m[Process exited with code ${Z}]\x1B[0m\r
|
|
647
|
+
`))});return()=>{Ge(),Te(),Xe(),re()}},[m,$?.sessionId,$?.id,$,V,J,q,D,he,P]),a.useEffect(()=>{V==="connected"&&s&&N.current!==s&&$&&(N.current=s,setTimeout(()=>{de(s+`
|
|
648
|
+
`)},500))},[V,s,de,$,g]),a.useEffect(()=>{if(!t)return;const Ae=Ce=>{if(!(!Ce.ctrlKey&&!Ce.metaKey)){if(Ce.code==="Equal"||Ce.code==="NumpadAdd"){if(Ce.preventDefault(),j.current){const Ge=j.current.options.fontSize||14;j.current.options.fontSize=Math.min(Ge+1,32),_.current?.fit()}return}if(Ce.code==="Minus"||Ce.code==="NumpadSubtract"){if(Ce.preventDefault(),j.current){const Ge=j.current.options.fontSize||14;j.current.options.fontSize=Math.max(Ge-1,8),_.current?.fit()}return}if(Ce.code==="Digit0"||Ce.code==="Numpad0"){Ce.preventDefault(),j.current&&(j.current.options.fontSize=14,_.current?.fit());return}}};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[t]),a.useEffect(()=>{if(!t)return;const Ae=Ce=>{Ce.key==="Escape"&&n()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[t,n]),a.useEffect(()=>{V==="connected"&&j.current&&setTimeout(()=>{if(!j.current||!k.current)return;const Ae=k.current.querySelector(".xterm-helper-textarea");Ae&&Ae.focus();try{k.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[V]);const Re=a.useCallback(()=>{if(!k.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;j.current?.focus();const Ce=k.current.querySelector(".xterm-helper-textarea");if(!Ce)return;Ce.autocapitalize="off",Ce.autocomplete="off",Ce.autocorrect="off",Ce.spellcheck=!1,Ce.setAttribute("inputmode","text");try{Ce.focus({preventScroll:!0})}catch{Ce.focus()}const Ge=Ce.value.length;Ce.setSelectionRange(Ge,Ge)},[]);a.useEffect(()=>me(()=>{j.current?.clear(),d(null),N.current=!1,j.current&&(j.current.dispose(),j.current=null),_.current=null,M.current=!1,c(!1),h(null),C().catch(Ce=>{console.error("Failed to replace invalid terminal session:",Ce)})}),[me,C]);const ve=a.useCallback(Ae=>{Ae.target===Ae.currentTarget&&n()},[n]),Me=a.useCallback(()=>{j.current?.clear()},[]),_e=a.useCallback(async()=>{j.current?.clear(),d(null),N.current=!1;try{await O()}catch(Ae){l(fe(Ae)||"Failed to restart terminal session")}},[O]),De=a.useCallback(()=>{j.current&&(j.current.dispose(),j.current=null),_.current=null,M.current=!1,h(null),c(!1)},[]),Oe=a.useCallback(()=>{window.location.reload()},[]);if(!t)return null;const ze=()=>{switch(V){case"connected":return e.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return e.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return e.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Be=!T||!$&&!S||!m&&!u;return e.jsx("div",{className:"modal-overlay open",onClick:ve,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:e.jsxs("div",{ref:A,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:[e.jsxs("div",{className:"terminal-header",children:[e.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[ee.map(Ae=>e.jsxs("div",{className:`terminal-tab ${Ae.isActive?"terminal-tab--active":""}`,onClick:()=>G(Ae.id),title:Ae.title,role:"tab","aria-selected":Ae.isActive,children:[e.jsx("span",{className:"terminal-tab-label",children:Ae.title}),ee.length>1&&e.jsx("button",{className:"terminal-tab-close",onClick:Ce=>{Ce.stopPropagation(),K(Ae.id)},title:"Close tab",children:"×"})]},Ae.id)),e.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:Y,title:"New terminal",children:"+"})]}),e.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[e.jsx(Os,{size:16}),ze()]}),e.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[V==="disconnected"&&$&&e.jsxs("button",{className:"terminal-reconnect-btn",onClick:W,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[e.jsx(vn,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),o!==null&&e.jsxs("button",{className:"terminal-restart-btn",onClick:_e,title:"New Session","data-testid":"terminal-restart-btn",children:[e.jsx(vn,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),e.jsxs("button",{className:"terminal-clear-btn",onClick:Me,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[e.jsx(Ut,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),e.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:e.jsx(Ft,{size:20})})]})]}),r&&e.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),e.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Be&&!S&&e.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[e.jsx("div",{className:"terminal-spinner"}),e.jsx("span",{children:"Starting terminal..."})]}),S&&!$&&e.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:e.jsxs("div",{className:"terminal-error-content",children:[e.jsxs("span",{children:["Failed to start terminal: ",S]}),e.jsxs("div",{className:"terminal-error-actions",children:[e.jsxs("button",{className:"terminal-retry-btn",onClick:X,"data-testid":"terminal-retry-btn",children:[e.jsx(vn,{size:14}),"Retry"]}),e.jsxs("button",{className:"terminal-retry-btn",onClick:Oe,"data-testid":"terminal-bootstrap-refresh-btn",children:[e.jsx(vn,{size:14}),"Refresh page"]})]})]})}),u&&$&&e.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:e.jsxs("div",{className:"terminal-error-content",children:[e.jsxs("span",{children:["Terminal UI failed to initialize: ",u]}),e.jsxs("div",{className:"terminal-error-actions",children:[e.jsxs("button",{className:"terminal-retry-btn",onClick:De,"data-testid":"terminal-reinit-btn",children:[e.jsx(vn,{size:14}),"Reinitialize"]}),e.jsxs("button",{className:"terminal-retry-btn",onClick:Oe,"data-testid":"terminal-xterm-refresh-btn",children:[e.jsx(vn,{size:14}),"Refresh page"]})]})]})}),e.jsx("div",{ref:k,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Re,onTouchStart:Re},$?.sessionId)]}),e.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[e.jsxs("span",{className:`terminal-connection-status ${V}`,children:[V==="connected"&&"Connected",V==="connecting"&&"Connecting...",V==="reconnecting"&&"Reconnecting...",V==="disconnected"&&"Disconnected"]}),o!==null&&e.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",o]}),e.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • Ctrl+L clear • Esc close"})]})]})})}const va={name:"",command:""};function dm(t){return/^[a-zA-Z0-9_-]+$/.test(t)}function yA(t,n=60){return t.length<=n?t:t.slice(0,n-3)+"..."}function kA({isOpen:t,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[l,o]=a.useState({}),[d,m]=a.useState(!0),[c,u]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(va),[b,v]=a.useState(!1),[y,k]=a.useState(null),[A,j]=a.useState(null),_=a.useCallback(async()=>{try{m(!0);const T=await Wa(i);o(T)}catch(T){s(fe(T)||"Failed to load scripts","error")}finally{m(!1)}},[s,i]);a.useEffect(()=>{t&&_()},[t,_]);const N=a.useCallback(()=>{u(!0),g(null),f(va),j(null)},[]),M=a.useCallback((T,S)=>{g(T),u(!1),f({name:T,command:S}),j(null)},[]),w=a.useCallback(()=>{g(null),u(!1),f(va),j(null)},[]),R=a.useCallback(T=>{f(S=>({...S,name:T})),T&&!dm(T)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),E=a.useCallback(async()=>{const T=p.name.trim(),S=p.command.trim();if(!T){s("Script name is required","error");return}if(!dm(T)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!S){s("Script command is required","error");return}v(!0);try{await gy(T,S,i),s(h?"Script updated":"Script created","success"),g(null),u(!1),f(va),j(null),await _()}catch(Y){const K=fe(Y);K?.includes("already exists")?s("A script with this name already exists","error"):s(K||"Failed to save script","error")}finally{v(!1)}},[p,h,s,_,i]),I=a.useCallback(async T=>{try{await by(T,i),s("Script deleted","success"),k(null),h===T&&(g(null),f(va)),await _()}catch(S){s(fe(S)||"Failed to delete script","error")}},[h,s,_,i]),L=a.useCallback((T,S)=>{r&&r(T,S)},[r]);if(!t)return null;const ee=c||h!==null,$=Object.entries(l).map(([T,S])=>({name:T,command:S}));return e.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:e.jsxs("div",{className:"modal scripts-modal",onClick:T=>T.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx(Os,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),e.jsx("div",{className:"modal-body scripts-modal-body",children:d?e.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[e.jsx(ct,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):ee?e.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),e.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:T=>R(T.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:A?"var(--color-error)":void 0}}),A&&e.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:A}),e.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),e.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:T=>f(S=>({...S,command:T.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),e.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[e.jsx("button",{className:"btn btn-secondary",onClick:w,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:E,disabled:b||!!A,"data-testid":"script-save-btn",children:b?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[e.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),e.jsxs("button",{className:"btn btn-primary",onClick:N,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(qt,{size:14}),"Add Script"]})]}),$.length===0?e.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:[e.jsx(Os,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),e.jsx("div",{children:"No scripts defined yet."}),e.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):e.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:$.map(T=>e.jsx("div",{className:"script-card","data-testid":`script-${T.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children:e.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:e.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:T.name})}),e.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:T.command,children:yA(T.command)})]}),e.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[e.jsxs("button",{className:"btn btn-secondary",onClick:()=>L(T.name,T.command),title:"Run script","aria-label":`Run ${T.name}`,"data-testid":`run-script-${T.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[e.jsx(an,{size:12}),"Run"]}),e.jsx("button",{className:"btn-icon",onClick:()=>M(T.name,T.command),title:"Edit","aria-label":`Edit ${T.name}`,"data-testid":`edit-script-${T.name}`,children:e.jsx(qt,{size:14,style:{transform:"rotate(45deg)"}})}),y===T.name?e.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[e.jsx("button",{className:"btn-icon",onClick:()=>I(T.name),title:"Confirm delete","aria-label":`Confirm delete ${T.name}`,"data-testid":`confirm-delete-script-${T.name}`,style:{color:"var(--color-error)"},children:e.jsx(Ut,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>k(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${T.name}`,children:e.jsx(Ft,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>k(T.name),title:"Delete","aria-label":`Delete ${T.name}`,"data-testid":`delete-script-${T.name}`,children:e.jsx(Ut,{size:14})})]})]})},T.name))})]})})]})})}function jA(t,n,s){const[i,r]=a.useState([]),[l,o]=a.useState("."),[d,m]=a.useState(!1),[c,u]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(b=>b+1)},[]),f=a.useCallback(b=>{o(b),u(null)},[]);return a.useEffect(()=>{o("."),u(null),r([])},[t]),a.useEffect(()=>{if(!t)return;let b=!1;async function v(){m(!0),u(null);try{const y=await Iv(t,l==="."?void 0:l,s);b||r(y.entries)}catch(y){b||(u(fe(y)||"Failed to load files"),r([]))}finally{b||m(!1)}}return v(),()=>{b=!0}},[t,l,n,h,s]),{entries:i,currentPath:l,setPath:f,loading:d,error:c,refresh:p}}function wA(t,n,s,i){const[r,l]=a.useState(""),[o,d]=a.useState(""),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,p]=a.useState(!1),[f,b]=a.useState(null),v=a.useCallback(A=>{l(A),b(null)},[]);a.useEffect(()=>{if(!t||!n){l(""),d(""),c(null),b(null);return}let A=!1;async function j(){h(!0),b(null);try{const _=await $v(t,n,i);A||(l(_.content),d(_.content),c(_.mtime))}catch(_){A||(b(fe(_)||"Failed to load file"),l(""),d(""),c(null))}finally{A||h(!1)}}return j(),()=>{A=!0}},[t,n,s,i]);const y=r!==o,k=a.useCallback(async()=>{if(!(!t||!n||!y)){p(!0),b(null);try{const A=await Dv(t,n,r,i);d(r),c(A.mtime)}catch(A){throw b(fe(A)||"Failed to save file"),A}finally{p(!1)}}},[t,n,r,y,i]);return{content:r,setContent:v,originalContent:o,loading:u,saving:g,error:f,save:k,hasChanges:y,mtime:m}}const NA=1e4;function SA(t){const s=t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||t||"Project Root"}function CA(t){return{id:t.id,label:t.id,title:t.title,worktree:t.worktree,kind:"task"}}function EA(t){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[l,o]=a.useState(!0),[d,m]=a.useState(null);return a.useEffect(()=>{let c=!1;async function u(){try{const g=await Rv(t);if(c)return;s(SA(g.project)),r(g.tasks.map(CA)),m(null)}catch(g){c||m(fe(g)||"Failed to load workspaces")}finally{c||o(!1)}}u();const h=window.setInterval(()=>{u()},NA);return()=>{c=!0,window.clearInterval(h)}},[t]),{projectName:n,workspaces:i,loading:l,error:d}}function MA(t){return t===void 0?"":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function AA(t){return t?new Date(t).toLocaleDateString():""}function um(t,n){return t==="."?n:`${t}/${n}`}const ya={visible:!1,x:0,y:0,entry:null,entryFullPath:""},eo={type:null,entry:null,entryFullPath:""},PA=200,_A=500,mm=10;function TA({x:t,y:n,entry:s,onAction:i,onClose:r}){const l=a.useRef(null),[o,d]=a.useState({x:t,y:n});a.useEffect(()=>{const u=l.current;if(!u)return;const h=u.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,v=g?.offsetTop??0,y=8;let k=t-b,A=n-v;k+h.width>p-y&&(k=p-y-h.width),A+h.height>f-y&&(A=f-y-h.height),k<y&&(k=y),A<y&&(A=y),d({x:k+b,y:A+v})},[t,n]),a.useEffect(()=>{const u=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const m=s.type==="directory",c=[{id:"copy",label:"Copy",icon:qi,disabled:!1},{id:"move",label:"Move",icon:bb,disabled:!1},{id:"rename",label:"Rename",icon:Dn,disabled:!1},...m?[{id:"download-zip",label:"Download as ZIP",icon:qr,disabled:!1}]:[{id:"download",label:"Download",icon:hg,disabled:!1}],{id:"divider",label:"",icon:qi,disabled:!0},{id:"delete",label:"Delete",icon:Ut,disabled:!1}];return e.jsx("div",{className:"context-menu-overlay",onClick:r,children:e.jsx("div",{ref:l,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:o.x,top:o.y},onClick:u=>u.stopPropagation(),children:c.map(u=>u.id==="divider"?e.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):e.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${u.disabled?"file-browser-context-menu__disabled":""} ${u.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:u.disabled,onClick:()=>i(u.id),children:[e.jsx(u.icon,{size:14,className:"file-browser-context-menu__item-icon"}),e.jsx("span",{children:u.label})]},u.id))})})}function RA({type:t,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:l,error:o}){const d=a.useRef(null),m=t==="rename"?n.name:"",[c,u]=a.useState(m);a.useEffect(()=>{setTimeout(()=>d.current?.focus(),50)},[]),a.useEffect(()=>{if(t==="rename"&&d.current){const f=n.name.lastIndexOf(".");f>0?d.current.setSelectionRange(0,f):d.current.select()}},[t,n.name]);const h=f=>{f.key==="Enter"&&c.trim()&&i(c.trim()),f.key==="Escape"&&r()};if(t==="delete")return e.jsx("div",{className:"context-menu-overlay",onClick:r,children:e.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),e.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",e.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),o&&e.jsx("div",{className:"file-browser-dialog-error",children:o}),e.jsxs("div",{className:"file-browser-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:r,disabled:l,children:"Cancel"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:l,children:l?"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"}}[t];return e.jsx("div",{className:"context-menu-overlay",onClick:r,children:e.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[e.jsx("div",{className:"file-browser-dialog-title",children:p.title}),e.jsx("div",{className:"file-browser-dialog-info",children:t==="rename"?n.name:s}),e.jsx("input",{ref:d,className:"file-browser-dialog-input",type:"text",value:c,onChange:f=>u(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:l}),o&&e.jsx("div",{className:"file-browser-dialog-error",children:o}),e.jsxs("div",{className:"file-browser-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:r,disabled:l,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(c.trim()),disabled:l||!c.trim(),children:l?`${p.confirm}ing...`:p.confirm})]})]})})}function IA({entries:t,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:l,onRetry:o,workspace:d,onRefresh:m,projectId:c}){const[u,h]=a.useState(ya),[g,p]=a.useState(eo),[f,b]=a.useState(!1),[v,y]=a.useState(null),[k,A]=a.useState(!1),[j,_]=a.useState(null),N=a.useRef(null),M=a.useRef(null),w=a.useRef(null),R=a.useRef(!1),E=a.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),I=a.useCallback(()=>{E(),w.current=null,A(!1),_(null)},[E]);a.useEffect(()=>()=>{E()},[E]);const L=a.useCallback((O,X,C,V)=>{h({visible:!0,x:O,y:X,entry:C,entryFullPath:V})},[]),ee=a.useCallback((O,X,C)=>{if(O.touches.length!==1)return;const V=O.touches[0];V&&(I(),w.current={x:V.clientX,y:V.clientY},M.current=window.setTimeout(()=>{A(!0),_(C)},PA),N.current=window.setTimeout(()=>{const de=w.current;de&&(R.current=!0,A(!1),_(null),E(),L(de.x,de.y,X,C))},_A))},[I,E,L]),$=a.useCallback(O=>{const X=w.current,C=O.touches[0];!X||!C||(Math.abs(C.clientX-X.x)>mm||Math.abs(C.clientY-X.y)>mm)&&I()},[I]),T=a.useCallback(()=>{I()},[I]);a.useEffect(()=>{if(!u.visible)return;const O=document.querySelector(".file-browser-list"),X=()=>{R.current=!1,I(),h(ya)};return O?.addEventListener("scroll",X),()=>O?.removeEventListener("scroll",X)},[I,u.visible]),a.useEffect(()=>{if(!u.visible)return;const O=X=>{X.key==="Escape"&&(R.current=!1,h(ya))};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[u.visible]);const S=a.useCallback((O,X)=>{O.preventDefault(),O.stopPropagation(),I(),R.current=!1,L(O.clientX,O.clientY,X,um(n,X.name))},[I,n,L]),Y=a.useCallback(O=>{if(!u.entry)return;R.current=!1;const X=u.entry,C=u.entryFullPath;if(h(ya),O==="download"){if(!d)return;const V=ch(d,C,c);window.open(Ps(V),"_blank");return}if(O==="download-zip"){if(!d)return;const V=Uv(d,C,c);window.open(Ps(V),"_blank");return}p({type:O,entry:X,entryFullPath:C}),y(null)},[u,d,c]),K=a.useCallback(async O=>{if(!(!g.type||!g.entry||!d)){b(!0),y(null);try{switch(g.type){case"copy":await Lv(d,g.entryFullPath,O,c);break;case"move":await zv(d,g.entryFullPath,O,c);break;case"rename":await Bv(d,g.entryFullPath,O,c);break;case"delete":await Ov(d,g.entryFullPath,c);break}p(eo),m?.()}catch(X){y(fe(X)||"Operation failed")}finally{b(!1)}}},[g,d,m,c]),G=a.useCallback(()=>{p(eo),y(null)},[]),P=a.useCallback((O,X)=>{if(R.current){R.current=!1;return}u.visible||(O.type==="directory"?i(X):s(X))},[u.visible,i,s]);return r?e.jsxs("div",{className:"file-browser-loading",children:[e.jsx(ct,{className:"spin",size:24}),e.jsx("span",{children:"Loading files..."})]}):l?e.jsxs("div",{className:"file-browser-error",children:[e.jsxs("p",{children:["Error: ",l]}),o&&e.jsx("button",{className:"btn btn-sm",onClick:o,children:"Retry"})]}):e.jsxs("div",{className:"file-browser",children:[e.jsxs("div",{className:"file-browser-header",children:[n!=="."&&e.jsxs("button",{className:"file-browser-up",onClick:()=>{const O=n.split("/").filter(Boolean);O.pop(),i(O.length===0?".":O.join("/"))},children:[e.jsx(rn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),e.jsx("span",{className:"file-browser-path",children:n==="."?"Root":n})]}),e.jsx("div",{className:"file-browser-list",children:t.length===0?e.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):t.map(O=>{const X=um(n,O.name),C=k&&j===X;return e.jsxs("div",{className:`file-node file-node--${O.type} ${C?"file-node--long-pressing":""}`,onClick:()=>P(O,X),onContextMenu:V=>S(V,O),onTouchStart:V=>ee(V,O,X),onTouchMove:$,onTouchEnd:T,onTouchCancel:T,children:[e.jsx("div",{className:"file-node-icon",children:O.type==="directory"?e.jsx(Pn,{size:16}):e.jsx(Km,{size:16})}),e.jsx("div",{className:"file-node-name",children:O.name}),O.type==="file"&&O.size!==void 0&&e.jsx("div",{className:"file-node-size",children:MA(O.size)}),O.mtime&&e.jsx("div",{className:"file-node-time",children:AA(O.mtime)})]},O.name)})}),u.visible&&u.entry&&e.jsx(TA,{x:u.x,y:u.y,entry:u.entry,onAction:Y,onClose:()=>{R.current=!1,h(ya)}}),g.type&&g.entry&&e.jsx(RA,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:K,onCancel:G,loading:f,error:v})]})}function $A(t,n=44){if(t)return t.length<=n?t:`${t.slice(0,n-1)}…`}function DA({currentWorkspace:t,projectName:n,workspaces:s,onSelect:i}){const[r,l]=a.useState(!1),o=a.useMemo(()=>t==="project"?n||"Project Root":s.find(m=>m.id===t)?.label??t,[t,n,s]);return e.jsxs("div",{className:"workspace-selector",children:[e.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>l(d=>!d),"aria-haspopup":"listbox","aria-expanded":r,children:[t==="project"?e.jsx(zc,{size:14}):e.jsx(ho,{size:14}),e.jsx("span",{className:"workspace-selector-trigger-label",children:o}),e.jsx(Lt,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&e.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[e.jsxs("button",{type:"button",className:`workspace-selector-option${t==="project"?" active":""}`,onClick:()=>{i("project"),l(!1)},children:[e.jsxs("div",{className:"workspace-selector-option-main",children:[e.jsx(zc,{size:14}),e.jsx("span",{children:"Project Root"})]}),e.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&e.jsxs("div",{className:"workspace-selector-group",children:[e.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(d=>e.jsxs("button",{type:"button",className:`workspace-selector-option${t===d.id?" active":""}`,onClick:()=>{i(d.id),l(!1)},children:[e.jsxs("div",{className:"workspace-selector-option-main",children:[e.jsx(ho,{size:14}),e.jsx("span",{children:d.id})]}),d.title&&e.jsx("span",{className:"workspace-selector-option-meta",title:d.title,children:$A(d.title)})]},d.id))]})]})]})}const FA=768,Yp=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),LA=new Set([...Yp,".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 hm(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return LA.has(n)}function zA(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return Yp.has(n)}function OA({initialWorkspace:t="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:l}=EA(i),[o,d]=a.useState(t),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,p]=a.useState("list"),{entries:f,currentPath:b,setPath:v,loading:y,error:k,refresh:A}=jA(o,!0,i),{content:j,setContent:_,originalContent:N,loading:M,saving:w,error:R,save:E,hasChanges:I,mtime:L}=wA(o,m,!0,i);a.useEffect(()=>{d(t)},[t]),a.useEffect(()=>{const O=()=>{h(window.innerWidth<=FA)};return O(),window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]),a.useEffect(()=>{m||p("list")},[m]),a.useEffect(()=>{const O=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),I&&!w&&E())};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[n,I,w,E]);const ee=a.useCallback(O=>{c(O),u&&p("editor")},[u]),$=a.useCallback(()=>{p("list")},[]),T=a.useCallback(()=>{_(N)},[N,_]),S=a.useCallback(O=>{d(O),c(null),p("list"),s?.(O)},[s]),K=`Files — ${a.useMemo(()=>o==="project"?"Project":l.find(O=>O.id===o)?.id??o,[o,l])}`,G=a.useMemo(()=>!m||!zA(m)?null:ch(o,m,i),[m,o,i]),P=O=>{const X=new Blob([O]).size;return X<1024?`${X} B`:`${(X/1024).toFixed(1)} KB`};return e.jsx("div",{className:"modal-overlay open",onClick:n,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal file-browser-modal",onClick:O=>O.stopPropagation(),children:[e.jsxs("div",{className:"modal-header file-browser-modal-header",children:[e.jsxs("div",{className:"file-browser-header-title",children:[e.jsx(Pn,{size:18}),e.jsx("span",{children:K}),m&&e.jsx("span",{className:"file-browser-header-path",children:m})]}),e.jsxs("div",{className:"file-browser-header-actions",children:[e.jsx(DA,{currentWorkspace:o,projectName:r,workspaces:l,onSelect:S}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsxs("div",{className:"file-browser-body",children:[e.jsx("div",{className:`file-browser-sidebar ${u?"mobile":""} ${g==="list"?"active":""}`,children:e.jsx(IA,{entries:f,currentPath:b,onSelectFile:ee,onNavigate:v,loading:y,error:k,onRetry:A,workspace:o,onRefresh:A,projectId:i})}),e.jsx("div",{className:`file-browser-content ${u?"mobile":""} ${g==="editor"?"active":""}`,children:m?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"file-browser-toolbar",children:[e.jsxs("div",{className:"file-browser-file-info",children:[u&&g==="editor"&&e.jsxs("button",{className:"file-browser-back-button",onClick:$,"aria-label":"Back to file list",children:[e.jsx(sa,{size:16}),e.jsx("span",{children:"Back"})]}),m,hm(m)&&e.jsxs("span",{className:"file-browser-binary-indicator",children:[e.jsx(Rg,{size:12}),"Binary file — read only"]}),L&&e.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(L).toLocaleString()]}),M&&e.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),e.jsx("div",{className:"file-browser-actions",children:!G&&I&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:T,disabled:w,children:[e.jsx(Ab,{size:14}),"Discard"]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void E(),disabled:w,children:[e.jsx(Zm,{size:14}),w?"Saving...":"Save"]})]})})]}),R&&!G&&e.jsx("div",{className:"file-browser-error-banner",children:R}),G?e.jsx("div",{className:"file-browser-image-preview",children:e.jsx("img",{src:G,alt:m??"",className:"file-browser-image"})}):e.jsx("div",{className:"file-editor-wrapper",children:e.jsx(Kp,{content:j,onChange:_,filePath:m,readOnly:hm(m)})}),!G&&e.jsxs("div",{className:"file-browser-footer",children:[e.jsx("span",{children:P(j)}),I&&e.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):e.jsxs("div",{className:"file-browser-placeholder",children:[e.jsx(Pn,{size:48,opacity:.3}),e.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function BA(t={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=t,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null}),l=a.useRef(null),o=a.useRef(null),d=a.useCallback(async(c=!1)=>{o.current&&o.current.abort(),o.current=new AbortController,c&&r(u=>({...u,loading:!0,error:null}));try{const{providers:u}=await tv();r({providers:u,loading:!1,error:null,lastUpdated:new Date})}catch(u){if(u instanceof Error&&u.name==="AbortError")return;r(h=>({...h,loading:!1,error:fe(u)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{d()},[d]),a.useEffect(()=>{if(s)return l.current=setInterval(()=>{d(!1)},n),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,n,d]),a.useEffect(()=>()=>{o.current&&o.current.abort(),l.current&&clearInterval(l.current)},[]);const m=a.useCallback(()=>d(!0),[d]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:m}}function UA(t){const n=new Date(t),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const l=new Date(s.getFullYear(),s.getMonth(),s.getDate()),o=new Date(n.getFullYear(),n.getMonth(),n.getDate()),d=Math.round((o.getTime()-l.getTime())/(1440*60*1e3));return d>=1&&d<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function HA(t){return t>90?"usage-progress-fill--high":t>70?"usage-progress-fill--medium":"usage-progress-fill--low"}function qA({window:t,viewMode:n,providerName:s}){const i=HA(t.percentUsed),r=n==="remaining",l=Math.round(r?t.percentLeft:t.percentUsed),o=r?`${Math.round(t.percentLeft)}% remaining`:`${Math.round(t.percentUsed)}% used`,d=r?`${Math.round(t.percentUsed)}% used`:`${Math.round(t.percentLeft)}% left`;let m=t.resetText;if(!m&&t.resetAt){const b=new Date(t.resetAt).getTime()-Date.now();if(b>0){const v=Math.floor(b/36e5),y=Math.floor(v/24),k=v%24;y>0&&k>0?m=`resets in ${y}d ${k}h`:y>0?m=`resets in ${y}d`:v>0?m=`resets in ${v}h`:m=`resets in ${Math.floor(b/6e4)}m`}}const c=t.pace,u=c!==void 0;let h=0;u&&(h=r?100-c.percentElapsed:c.percentElapsed);const g=c?.status==="ahead",p=c?.status==="behind",f=c?.status==="on-track";return e.jsxs("div",{className:"usage-window",children:[e.jsxs("div",{className:"usage-window-header",children:[e.jsx("span",{className:"usage-window-label",children:t.label}),e.jsx("span",{className:"usage-window-percentage",children:o})]}),e.jsxs("div",{className:"usage-progress-wrapper",children:[e.jsx("div",{className:"usage-progress-bar",children:e.jsx("div",{className:`usage-progress-fill ${i}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${t.label}: ${o}`})}),u&&e.jsx("div",{className:"usage-pace-marker",style:{left:`${h}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),e.jsxs("div",{className:"usage-window-footer",children:[e.jsx("span",{className:"usage-window-left",children:d}),e.jsxs("span",{className:"usage-window-reset-group",children:[m&&e.jsx("span",{className:"usage-window-reset",children:m}),t.resetAt&&e.jsx("span",{className:"usage-window-reset-at",children:UA(t.resetAt)})]})]}),u&&e.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(Wo,{size:14,className:"pace-icon pace-ahead"}),e.jsx("span",{className:"pace-text pace-ahead",children:c.message})]}),p&&e.jsxs(e.Fragment,{children:[e.jsx(Kb,{size:14,className:"pace-icon pace-behind"}),e.jsx("span",{className:"pace-text pace-behind",children:c.message})]}),f&&e.jsxs(e.Fragment,{children:[e.jsx(en,{size:14,className:"pace-icon pace-ontrack"}),e.jsx("span",{className:"pace-text pace-ontrack",children:c.message})]})]})]})}function VA(t){const n=t.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")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":t}function WA({provider:t,viewMode:n}){const s=()=>{switch(t.status){case"ok":return e.jsx("span",{className:"usage-status-badge usage-status-badge--connected",children:"Connected"});case"error":return e.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return e.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return e.jsxs("div",{className:"usage-provider","data-provider":t.name,"data-status":t.status,children:[e.jsxs("div",{className:"usage-provider-header",children:[e.jsxs("div",{className:"usage-provider-info",children:[e.jsx(ss,{provider:VA(t.name),size:"md"}),e.jsx("span",{className:"usage-provider-name",children:t.name})]}),s()]}),t.error&&e.jsx("div",{className:"usage-provider-error",children:t.error}),t.plan&&e.jsx("div",{className:"usage-provider-meta",children:e.jsx("span",{className:"usage-provider-plan",children:t.plan})}),t.windows.length>0?e.jsx("div",{className:"usage-provider-windows",children:t.windows.map((i,r)=>e.jsx(qA,{window:i,viewMode:n,providerName:t.name},`${t.name}-${i.label}-${r}`))}):t.status==="ok"?e.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function KA(){return e.jsx("div",{className:"usage-skeleton",children:[1,2,3].map(t=>e.jsxs("div",{className:"usage-skeleton-provider",children:[e.jsxs("div",{className:"usage-skeleton-header",children:[e.jsx("div",{className:"usage-skeleton-icon"}),e.jsx("div",{className:"usage-skeleton-name"}),e.jsx("div",{className:"usage-skeleton-badge"})]}),e.jsx("div",{className:"usage-skeleton-bar"}),e.jsx("div",{className:"usage-skeleton-text"})]},t))})}function GA({isOpen:t,onClose:n,projectId:s}){const{providers:i,loading:r,error:l,lastUpdated:o,refresh:d}=BA({autoRefresh:t}),[m,c]=a.useState(!1),[u,h]=a.useState("used"),g=a.useRef(null),p=a.useRef(t),f=a.useRef(!1);a.useEffect(()=>{t||(f.current=!1)},[t]),a.useEffect(()=>{i.length>0&&(f.current=!0)},[i.length]),a.useEffect(()=>{!p.current&&t&&(!o||Date.now()-o.getTime()>5e3)&&d(),p.current=t},[t,o,d]),a.useEffect(()=>{const k=In("kb-usage-view-mode",s);if(k==="used"||k==="remaining"){h(k);return}h("used")},[s]);const b=a.useCallback(k=>{h(k),ms("kb-usage-view-mode",k,s)},[s]),v=a.useCallback(async()=>{c(!0),await d(),c(!1)},[d]);a.useEffect(()=>{if(!t)return;const k=A=>{A.key==="Escape"&&n()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t,n]);const y=a.useCallback(k=>{k.target===k.currentTarget&&n()},[n]);return t?e.jsx("div",{className:"modal-overlay open",onClick:y,"data-testid":"usage-modal-overlay",children:e.jsxs("div",{className:"modal usage-modal","data-testid":"usage-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"usage-header",children:[e.jsx(Ns,{size:18,className:"usage-header-icon"}),e.jsx("h3",{children:"Usage"})]}),e.jsxs("div",{className:"usage-header-actions",children:[e.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[e.jsx("button",{className:`usage-view-toggle-btn ${u==="used"?"active":""}`,onClick:()=>b("used"),"aria-pressed":u==="used","data-testid":"usage-view-toggle-used",children:"Used"}),e.jsx("button",{className:`usage-view-toggle-btn ${u==="remaining"?"active":""}`,onClick:()=>b("remaining"),"aria-pressed":u==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:e.jsx(Ft,{size:20})})]})]}),e.jsx("div",{className:"usage-content",ref:g,children:(r||!f.current&&!l)&&i.length===0?e.jsx(KA,{}):l&&i.length===0?e.jsxs("div",{className:"usage-error",children:[e.jsx("p",{children:"Failed to load usage data"}),e.jsx("p",{className:"usage-error-message",children:l}),e.jsx("button",{className:"btn btn-sm",onClick:v,children:"Retry"})]}):i.length===0?e.jsxs("div",{className:"usage-empty",children:[e.jsx("p",{children:"No AI providers configured"}),e.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):e.jsx("div",{className:"usage-providers",children:i.map(k=>e.jsx(WA,{provider:k,viewMode:u},k.name))})}),e.jsxs("div",{className:"modal-actions usage-actions",children:[e.jsx("div",{className:"modal-actions-left usage-actions-left",children:e.jsx("div",{className:"usage-last-updated",children:o&&e.jsxs("span",{children:["Last updated: ",o.toLocaleTimeString()]})})}),e.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[e.jsxs("button",{className:"btn btn-sm",onClick:v,disabled:r||m,"data-testid":"usage-refresh-btn",children:[e.jsx(vn,{size:14,className:m?"spin":"",style:{marginRight:6}}),"Refresh"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function Qp(t){if(t<1e3)return`${t}ms`;const n=Math.floor(t/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),l=s%60;return l>0?`${r}h ${l}m`:`${r}h`}function Br(t){const n=Date.now(),s=new Date(t).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 JA={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Xp={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},YA={cron:Hm,webhook:th,api:qm,manual:Sn},QA={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},XA={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function ZA({result:t}){const n=t.completedAt&&t.startedAt?new Date(t.completedAt).getTime()-new Date(t.startedAt).getTime():0;return e.jsxs("span",{className:`schedule-run-badge ${t.success?"success":"failure"}`,children:[t.success?e.jsx(en,{size:12}):e.jsx(Ua,{size:12}),e.jsx("span",{children:t.success?"Success":"Failed"}),n>0&&e.jsx("span",{className:"schedule-run-duration",children:Qp(n)})]})}function eP({result:t,index:n}){const[s,i]=a.useState(!1),r=t.completedAt&&t.startedAt?new Date(t.completedAt).getTime()-new Date(t.startedAt).getTime():0;return e.jsxs("div",{className:"schedule-history-item",children:[e.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${t.success?"succeeded":"failed"} ${Br(t.startedAt)}`,children:[e.jsx("span",{className:`schedule-history-status ${t.success?"success":"failure"}`,children:t.success?e.jsx(en,{size:12}):e.jsx(Ua,{size:12})}),e.jsx("span",{className:"schedule-history-time",children:Br(t.startedAt)}),t.triggerType&&e.jsx("span",{className:"routine-history-trigger-type",children:Xp[t.triggerType]}),e.jsx("span",{className:"schedule-history-duration",children:Qp(r)}),s?e.jsx(Fs,{size:12}):e.jsx(Lt,{size:12})]}),s&&e.jsxs("div",{className:"schedule-history-detail",children:[t.output&&e.jsx("pre",{className:"schedule-history-output",children:t.output}),t.error&&e.jsx("div",{className:"schedule-history-error",children:t.error})]})]})}function tP({routine:t,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:l}){const[o,d]=a.useState(!1),m=a.useCallback(()=>{window.confirm(`Delete routine "${t.name}"? This cannot be undone.`)&&s(t)},[t,s]),c=JA[t.trigger.type],u=YA[t.trigger.type],h=t.trigger.type==="cron"?("cronExpression"in t.trigger?t.trigger.cronExpression:void 0)||t.cronExpression||"":t.cronExpression||"";return e.jsxs("div",{className:`routine-card${t.enabled?"":" disabled"}`,children:[e.jsxs("div",{className:"routine-card-header",children:[e.jsxs("div",{className:"routine-card-info",children:[e.jsxs("div",{className:"routine-card-name-row",children:[e.jsx("span",{className:"routine-card-name",children:t.name}),e.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:c,color:c},children:[e.jsx(u,{size:10}),Xp[t.trigger.type]]}),t.scope&&e.jsxs("span",{className:`routine-scope-badge${t.scope==="global"?" global":" project"}`,title:`${t.scope==="global"?"Global":"Project"}-scoped routine`,children:[t.scope==="global"?e.jsx(yi,{size:10}):e.jsx(Pn,{size:10}),t.scope]})]}),t.description&&e.jsx("p",{className:"routine-card-description",children:t.description})]}),e.jsxs("div",{className:"routine-card-actions",children:[e.jsx("button",{className:"btn-icon",onClick:()=>i(t),disabled:l,title:l?"Running…":"Run now","aria-label":l?"Running…":`Run ${t.name} now`,children:e.jsx(an,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>r(t),title:t.enabled?"Disable":"Enable","aria-label":t.enabled?`Disable ${t.name}`:`Enable ${t.name}`,"aria-pressed":t.enabled,children:t.enabled?e.jsx(Ds,{size:14}):e.jsx(an,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>n(t),title:"Edit","aria-label":`Edit ${t.name}`,children:e.jsx(Dn,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${t.name}`,children:e.jsx(Ut,{size:14})})]})]}),e.jsxs("div",{className:"routine-card-meta",children:[t.steps&&t.steps.length>0?e.jsxs("div",{className:"routine-meta-item",children:[e.jsx(ki,{size:12}),e.jsxs("span",{className:"routine-policy-badge",children:[t.steps.length," step",t.steps.length===1?"":"s"]})]}):t.command?e.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:t.command,children:e.jsx("code",{className:"routine-cron",children:t.command})}):null,t.trigger.type==="cron"&&h&&e.jsxs("div",{className:"routine-meta-item",children:[e.jsx(Hi,{size:12}),e.jsx("code",{className:"routine-cron",children:h})]}),e.jsx("div",{className:"routine-meta-item",children:e.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${t.executionPolicy}`,children:QA[t.executionPolicy]})}),e.jsx("div",{className:"routine-meta-item",children:e.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${t.catchUpPolicy}`,children:XA[t.catchUpPolicy]})}),t.nextRunAt&&t.enabled&&e.jsxs("div",{className:"routine-meta-item",children:[e.jsx("span",{className:"routine-meta-label",children:"Next:"}),e.jsx("span",{title:t.nextRunAt,children:Br(t.nextRunAt)})]}),t.lastRunAt&&e.jsxs("div",{className:"routine-meta-item",children:[e.jsx("span",{className:"routine-meta-label",children:"Last:"}),e.jsx("span",{title:t.lastRunAt,children:Br(t.lastRunAt)})]}),t.lastRunResult&&e.jsx(ZA,{result:t.lastRunResult}),e.jsxs("div",{className:"routine-meta-item",children:[e.jsx("span",{className:"routine-meta-label",children:"Runs:"}),e.jsx("span",{children:t.runCount})]})]}),t.runHistory.length>0&&e.jsxs("div",{className:"routine-card-history",children:[e.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":o,children:[o?e.jsx(Fs,{size:12}):e.jsx(Lt,{size:12}),e.jsxs("span",{children:["Run History (",t.runHistory.length,")"]})]}),o&&e.jsxs("div",{className:"schedule-history-list",children:[t.runHistory.slice(0,10).map((g,p)=>e.jsx(eP,{result:g,index:p},`${g.startedAt}-${p}`)),t.runHistory.length>10&&e.jsxs("div",{className:"schedule-history-more",children:["…and ",t.runHistory.length-10," more"]})]})]})]})}function nP({type:t,size:n=12}){return t==="command"?e.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[e.jsx(Os,{size:n}),e.jsx("span",{children:"Command"})]}):t==="create-task"?e.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[e.jsx(ib,{size:n}),e.jsx("span",{children:"Create Task"})]}):e.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[e.jsx(Ln,{size:n}),e.jsx("span",{children:"AI Prompt"})]})}function to(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function sP(t){return t==="command"?{id:to(),type:t,name:"New Command Step",command:"",continueOnFailure:!1}:t==="ai-prompt"?{id:to(),type:t,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:to(),type:t,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function iP({step:t,onSave:n,onCancel:s}){const[i,r]=a.useState(t.name),[l,o]=a.useState(t.type),[d,m]=a.useState(t.command??""),[c,u]=a.useState(t.prompt??""),[h,g]=a.useState(t.modelProvider??""),[p,f]=a.useState(t.modelId??""),[b,v]=a.useState(t.taskTitle??""),[y,k]=a.useState(t.taskDescription??""),[A,j]=a.useState(t.taskColumn??"triage"),[_,N]=a.useState(t.timeoutMs),[M,w]=a.useState(t.continueOnFailure??!1),[R,E]=a.useState({}),[I,L]=a.useState([]),[ee,$]=a.useState(!1),[T,S]=a.useState(null);a.useEffect(()=>{let O=!1;return $(!0),S(null),Kn().then(X=>{O||L(X.models)}).catch(X=>{O||S(X instanceof Error?X.message:"Failed to load models")}).finally(()=>{O||$(!1)}),()=>{O=!0}},[]);const Y=a.useCallback(()=>{const O={};return i.trim()||(O.name="Step name is required"),l==="command"&&!d.trim()&&(O.command="Command is required"),l==="ai-prompt"&&!c.trim()&&(O.prompt="Prompt is required"),l==="create-task"&&!y.trim()&&(O.taskDescription="Task description is required"),(l==="ai-prompt"||l==="create-task")&&(h||p)&&(!h||!p)&&(O.modelProvider="Both model provider and model ID must be set together"),_!==void 0&&_<1e3&&(O.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(O),Object.keys(O).length===0},[i,l,d,c,y,h,p,_]),K=h&&p?`${h}/${p}`:"",G=a.useCallback(O=>{if(!O)g(""),f("");else{const X=O.indexOf("/");X!==-1&&(g(O.slice(0,X)),f(O.slice(X+1)))}},[]),P=a.useCallback(()=>{if(!Y())return;const O={...t,name:i.trim(),type:l,command:l==="command"?d.trim():void 0,prompt:l==="ai-prompt"?c.trim():void 0,taskTitle:l==="create-task"&&b.trim()?b.trim():void 0,taskDescription:l==="create-task"&&y.trim()?y.trim():void 0,taskColumn:l==="create-task"?A:void 0,modelProvider:(l==="ai-prompt"||l==="create-task")&&h.trim()?h.trim():void 0,modelId:(l==="ai-prompt"||l==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:_||void 0,continueOnFailure:M};l!=="ai-prompt"&&delete O.prompt,l!=="create-task"&&(delete O.taskTitle,delete O.taskDescription,delete O.taskColumn),n(O)},[Y,n,t,i,l,d,c,b,y,A,h,p,_,M]);return e.jsxs("div",{className:"step-editor",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-name-${t.id}`,children:"Step Name"}),e.jsx("input",{id:`step-name-${t.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:O=>r(O.target.value),"aria-invalid":!!R.name}),R.name&&e.jsx("small",{className:"field-error",children:R.name})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-type-${t.id}`,children:"Step Type"}),e.jsxs("select",{id:`step-type-${t.id}`,value:l,onChange:O=>o(O.target.value),children:[e.jsx("option",{value:"command",children:"Command"}),e.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),e.jsx("option",{value:"create-task",children:"Create Task"})]})]}),l==="command"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-command-${t.id}`,children:"Command"}),e.jsx("textarea",{id:`step-command-${t.id}`,placeholder:"e.g. npm test",value:d,onChange:O=>m(O.target.value),rows:2,"aria-invalid":!!R.command}),R.command&&e.jsx("small",{className:"field-error",children:R.command})]}),l==="ai-prompt"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-prompt-${t.id}`,children:"Prompt"}),e.jsx("textarea",{id:`step-prompt-${t.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:c,onChange:O=>u(O.target.value),rows:3,"aria-invalid":!!R.prompt}),R.prompt&&e.jsx("small",{className:"field-error",children:R.prompt})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-model-${t.id}`,children:"Model (optional)"}),e.jsx(Kt,{id:`step-model-${t.id}`,label:"Model",models:I,value:K,onChange:G,placeholder:"Use default",disabled:ee}),T&&e.jsx("small",{className:"field-error",children:T}),e.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),l==="create-task"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-task-title-${t.id}`,children:"Task Title (optional)"}),e.jsx("input",{id:`step-task-title-${t.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:O=>v(O.target.value)}),e.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-task-description-${t.id}`,children:"Task Description *"}),e.jsx("textarea",{id:`step-task-description-${t.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:y,onChange:O=>k(O.target.value),rows:4,"aria-invalid":!!R.taskDescription}),R.taskDescription&&e.jsx("small",{className:"field-error",children:R.taskDescription})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-task-column-${t.id}`,children:"Target Column"}),e.jsxs("select",{id:`step-task-column-${t.id}`,value:A,onChange:O=>j(O.target.value),children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"todo",children:"To Do"})]}),e.jsx("small",{children:"Column where the new task will be created"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-task-model-${t.id}`,children:"Executor Model (optional)"}),e.jsx(Kt,{id:`step-task-model-${t.id}`,label:"Model",models:I,value:K,onChange:G,placeholder:"Use default",disabled:ee}),T&&e.jsx("small",{className:"field-error",children:T}),R.modelProvider&&e.jsx("small",{className:"field-error",children:R.modelProvider}),e.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-timeout-${t.id}`,children:"Timeout (ms, optional)"}),e.jsx("input",{id:`step-timeout-${t.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:_??"",onChange:O=>N(O.target.value?Number(O.target.value):void 0),"aria-invalid":!!R.timeoutMs}),R.timeoutMs&&e.jsx("small",{className:"field-error",children:R.timeoutMs})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:`step-continue-${t.id}`,className:"checkbox-label",children:[e.jsx("input",{id:`step-continue-${t.id}`,type:"checkbox",checked:M,onChange:O=>w(O.target.checked)}),"Continue on failure"]}),e.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),e.jsxs("div",{className:"step-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:P,children:"Save Step"})]})]})}function aP({steps:t,onChange:n,onEditingChange:s}){const[i,r]=a.useState(null);a.useEffect(()=>{s?.(i!==null)},[i,s]);const l=a.useCallback(c=>{const u=sP(c);n([...t,u]),r(u.id)},[t,n]),o=a.useCallback(c=>{n(t.filter(u=>u.id!==c)),i===c&&r(null)},[t,n,i]),d=a.useCallback((c,u)=>{const h=t.findIndex(f=>f.id===c);if(h<0)return;const g=u==="up"?h-1:h+1;if(g<0||g>=t.length)return;const p=[...t];[p[h],p[g]]=[p[g],p[h]],n(p)},[t,n]),m=a.useCallback(c=>{n(t.map(u=>u.id===c.id?c:u)),r(null)},[t,n]);return e.jsxs("div",{className:"steps-editor",children:[e.jsx("div",{className:"steps-editor-header",children:e.jsxs("span",{className:"steps-editor-title",children:["Steps (",t.length,")"]})}),t.length===0&&e.jsx("div",{className:"steps-empty-state",children:e.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),e.jsx("div",{className:"steps-list",children:t.map((c,u)=>e.jsx("div",{className:"step-card",children:i===c.id?e.jsx(iP,{step:c,onSave:m,onCancel:()=>r(null)}):e.jsxs("div",{className:"step-card-row",children:[e.jsx("div",{className:"step-card-drag",children:e.jsx(Vo,{size:14})}),e.jsx("span",{className:"step-card-index",children:u+1}),e.jsx(nP,{type:c.type}),e.jsx("span",{className:"step-card-name",children:c.name}),c.continueOnFailure&&e.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),e.jsxs("div",{className:"step-card-actions",children:[e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>d(c.id,"up"),disabled:u===0,title:"Move up","aria-label":`Move ${c.name} up`,children:e.jsx(Fs,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>d(c.id,"down"),disabled:u===t.length-1,title:"Move down","aria-label":`Move ${c.name} down`,children:e.jsx(Lt,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(c.id),title:"Edit","aria-label":`Edit ${c.name}`,children:e.jsx(Dn,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>o(c.id),title:"Delete","aria-label":`Delete ${c.name}`,children:e.jsx(Ut,{size:14})})]})]})},c.id))}),e.jsxs("div",{className:"steps-add-buttons",children:[e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("command"),children:[e.jsx(qt,{size:14}),"Add Command Step"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("ai-prompt"),children:[e.jsx(qt,{size:14}),"Add AI Prompt Step"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("create-task"),children:[e.jsx(qt,{size:14}),"Add Create Task Step"]})]})]})}const Zp={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},rP={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function lP(t){const n=t.trim();for(const[s,i]of Object.entries(Zp))if(i===n)return s;return"custom"}function oP(t){const n=t.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function cP(t,n,s,i,r){switch(t){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 dP(t){const n=t.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 uP=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],mP=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function pm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function fm({routine:t,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:l}){const o=!!t,d=t?dP(t):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[m,c]=a.useState(t?.name??""),[u,h]=a.useState(t?.description??""),[g,p]=a.useState(d.triggerType),[f,b]=a.useState(d.cronExpression),[v,y]=a.useState(()=>d.triggerType!=="cron"?"custom":lP(d.cronExpression)),[k,A]=a.useState(d.webhookPath),[j,_]=a.useState(d.webhookSecret),[N,M]=a.useState(d.endpoint),[w,R]=a.useState(t?.executionPolicy??"queue"),[E,I]=a.useState(t?.catchUpPolicy??"run_one"),[L,ee]=a.useState(t?.enabled??!0),$=t?.steps&&t.steps.length===1&&t.steps[0].type==="ai-prompt"&&!t.command,T=t?.steps&&t.steps.length===1&&t.steps[0].type==="create-task"&&!t.command,[S,Y]=a.useState(t?.steps&&t.steps.length>0&&!$&&!T?"advanced":"simple"),[K,G]=a.useState(()=>$?"ai-prompt":T?"create-task":"command"),[P,O]=a.useState(t?.command??""),[X,C]=a.useState(t?.steps??[]),[V,de]=a.useState(!1),[B,J]=a.useState(t?.timeoutMs??3e5),[D,he]=a.useState($?t.steps?.[0]?.prompt??"":""),[q,W]=a.useState(T?t.steps?.[0]?.taskTitle??"":""),[me,Re]=a.useState(T?t.steps?.[0]?.taskDescription??"":""),[ve,Me]=a.useState(T?t.steps?.[0]?.taskColumn??"triage":"triage"),[_e,De]=a.useState($||T?t.steps?.[0]?.modelProvider??"":""),[Oe,ze]=a.useState($||T?t.steps?.[0]?.modelId??"":""),[Be,Ae]=a.useState([]),[Ce,Ge]=a.useState(!1),[Te,Xe]=a.useState(null),[re,Z]=a.useState(i??"global"),[ye,ie]=a.useState({}),[Ie,pe]=a.useState(!1),Ue=a.useRef(!0);a.useEffect(()=>()=>{Ue.current=!1},[]),a.useEffect(()=>{i&&Z(i)},[i]),a.useEffect(()=>{let Pe=!1;return Ge(!0),Xe(null),Kn().then(nt=>{Pe||Ae(nt.models)}).catch(nt=>{Pe||Xe(nt instanceof Error?nt.message:"Failed to load models")}).finally(()=>{Pe||Ge(!1)}),()=>{Pe=!0}},[]);const dt=_e&&Oe?`${_e}/${Oe}`:"",ht=a.useCallback(Pe=>{if(!Pe){De(""),ze("");return}const nt=Pe.indexOf("/");nt!==-1&&(De(Pe.slice(0,nt)),ze(Pe.slice(nt+1)))},[]),ue=a.useCallback(()=>{const Pe={};if(m.trim()||(Pe.name="Name is required"),re==="project"&&!r&&(Pe.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?oP(f)||(Pe.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Pe.cronExpression="Cron expression is required"),g==="webhook"&&!k.trim()&&(Pe.webhookPath="Webhook path is required"),g==="api"&&!N.trim()&&(Pe.endpoint="API endpoint is required"),S==="simple")K==="command"&&!P.trim()&&(Pe.command="Command is required"),K==="ai-prompt"&&!D.trim()&&(Pe.prompt="Prompt is required"),K==="create-task"&&!me.trim()&&(Pe.taskDescription="Task description is required"),(_e.trim()&&!Oe.trim()||!_e.trim()&&Oe.trim())&&(Pe.model="Both model provider and model ID must be set, or both must be empty");else{X.length===0&&(Pe.steps="At least one step is required"),V&&(Pe.stepsEditing="Please save or cancel all step edits before saving the routine");const nt=[];X.forEach((kt,yt)=>{kt.name?.trim()||nt.push(`Step ${yt+1}: Name is required`),kt.type==="command"&&!kt.command?.trim()&&nt.push(`Step ${yt+1}: Command is required`),kt.type==="ai-prompt"&&!kt.prompt?.trim()&&nt.push(`Step ${yt+1}: Prompt is required`),kt.type==="create-task"&&!kt.taskDescription?.trim()&&nt.push(`Step ${yt+1}: Task description is required`)}),nt.length>0&&(Pe.steps=nt.join("; "))}return B<1e3&&(Pe.timeoutMs="Timeout must be at least 1 second (1000ms)"),ie(Pe),Object.keys(Pe).length===0},[m,g,f,v,k,N,re,r,S,K,P,D,me,_e,Oe,X,V,B]),te=a.useCallback(async Pe=>{if(Pe.preventDefault(),!!ue()){pe(!0);try{let nt=t?.scope??re??(r?"project":"global");nt==="project"&&!r&&(nt="global");const kt=cP(g,f,k,j,N);let yt,Ct;S==="simple"?K==="command"?yt=P.trim()||void 0:K==="ai-prompt"?Ct=[{id:pm(),type:"ai-prompt",name:m.trim(),prompt:D.trim(),modelProvider:_e.trim()||void 0,modelId:Oe.trim()||void 0}]:Ct=[{id:pm(),type:"create-task",name:m.trim(),taskTitle:q.trim()||void 0,taskDescription:me.trim(),taskColumn:ve,modelProvider:_e.trim()||void 0,modelId:Oe.trim()||void 0}]:Ct=X;const Et={name:m.trim(),agentId:t?.agentId??"",description:u.trim()||void 0,trigger:kt,command:yt,steps:Ct,timeoutMs:B,executionPolicy:w,catchUpPolicy:E,enabled:L,scope:nt};await n(Et)}finally{Ue.current&&pe(!1)}}},[ue,n,m,u,g,f,k,j,N,S,K,P,D,_e,Oe,q,me,ve,X,B,w,E,L,re,r,t?.scope,t?.agentId]),ke="routine-name-error",Ne="routine-cron-error",Ze="routine-webhook-error",xe="routine-endpoint-error",st="routine-command-error",Ee="routine-prompt-error",He="routine-task-description-error",ce="routine-model-error",qe="routine-timeout-error",We=a.useCallback(Pe=>{y(Pe),Pe!=="custom"&&b(Zp[Pe])},[]);return e.jsxs("form",{className:"routine-form",onSubmit:te,noValidate:!0,children:[e.jsx("h4",{className:"settings-section-heading",children:o?"Edit Routine":"New Routine"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-name",children:"Name"}),e.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:m,onChange:Pe=>c(Pe.target.value),"aria-invalid":!!ye.name,"aria-describedby":ye.name?ke:void 0}),ye.name&&e.jsx("small",{id:ke,className:"field-error",children:ye.name})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),e.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:u,onChange:Pe=>h(Pe.target.value),rows:2})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Scope"}),e.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[e.jsxs("button",{type:"button",className:`routine-scope-btn${re==="global"?" active":""}`,onClick:()=>{Z("global"),l?.("global")},role:"radio","aria-checked":re==="global"?"true":"false",disabled:!!t?.scope,title:t?.scope?`Scope is locked to ${t.scope} for existing routines`:"Global scope",children:[e.jsx(yi,{size:12}),"Global"]}),e.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{Z("project"),l?.("project")},role:"radio","aria-checked":re==="project"?"true":"false",disabled:!!t?.scope||!r,title:t?.scope?`Scope is locked to ${t.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[e.jsx(Pn,{size:12}),"Project"]})]}),e.jsx("small",{children:!r&&!t?.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."}),ye.scope&&e.jsx("small",{className:"field-error",children:ye.scope})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Trigger Type"}),e.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[e.jsx(Hm,{size:14}),"Cron"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[e.jsx(th,{size:14}),"Webhook"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[e.jsx(qm,{size:14}),"API"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[e.jsx(Sn,{size:14}),"Manual"]})]})]}),g==="cron"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),e.jsx("select",{id:"routine-frequency",value:v,onChange:Pe=>We(Pe.target.value),children:Object.entries(rP).map(([Pe,nt])=>e.jsx("option",{value:Pe,children:nt},Pe))}),e.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),e.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:Pe=>b(Pe.target.value),disabled:v!=="custom","aria-invalid":!!ye.cronExpression,"aria-describedby":ye.cronExpression?Ne:void 0}),ye.cronExpression?e.jsx("small",{id:Ne,className:"field-error",children:ye.cronExpression}):e.jsx("small",{children:v==="custom"?e.jsxs(e.Fragment,{children:["min hour day month weekday — ",e.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),e.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:k,onChange:Pe=>A(Pe.target.value),"aria-invalid":!!ye.webhookPath,"aria-describedby":ye.webhookPath?Ze:void 0}),ye.webhookPath?e.jsx("small",{id:Ze,className:"field-error",children:ye.webhookPath}):e.jsx("small",{children:"URL path for the webhook endpoint"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),e.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:Pe=>_(Pe.target.value)}),e.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="api"&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),e.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:N,onChange:Pe=>M(Pe.target.value),"aria-invalid":!!ye.endpoint,"aria-describedby":ye.endpoint?xe:void 0}),ye.endpoint?e.jsx("small",{id:xe,className:"field-error",children:ye.endpoint}):e.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Action Mode"}),e.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[e.jsx("button",{type:"button",className:`schedule-mode-btn${S==="simple"?" active":""}`,onClick:()=>Y("simple"),role:"radio","aria-checked":S==="simple",children:"Simple"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${S==="advanced"?" active":""}`,onClick:()=>Y("advanced"),role:"radio","aria-checked":S==="advanced",children:"Multi-Step"})]}),e.jsx("small",{children:S==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),S==="simple"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Action Type"}),e.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[e.jsx("button",{type:"button",className:`schedule-mode-btn${K==="command"?" active":""}`,onClick:()=>G("command"),role:"radio","aria-checked":K==="command",children:"Command"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${K==="ai-prompt"?" active":""}`,onClick:()=>G("ai-prompt"),role:"radio","aria-checked":K==="ai-prompt",children:"AI Prompt"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${K==="create-task"?" active":""}`,onClick:()=>G("create-task"),role:"radio","aria-checked":K==="create-task",children:"Create Task"})]})]}),K==="command"?e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-command",children:"Command"}),e.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:P,onChange:Pe=>O(Pe.target.value),"aria-invalid":!!ye.command,"aria-describedby":ye.command?st:void 0}),ye.command?e.jsx("small",{id:st,className:"field-error",children:ye.command}):e.jsx("small",{children:"Shell command to execute."})]}):K==="ai-prompt"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),e.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:D,onChange:Pe=>he(Pe.target.value),rows:3,"aria-invalid":!!ye.prompt,"aria-describedby":ye.prompt?Ee:void 0}),ye.prompt?e.jsx("small",{id:Ee,className:"field-error",children:ye.prompt}):e.jsx("small",{children:"AI prompt to execute."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),e.jsx(Kt,{id:"routine-model",label:"Model",models:Be,value:dt,onChange:ht,placeholder:"Use default",disabled:Ce}),Te&&e.jsx("small",{className:"field-error",children:Te}),ye.model&&e.jsx("small",{id:ce,className:"field-error",children:ye.model})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),e.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:q,onChange:Pe=>W(Pe.target.value)})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),e.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:me,onChange:Pe=>Re(Pe.target.value),rows:4,"aria-invalid":!!ye.taskDescription,"aria-describedby":ye.taskDescription?He:void 0}),ye.taskDescription?e.jsx("small",{id:He,className:"field-error",children:ye.taskDescription}):e.jsx("small",{children:"Describes the task that will be created."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),e.jsxs("select",{id:"routine-task-column",value:ve,onChange:Pe=>Me(Pe.target.value),children:[e.jsx("option",{value:"triage",children:"Triage"}),e.jsx("option",{value:"todo",children:"To Do"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),e.jsx(Kt,{id:"routine-task-model",label:"Executor Model",models:Be,value:dt,onChange:ht,placeholder:"Use default",disabled:Ce}),Te&&e.jsx("small",{className:"field-error",children:Te}),ye.model&&e.jsx("small",{id:ce,className:"field-error",children:ye.model})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(aP,{steps:X,onChange:C,onEditingChange:de}),ye.steps&&e.jsx("small",{className:"field-error",children:ye.steps}),ye.stepsEditing&&e.jsx("small",{className:"field-error",children:ye.stepsEditing})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),e.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:B,onChange:Pe=>J(Number(Pe.target.value)),"aria-invalid":!!ye.timeoutMs,"aria-describedby":ye.timeoutMs?qe:void 0}),ye.timeoutMs?e.jsx("small",{id:qe,className:"field-error",children:ye.timeoutMs}):e.jsx("small",{children:"Maximum execution time in milliseconds."})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),e.jsx("select",{id:"routine-execution-policy",value:w,onChange:Pe=>R(Pe.target.value),children:uP.map(Pe=>e.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))}),e.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),e.jsx("select",{id:"routine-catchup-policy",value:E,onChange:Pe=>I(Pe.target.value),children:mP.map(Pe=>e.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))}),e.jsx("small",{children:"What to do when a scheduled run is missed"})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[e.jsx("input",{id:"routine-enabled",type:"checkbox",checked:L,onChange:Pe=>ee(Pe.target.checked)}),"Enabled"]}),e.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:Ie,children:"Cancel"}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ie,children:Ie?"Saving…":o?"Save Changes":"Create Routine"})]})]})}const hP=3e4;function pP({onClose:t,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[l,o]=a.useState([]),[d,m]=a.useState("list"),[c,u]=a.useState(),[h,g]=a.useState(null),p=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),f=a.useCallback(async()=>{try{const I=await ry(p);o(I)}catch(I){n(fe(I)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const I=setInterval(()=>{f()},hP);return()=>clearInterval(I)},[f]),a.useEffect(()=>{const I=L=>{L.key==="Escape"&&(d!=="list"?(m("list"),u(void 0)):t())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[t,d]);const b=a.useCallback(I=>{I.target===I.currentTarget&&t()},[t]),v=a.useCallback(async I=>{try{await ly(I,p),n("Routine created","success"),m("list"),await f()}catch(L){n(fe(L)||"Failed to create routine","error")}},[n,f,p]),y=a.useCallback(I=>{u(I),m("edit")},[]),k=a.useCallback(async I=>{if(c)try{await td(c.id,I,p),n("Routine updated","success"),m("list"),u(void 0),await f()}catch(L){n(fe(L)||"Failed to update routine","error")}},[c,n,f,p]),A=a.useCallback(async I=>{try{await oy(I.id,p),n(`Deleted "${I.name}"`,"success"),await f()}catch(L){n(fe(L)||"Failed to delete routine","error")}},[n,f,p]),j=a.useCallback(async I=>{g(I.id);try{const{result:L}=await cy(I.id,p);L.success?n(`"${I.name}" completed successfully`,"success"):n(`"${I.name}" failed: ${L.error||"Unknown error"}`,"error"),await f()}catch(L){n(fe(L)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),_=a.useCallback(async I=>{try{await td(I.id,{enabled:!I.enabled},p),n(`"${I.name}" ${I.enabled?"disabled":"enabled"}`,"success"),await f()}catch(L){n(fe(L)||"Failed to toggle routine","error")}},[n,f,p]),N=a.useCallback(()=>{m("list"),u(void 0)},[]),M=a.useCallback(I=>{r(I),m("list"),u(void 0)},[]),w=()=>d==="create"?e.jsx(fm,{onSubmit:v,onCancel:N,scope:i,projectId:s}):d==="edit"&&c?e.jsx(fm,{routine:c,onSubmit:k,onCancel:N,scope:i,projectId:s}):l.length===0?e.jsxs("div",{className:"routine-empty-state",children:[e.jsx(Sn,{size:48,strokeWidth:1}),e.jsx("h4",{children:"No automations yet"}),e.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),children:[e.jsx(qt,{size:14}),"Create your first automation"]})]}):e.jsx("div",{className:"routine-list",children:l.map(I=>e.jsx(tP,{routine:I,onEdit:y,onDelete:A,onRun:j,onToggle:_,running:h===I.id},I.id))}),R=()=>w(),E=d==="list"&&l.length>0;return e.jsx("div",{className:"modal-overlay open",onClick:b,children:e.jsxs("div",{className:"modal modal-lg",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[e.jsxs("div",{className:"modal-header scheduling-modal-header",children:[e.jsxs("div",{className:"scheduling-header-main-row",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx(Sn,{size:20,className:"icon-triage"}),e.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),e.jsxs("div",{className:"modal-header-actions",children:[E&&e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),"aria-label":"Create new automation",children:[e.jsx(qt,{size:14}),"New Automation"]}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:e.jsx(Ft,{size:20})})]})]}),e.jsx("div",{className:"scheduling-header-scope-row",role:"group","aria-label":"Scheduling scope",children:e.jsxs("div",{className:"scheduling-scope-selector",children:[e.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>M("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[e.jsx(yi,{size:14}),"Global"]}),e.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>M("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[e.jsx(Pn,{size:14}),"Project"]})]})})]}),e.jsxs("div",{className:"scheduling-summary","aria-live":"polite",children:[e.jsx(Sn,{size:14}),e.jsxs("span",{children:[l.length," automation",l.length===1?"":"s"]})]}),e.jsx("div",{className:"detail-tabs",role:"tablist",children:e.jsxs("button",{className:"detail-tab detail-tab-active",role:"tab",id:"tab-routines","aria-selected":"true","aria-controls":"scheduled-tasks-content",onClick:()=>{m("list"),u(void 0)},children:[e.jsx(Sn,{size:14})," Routines"]})}),e.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:R()})]})})}const fP=3e4,Fo=new Map,no=new Map;function gm(t){return t??"default"}function bm(t){const n=Fo.get(t);return n?Date.now()>=n.expiresAt?(Fo.delete(t),null):n:null}function gP(t,n){const s=t.some(r=>r.id!=="github"&&r.authenticated),i=t.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function bP(t){const n=no.get(t);if(n)return n;const s=wi().then(({providers:i,ghCli:r})=>{const o={...gP(i,r),ghCli:r,expiresAt:Date.now()+fP};return Fo.set(t,o),o}).finally(()=>{no.delete(t)});return no.set(t,s),s}function ef(t){const n=gm(t),s=bm(n),[i,r]=a.useState(s?.hasAiProvider??!1),[l,o]=a.useState(s?.hasGithub??!1),[,d]=a.useState(s?.ghCli),[m,c]=a.useState(s==null),u=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=gm(t),p=bm(g);if(p)return r(p.hasAiProvider),o(p.hasGithub),d(p.ghCli),c(!1),u.current=!0,()=>{h=!0};u.current=!1;async function f(){!u.current&&c(!0);try{const v=await bP(g);if(h)return;r(v.hasAiProvider),o(v.hasGithub),d(v.ghCli)}catch{}finally{h||(u.current=!0,c(!1))}}return f(),()=>{h=!0}},[t]),a.useMemo(()=>({hasAiProvider:i,hasGithub:l,loading:m,hasWarnings:!i||!l}),[i,l,m])}function tf({hasAiProvider:t,hasGithub:n,compact:s=!1,onDismiss:i}){if(t&&n)return null;const r=i?e.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:e.jsx(Ft,{size:16,"aria-hidden":"true"})}):null;if(s)return e.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[e.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const l=[];return t||l.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||l.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."}),e.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,l.map(o=>e.jsxs("div",{className:"setup-warning-banner__item",children:[e.jsx("strong",{className:"setup-warning-banner__title",children:o.title}),e.jsx("p",{className:"setup-warning-banner__description",children:o.description})]},o.key))]})}function xP({isOpen:t,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:l,onPlanningMode:o,onSubtaskBreakdown:d}){const[m,c]=a.useState(""),[u,h]=a.useState([]),[g,p]=a.useState([]),[f,b]=a.useState(!1),[v,y]=a.useState(""),[k,A]=a.useState(""),[j,_]=a.useState(""),[N,M]=a.useState(""),[w,R]=a.useState(""),[E,I]=a.useState("default"),[L,ee]=a.useState(!1),[$,T]=a.useState([]),[S,Y]=a.useState(!1),[K,G]=a.useState(void 0),[P,O]=a.useState(ds),[X,C]=a.useState(null),[V,de]=a.useState([]),[B,J]=a.useState(!1),[D,he]=a.useState(!1),q=a.useRef(null),[W,me]=a.useState(!1),[Re,ve]=a.useState(""),Me=a.useRef(null),{hasAiProvider:_e,hasGithub:De,loading:Oe}=ef(s),ze=a.useCallback(pe=>{Y(!0),T(pe)},[]),Be=a.useCallback(()=>{Y(!1)},[]),Ae=a.useCallback(async()=>{if(V.length>0){J(!0);return}he(!0);try{const pe=await aa(void 0,s);de(pe),J(!0)}catch(pe){const Ue=fe(pe);l(Ue?`Failed to load agents: ${Ue}`:"Failed to load agents","error"),J(!1)}finally{he(!1)}},[V.length,s,l]);a.useEffect(()=>{if(!B)return;const pe=Ue=>{q.current&&!q.current.contains(Ue.target)&&J(!1)};return document.addEventListener("mousedown",pe),()=>document.removeEventListener("mousedown",pe)},[B]),a.useEffect(()=>{if(!W)return;const pe=Ue=>{Me.current&&!Me.current.contains(Ue.target)&&(me(!1),ve(""))};return document.addEventListener("mousedown",pe),()=>document.removeEventListener("mousedown",pe)},[W]);const Ce=i.filter(pe=>!u.includes(pe.id)).sort((pe,Ue)=>{const dt=Ue.createdAt.localeCompare(pe.createdAt);if(dt!==0)return dt;const ht=parseInt(pe.id.slice(pe.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ue.id.slice(Ue.id.lastIndexOf("-")+1),10)||0)-ht}),Ge=Re?Ce.filter(pe=>pe.id.toLowerCase().includes(Re.toLowerCase())||pe.title&&pe.title.toLowerCase().includes(Re.toLowerCase())||pe.description&&pe.description.toLowerCase().includes(Re.toLowerCase())):Ce,Te=(pe,Ue)=>pe.length>Ue?pe.slice(0,Ue)+"…":pe;a.useEffect(()=>{const pe=m.trim()!==""||u.length>0||g.length>0||v!==""||k!==""||j!==""||N!==""||$.length>0||X!==null||K!==void 0||P!==ds;ee(pe)},[m,u,g,v,k,j,N,$,X,K,P]);const Xe=a.useCallback(()=>{L&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(pe=>URL.revokeObjectURL(pe.previewUrl)),p([]),c(""),h([]),y(""),A(""),_(""),M(""),R(""),I("default"),T([]),Y(!1),C(null),J(!1),G(void 0),O(ds),ee(!1),n())},[L,n,g]),re=a.useCallback(async()=>{const pe=m.trim();if(!(!pe||f)){b(!0);try{const Ue=v.indexOf("/"),dt=k.indexOf("/"),ht=j.indexOf("/"),ue=await r({title:void 0,description:pe,column:"triage",dependencies:u.length?u:void 0,enabledWorkflowSteps:S?$.length>0?$:[]:void 0,...X?{assignedAgentId:X}:{},modelPresetId:E==="preset"&&w||void 0,modelProvider:v&&Ue!==-1?v.slice(0,Ue):void 0,modelId:v&&Ue!==-1?v.slice(Ue+1):void 0,validatorModelProvider:k&&dt!==-1?k.slice(0,dt):void 0,validatorModelId:k&&dt!==-1?k.slice(dt+1):void 0,planningModelProvider:j&&ht!==-1?j.slice(0,ht):void 0,planningModelId:j&&ht!==-1?j.slice(ht+1):void 0,thinkingLevel:N!==""?N:void 0,reviewLevel:K,priority:P});if(g.length>0){const te=[];for(const ke of g)try{await Da(ue.id,ke.file,s)}catch{te.push(ke.file.name)}te.length>0&&l(`Failed to upload: ${te.join(", ")}`,"error")}g.forEach(te=>URL.revokeObjectURL(te.previewUrl)),p([]),c(""),h([]),y(""),A(""),_(""),M(""),R(""),I("default"),T([]),Y(!1),C(null),J(!1),G(void 0),O(ds),l(`Created ${ue.id}`,"success"),n()}catch(Ue){l(fe(Ue)||"Failed to create task","error")}finally{b(!1)}}},[m,u,g,v,k,j,N,f,r,l,n,s,E,w,$,S,X,K,P]),Z=a.useCallback(pe=>{pe.key==="Escape"&&(pe.preventDefault(),Xe())},[Xe]),ie=(X?V.find(pe=>pe.id===X):void 0)?.name??X,Ie=e.jsxs("div",{className:"new-task-quick-fields",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Dependencies"}),e.jsxs("div",{className:"dep-trigger-wrap",ref:Me,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>me(pe=>!pe),disabled:f,"data-testid":"dep-trigger",children:u.length>0?`${u.length} selected`:"Add dependencies"}),W&&e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Re,onChange:pe=>ve(pe.target.value),onClick:pe=>pe.stopPropagation()}),Ge.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ge.map(pe=>e.jsxs("div",{className:`dep-dropdown-item${u.includes(pe.id)?" selected":""}`,onClick:()=>{h(u.includes(pe.id)?u.filter(Ue=>Ue!==pe.id):[...u,pe.id]),me(!1),ve("")},onMouseDown:Ue=>Ue.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:pe.id}),e.jsx("span",{className:"dep-dropdown-title",children:Te(pe.title||pe.description||pe.id,30)})]},pe.id))]})]}),u.length>0&&e.jsx("div",{className:"selected-deps",children:u.map(pe=>e.jsxs("span",{className:"dep-chip",children:[pe,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(u.filter(Ue=>Ue!==pe)),disabled:f,children:"×"})]},pe))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Assign Agent"}),e.jsxs("div",{className:"agent-trigger-wrap",ref:q,children:[e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{B?J(!1):Ae()},disabled:f,"data-testid":"new-task-agent-button",children:[e.jsx(sn,{size:12,style:{verticalAlign:"middle"}}),ie?` ${ie}`:" Assign agent"]}),B&&e.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:pe=>pe.preventDefault(),children:[e.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),D&&e.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!D&&V.filter(pe=>pe.state!=="terminated").map(pe=>e.jsxs("div",{className:`dep-dropdown-item${X===pe.id?" selected":""}`,onMouseDown:Ue=>Ue.preventDefault(),onClick:()=>{C(pe.id===X?null:pe.id),J(!1)},"data-testid":`agent-option-${pe.id}`,children:[e.jsx(sn,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:pe.role}),e.jsx("span",{className:"dep-dropdown-title",children:pe.name})]},pe.id)),!D&&V.filter(pe=>pe.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),X&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:pe=>pe.preventDefault(),onClick:()=>{C(null),J(!1)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return t?e.jsx("div",{className:"modal-overlay open",onClick:Xe,onKeyDown:Z,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:pe=>pe.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"New Task"}),e.jsx("button",{className:"modal-close",onClick:Xe,disabled:f,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[!Oe&&e.jsx(tf,{hasAiProvider:_e,hasGithub:De}),e.jsx(Wp,{mode:"create",description:m,onDescriptionChange:c,dependencies:u,onDependenciesChange:h,executorModel:v,onExecutorModelChange:y,validatorModel:k,onValidatorModelChange:A,presetMode:E,onPresetModeChange:I,selectedPresetId:w,onSelectedPresetIdChange:R,selectedWorkflowSteps:$,onWorkflowStepsChange:ze,onDefaultOnApplied:Be,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:l,isActive:t,onPlanningMode:o,onSubtaskBreakdown:d,onClose:Xe,planningModel:j,onPlanningModelChange:_,thinkingLevel:N,onThinkingLevelChange:M,reviewLevel:K,onReviewLevelChange:G,priority:P,onPriorityChange:O,renderBelowPrimary:Ie,hideDependencies:!0})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:Xe,disabled:f,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:re,disabled:!m.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const vP=5e3;function yP(t={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:l=!1}=t,[o,d]=a.useState([]),[m,c]=a.useState(!1),[u,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{c(!0),h(null);let A;l?A=await dd({limit:i,projectId:n,type:s}):A=(await nd({limit:i,type:s,projectId:n})).map(_=>({..._,projectId:n??"",projectName:""})),d(A),p(A.length===i),A.length>0&&(b.current=A[A.length-1].timestamp)}catch(A){h(A instanceof Error?A.message:"Failed to load activity log")}finally{c(!1)}},[i,n,s,l]),y=a.useCallback(async()=>{if(b.current)try{c(!0);let A;l?A=await dd({limit:i,projectId:n,type:s,since:b.current}):A=(await nd({limit:i,type:s,since:b.current,projectId:n})).map(_=>({..._,projectId:n??"",projectName:""})),d(j=>[...j,...A]),p(A.length===i),A.length>0&&(b.current=A[A.length-1].timestamp)}catch(A){h(A instanceof Error?A.message:"Failed to load more entries")}finally{c(!1)}},[i,n,s,l]),k=a.useCallback(()=>{d([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},vP),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:o,loading:m,error:u,refresh:v,clear:k,hasMore:g,loadMore:y}}const so={"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"},kP={"task:created":e.jsx(qt,{size:14,className:"activity-icon created"}),"task:moved":e.jsx(Ba,{size:14,className:"activity-icon moved"}),"task:updated":e.jsx(vn,{size:14,className:"activity-icon updated"}),"task:deleted":e.jsx(Ft,{size:14,className:"activity-icon deleted"}),"task:merged":e.jsx(en,{size:14,className:"activity-icon merged"}),"task:failed":e.jsx(Ua,{size:14,className:"activity-icon failed"}),"settings:updated":e.jsx($a,{size:14,className:"activity-icon settings"})};function jP(t){const n=new Date(t),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),l=Math.floor(i/36e5),o=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function wP({isOpen:t,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:l=[],onProjectFilterChange:o,currentProject:d}){const[m,c]=a.useState("all"),[u,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=m==="all"?void 0:m,b=u==="all"?void 0:u,v=!d&&l.length>0,{entries:y,loading:k,error:A,refresh:j,hasMore:_}=yP({projectId:b,type:f,limit:100,autoRefresh:t,useCentralFeed:v}),N=y.map(I=>({id:I.id,timestamp:I.timestamp,type:I.type,taskId:I.taskId,taskTitle:I.taskTitle,details:I.details,metadata:I.metadata,projectId:I.projectId,projectName:I.projectName})),M=async()=>{try{await dy(),j(),p(!1)}catch{p(!1)}},w=I=>{i&&i(I)},R=I=>{h(I),o?.(I==="all"?void 0:I)};a.useEffect(()=>{if(!t)return;const I=L=>{L.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[t,n,g]);const E=m!=="all"||u!=="all";return t?e.jsx("div",{className:"modal-overlay open",onClick:I=>{I.target===I.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:e.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[e.jsxs("div",{className:"modal-header activity-log-header",children:[e.jsxs("div",{className:"activity-log-title",children:[e.jsx(Ra,{size:18}),e.jsx("span",{children:"Activity Log"})]}),e.jsxs("div",{className:"activity-log-actions",children:[l.length>0&&e.jsxs("div",{className:"activity-log-filter activity-log-filter--project",children:[e.jsx(Pn,{size:14}),e.jsxs("select",{value:u,onChange:I=>R(I.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[e.jsx("option",{value:"all",children:"All Projects"}),l.map(I=>e.jsx("option",{value:I.id,children:I.name},I.id))]})]}),e.jsxs("div",{className:"activity-log-filter",children:[e.jsx(Er,{size:14}),e.jsxs("select",{value:m,onChange:I=>c(I.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[e.jsx("option",{value:"all",children:"All Events"}),Object.entries(so).map(([I,L])=>e.jsx("option",{value:I,children:L},I))]})]}),e.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:k?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14})}),N.length>0&&e.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:e.jsx(Ut,{size:14})})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&e.jsxs("div",{className:"activity-log-active-filters",children:[e.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),u!=="all"&&e.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",l.find(I=>I.id===u)?.name||u]}),m!=="all"&&e.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",so[m]]}),e.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{c("all"),h("all"),o?.(void 0)},children:"Clear all"})]}),e.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[A&&e.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[e.jsx(is,{size:16}),e.jsx("span",{children:A})]}),N.length===0&&!k&&!A&&e.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[e.jsx(Ra,{size:48,className:"activity-log-empty-icon"}),e.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&e.jsx("button",{className:"btn btn-secondary",onClick:()=>{c("all"),h("all"),o?.(void 0)},children:"Clear Filters"})]}),e.jsx("div",{className:"activity-log-list",children:N.map(I=>e.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[e.jsx("div",{className:"activity-log-entry-icon",children:kP[I.type]}),e.jsxs("div",{className:"activity-log-entry-content",children:[e.jsxs("div",{className:"activity-log-entry-header",children:[e.jsx("span",{className:"activity-log-entry-type",children:so[I.type]}),e.jsx("span",{className:"activity-log-entry-time",children:jP(I.timestamp)})]}),e.jsxs("div",{className:"activity-log-entry-details",children:[I.taskId&&e.jsx("button",{className:"activity-log-task-link",onClick:()=>w(I.taskId),"data-testid":"activity-task-link",children:I.taskId}),I.taskTitle&&e.jsx("span",{className:"activity-log-task-title",children:I.taskTitle}),e.jsx("span",{className:"activity-log-entry-text",children:I.details})]}),I.metadata&&Object.keys(I.metadata).length>0&&e.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof I.metadata.from=="string"&&typeof I.metadata.to=="string"&&e.jsxs("span",{className:"activity-log-metadata-item",children:[I.metadata.from," → ",I.metadata.to]}),typeof I.metadata.merged=="boolean"&&e.jsx("span",{className:`activity-log-metadata-item ${I.metadata.merged?"success":"error"}`,children:I.metadata.merged?"Merged":"Not merged"})]})]})]},I.id))}),_&&!k&&e.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),k&&N.length>0&&e.jsx("div",{className:"activity-log-loading",children:e.jsx(ct,{size:20,className:"spin"})})]}),g&&e.jsx("div",{className:"activity-log-confirm-overlay",children:e.jsxs("div",{className:"activity-log-confirm-dialog",children:[e.jsx("h3",{children:"Clear Activity Log?"}),e.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),e.jsxs("div",{className:"activity-log-confirm-actions",children:[e.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),e.jsx("button",{className:"activity-log-confirm-clear",onClick:M,children:"Clear Log"})]})]})})]})}):null}const ka=[{id:"status",label:"Status",icon:Xm},{id:"changes",label:"Changes",icon:Vm},{id:"commits",label:"Commits",icon:Ta},{id:"branches",label:"Branches",icon:Ls},{id:"worktrees",label:"Worktrees",icon:Kg},{id:"stashes",label:"Stashes",icon:qr},{id:"remotes",label:"Remotes",icon:Gm}];function xm({status:t}){switch(t){case"added":case"untracked":return e.jsx(Mg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return e.jsx(Wm,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return e.jsx(Sg,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return e.jsx(vi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return e.jsx(Pg,{size:14,className:"gm-file-icon"})}}function vm({status:t}){const n=t==="untracked"?"U":t==="added"?"A":t==="modified"?"M":t==="deleted"?"D":t==="renamed"?"R":t==="copied"?"C":"?";return e.jsx("span",{className:`gm-file-badge gm-file-badge-${t}`,children:n})}function NP(t){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),t(`Copied ${s||"to clipboard"}`,"success")}catch{t("Failed to copy","error")}},[t])}function Xi(t){if(!t)return"—";const n=new Date(t);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 l=Math.floor(r/60);if(l<24)return`${l}h ago`;const o=Math.floor(l/24);return o<30?`${o}d ago`:n.toLocaleDateString()}function SP({isOpen:t,onClose:n,tasks:s,addToast:i,projectId:r}){const[l,o]=a.useState("status"),[d,m]=a.useState(!1),[c,u]=a.useState(null),h=a.useRef(null),g=NP(i),[p,f]=a.useState(null),[b,v]=a.useState([]),[y,k]=a.useState(new Set),[A,j]=a.useState(""),[_,N]=a.useState(!1),[M,w]=a.useState(null),[R,E]=a.useState(!1),[I,L]=a.useState(null),[ee,$]=a.useState(null),T=a.useRef(0),[S,Y]=a.useState([]),[K,G]=a.useState(null),[P,O]=a.useState(null),[X,C]=a.useState(!1),[V,de]=a.useState(20),[B,J]=a.useState(""),[D,he]=a.useState([]),[q,W]=a.useState(""),[me,Re]=a.useState(""),[ve,Me]=a.useState(""),[_e,De]=a.useState(null),[Oe,ze]=a.useState([]),[Be,Ae]=a.useState(!1),[Ce,Ge]=a.useState(null),[Te,Xe]=a.useState(null),[re,Z]=a.useState(!1),[ye,ie]=a.useState([]),[Ie,pe]=a.useState([]),[Ue,dt]=a.useState(""),[ht,ue]=a.useState(null),[te,ke]=a.useState(null),[Ne,Ze]=a.useState(null),xe=a.useCallback(async()=>{if(t){m(!0),u(null);try{switch(l){case"status":{const je=await Es(r);f(je);break}case"changes":{const[je,Ke]=await Promise.all([Es(r),_i(r)]);f(je),v(Ke),k(new Set),$(null),w(null),L(null);break}case"commits":{const je=await bv(V,r);Y(je);break}case"branches":{const[je,Ke]=await Promise.all([ca(r),Es(r)]);he(je),f(Ke);break}case"worktrees":{const je=await kv(r);ie(je);break}case"stashes":{const je=await sr(r);pe(je);break}case"remotes":{const je=await Es(r);f(je);break}}}catch(je){u(fe(je)||"Failed to fetch git data"),i(fe(je)||"Failed to fetch git data","error")}finally{m(!1)}}},[l,t,V,i,r]);a.useEffect(()=>{t&&xe()},[xe,t]),a.useEffect(()=>{if(!t)return;const je=Ke=>{if(Ke.key==="Escape"){n();return}if((Ke.key==="ArrowUp"||Ke.key==="ArrowDown")&&Ke.altKey){Ke.preventDefault();const pt=ka.findIndex(Ht=>Ht.id===l);Ke.key==="ArrowUp"&&pt>0?o(ka[pt-1].id):Ke.key==="ArrowDown"&&pt<ka.length-1&&o(ka[pt+1].id)}};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[t,n,l]);const st=a.useCallback(async je=>{try{await Qc(je,r),i(`Staged ${je.length} file(s)`,"success");const Ke=await _i(r);v(Ke),k(new Set),$(null),w(null),L(null)}catch(Ke){i(fe(Ke)||"Failed to stage files","error")}},[i,r]),Ee=a.useCallback(async je=>{try{await _v(je,r),i(`Unstaged ${je.length} file(s)`,"success");const Ke=await _i(r);v(Ke),k(new Set),$(null),w(null),L(null)}catch(Ke){i(fe(Ke)||"Failed to unstage files","error")}},[i,r]),He=a.useCallback(async je=>{if(confirm(`Discard changes to ${je.length} file(s)? This cannot be undone.`))try{await Tv(je,r),i(`Discarded changes to ${je.length} file(s)`,"success");const[Ke,pt]=await Promise.all([_i(r),Es(r)]);v(Ke),f(pt),k(new Set),$(null),w(null),L(null)}catch(Ke){i(fe(Ke)||"Failed to discard changes","error")}},[i,r]),ce=a.useCallback(async je=>{if(je.preventDefault(),!!A.trim()){N(!0);try{const Ke=await Xc(A.trim(),r);i(`Committed: ${Ke.hash}`,"success"),j("");const[pt,Ht]=await Promise.all([_i(r),Es(r)]);v(pt),f(Ht),$(null),w(null),L(null)}catch(Ke){i(fe(Ke)||"Failed to commit","error")}finally{N(!1)}}},[A,i,r]),qe=a.useCallback(async()=>{if(A.trim()){N(!0);try{const je=b.filter(fn=>!fn.staged).map(fn=>fn.file);je.length>0&&await Qc(je,r);const Ke=await Xc(A.trim(),r);i(`Committed: ${Ke.hash}`,"success"),j("");const[pt,Ht]=await Promise.all([_i(r),Es(r)]);v(pt),f(Ht),$(null),w(null),L(null)}catch(je){i(fe(je)||"Failed to commit","error")}finally{N(!1)}}},[A,b,i,r]),We=a.useCallback(async(je,Ke)=>{$({file:je,staged:Ke}),E(!0),L(null);const pt=T.current+1;T.current=pt;try{const Ht=await Pv(je,Ke,r);if(T.current!==pt)return;w(Ht)}catch(Ht){if(T.current!==pt)return;const fn=fe(Ht)||"Failed to load file diff";w(null),L(fn),i(fn,"error")}finally{T.current===pt&&E(!1)}},[i,r]),Pe=a.useCallback(je=>{k(Ke=>{const pt=new Set(Ke);return pt.has(je)?pt.delete(je):pt.add(je),pt})},[]),nt=a.useCallback(async je=>{if(K===je){G(null),O(null);return}G(je),C(!0);try{const Ke=await Tr(je,r);O(Ke)}catch(Ke){i(fe(Ke)||"Failed to load diff","error"),O(null)}finally{C(!1)}},[K,i,r]),kt=a.useCallback(()=>{de(je=>Math.min(je+20,100))},[]),yt=a.useMemo(()=>{if(!B.trim())return S;const je=B.toLowerCase();return S.filter(Ke=>Ke.message.toLowerCase().includes(je)||Ke.author.toLowerCase().includes(je)||Ke.shortHash.toLowerCase().includes(je))},[S,B]),Ct=a.useCallback(async je=>{if(je.preventDefault(),!!q.trim()){m(!0);try{await jv(q.trim(),me.trim()||void 0,r),i(`Created branch ${q}`,"success"),W(""),Re("");const Ke=await ca(r);he(Ke)}catch(Ke){i(fe(Ke)||"Failed to create branch","error")}finally{m(!1)}}},[q,me,i,r]),Et=a.useCallback(async je=>{m(!0);try{await wv(je,r),i(`Switched to ${je}`,"success");const[Ke,pt]=await Promise.all([Es(r),ca(r)]);f(Ke),he(pt)}catch(Ke){i(fe(Ke)||"Failed to checkout branch","error")}finally{m(!1)}},[i,r]),Pt=a.useCallback(async je=>{if(confirm(`Delete branch "${je}"?`)){m(!0);try{await Yc(je,void 0,r),i(`Deleted branch ${je}`,"success");const Ke=await ca(r);he(Ke)}catch(Ke){if(fe(Ke).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await Yc(je,!0,r),i(`Force deleted branch ${je}`,"success");const pt=await ca(r);he(pt)}catch(pt){i(fe(pt)||"Failed to delete branch","error")}}else i(fe(Ke)||"Failed to delete branch","error")}finally{m(!1)}}},[i,r]),It=a.useMemo(()=>{if(!ve.trim())return D;const je=ve.toLowerCase();return D.filter(Ke=>Ke.name.toLowerCase().includes(je))},[D,ve]),bt=a.useCallback(async je=>{if(_e===je){De(null),ze([]),Ge(null),Xe(null);return}De(je),ze([]),Ge(null),Xe(null),Ae(!0);try{const Ke=await yv(je,10,r);ze(Ke)}catch{ze([])}finally{Ae(!1)}},[_e,r]),_t=a.useCallback(async je=>{if(Ce===je){Ge(null),Xe(null);return}Ge(je),Xe(null),Z(!0);try{const Ke=await Tr(je,r);Xe(Ke)}catch{Xe(null)}finally{Z(!1)}},[Ce,r]),Ve=a.useCallback(()=>{De(null),ze([]),Ge(null),Xe(null)},[]),ft=a.useCallback(async je=>{je.preventDefault(),ue("create");try{await Ev(Ue.trim()||void 0,r),i("Changes stashed","success"),dt("");const Ke=await sr(r);pe(Ke)}catch(Ke){i(fe(Ke)||"Failed to stash changes","error")}finally{ue(null)}},[Ue,i,r]),Fe=a.useCallback(async(je,Ke=!1)=>{ue(`apply-${je}`);try{await Mv(je,Ke,r),i(Ke?"Stash popped":"Stash applied","success");const pt=await sr(r);pe(pt)}catch(pt){i(fe(pt)||"Failed to apply stash","error")}finally{ue(null)}},[i,r]),lt=a.useCallback(async je=>{if(confirm(`Drop stash@{${je}}? This cannot be undone.`)){ue(`drop-${je}`);try{await Av(je,r),i("Stash dropped","success");const Ke=await sr(r);pe(Ke)}catch(Ke){i(fe(Ke)||"Failed to drop stash","error")}finally{ue(null)}}},[i,r]),be=a.useCallback(async()=>{ke("fetch");try{const je=await Nv(void 0,r);Ze(je),i(je.message||"Fetch completed",je.fetched?"success":"info");const Ke=await Es(r);f(Ke)}catch(je){i(fe(je)||"Fetch failed","error")}finally{ke(null)}},[i,r]),U=a.useCallback(async()=>{ke("pull");try{const je=await Sv(r);Ze(je),je.conflict?i("Merge conflict detected. Resolve manually.","error"):i(je.message||"Pull completed","success");const Ke=await Es(r);f(Ke)}catch(je){i(fe(je)||"Pull failed","error")}finally{ke(null)}},[i,r]),we=a.useCallback(async()=>{ke("push");try{const je=await Cv(r);Ze(je),i(je.message||"Push completed","success");const Ke=await Es(r);f(Ke)}catch(je){i(fe(je)||"Push failed","error")}finally{ke(null)}},[i,r]),rt=a.useMemo(()=>b.filter(je=>je.staged),[b]),xt=a.useMemo(()=>b.filter(je=>!je.staged),[b]);return t?e.jsx("div",{className:"modal-overlay open",onClick:je=>je.target===je.currentTarget&&n(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal gm-modal",ref:h,children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h3",{children:[e.jsx(ho,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),e.jsxs("div",{className:"gm-header-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:xe,disabled:d,title:"Refresh",children:e.jsx(vn,{size:14,className:d?"spin":""})}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Ft,{size:18})})]})]}),e.jsxs("div",{className:"gm-layout",children:[e.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ka.map(je=>{const Ke=je.icon;return e.jsxs("button",{role:"tab","aria-selected":l===je.id,className:`gm-nav-item${l===je.id?" active":""}`,onClick:()=>o(je.id),children:[e.jsx(Ke,{size:16}),e.jsx("span",{className:"gm-nav-label",children:je.label})]},je.id)})}),e.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&e.jsxs("div",{className:"gm-loading",children:[e.jsx(ct,{size:24,className:"spin"}),e.jsx("span",{children:"Loading..."})]}),c&&!d&&e.jsxs("div",{className:"gm-error",children:[e.jsx(is,{size:18}),e.jsx("span",{children:c}),e.jsx("button",{className:"btn btn-sm",onClick:xe,children:"Retry"})]}),l==="status"&&!d&&p&&e.jsx(CP,{status:p,copyToClipboard:g}),l==="changes"&&!d&&e.jsx(EP,{status:p,stagedFiles:rt,unstagedFiles:xt,selectedFiles:y,toggleFileSelection:Pe,onStageFiles:st,onUnstageFiles:Ee,onDiscardChanges:He,onSelectDiffFile:We,selectedDiffTarget:ee,changeDiff:M,loadingChangeDiff:R,changeDiffError:I,commitMessage:A,setCommitMessage:j,onCommit:ce,onStageAllAndCommit:qe,committing:_}),l==="commits"&&!d&&e.jsx(MP,{commits:yt,commitSearch:B,setCommitSearch:J,selectedCommit:K,commitDiff:P,loadingDiff:X,onCommitClick:nt,onLoadMore:kt,canLoadMore:S.length>=V&&V<100,copyToClipboard:g}),l==="branches"&&!d&&e.jsx(AP,{branches:It,branchSearch:ve,setBranchSearch:Me,newBranchName:q,setNewBranchName:W,branchBase:me,setBranchBase:Re,onCreateBranch:Ct,onCheckoutBranch:Et,onDeleteBranch:Pt,loading:d,allBranches:D,selectedBranch:_e,branchCommits:Oe,loadingBranchCommits:Be,expandedBranchCommit:Ce,branchCommitDiff:Te,loadingBranchCommitDiff:re,onSelectBranch:bt,onBranchCommitClick:_t,onCloseBranchDetails:Ve}),l==="worktrees"&&!d&&e.jsx(PP,{worktrees:ye}),l==="stashes"&&!d&&e.jsx(_P,{stashes:Ie,stashMessage:Ue,setStashMessage:dt,onCreateStash:ft,onApplyStash:Fe,onDropStash:lt,stashLoading:ht}),l==="remotes"&&!d&&e.jsx(TP,{status:p,remoteLoading:te,lastRemoteResult:Ne,onFetch:be,onPull:U,onPush:we,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function CP({status:t,copyToClipboard:n}){return e.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[e.jsx("div",{className:"gm-panel-header",children:e.jsx("h4",{children:"Repository Status"})}),e.jsxs("div",{className:"gm-status-grid",children:[e.jsxs("div",{className:"gm-status-card",children:[e.jsx("span",{className:"gm-status-label",children:"Branch"}),e.jsxs("span",{className:"gm-status-value",children:[e.jsx(Ls,{size:14}),e.jsx("span",{children:t.branch})]})]}),e.jsxs("div",{className:"gm-status-card",children:[e.jsx("span",{className:"gm-status-label",children:"Commit"}),e.jsxs("span",{className:"gm-status-value",children:[e.jsx("code",{className:"gm-hash",children:t.commit}),e.jsx("button",{className:"gm-icon-btn",onClick:()=>n(t.commit,"commit hash"),title:"Copy commit hash",children:e.jsx(qi,{size:12})})]})]}),e.jsxs("div",{className:"gm-status-card",children:[e.jsx("span",{className:"gm-status-label",children:"Working Tree"}),e.jsx("span",{className:`gm-status-badge ${t.isDirty?"dirty":"clean"}`,children:t.isDirty?e.jsxs(e.Fragment,{children:[e.jsx(is,{size:12}),"Modified"]}):e.jsxs(e.Fragment,{children:[e.jsx(en,{size:12}),"Clean"]})})]}),e.jsxs("div",{className:"gm-status-card",children:[e.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),e.jsxs("span",{className:"gm-status-value",children:[t.ahead>0&&e.jsxs("span",{className:"gm-ahead",title:`${t.ahead} commit(s) ahead`,children:[e.jsx(bi,{size:12}),t.ahead]}),t.behind>0&&e.jsxs("span",{className:"gm-behind",title:`${t.behind} commit(s) behind`,children:[e.jsx(Oa,{size:12}),t.behind]}),t.ahead===0&&t.behind===0&&e.jsxs("span",{className:"gm-in-sync",children:[e.jsx(en,{size:12}),"Up to date"]})]})]})]})]})}function EP({status:t,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:l,onUnstageFiles:o,onDiscardChanges:d,onSelectDiffFile:m,selectedDiffTarget:c,changeDiff:u,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:b,onStageAllAndCommit:v,committing:y}){const k=s.filter(j=>i.has(`unstaged:${j.file}`)),A=n.filter(j=>i.has(`staged:${j.file}`));return e.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[t&&e.jsxs("div",{className:"gm-changes-header",children:[e.jsxs("span",{className:"gm-branch-indicator",children:[e.jsx(Ls,{size:14}),t.branch]}),t.isDirty&&e.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),e.jsxs("div",{className:"gm-file-section",children:[e.jsxs("div",{className:"gm-file-section-header",children:[e.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),e.jsxs("div",{className:"gm-file-section-actions",children:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>l(k.map(j=>j.file)),title:"Stage selected",children:[e.jsx(qt,{size:12})," Stage (",k.length,")"]}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>d(k.map(j=>j.file)),title:"Discard selected",children:e.jsx(Ua,{size:12})})]}),s.length>0&&e.jsx("button",{className:"btn btn-sm",onClick:()=>l(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),e.jsx("div",{className:"gm-file-list",children:s.length===0?e.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const _=c?.file===j.file&&c.staged===!1;return e.jsxs("div",{className:`gm-file-item${_?" active":""}`,onClick:()=>m(j.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),m(j.file,!1))},children:[e.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),e.jsx(xm,{status:j.status}),e.jsx("span",{className:"gm-file-name",title:j.file,children:j.file}),e.jsx(vm,{status:j.status}),e.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([j.file])},title:"Stage file",children:e.jsx(qt,{size:12})})]},`unstaged:${j.file}`)})})]}),e.jsxs("div",{className:"gm-file-section",children:[e.jsxs("div",{className:"gm-file-section-header",children:[e.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),e.jsxs("div",{className:"gm-file-section-actions",children:[A.length>0&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>o(A.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",A.length,")"]}),n.length>0&&e.jsx("button",{className:"btn btn-sm",onClick:()=>o(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),e.jsx("div",{className:"gm-file-list",children:n.length===0?e.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const _=c?.file===j.file&&c.staged===!0;return e.jsxs("div",{className:`gm-file-item staged${_?" active":""}`,onClick:()=>m(j.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),m(j.file,!0))},children:[e.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),e.jsx(xm,{status:j.status}),e.jsx("span",{className:"gm-file-name",title:j.file,children:j.file}),e.jsx(vm,{status:j.status}),e.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([j.file])},title:"Unstage file",children:e.jsx(Ft,{size:12})})]},`staged:${j.file}`)})})]}),(c||h||u||g)&&e.jsxs("div",{className:"gm-diff-section",children:[c&&e.jsxs("div",{className:"gm-diff-target",children:[e.jsx(Vm,{size:14}),e.jsxs("span",{children:[c.staged?"Staged":"Unstaged"," diff: "]}),e.jsx("code",{children:c.file})]}),h&&e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&e.jsx("div",{className:"gm-diff-error",children:g}),u&&!h&&e.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&e.jsx("pre",{className:"gm-diff-stat",children:u.stat}),e.jsx("pre",{className:"gm-diff-patch",children:u.patch})]})]}),e.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[e.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>f(j.target.value),rows:3,disabled:y}),e.jsxs("div",{className:"gm-commit-actions",children:[e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:y||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[y?e.jsx(ct,{size:14,className:"spin"}):e.jsx(gi,{size:14}),"Commit"]}),s.length>0&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:y||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function MP({commits:t,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:l,onCommitClick:o,onLoadMore:d,canLoadMore:m,copyToClipboard:c}){return e.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[e.jsxs("div",{className:"gm-panel-header",children:[e.jsx("h4",{children:"Commits"}),e.jsxs("div",{className:"gm-search-box",children:[e.jsx(Oi,{size:14}),e.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:u=>s(u.target.value)})]})]}),e.jsx("div",{className:"gm-commits-list",children:t.length===0?e.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):t.map((u,h)=>e.jsxs("div",{className:"gm-commit-item",children:[e.jsxs("div",{className:"gm-commit-graph",children:[e.jsx("div",{className:"gm-commit-dot"}),h<t.length-1&&e.jsx("div",{className:"gm-commit-line"})]}),e.jsxs("div",{className:"gm-commit-body",children:[e.jsxs("button",{className:"gm-commit-header",onClick:()=>o(u.hash),children:[e.jsxs("div",{className:"gm-commit-top-row",children:[e.jsx("code",{className:"gm-hash",children:u.shortHash}),e.jsx("span",{className:"gm-commit-message",title:u.message,children:u.message})]}),e.jsxs("div",{className:"gm-commit-meta",children:[e.jsx("span",{children:u.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Xi(u.date)}),u.parents.length>1&&e.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),e.jsx("div",{className:"gm-commit-actions-row",children:e.jsx("button",{className:"gm-icon-btn",onClick:()=>c(u.hash,"commit hash"),title:"Copy full hash",children:e.jsx(qi,{size:12})})}),i===u.hash&&e.jsx("div",{className:"gm-commit-diff",children:l?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}):r?e.jsxs(e.Fragment,{children:[r.stat&&e.jsx("pre",{className:"gm-diff-stat",children:r.stat}),e.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},u.hash))}),m&&e.jsx("button",{className:"gm-load-more",onClick:d,children:"Load more commits"})]})}function AP({branches:t,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:l,setBranchBase:o,onCreateBranch:d,onCheckoutBranch:m,onDeleteBranch:c,loading:u,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:y,onSelectBranch:k,onBranchCommitClick:A,onCloseBranchDetails:j}){return e.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[e.jsxs("div",{className:"gm-panel-header",children:[e.jsx("h4",{children:"Branches"}),e.jsxs("div",{className:"gm-search-box",children:[e.jsx(Oi,{size:14}),e.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:_=>s(_.target.value)})]})]}),e.jsxs("form",{className:"gm-create-form",onSubmit:d,children:[e.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:_=>r(_.target.value),disabled:u}),e.jsxs("select",{value:l,onChange:_=>o(_.target.value),disabled:u,className:"gm-branch-select",children:[e.jsx("option",{value:"",children:"Base: HEAD"}),h.map(_=>e.jsx("option",{value:_.name,children:_.name},_.name))]}),e.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:u||!i.trim(),children:[e.jsx(qt,{size:14}),"Create"]})]}),e.jsx("div",{className:"gm-branches-list",children:t.length===0?e.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):t.map(_=>e.jsxs("div",{children:[e.jsxs("div",{className:`gm-branch-item${_.isCurrent?" current":""}${g===_.name?" selected":""}`,onClick:()=>k(_.name),children:[e.jsxs("div",{className:"gm-branch-info",children:[e.jsxs("span",{className:"gm-branch-name",children:[_.isCurrent&&e.jsx(An,{size:14,className:"gm-current-icon"}),_.name]}),_.remote&&e.jsxs("span",{className:"gm-branch-remote",children:["→ ",_.remote]}),_.lastCommitDate&&e.jsx("span",{className:"gm-branch-date",children:Xi(_.lastCommitDate)})]}),e.jsx("div",{className:"gm-branch-actions",children:!_.isCurrent&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),m(_.name)},disabled:u,title:"Checkout",children:e.jsx(Ls,{size:14})}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),c(_.name)},disabled:u,title:"Delete",children:e.jsx(Ut,{size:14})})]})})]}),g===_.name&&e.jsxs("div",{className:"gm-branch-details",children:[e.jsxs("div",{className:"gm-branch-details-header",children:[e.jsxs("span",{className:"gm-branch-details-title",children:[e.jsx(Ta,{size:14}),"Commits on ",_.name]}),e.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:e.jsx(Ft,{size:14})})]}),f?e.jsxs("div",{className:"gm-branch-details-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?e.jsx("div",{className:"gm-empty",children:"No commits found"}):e.jsx("div",{className:"gm-branch-commits-list",children:p.map(N=>e.jsxs("div",{className:"gm-branch-commit",children:[e.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>A(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[e.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),e.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),e.jsxs("div",{className:"gm-commit-meta",children:[e.jsx("span",{children:N.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Xi(N.date)}),N.parents.length>1&&e.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===N.hash&&e.jsx("div",{className:"gm-commit-diff",children:y?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}):v?e.jsxs(e.Fragment,{children:[v.stat&&e.jsx("pre",{className:"gm-diff-stat",children:v.stat}),e.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},N.hash))})]})]},_.name))})]})}function PP({worktrees:t}){return e.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[e.jsxs("div",{className:"gm-panel-header",children:[e.jsx("h4",{children:"Worktrees"}),e.jsxs("div",{className:"gm-worktree-stats",children:[e.jsxs("span",{children:[t.length," total"]}),e.jsx("span",{className:"gm-stat-separator",children:"•"}),e.jsxs("span",{children:[t.filter(n=>n.taskId).length," in use"]})]})]}),e.jsx("div",{className:"gm-worktrees-list",children:t.map(n=>e.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:e.jsxs("div",{className:"gm-worktree-info",children:[e.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&e.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&e.jsx("span",{className:"gm-badge bare",children:"bare"}),e.jsx("span",{className:"gm-worktree-path",title:n.path,children:n.path.split("/").pop()||n.path})]}),e.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&e.jsxs("span",{className:"gm-worktree-branch",children:[e.jsx(Ls,{size:12}),n.branch]}),n.taskId&&e.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function _P({stashes:t,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:l,stashLoading:o}){return e.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[e.jsx("div",{className:"gm-panel-header",children:e.jsx("h4",{children:"Stashes"})}),e.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[e.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:d=>s(d.target.value),disabled:o!==null}),e.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:o!==null,children:[o==="create"?e.jsx(ct,{size:14,className:"spin"}):e.jsx(qr,{size:14}),"Stash"]})]}),e.jsx("div",{className:"gm-stash-list",children:t.length===0?e.jsx("div",{className:"gm-empty",children:"No stashes"}):t.map(d=>e.jsxs("div",{className:"gm-stash-item",children:[e.jsxs("div",{className:"gm-stash-info",children:[e.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${d.index}}`]}),e.jsx("span",{className:"gm-stash-message",children:d.message}),e.jsxs("div",{className:"gm-stash-meta",children:[d.branch&&e.jsxs("span",{className:"gm-stash-branch",children:[e.jsx(Ls,{size:12}),d.branch]}),e.jsx("span",{children:Xi(d.date)})]})]}),e.jsxs("div",{className:"gm-stash-actions",children:[e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(d.index,!1),disabled:o!==null,title:"Apply stash (keep)",children:o===`apply-${d.index}`?e.jsx(ct,{size:14,className:"spin"}):"Apply"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>r(d.index,!0),disabled:o!==null,title:"Pop stash (apply and drop)",children:"Pop"}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>l(d.index),disabled:o!==null,title:"Drop stash",children:o===`drop-${d.index}`?e.jsx(ct,{size:14,className:"spin"}):e.jsx(Ut,{size:14})})]})]},d.index))})]})}function TP({status:t,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:l,addToast:o,projectId:d,copyToClipboard:m}){const c=Z=>{try{return new URL(Z).hostname}catch{return Z.replace(/^git@/,"").split(":")[0]||Z}},[u,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[v,y]=a.useState(""),[k,A]=a.useState(""),[j,_]=a.useState(null),[N,M]=a.useState(""),[w,R]=a.useState(""),[E,I]=a.useState(!1),[L,ee]=a.useState([]),[$,T]=a.useState(!1),[S,Y]=a.useState(null),[K,G]=a.useState([]),[P,O]=a.useState(!1),[X,C]=a.useState(null),V=u.find(Z=>Z.name===S),[de,B]=a.useState(null),[J,D]=a.useState(null),[he,q]=a.useState(!1),[W,me]=a.useState(null),[Re,ve]=a.useState(null),[Me,_e]=a.useState(!1);a.useEffect(()=>{De()},[]),a.useEffect(()=>{t&&t.ahead>0?Oe():t&&t.ahead===0&&ee([])},[t?.ahead]),a.useEffect(()=>{u.length>0&&!S&&Y(u[0].name)},[u]),a.useEffect(()=>{S?ze(S):(G([]),C(null))},[S]),a.useEffect(()=>{S&&!u.find(Z=>Z.name===S)&&Y(u.length>0?u[0].name:null)},[u,S]);const De=async()=>{p(!0);try{const Z=await oh(d);h(Z)}catch(Z){o(fe(Z)||"Failed to load remotes","error")}finally{p(!1)}},Oe=async()=>{T(!0);try{const Z=await xv(d);ee(Z)}catch{ee([])}finally{T(!1)}},ze=async Z=>{O(!0),C(null);try{const ye=await vv(Z,void 0,10,d);G(ye)}catch(ye){C(fe(ye)||"Failed to load remote commits"),G([])}finally{O(!1)}},Be=async Z=>{if(Z.preventDefault(),!(!v.trim()||!k.trim())){b("add");try{await cv(v.trim(),k.trim(),d),o(`Remote '${v}' added successfully`,"success"),y(""),A(""),I(!1),await De()}catch(ye){o(fe(ye)||"Failed to add remote","error")}finally{b(null)}}},Ae=async Z=>{if(confirm(`Are you sure you want to remove remote '${Z}'?`)){b(`remove-${Z}`);try{await dv(Z,d),o(`Remote '${Z}' removed`,"success"),await De()}catch(ye){o(fe(ye)||"Failed to remove remote","error")}finally{b(null)}}},Ce=async Z=>{if(w.trim()){b(`rename-${Z}`);try{await uv(Z,w.trim(),d),o(`Remote renamed to '${w.trim()}'`,"success"),_(null),R(""),await De()}catch(ye){o(fe(ye)||"Failed to rename remote","error")}finally{b(null)}}},Ge=async Z=>{if(N.trim()){b(`url-${Z}`);try{await mv(Z,N.trim(),d),o("Remote URL updated","success"),_(null),M(""),await De()}catch(ye){o(fe(ye)||"Failed to update remote URL","error")}finally{b(null)}}},Te=a.useCallback(async(Z,ye)=>{if(ye==="ahead"){if(de===Z){B(null),D(null);return}B(Z),D(null),q(!0);try{const ie=await Tr(Z);D(ie)}catch{D(null)}finally{q(!1)}}else{if(W===Z){me(null),ve(null);return}me(Z),ve(null),_e(!0);try{const ie=await Tr(Z);ve(ie)}catch{ve(null)}finally{_e(!1)}}},[de,W]),Xe=Z=>{_(`url-${Z.name}`),M(Z.pushUrl||Z.fetchUrl)},re=Z=>{_(`name-${Z.name}`),R(Z.name)};return e.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:e.jsxs("div",{className:"gm-remotes-layout",children:[e.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[e.jsxs("div",{className:"gm-remote-selector-header",children:[e.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>I(!E),disabled:f!==null,title:E?"Cancel":"Add Remote",children:E?e.jsx(Ft,{size:14}):e.jsx(qt,{size:14})})]}),E&&e.jsxs("form",{className:"gm-remote-form",onSubmit:Be,children:[e.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:Z=>y(Z.target.value),disabled:f==="add",className:"gm-input"}),e.jsx("input",{type:"text",placeholder:"Repository URL",value:k,onChange:Z=>A(Z.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!k.trim()||f==="add",children:[f==="add"?e.jsx(ct,{size:12,className:"spin"}):e.jsx(qt,{size:12}),"Add"]})]}),g?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading..."]}):u.length===0?e.jsx("div",{className:"gm-empty",children:"No remotes"}):u.map(Z=>e.jsxs("div",{className:`gm-remote-selector-item${S===Z.name?" selected":""}`,onClick:()=>Y(Z.name),role:"button",tabIndex:0,children:[e.jsxs("div",{className:"gm-remote-selector-info",children:[e.jsxs("span",{className:"gm-remote-selector-name",children:[Z.name,Z.name==="origin"&&e.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),e.jsx("span",{className:"gm-remote-selector-host",children:c(Z.fetchUrl)})]}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:ye=>{ye.stopPropagation(),Ae(Z.name)},disabled:f!==null,title:"Remove remote",children:e.jsx(Ut,{size:14})})]},Z.name))]}),e.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[S&&V?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[e.jsxs("div",{className:"gm-remote-sync-card-header",children:[e.jsx("span",{className:"gm-remote-sync-card-title",children:S}),t&&(t.ahead>0||t.behind>0)&&e.jsxs("div",{className:"gm-remote-status",children:[t.ahead>0&&e.jsxs("div",{className:"gm-remote-indicator ahead",children:[e.jsx(bi,{size:14}),t.ahead," to push"]}),t.behind>0&&e.jsxs("div",{className:"gm-remote-indicator behind",children:[e.jsx(Oa,{size:14}),t.behind," to pull"]})]})]}),e.jsxs("div",{className:"gm-remote-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?e.jsx(ct,{size:14,className:"spin"}):e.jsx(vn,{size:14}),"Fetch"]}),e.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?e.jsx(ct,{size:14,className:"spin"}):e.jsx(ts,{size:14}),"Pull"]}),e.jsxs("button",{className:"btn btn-primary",onClick:l,disabled:n!==null||g,children:[n==="push"?e.jsx(ct,{size:14,className:"spin"}):e.jsx(bi,{size:14}),"Push"]})]})]}),e.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[e.jsxs("div",{className:"gm-remote-detail-urls",children:[e.jsxs("div",{className:"gm-remote-detail-url-row",children:[e.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${S}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:N,onChange:Z=>M(Z.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ge(S),disabled:f===`url-${S}`,children:f===`url-${S}`?e.jsx(ct,{size:12,className:"spin"}):e.jsx(An,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{_(null),M("")},title:"Cancel",children:e.jsx(Ft,{size:12})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"gm-url-value",title:V.fetchUrl,children:V.fetchUrl}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>m(V.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:e.jsx(qi,{size:14})}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Xe(V),disabled:f!==null,title:"Edit remote URL",children:e.jsx(Dn,{size:14})})]})]}),V.pushUrl&&V.pushUrl!==V.fetchUrl&&e.jsxs("div",{className:"gm-remote-detail-url-row",children:[e.jsx("span",{className:"gm-url-label",children:"Push:"}),e.jsx("span",{className:"gm-url-value",title:V.pushUrl,children:V.pushUrl}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>m(V.pushUrl,"push URL"),title:"Copy push URL",children:e.jsx(qi,{size:14})})]})]}),e.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${S}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:w,onChange:Z=>R(Z.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ce(S),disabled:f===`rename-${S}`,children:f===`rename-${S}`?e.jsx(ct,{size:12,className:"spin"}):e.jsx(An,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{_(null),R("")},title:"Cancel",children:e.jsx(Ft,{size:12})})]}):e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(V),disabled:f!==null,title:"Edit remote name",children:e.jsx(Dn,{size:14})})})]}),t&&t.ahead>0&&e.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[e.jsx("div",{className:"gm-section-subheader",children:e.jsxs("h5",{children:[e.jsx(bi,{size:14}),"Commits to Push (",t.ahead,")"]})}),$?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ct,{size:14,className:"spin"}),"Loading..."]}):L.length>0?e.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:L.map(Z=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Te(Z.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[e.jsx("div",{className:"gm-commit-compact-hash",children:e.jsx("code",{className:"gm-hash",children:Z.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:Z.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Xi(Z.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:de===Z.hash?e.jsx(Lt,{size:14}):e.jsx(rn,{size:14})})]}),de===Z.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:he?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}):J?e.jsxs(e.Fragment,{children:[Z.message&&e.jsx("div",{className:"gm-commit-message-full",children:Z.message}),J.stat&&e.jsx("pre",{className:"gm-diff-stat",children:J.stat}),e.jsx("pre",{className:"gm-diff-patch",children:J.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.hash))}):e.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),e.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[e.jsx("div",{className:"gm-section-subheader",children:e.jsxs("h5",{children:[e.jsx(Xm,{size:14}),"Recent commits on ",S]})}),P?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ct,{size:14,className:"spin"}),"Loading commits..."]}):X?e.jsxs("div",{className:"gm-error",children:[e.jsx(is,{size:14}),X]}):K.length===0?e.jsxs("div",{className:"gm-empty",children:["No commits found on ",S,". Try fetching first."]}):e.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:K.map(Z=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Te(Z.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[e.jsx("div",{className:"gm-commit-compact-hash",children:e.jsx("code",{className:"gm-hash",children:Z.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:Z.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Xi(Z.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:W===Z.hash?e.jsx(Lt,{size:14}):e.jsx(rn,{size:14})})]}),W===Z.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Me?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}):Re?e.jsxs(e.Fragment,{children:[Z.message&&e.jsx("div",{className:"gm-commit-message-full",children:Z.message}),Re.stat&&e.jsx("pre",{className:"gm-diff-stat",children:Re.stat}),e.jsx("pre",{className:"gm-diff-patch",children:Re.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.hash))})]})]}):e.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&e.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const ja={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function RP(t,n){return t&&n?`${t}/${n}`:""}function IP(t){if(!t)return{provider:"",modelId:""};const n=t.indexOf("/");return n===-1?{provider:"",modelId:""}:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function $P(t){switch(t){case"file-text":return vi;case"check-circle":return en;case"shield":return Lb;case"zap":return Sn;case"eye":return qo;case"globe":return yi;case"layout-grid":return ji;default:return en}}function DP(t){switch(t.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 FP({isOpen:t,onClose:n,addToast:s,projectId:i}){const[r,l]=a.useState([]),[o,d]=a.useState([]),[m,c]=a.useState(!0),[u,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,b]=a.useState(null),[v,y]=a.useState(!1),[k,A]=a.useState(ja),[j,_]=a.useState(!1),[N,M]=a.useState(!1),[w,R]=a.useState(null),[E,I]=a.useState(null),[L,ee]=a.useState({}),[$,T]=a.useState([]),S=a.useCallback(async()=>{try{c(!0);const D=await Yr(i);l(D)}catch(D){s(fe(D)||"Failed to load workflow steps","error")}finally{c(!1)}},[s,i]),Y=a.useCallback(async()=>{try{const D=await Wa(i);ee(D||{})}catch{}},[i]),K=a.useCallback(async()=>{try{const D=await Kn();T(D.models||[])}catch{}},[]),G=a.useCallback(async()=>{try{h(!0);const D=await py();d(D.templates)}catch(D){s(fe(D)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{t&&(S(),G(),Y(),K())},[t,S,G,Y,K]);const P=a.useCallback(()=>{y(!0),b(null),A(ja)},[]),O=a.useCallback(D=>{b(D.id),y(!1),A({name:D.name,description:D.description,mode:D.mode||"prompt",phase:D.phase||"pre-merge",prompt:D.prompt,scriptName:D.scriptName||"",enabled:D.enabled,defaultOn:D.defaultOn||!1,modelProvider:D.modelProvider||"",modelId:D.modelId||""})},[]),X=a.useCallback(()=>{b(null),y(!1),A(ja)},[]),C=a.useCallback(async()=>{if(!k.name.trim()||!k.description.trim()){s("Name and description are required","error");return}_(!0);try{const D=k.mode==="prompt"&&k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:k.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const he={name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"&&k.prompt.trim()||void 0,scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...D};await sd(he,i),s("Workflow step created","success")}else f&&(await uy(f,{name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"?k.prompt:"",scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn,...D},i),s("Workflow step updated","success"));y(!1),b(null),A(ja),await S()}catch(D){s(fe(D)||"Failed to save workflow step","error")}finally{_(!1)}},[k,v,f,s,S]),V=a.useCallback(async D=>{try{await my(D,i),s("Workflow step deleted","success"),R(null),f===D&&(b(null),A(ja)),await S()}catch(he){s(fe(he)||"Failed to delete workflow step","error")}},[f,s,S]),de=a.useCallback(async()=>{if(!(!f&&!v)&&k.mode==="prompt"){if(v){if(!k.name.trim()||!k.description.trim()){s("Name and description are required before refining","error");return}_(!0);try{const D=k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:{},he={name:k.name.trim(),description:k.description.trim(),mode:"prompt",prompt:k.prompt.trim()||void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...D},q=await sd(he,i);y(!1),b(q.id),M(!0);const W=await id(q.id,i);A(me=>({...me,prompt:W.prompt})),s("Prompt refined with AI","success"),await S()}catch(D){s(fe(D)||"Failed to refine prompt","error")}finally{_(!1),M(!1)}return}if(f){M(!0);try{const D=await id(f,i);A(he=>({...he,prompt:D.prompt})),s("Prompt refined with AI","success"),await S()}catch(D){s(fe(D)||"Failed to refine prompt","error")}finally{M(!1)}}}},[f,v,k,s,S]),B=a.useCallback(async D=>{I(D.id);try{await fy(D.id,i),s(`Added ${D.name} workflow step`,"success"),await S(),p("my-steps")}catch(he){const q=fe(he);q?.includes("already exists")?s(`A workflow step named '${D.name}' already exists`,"error"):s(q||"Failed to add workflow step from template","error")}finally{I(null)}},[s,S]);if(!t)return null;const J=v||f!==null;return e.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"workflow-step-manager",children:e.jsxs("div",{className:"modal workflow-step-manager-modal",onClick:D=>D.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h2",{children:"Workflow Steps"}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),e.jsx("div",{className:"wfm-body",children:m?e.jsx("div",{className:"wfm-loading",children:"Loading..."}):e.jsxs(e.Fragment,{children:[!J&&e.jsxs("div",{className:"wfm-tab-row",children:[e.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[e.jsx(Um,{size:14}),"My Workflow Steps (",r.length,")"]}),e.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[e.jsx(ji,{size:14}),"Templates (",o.length,")"]})]}),g==="my-steps"&&!J&&e.jsxs(e.Fragment,{children:[r.length===0&&e.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&&e.jsx("div",{className:"wfm-step-list",children:r.map(D=>e.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${D.id}`,children:e.jsxs("div",{className:"wfm-step-card-top",children:[e.jsxs("div",{className:"wfm-step-card-info",children:[e.jsxs("div",{className:"wfm-step-card-title-row",children:[e.jsx("span",{className:"wfm-step-card-name",children:D.name}),e.jsx("span",{className:`wfm-badge ${D.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:D.enabled?"Enabled":"Disabled"}),e.jsx("span",{className:`wfm-badge ${(D.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(D.mode||"prompt")==="script"?"Script":"AI Prompt"}),e.jsx("span",{className:`wfm-badge ${(D.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(D.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),D.defaultOn&&e.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),e.jsx("div",{className:"wfm-step-card-desc",children:D.description})]}),e.jsxs("div",{className:"wfm-step-card-actions",children:[e.jsx("button",{className:"btn-icon",onClick:()=>O(D),title:"Edit","aria-label":`Edit ${D.name}`,children:e.jsx(Dn,{size:14})}),w===D.id?e.jsxs("div",{className:"wfm-delete-confirm",children:[e.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>V(D.id),title:"Confirm delete","aria-label":`Confirm delete ${D.name}`,children:e.jsx(An,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>R(null),title:"Cancel delete","aria-label":"Cancel delete",children:e.jsx(Ft,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>R(D.id),title:"Delete","aria-label":`Delete ${D.name}`,children:e.jsx(Ut,{size:14})})]})]})},D.id))})]}),g==="templates"&&!J&&e.jsx(e.Fragment,{children:u?e.jsxs("div",{className:"wfm-loading",children:[e.jsx(ct,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):o.length===0?e.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):e.jsx("div",{className:"wfm-template-list",children:o.map(D=>{const he=$P(D.icon),q=DP(D.category),W=E===D.id;return e.jsx("div",{className:"wfm-template-card","data-testid":`template-${D.id}`,children:e.jsxs("div",{className:"wfm-template-inner",children:[e.jsx("div",{className:"wfm-template-icon",children:e.jsx(he,{size:20})}),e.jsxs("div",{className:"wfm-template-content",children:[e.jsxs("div",{className:"wfm-template-title-row",children:[e.jsx("span",{className:"wfm-template-name",children:D.name}),e.jsx("span",{className:q,children:D.category})]}),e.jsx("div",{className:"wfm-template-desc",children:D.description}),e.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>B(D),disabled:W,"data-testid":`add-template-${D.id}`,children:W?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:12,className:"spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qt,{size:12}),"Add"]})})]})]})},D.id)})})}),J&&e.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[e.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),e.jsxs("div",{className:"wfm-form-fields",children:[e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Name"}),e.jsx("input",{type:"text",value:k.name,onChange:D=>A(he=>({...he,name:D.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{value:k.description,onChange:D=>A(he=>({...he,description:D.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Execution Mode"}),e.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[e.jsxs("button",{className:`btn ${k.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>A(D=>({...D,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[e.jsx(ei,{size:14}),"AI Prompt"]}),e.jsxs("button",{className:`btn ${k.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>A(D=>({...D,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[e.jsx(Os,{size:14}),"Run Script"]})]})]}),e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Execution Phase"}),e.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[e.jsx("button",{className:`btn ${k.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>A(D=>({...D,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),e.jsx("button",{className:`btn ${k.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>A(D=>({...D,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),e.jsx("div",{className:"wfm-field-hint",children:k.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),k.mode==="prompt"&&e.jsxs("div",{className:"wfm-field",children:[e.jsxs("div",{className:"wfm-prompt-header",children:[e.jsx("label",{children:"Agent Prompt"}),e.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:de,disabled:!k.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?e.jsx(ct,{size:12,className:"spin"}):e.jsx(Ln,{size:12}),e.jsx("span",{children:"Refine with AI"})]})]}),e.jsx("textarea",{value:k.prompt,onChange:D=>A(he=>({...he,prompt:D.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),k.mode==="prompt"&&e.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[e.jsxs("div",{className:"wfm-model-header",children:[e.jsx("label",{children:"Model Override"}),k.modelProvider&&k.modelId&&e.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>A(D=>({...D,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[e.jsx(Ft,{size:12}),e.jsx("span",{children:"Use default"})]})]}),e.jsx("span",{className:"wfm-model-hint",children:k.modelProvider&&k.modelId?`Using ${k.modelProvider}/${k.modelId}`:"Using global default model"}),e.jsx("div",{"data-testid":"workflow-step-model-select",children:e.jsx(Kt,{models:$,value:RP(k.modelProvider,k.modelId),onChange:D=>{const he=IP(D);A(q=>({...q,modelProvider:he.provider,modelId:he.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),k.mode==="script"&&e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Script"}),Object.keys(L).length===0?e.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):e.jsxs("select",{value:k.scriptName,onChange:D=>A(he=>({...he,scriptName:D.target.value})),"data-testid":"workflow-step-script-select",children:[e.jsx("option",{value:"",children:"Select a script…"}),Object.entries(L).map(([D,he])=>e.jsxs("option",{value:D,children:[D," (",he,")"]},D))]})]}),e.jsxs("label",{className:"wfm-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:k.enabled,onChange:D=>A(he=>({...he,enabled:D.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),e.jsxs("label",{className:"wfm-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:k.defaultOn,onChange:D=>A(he=>({...he,defaultOn:D.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),e.jsxs("div",{className:"wfm-form-actions",children:[e.jsx("button",{className:"btn btn-secondary",onClick:X,disabled:j,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:C,disabled:j||!k.name.trim()||!k.description.trim()||k.mode==="script"&&!k.scriptName.trim(),"data-testid":"save-workflow-step",children:j?"Saving...":v?"Create":"Save"})]})]})]})]})}),!J&&e.jsx("div",{className:"wfm-footer",children:e.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:P,"data-testid":"add-workflow-step",children:[e.jsx(qt,{size:14}),"Add Workflow Step"]})})]})})}const LP=36e5,zP=3e5,io=[{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 OP(t){return t<1e3?`${t}ms`:t<6e4?`${Math.round(t/1e3)}s`:t<36e5?`${Math.round(t/6e4)}m`:t<864e5?`${Math.round(t/36e5)}h`:t<6048e5?`${Math.round(t/864e5)}d`:`${Math.round(t/6048e5)}w`}function BP(t){return typeof t!="number"||!Number.isFinite(t)?LP:Math.max(zP,Math.round(t))}function qI(t){if(io.some(s=>s.value===t))return[...io];const n={value:t,label:`${OP(t)} (custom)`};return[...io,n].sort((s,i)=>s.value-i.value)}const UP=4,HP=5*6e4;function qP(t){const n=BP(t?.heartbeatIntervalMs);return Math.max(n*UP,HP)}function VP(t){const n=t.metadata;return n&&(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor")?!0:!!(t.role==="executor"&&t.name?.startsWith("executor-")&&t.taskId)}function WP(t){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:l}=t,o=VP(t);if(n==="terminated")return{label:"Terminated",icon:e.jsx(cs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:e.jsx(Ns,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:e.jsx(Ds,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||o&&n==="active")return{label:"Running",icon:e.jsx(Ns,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:e.jsx(sn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),m=Date.now()-d,c=qP(l);return m>c?{label:"Unresponsive",icon:e.jsx(Ns,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:e.jsx(Jg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const wa=[{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 KP({isOpen:t,onClose:n,addToast:s,projectId:i}){const[r,l]=a.useState([]),[o,d]=a.useState(!1),[m,c]=a.useState(!1),[u,h]=a.useState(""),[g,p]=a.useState("custom"),[f,b]=a.useState("all"),[v,y]=a.useState(()=>{if(typeof window>"u")return"list";const S=In("fn-agent-view",i);return S==="board"||S==="list"?S:"list"});a.useEffect(()=>{const S=In("fn-agent-view",i);if(S==="board"||S==="list"){y(S);return}y("list")},[i]),a.useEffect(()=>{ms("fn-agent-view",v,i)},[i,v]);const[k,A]=a.useState(null),j=a.useRef(null),_=a.useMemo(()=>f==="all"?r.filter(S=>S.state!=="terminated"):r,[r,f]),N=a.useCallback(async()=>{d(!0);try{const Y=await aa(f!=="all"?{state:f}:void 0,i);l(Y)}catch(S){s(`Failed to load agents: ${fe(S)}`,"error")}finally{d(!1)}},[f,s,i]);a.useEffect(()=>{t&&N()},[t,N]),a.useEffect(()=>{if(!t)return;const S=setInterval(()=>{N()},3e4);return()=>{clearInterval(S)}},[t,N]);const M=async()=>{if(u.trim())try{await Ny({name:u.trim(),role:g},i),s(`Agent "${u}" created`,"success"),h(""),c(!1),N()}catch(S){s(`Failed to create agent: ${fe(S)}`,"error")}},w=async(S,Y)=>{try{await Cy(S,Y,i),s(`Agent state updated to ${Y}`,"success"),N()}catch(K){s(`Failed to update state: ${fe(K)}`,"error")}},R=async(S,Y)=>{if(confirm(`Delete agent "${Y}"? This cannot be undone.`))try{await Ey(S,i),s(`Agent "${Y}" deleted`,"success"),N()}catch(K){s(`Failed to delete agent: ${fe(K)}`,"error")}},E=async(S,Y)=>{const K=r.find(G=>G.id===S);if(K){if(K.role===Y){A(null);return}try{await Sy(S,{role:Y},i),s(`Agent role updated to ${wa.find(G=>G.value===Y)?.label??Y}`,"success"),A(null),N()}catch(G){s(`Failed to update role: ${fe(G)}`,"error")}}},I=(S,Y)=>{S.key==="Escape"&&A(null)},L=S=>wa.find(Y=>Y.value===S)?.label??S,ee=S=>wa.find(Y=>Y.value===S)?.icon??"◆",$=S=>WP(S),T=S=>S.color==="var(--state-active-text)"?"active":S.color==="var(--state-paused-text)"?"paused":S.color==="var(--state-error-text)"?"error":"muted";return t?e.jsx("div",{className:"modal-overlay open",onClick:S=>S.target===S.currentTarget&&n(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{className:"modal-title",children:[e.jsx(sn,{size:20}),"Agents"]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>y("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:e.jsx(ji,{size:16})}),e.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>y("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:e.jsx(po,{size:16})})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void N(),title:"Refresh",disabled:o,children:e.jsx(vn,{size:16,className:o?"spin":""})}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]})]}),e.jsxs("div",{className:"modal-content agent-modal-content",children:[e.jsxs("div",{className:"agent-controls",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(Er,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:S=>b(S.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"terminated",children:"Terminated"})]})]}),e.jsxs("button",{className:"btn btn--primary",onClick:()=>c(!m),children:[e.jsx(qt,{size:16}),m?"Cancel":"New Agent"]})]}),m&&e.jsxs("div",{className:"agent-create-form",children:[e.jsx("input",{type:"text",placeholder:"Agent name...",value:u,onChange:S=>h(S.target.value),onKeyDown:S=>S.key==="Enter"&&M(),className:"input",autoFocus:!0}),e.jsx("select",{className:"select",value:g,onChange:S=>p(S.target.value),children:wa.map(S=>e.jsxs("option",{value:S.value,children:[S.icon," ",S.label]},S.value))}),e.jsx("button",{className:"btn btn--primary",onClick:()=>void M(),children:"Create"})]}),e.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:_.length===0?e.jsxs("div",{className:"agent-empty",children:[e.jsx(sn,{size:48,opacity:.3}),e.jsx("p",{children:"No agents found"}),e.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?_.map(S=>{const Y=$(S),K=T(Y);return e.jsxs("div",{className:"agent-board-card","data-state":S.state,children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:ee(S.role)}),e.jsx("span",{className:"agent-board-badge","data-state":S.state,children:S.state}),e.jsx("span",{className:"agent-board-health","data-health":K,title:Y.label,children:Y.icon})]}),e.jsx("div",{className:"agent-board-name",title:S.name,children:S.name}),e.jsx("div",{className:"agent-board-id",children:S.id}),e.jsxs("div",{className:"agent-board-actions",children:[S.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"active"),title:"Activate",children:e.jsx(an,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(S.id,S.name),title:"Delete",children:e.jsx(Ut,{size:14})})]}),S.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"paused"),title:"Pause",children:e.jsx(Ds,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),S.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"active"),title:"Resume",children:e.jsx(an,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),S.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"paused"),title:"Pause",children:e.jsx(Ds,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),S.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"active"),title:"Retry",children:e.jsx(an,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),S.state==="terminated"&&e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(S.id,S.name),title:"Delete",children:e.jsx(Ut,{size:14})})]})]},S.id)}):_.map(S=>{const Y=$(S),K=T(Y);return e.jsxs("div",{className:"agent-card","data-state":S.state,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[k===S.id?e.jsx("select",{ref:j,className:"select agent-role-select",value:S.role,onChange:G=>void E(S.id,G.target.value),onKeyDown:G=>I(G,S.id),onBlur:()=>A(null),autoFocus:!0,children:wa.map(G=>e.jsxs("option",{value:G.value,children:[G.icon," ",G.label]},G.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>A(S.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&A(S.id)},children:ee(S.role)}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:S.name}),e.jsx("span",{className:"agent-id text-secondary",children:S.id})]})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:"badge agent-list-state-badge","data-state":S.state,children:S.state}),e.jsxs("span",{className:"badge agent-list-health-badge","data-health":K,title:Y.label,children:[Y.icon,!Y.stateDerived&&` ${Y.label}`]}),e.jsx("span",{className:"badge text-secondary",children:L(S.role)})]})]}),e.jsxs("div",{className:"agent-card-body",children:[S.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:S.taskId})]}),S.lastHeartbeatAt&&e.jsxs("div",{className:"agent-heartbeat",children:[e.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),e.jsx("span",{children:new Date(S.lastHeartbeatAt).toLocaleString()})]})]}),e.jsxs("div",{className:"agent-card-actions",children:[S.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"active"),title:"Activate",children:[e.jsx(an,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(S.id,S.name),title:"Delete",children:[e.jsx(Ut,{size:14})," Delete"]})]}),S.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"paused"),title:"Pause",children:[e.jsx(Ds,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),S.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"active"),title:"Resume",children:[e.jsx(an,{size:14})," Resume"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),S.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"paused"),title:"Pause",children:[e.jsx(Ds,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),S.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void w(S.id,"active"),title:"Retry",children:[e.jsx(an,{size:14})," Retry"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void w(S.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),S.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void w(S.id,"active"),title:"Start",children:[e.jsx(an,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(S.id,S.name),title:"Delete",children:[e.jsx(Ut,{size:14})," Delete"]})]})]})]},S.id)})})]})]})}):null}const Si="fusion_model_onboarding_state",Zi=[],ea=[],Ur=!1,Hr=!1,ta={},GP=void 0,Xs=["ai-setup","github","project-setup","first-task"],JP={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ps(){if(typeof window>"u")return null;try{const t=localStorage.getItem(Si);if(!t)return null;const n=JSON.parse(t);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?YP(n):null}catch{return null}}function YP(t){const n=t.postOnboardingDismissedAt??GP;return{...t,completedSteps:t.completedSteps??Zi,skippedSteps:t.skippedSteps??ea,dismissed:t.dismissed??Ur,completed:t.completed??Hr,stepData:t.stepData??ta,...n?{postOnboardingDismissedAt:n}:{}}}function kr(t,n){if(!(typeof window>"u")){if(!n){const s={currentStep:t,updatedAt:new Date().toISOString(),completedSteps:Zi,skippedSteps:ea,dismissed:Ur,completed:Hr,stepData:ta};try{localStorage.setItem(Si,JSON.stringify(s))}catch{}return}try{const s=ps(),i=new Date().toISOString(),r=n.completed??Hr;let l=n.dismissed??Ur;r&&(l=!1);const o=n.completedSteps??s?.completedSteps??Zi,d=n.skippedSteps??s?.skippedSteps??ea,m={...s?.stepData??ta};if(n.stepData)for(const[u,h]of Object.entries(n.stepData))h!==void 0&&(m[u]={...m[u]??{},...h});const c={currentStep:t,updatedAt:i,completedSteps:o,skippedSteps:d,dismissed:l,completed:r,stepData:m};localStorage.setItem(Si,JSON.stringify(c))}catch{}}}function QP(t){if(!(typeof window>"u"))try{const n=ps(),s=new Date().toISOString();if(!n){const l={currentStep:t,updatedAt:s,completedSteps:Zi,skippedSteps:[t],dismissed:Ur,completed:Hr,stepData:ta};localStorage.setItem(Si,JSON.stringify(l));return}const i=n.skippedSteps.includes(t)?n.skippedSteps:[...n.skippedSteps,t],r={...n,skippedSteps:i,completedSteps:n.completedSteps.filter(l=>l!==t),updatedAt:s};localStorage.setItem(Si,JSON.stringify(r))}catch{}}function ym(){if(!(typeof window>"u"))try{const t=ps(),n=new Date().toISOString(),s=t?{...t,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Zi,skippedSteps:ea,dismissed:!1,completed:!0,stepData:ta};localStorage.setItem(Si,JSON.stringify(s))}catch{}}function na(){const t=ps();return t?t.completed===!0?!0:typeof t.completedAt=="string"&&t.completedAt.length>0:!1}function XP(){if(!(typeof window>"u"))try{const t=ps(),n=new Date().toISOString(),s=t?{...t,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Zi,skippedSteps:ea,dismissed:!1,completed:!1,stepData:ta,postOnboardingDismissedAt:n};localStorage.setItem(Si,JSON.stringify(s))}catch{}}function nf(){const t=ps();return t?typeof t.postOnboardingDismissedAt=="string"&&t.postOnboardingDismissedAt.length>0:!1}function ZP(){const t=ps();return!t||na()?!1:t.currentStep!=="complete"}function e_(){const t=ps();if(!t||na()||t.currentStep==="complete")return null;const n=t.currentStep,s=JP[n]??s_(t.currentStep);return{currentStep:t.currentStep,label:s,completedSteps:t.completedSteps}}function t_(){const t=ps();return t?t.skippedSteps:ea}function n_(t){const n=ps();return!n||!n.stepData?null:n.stepData[t]??null}function s_(t){return t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const sf="fusion_onboarding_events",km="fusion_onboarding_session_id",i_=200,a_=50;function ks(t,n={}){if(!(typeof window>"u"))try{const s=l_(),i=d_(n.step),r={type:t,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:r_()},l=c_([...s,r]);o_(l)}catch{}}function r_(){if(typeof window>"u")return"server-session";try{const t=sessionStorage.getItem(km);if(t)return t;const n=jm();return sessionStorage.setItem(km,n),n}catch{return jm()}}function jm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function l_(){try{const t=localStorage.getItem(sf);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(u_):[]}catch{return[]}}function o_(t){try{localStorage.setItem(sf,JSON.stringify(t))}catch{}}function c_(t){const n=[...t];for(;n.length>i_;)n.splice(0,a_);return n}function d_(t){if(t==="ai-setup"||t==="github"||t==="first-task"||t==="complete")return t}function u_(t){if(!t||typeof t!="object")return!1;const n=t;return typeof n.type=="string"&&typeof n.timestamp=="string"&&typeof n.sessionId=="string"&&!!n.metadata&&typeof n.metadata=="object"}const m_=1e4,h_=1e3;function p_(){const[t,n]=a.useState([]),[s,i]=a.useState(!0),[r,l]=a.useState(null),o=a.useRef(null),d=a.useRef(0),m=a.useCallback(async()=>{try{l(null);const p=await od();n(p)}catch(p){l(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await od();p||(n(v),l(null))}catch(v){p||l(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-d.current<h_||(d.current=v,m())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[m]),a.useEffect(()=>{if(!s)return o.current=setInterval(()=>{m()},m_),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async p=>{const f=await Ty(p);return n(b=>[...b,f]),f},[]),u=a.useCallback(async(p,f)=>{const b=await Ry(p,f);return n(v=>v.map(y=>y.id===p?b:y)),b},[]),h=a.useCallback(async p=>{await Iy(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await $y(p);n(b=>b.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:t,loading:s,error:r,refresh:m,register:c,update:u,unregister:h,healthCheck:g}}function af({toasts:t}){return e.jsx("div",{className:"toast-container",id:"toasts",children:t.map(n=>e.jsx("div",{className:`toast toast-${n.type}`,children:n.message},n.id))})}const f_={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"}}},rf={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:"..."}},g_={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},wm={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 Lo(t){if(wm[t])return wm[t];const n=t.trim();return n?n.split(/[-_\s]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"This provider"}const ao=["anthropic","openai","google","gemini","ollama"],b_=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],x_={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"},v_={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function zo(t){return x_[t]??t}function Nm(t){const n=zo(t),s=b_.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Sm(t,n){if(t.authenticated!==n.authenticated)return t.authenticated?-1:1;const s=Nm(t.id),i=Nm(n.id);if(s!==i)return s-i;const r=zo(t.id),l=zo(n.id);if(r!==l)return r.localeCompare(l);const o=v_[r];if(o){const m=o.indexOf(t.id),c=o.indexOf(n.id);if(m!==c)return(m===-1?Number.POSITIVE_INFINITY:m)-(c===-1?Number.POSITIVE_INFINITY:c)}const d=t.name.localeCompare(n.name);return d!==0?d:t.id.localeCompare(n.id)}function y_(t,n){const s=n.trim();if(!s)return"API key is required";const i=rf[t]??g_;return i.pattern.test(s)?null:`${Lo(t)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const lf={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"},k_={description:"AI provider — connect to start using AI models",apiKeyInfo:lf};function Oo(t){return f_[t]??k_}function j_(t){return Oo(t.id).apiKeyInfo??lf}function $s({summary:t,children:n,className:s=""}){const[i,r]=a.useState(!1);return e.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[e.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[e.jsx(rn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),e.jsx("span",{children:t})]}),i&&e.jsx("div",{className:"onboarding-disclosure-content",children:n})]})}function w_({items:t}){return t.some(s=>s.status!=="connected")?e.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[e.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),t.map(s=>{const i=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return e.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[e.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:i}),e.jsxs("span",{className:"onboarding-readiness-content",children:[e.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&e.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):e.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:e.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function N_({provider:t,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:l,isConnected:o,onInputChange:d,onSave:m,onClear:c}){const u=`onboarding-apikey-input-${t.id}`,h=i||!s.trim(),g=rf[t.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${l?" onboarding-apikey-input--success":""}`,f=e.jsxs(e.Fragment,{children:[g&&e.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),e.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&e.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),e.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return o?e.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${t.id}`,children:[e.jsxs("div",{className:"onboarding-apikey-connected-header",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),e.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),e.jsx("button",{className:"btn btn-sm",onClick:()=>c(t.id),disabled:i,children:i?"Removing…":"Remove Key"}),e.jsx($s,{summary:"Advanced setup details",children:f}),r&&e.jsx("small",{className:"field-error",children:r})]}):e.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${t.id}`,children:[e.jsx("label",{htmlFor:u,className:"onboarding-apikey-field-label",children:n.fieldLabel}),e.jsxs("div",{className:"onboarding-apikey-input-row",children:[e.jsx("input",{id:u,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>d(t.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&m(t.id,s)},"data-testid":u}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${t.id}`,children:i?"Saving…":"Save"})]}),r&&e.jsx("small",{className:"field-error",children:r}),l&&!r&&e.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${t.id}`,children:l}),e.jsx($s,{summary:"Advanced setup details",children:f})]})}const S_=150;function C_({onComplete:t,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:l,firstCreatedTask:o,onViewTask:d}){const m=ps(),c=m?.currentStep,u=c==="complete"?"ai-setup":Xs.includes(c)?c:"ai-setup",h=m?.completedSteps??[],g=m?.skippedSteps??t_(),[p,f]=a.useState(!0),[b,v]=a.useState(u),[y,k]=a.useState(h),[A,j]=a.useState(g),[_,N]=a.useState(!1),[M,w]=a.useState(""),[R,E]=a.useState(!1),[I,L]=a.useState(null),[ee,$]=a.useState(null),[T,S]=a.useState([]),[Y,K]=a.useState(void 0),[G,P]=a.useState(!0),[O,X]=a.useState(null),[C,V]=a.useState({}),[de,B]=a.useState([]),[J,D]=a.useState(""),[he,q]=a.useState(!1),[W,me]=a.useState({}),[Re,ve]=a.useState({}),[Me,_e]=a.useState({}),De=a.useRef({}),Oe=a.useRef(null),ze=a.useRef(null),[Be,Ae]=a.useState({}),[Ce,Ge]=a.useState(()=>ps()?.stepData?.github?.skipped===!0),Te=a.useRef(0),Xe=a.useRef(o),re=a.useRef(!1),Z=m?.currentStep,ye=!!m&&m.currentStep!=="complete",[ie,Ie]=a.useState(()=>ps()?.stepData?.["ai-setup"]?.skippedProviders??{}),pe=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Ue=pe.findIndex(x=>x.key===b),dt=b==="complete"?pe.length:Ue;a.useEffect(()=>{b!=="complete"&&kr(b,{completedSteps:y,skippedSteps:A})},[b,y,A]),a.useEffect(()=>{re.current||(re.current=!0,ks("onboarding:wizard-opened",{source:ye?"resume":"initial",resumedFromStep:Z}))},[ye,Z]),a.useEffect(()=>{const x=Xe.current!=null,F=o!=null;!x&&F&&N(!0),F||N(!1),Xe.current=o},[o]);const ht=a.useRef(u);a.useEffect(()=>{if(ht.current==="ai-setup"&&b!=="ai-setup"&&!T.some(F=>F.id!=="github"&&F.authenticated)){const F={};for(const ne of T)ne.id!=="github"&&!ne.authenticated&&!ie[ne.id]&&(F[ne.id]=!0);if(Object.keys(F).length>0){const ne={...ie,...F};Ie(ne),kr(b,{stepData:{"ai-setup":{skippedProviders:ne}}})}}ht.current=b},[b,T,ie]);const ue=a.useCallback(async()=>{try{const{providers:x,ghCli:F}=await wi();S(x),K(F),V(ne=>{const ae={};for(const[oe,ge]of Object.entries(ne)){const et=x.find(jt=>jt.id===oe);et&&!et.authenticated&&(ae[oe]=ge)}return Object.keys(ae).length===Object.keys(ne).length?ne:ae}),Ie(ne=>{const ae={...ne};for(const oe of x)oe.authenticated&&ae[oe.id]&&delete ae[oe.id];return Object.keys(ae).length===Object.keys(ne).length?ne:ae})}catch{}},[]),te=a.useRef(!1);a.useEffect(()=>{te.current&&ue(),te.current=b!=="ai-setup"},[b,ue]);const ke=T.find(x=>x.id==="github"),Ne=!!ke,Ze=ke?.authenticated??!1,xe=Y?.authenticated??!1,st=Ze||xe,Ee=!Ze&&xe,He=a.useCallback(x=>{if(x.authenticated)return"connected";const F=Be?.[x.id];return F==="timeout"||F==="failed"?"retry":ie[x.id]?"skipped":"not-connected"},[Be,ie]);function ce({status:x}){const F={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:ne,className:ae}=F[x];return e.jsx("span",{"data-testid":"provider-status-badge",className:ae,"data-status":x,children:ne})}const qe=a.useCallback(()=>{if(st)return"connected";const x=Be.github;return x==="pending"?"pending":x==="failed"||x==="timeout"?"failed":Ce?"skipped":"not-connected"},[st,Be,Ce]);function We({status:x}){const F={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:ne,className:ae}=F[x];return e.jsx("span",{"data-testid":"github-status-badge",className:ae,"data-status":x,children:ne})}const Pe=a.useCallback(async()=>{try{const x=await Kn();B(x.models)}catch{}},[]),nt=a.useCallback(async()=>{try{const x=await ia();if(x.defaultProvider&&x.defaultModelId){const F=`${x.defaultProvider}/${x.defaultModelId}`;D(F)}}catch{}},[]);a.useEffect(()=>{Promise.all([ue(),Pe(),nt()]).finally(()=>P(!1))},[ue,Pe,nt]),a.useEffect(()=>{const x=n_("ai-setup");if(x?.loginOutcomes){const F=x.loginOutcomes,ne={};for(const[ae,oe]of Object.entries(F))oe!=="pending"&&(ne[ae]=oe);Object.keys(ne).length>0&&Ae(ne)}},[]);const kt=a.useCallback((x,F)=>{kr(b,{completedSteps:y,stepData:{"ai-setup":{loginOutcomes:{[x]:F}}}})},[b,y]);a.useEffect(()=>{const x=Object.entries(Be).filter(([F,ne])=>ne!=="pending");for(const[F,ne]of x)kt(F,ne)},[Be,kt]),a.useEffect(()=>()=>{ze.current&&clearInterval(ze.current),Object.values(De.current).forEach(clearTimeout),De.current={}},[]);const yt=a.useCallback(x=>{Ge(x),kr(b,{completedSteps:y,stepData:{github:{skipped:x}}})},[b,y]),Ct=a.useCallback(x=>x==="complete"?-1:Xs.indexOf(x),[]),Et=a.useCallback(()=>{k(F=>[...new Set([...F,b])]),j(F=>F.filter(ne=>ne!==b)),ks("onboarding:step-completed",{step:b}),b==="github"&&!Ze&&yt(!1);const x=Ct(b);x>=0&&x<Xs.length-1&&v(Xs[x+1])},[b,Ze,yt,Ct]),Pt=a.useCallback(()=>{j(F=>[...new Set([...F,b])]),QP(b),ks("onboarding:step-skipped",{step:b}),b==="github"&&!Ze&&yt(!0);const x=Ct(b);x>=0&&x<Xs.length-1&&v(Xs[x+1])},[b,Ze,yt,Ct]),It=a.useCallback(()=>{const x=b;k(ne=>ne.filter(ae=>ae!==x)),j(ne=>ne.filter(ae=>ae!==x)),x==="github"&&!Ze&&yt(!1);const F=Ct(b);F>0&&v(Xs[F-1])},[b,Ze,yt,Ct]),bt=a.useCallback(()=>{Pt()},[Pt]),_t=a.useCallback(async x=>{Ae(F=>{const ne=F[x];if(ne&&ne!=="pending"){const{[x]:ae,...oe}=F;return oe}return F}),V(F=>{if(!(x in F))return F;const ne={...F};return delete ne[x],ne}),Ae(F=>({...F,[x]:"pending"})),X(x),Te.current=0;try{const{url:F,instructions:ne}=await ih(x);ne?.trim()&&V(ae=>({...ae,[x]:ne})),window.open(Ps(F),"_blank"),ze.current=setInterval(async()=>{if(Te.current++,Te.current>=S_){ze.current&&(clearInterval(ze.current),ze.current=null),X(null),Ae(ae=>({...ae,[x]:"timeout"})),V(ae=>{if(!(x in ae))return ae;const oe={...ae};return delete oe[x],oe}),n("Login timed out. Please try again.","warning");return}try{const{providers:ae,ghCli:oe}=await wi();S(ae),K(oe),ae.find(et=>et.id===x)?.authenticated&&(ze.current&&(clearInterval(ze.current),ze.current=null),X(null),Ae(et=>({...et,[x]:"success"})),V(et=>{if(!(x in et))return et;const jt={...et};return delete jt[x],jt}),x==="github"&&yt(!1),n("Login successful","success"))}catch{}},2e3)}catch(F){F instanceof Error&&F.message.includes("already in progress")||F&&typeof F=="object"&&"status"in F&&F.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ae(ae=>({...ae,[x]:"failed"}))):(n(F instanceof Error?F.message:"Login failed","error"),Ae(ae=>({...ae,[x]:"failed"}))),X(null),V(ae=>{if(!(x in ae))return ae;const oe={...ae};return delete oe[x],oe})}},[n,yt]),Ve=a.useCallback(x=>{ze.current&&(clearInterval(ze.current),ze.current=null),X(null),Te.current=0,Ae(F=>({...F,[x]:"cancelled"})),V(F=>{if(!(x in F))return F;const ne={...F};return delete ne[x],ne})},[]),ft=a.useCallback((x,F)=>{me(ae=>({...ae,[x]:F}));const ne=De.current[x];ne&&(clearTimeout(ne),delete De.current[x]),ve(ae=>{if(!ae[x])return ae;const oe={...ae};return delete oe[x],oe}),_e(ae=>{if(!ae[x])return ae;const oe={...ae};return delete oe[x],oe})},[]),Fe=a.useCallback(()=>{const x=Oe.current;if(!x)return;const F=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof x.scrollTo=="function"){x.scrollTo({top:0,behavior:F?"auto":"smooth"});return}}catch{}x.scrollTop=0},[]),lt=a.useCallback(async(x,F)=>{const ne=(F??W[x]??"").trim(),ae=y_(x,ne);if(ae){ve(ge=>({...ge,[x]:ae}));return}const oe=De.current[x];oe&&(clearTimeout(oe),delete De.current[x]),X(x),ve(ge=>{const et={...ge};return delete et[x],et}),_e(ge=>{if(!ge[x])return ge;const et={...ge};return delete et[x],et});try{await rh(x,ne),await ue(),Fe(),me(ge=>{const et={...ge};return delete et[x],et}),ve(ge=>{if(!ge[x])return ge;const et={...ge};return delete et[x],et}),_e(ge=>({...ge,[x]:"✓ Key saved"})),De.current[x]=setTimeout(()=>{_e(ge=>{if(!ge[x])return ge;const et={...ge};return delete et[x],et}),delete De.current[x]},3e3),n("API key saved","success")}catch(ge){const et=ge instanceof TypeError&&ge.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":ge instanceof Error?ge.message:"Failed to save API key";ve(jt=>({...jt,[x]:et})),_e(jt=>{if(!jt[x])return jt;const Jt={...jt};return delete Jt[x],Jt}),n(et,"error")}finally{X(null)}},[W,n,ue,Fe]),be=a.useCallback(async x=>{X(x);try{await lh(x),await ue(),n("API key removed","success")}catch(F){n(F instanceof Error?F.message:"Failed to clear API key","error")}finally{X(null)}},[n,ue]),U=a.useCallback(async x=>{X(x);try{await ah(x),await ue(),n("Logged out","success")}catch(F){n(F instanceof Error?F.message:"Logout failed","error")}finally{X(null)}},[n,ue]),we=a.useCallback(x=>{D(x)},[]),rt=a.useCallback(async()=>{try{const x={modelOnboardingComplete:!0};if(J){const F=J.indexOf("/"),ne=F!==-1?J.slice(0,F):void 0,ae=F!==-1?J.slice(F+1):J,oe=de.find(ge=>ge.id===ae);oe?(x.defaultProvider=oe.provider,x.defaultModelId=oe.id):ne&&ae&&(x.defaultProvider=ne,x.defaultModelId=ae)}await Wt(x),ym()}catch{}},[J,de,Wt,ym]),xt=a.useCallback(async()=>{const x=[...new Set([...y,"first-task"])];q(!0);try{await rt(),ks("onboarding:completed",{completedSteps:x,skippedSteps:A}),k(x),j(F=>F.filter(ne=>ne!=="first-task")),v("complete")}finally{q(!1)}},[rt,y,A]),je=a.useCallback(async()=>{if(!s)return;const x=M.trim();if(!x){L("Please enter a task description.");return}L(null),E(!0);let F=!1;try{const ne=await sh({description:x},s);$(ne),N(!0),ks("onboarding:first-task-created",{taskId:ne?.id}),n("Task created","success"),F=!0}catch(ne){const ae=ne instanceof Error?ne.message:"Something went wrong creating your task. Please try again.";L(ae),n(ae,"error")}finally{E(!1)}F&&rt()},[s,M,n,rt]),Ke=a.useCallback(async()=>{q(!0);try{await rt()}finally{q(!1)}ks("onboarding:open-new-task",{}),r?.()},[rt,r]),pt=a.useCallback(async()=>{if(st){q(!0);try{await rt()}finally{q(!1)}f(!1),t(),ks("onboarding:open-github-import",{}),l?.()}},[rt,st,t,l]),Ht=a.useCallback(async()=>{ks("onboarding:dismissed",{currentStep:b,completedSteps:y,skippedSteps:A}),q(!0);try{await Wt({modelOnboardingComplete:!0})}catch{}f(!1),t()},[b,y,A,t]),fn=a.useCallback(()=>{ks("onboarding:finished",{}),f(!1),t()},[t]),hn=a.useCallback(()=>{const x=o??ee;x&&(rt(),d?.(x),t())},[o,ee,rt,d,t]),Jn=a.useCallback(()=>{rt(),t()},[rt,t]);if(!p)return null;const Ot=qe(),yn=T.filter(x=>x.id!=="github"),tn=[...yn].sort(Sm),dn=tn.some(x=>!x.type||x.type==="oauth"),nn=tn.some(x=>x.type==="api_key"),Cn=yn.filter(x=>x.authenticated),kn=Cn.length>0,jn=!!s,Yn=b==="github"&&!kn,un=(()=>{if(!J)return"";const x=J.indexOf("/"),F=x===-1?void 0:J.slice(0,x),ne=x===-1?J:J.slice(x+1),ae=de.find(oe=>oe.id===ne&&(!F||oe.provider===F));return ae?.name?ae.name:F?`${Lo(F)} ${ne}`:J})(),$t=[];if(jn?$t.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):$t.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),kn){const x=Lo(Cn[0]?.id??"");$t.push({label:"AI Provider",status:"connected",detail:`${x} connected — AI agents can work on tasks`})}else yn.length>0&&yn.some(x=>ie[x.id])?$t.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):$t.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});st?$t.push({label:"GitHub",status:"connected",detail:Ee?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Ne||Ce?$t.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):$t.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),un&&$t.push({label:"Default Model",status:"connected",detail:un});const wn=o??ee,On=wn?.description?.split(`
|
|
649
|
+
`)[0]?.trim()||wn?.title||"",Nn=new Set(ao),Bn=tn.filter(x=>Nn.has(x.id)).sort((x,F)=>{const ne=ao.indexOf(x.id),ae=ao.indexOf(F.id);return ne!==ae?ne-ae:Sm(x,F)}),rs=tn.filter(x=>x.authenticated&&!Nn.has(x.id)),Vt=tn.filter(x=>!x.authenticated&&!Nn.has(x.id)),_n=x=>{if(x.id==="claude-cli"&&x.type==="cli")return e.jsx(Gp,{authenticated:x.authenticated,onToggled:()=>{ue()}},x.id);if(x.type==="api_key"){const F=Oo(x.id),ne=j_(x);return e.jsxs("div",{"data-testid":`onboarding-provider-card-${x.id}`,className:`onboarding-provider-card${x.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ss,{provider:x.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsxs("strong",{className:"onboarding-provider-card__name",children:[e.jsx(Ym,{size:14,className:"onboarding-provider-key-icon"}),x.name]}),e.jsx("span",{className:"onboarding-provider-card__description",children:F.description}),e.jsx(ce,{status:He(x)}),x.authenticated&&x.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",x.keyHint]})]}),e.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:e.jsx(N_,{provider:x,apiKeyInfo:ne,inputValue:W[x.id]??"",isSaving:O===x.id,error:Re[x.id],success:Me[x.id],isConnected:x.authenticated,onInputChange:ft,onSave:lt,onClear:be})})]},x.id)}return e.jsxs("div",{"data-testid":`onboarding-provider-card-${x.id}`,className:`onboarding-provider-card${x.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ss,{provider:x.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:x.name}),e.jsx("span",{className:"onboarding-provider-card__description",children:Oo(x.id).description}),e.jsx(ce,{status:He(x)})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:O===x.id?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:x.authenticated?"Logging out…":"Waiting for login…"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Ve(x.id),children:"Cancel"})]}):x.authenticated?e.jsx("button",{className:"btn btn-sm",onClick:()=>U(x.id),children:"Logout"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_t(x.id),children:"Login"})}),O===x.id&&C[x.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`onboarding-login-instructions-${x.id}`,children:C[x.id]}),Be[x.id]==="timeout"&&O!==x.id&&e.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Be[x.id]==="failed"&&O!==x.id&&e.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},x.id)};return e.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:e.jsxs("div",{className:"modal model-onboarding-modal",children:[e.jsxs("div",{className:"model-onboarding-header",children:[e.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx(Sn,{size:24})," Set Up AI ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&e.jsxs(e.Fragment,{children:[e.jsx(ts,{size:24})," Connect GitHub ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&e.jsxs(e.Fragment,{children:[e.jsx(Oc,{size:24})," Set Up Your Project"]}),b==="first-task"&&e.jsxs(e.Fragment,{children:[e.jsx(Oc,{size:24})," Create Your First Task"]}),b==="complete"&&e.jsxs(e.Fragment,{children:[e.jsx(en,{size:24})," All Set!"]})]}),b!=="complete"&&e.jsx("button",{className:"modal-close",onClick:Ht,"aria-label":"Skip onboarding",title:"Skip for now",children:e.jsx(Ft,{size:20})})]}),e.jsx("div",{className:"model-onboarding-steps",children:pe.map((x,F)=>{const ne=dt>F,ae=y.includes(x.key)&&ne,oe=A.includes(x.key)&&!y.includes(x.key)&&ne,ge=ae||oe;return e.jsxs("div",{className:"onboarding-step-wrapper",children:[F>0&&e.jsx("div",{className:`model-onboarding-step-connector ${F<=dt?"done":""}`}),ge?e.jsxs("button",{className:`model-onboarding-step-indicator ${b===x.key?"active":""} ${ae?"done":""} ${oe?"skipped":""}`,onClick:()=>v(x.key),"aria-label":`Go back to ${x.label}`,title:`Review ${x.label}`,children:[e.jsx("span",{className:"step-number",children:ae?e.jsx(en,{size:14}):oe?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):F+1}),e.jsx("span",{className:"step-label",children:x.label})]}):e.jsxs("div",{className:`model-onboarding-step-indicator ${b===x.key?"active":""} ${ae?"done":""} ${oe?"skipped":""}`,children:[e.jsx("span",{className:"step-number",children:ae?e.jsx(en,{size:14}):oe?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):F+1}),e.jsx("span",{className:"step-label",children:x.label})]})]},x.key)})}),e.jsxs("div",{className:"model-onboarding-content",ref:Oe,children:[b==="ai-setup"&&e.jsxs("div",{className:"model-onboarding-ai-setup",children:[e.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."}),e.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!G&&T.length>0&&(()=>{const x=T.filter(ge=>ge.id!=="github"&&ge.authenticated).length,F=T.filter(ge=>ge.id!=="github").length,ne=Object.keys(ie).filter(ge=>!T.find(et=>et.id===ge)?.authenticated).length;if(F===0)return null;let ae="onboarding-provider-summary",oe="";return x>0?(ae+=" onboarding-provider-summary--connected",oe=`✓ ${x} of ${F} provider${F!==1?"s":""} connected`):ne>0?(ae+=" onboarding-provider-summary--skipped",oe=`${ne} provider${ne!==1?"s":""} skipped`):(ae+=" onboarding-provider-summary--none",oe="No providers connected yet"),e.jsx("div",{className:ae,"data-testid":"provider-summary",children:oe})})(),e.jsx($s,{summary:"What are AI providers?",children:e.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(x=>x.authenticated)&&e.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),G?e.jsxs("div",{className:"model-onboarding-loading",children:[e.jsx(ct,{size:24,className:"animate-spin"}),e.jsx("span",{children:"Loading providers…"})]}):T.length===0?e.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[e.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),Bn.length>0?e.jsx("div",{className:"model-onboarding-providers",children:Bn.map(x=>_n(x))}):e.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),rs.length>0&&e.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[e.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),e.jsx("div",{className:"model-onboarding-providers",children:rs.map(x=>_n(x))})]}),e.jsx($s,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:e.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Vt.length>0?e.jsx("div",{className:"model-onboarding-providers",children:Vt.map(x=>_n(x))}):e.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),dn&&e.jsx($s,{summary:"How does login work?",children:e.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."})}),nn&&e.jsx($s,{summary:"What is an API key?",children:e.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."})})]}),e.jsxs("div",{className:"onboarding-model-section",children:[e.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),e.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."}),e.jsx($s,{summary:"How do I choose a model?",children:e.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."})}),de.length===0?e.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):e.jsx("div",{className:"onboarding-model-selector",children:e.jsx(Kt,{models:de,value:J,onChange:we,placeholder:"Select a default model…",label:"Default model"})}),J&&e.jsx("div",{className:"onboarding-model-preview",children:e.jsxs("small",{className:"settings-muted",children:["Selected:"," ",de.find(x=>x.id===J)?.name??J]})})]})]}),b==="github"&&e.jsxs("div",{className:"model-onboarding-github",children:[e.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."}),e.jsx("div",{className:"onboarding-feature-list",children:e.jsxs("ul",{children:[e.jsx("li",{className:"onboarding-feature-list-heading",children:e.jsx("strong",{children:"Without GitHub (available now):"})}),e.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),e.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),e.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),e.jsx("li",{className:"onboarding-feature-list-heading",children:e.jsx("strong",{children:"With GitHub (after connecting):"})}),e.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),e.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),e.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),Yn&&e.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[e.jsx("strong",{children:"No AI provider connected"}),e.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."})]}),e.jsx($s,{summary:"What does GitHub integration do?",children:e.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."})}),Ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"onboarding-provider-row",children:[e.jsxs("div",{className:"onboarding-provider-info",children:[e.jsxs("strong",{children:[e.jsx(ts,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),e.jsx("span",{"data-testid":"onboarding-auth-status-github",children:e.jsx(We,{status:Ot})})]}),Ze&&(O==="github"?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>U("github"),children:"Disconnect"}))]}),(Ot==="not-connected"||Ot==="pending")&&e.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[O==="github"?e.jsxs("div",{className:"onboarding-github-connect-actions",children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Ve("github"),children:"Cancel"})]}):e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>_t("github"),children:[e.jsx(ts,{size:16}),"Connect"]}),O==="github"&&C.github&&e.jsx("p",{className:"auth-login-instructions","data-testid":"onboarding-login-instructions-github",children:C.github})]}),Ot==="connected"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Ee?"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."}),Ot==="failed"&&e.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[e.jsx("p",{children:"Connection failed or timed out."}),e.jsxs("div",{className:"onboarding-github-feedback-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>_t("github"),children:"Retry"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:bt,children:"Skip for now"})]})]}),Ot==="pending"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Ot==="skipped"&&e.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[e.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),e.jsx("div",{className:"onboarding-github-feedback-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>_t("github"),children:"Connect anyway"})})]}),Ot==="not-connected"&&e.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):e.jsxs("div",{className:"model-onboarding-github-optional",children:[e.jsx(ts,{size:48,className:"optional-icon"}),Ee?e.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth integration in Settings → Authentication is optional and only controls dashboard-managed connect/disconnect."}):e.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:"Continue without GitHub →"})]})]}),b==="project-setup"&&e.jsxs("div",{className:"model-onboarding-project-setup",children:[e.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."}),jn?e.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:e.jsx("p",{children:"Project selected — task creation and imports are available."})}):e.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[e.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),e.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),e.jsx($s,{summary:"What does project setup do?",children:e.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."})})]}),b==="first-task"&&e.jsxs("div",{className:"model-onboarding-first-task",children:[e.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),_&&wn?e.jsxs("div",{className:"onboarding-task-created",children:[e.jsx(en,{size:56,className:"success-icon"}),e.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),e.jsx("div",{className:"onboarding-task-created__task-id",children:wn.id}),On&&e.jsx("p",{className:"onboarding-task-created__description",children:On}),e.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),e.jsxs("div",{className:"onboarding-task-created__actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary",onClick:hn,children:"View Task"}),e.jsx("button",{type:"button",className:"btn",onClick:Jn,children:"Go to Dashboard"})]})]}):e.jsxs(e.Fragment,{children:[jn?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"onboarding-first-task-form",children:[e.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),e.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:M,onChange:x=>{w(x.target.value),L(null)},placeholder:"Example: Build a login page with email and password",rows:4}),e.jsx("div",{className:"onboarding-first-task-form__actions",children:e.jsx("button",{type:"button",className:"btn btn-primary",onClick:je,disabled:R,"data-testid":"onboarding-first-task-submit",children:R?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),I&&e.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[e.jsx("p",{className:"field-error",children:I}),e.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):e.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[e.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),e.jsx(w_,{items:$t}),jn&&e.jsxs(e.Fragment,{children:[e.jsx($s,{summary:"What happens when I create a task?",children:e.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."})}),e.jsxs("div",{className:"onboarding-cta-options",children:[e.jsxs("button",{className:"onboarding-cta-card primary",onClick:Ke,disabled:he,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(qt,{size:24})}),e.jsxs("div",{className:"cta-content",children:[e.jsx("strong",{children:"Create a New Task"}),e.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),e.jsxs("button",{className:`onboarding-cta-card${st?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:pt,disabled:he||!st,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(ts,{size:24})}),e.jsxs("div",{className:"cta-content",children:[e.jsx("strong",{children:"Import from GitHub"}),e.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!st&&e.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),e.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",e.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&e.jsxs("div",{className:"model-onboarding-complete",children:[e.jsx(en,{size:48,className:"success-icon"}),e.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),e.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Ht,disabled:he,children:"Skip for now"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Pt,children:"Skip setup →"}),e.jsx("button",{className:"btn btn-primary",onClick:Et,children:"Next →"})]}),b==="github"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Pt,children:"Skip GitHub →"}),e.jsx("button",{className:"btn btn-primary",onClick:Et,children:"Next →"})]}),b==="project-setup"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),e.jsx("button",{className:"btn btn-primary",onClick:Et,disabled:!jn,children:"Next →"})]}),b==="first-task"&&!_&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:It,children:"← Back"}),e.jsx("button",{className:"btn btn-primary",onClick:xt,disabled:he,children:he?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&e.jsxs("button",{className:"btn btn-primary",onClick:fn,children:[e.jsx(en,{size:16}),e.jsx("span",{children:"Get Started"})]})]})]})})}const E_=a.lazy(()=>Zt(()=>import("./SetupWizardModal-UxlAtKWA.js"),__vite__mapDeps([12,1,2,3,4,5])).then(t=>({default:t.SetupWizardModal})));function M_({projectId:t,tasks:n,projects:s,currentProject:i,addToast:r,toasts:l,removeToast:o,modalManager:d,projectActions:m,taskHandlers:c,taskOperations:u,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[b,v]=a.useState(null),y=p??d.closeSettings,k=a.useCallback(()=>{d.openNewTask()},[d]),A=a.useCallback(()=>{d.openGitHubImport()},[d]),j=a.useCallback(N=>{v(null),d.closeModelOnboarding(),d.openDetailTask(N)},[d]),_=a.useCallback(async N=>{const M=await c.handleModalCreate(N);return d.modelOnboardingOpen&&v(M),M},[c.handleModalCreate,d.modelOnboardingOpen]);return a.useEffect(()=>{!d.modelOnboardingOpen&&b&&v(null)},[d.modelOnboardingOpen,b]),e.jsxs(e.Fragment,{children:[d.detailTask&&e.jsx(mi,{children:e.jsx(IM,{task:d.detailTask,projectId:t,tasks:n,onClose:h.handleDetailClose,onOpenDetail:d.openDetailTask,onMoveTask:u.moveTask,onDeleteTask:u.deleteTask,onMergeTask:u.mergeTask,onRetryTask:u.retryTask,onDuplicateTask:u.duplicateTask,onTaskUpdated:d.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:d.detailTaskInitialTab})}),d.settingsOpen&&e.jsx(mi,{children:e.jsx(WM,{onClose:y,addToast:r,initialSection:d.settingsInitialSection,projectId:t,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})}),e.jsx(GM,{isOpen:d.githubImportOpen,onClose:d.closeGitHubImport,onImport:c.handleGitHubImport,tasks:n,projectId:t}),e.jsx(mi,{children:e.jsx(XM,{isOpen:d.isPlanningOpen,onClose:d.closePlanning,onTaskCreated:c.handlePlanningTaskCreated,onTasksCreated:c.handlePlanningTasksCreated,tasks:n,initialPlan:d.planningInitialPlan??void 0,projectId:t,resumeSessionId:d.planningResumeSessionId})}),e.jsx(mi,{children:e.jsx(iA,{isOpen:d.isSubtaskOpen,onClose:d.closeSubtask,initialDescription:d.subtaskInitialDescription??"",onTasksCreated:c.handleSubtaskTasksCreated,projectId:t,resumeSessionId:d.subtaskResumeSessionId})}),e.jsx(vA,{isOpen:d.terminalOpen,onClose:d.closeTerminal,initialCommand:d.terminalInitialCommand,projectId:t}),e.jsx(kA,{isOpen:d.scriptsOpen,onClose:d.closeScripts,addToast:r,onRunScript:d.runScript,projectId:t}),d.filesOpen&&e.jsx(OA,{initialWorkspace:d.fileBrowserWorkspace,isOpen:!0,onClose:d.closeFiles,onWorkspaceChange:d.setFileWorkspace,projectId:t}),e.jsx(GA,{isOpen:d.usageOpen,onClose:d.closeUsage,projectId:t}),d.schedulesOpen&&e.jsx(pP,{onClose:d.closeSchedules,addToast:r,projectId:t}),e.jsx(mi,{children:e.jsx(xP,{isOpen:d.newTaskModalOpen,onClose:d.closeNewTask,tasks:n,onCreateTask:_,addToast:r,projectId:t,onPlanningMode:d.openPlanningWithInitialPlan,onSubtaskBreakdown:d.openSubtaskBreakdown})}),e.jsx(wP,{isOpen:d.activityLogOpen,onClose:d.closeActivityLog,tasks:n,projectId:t,projects:s,currentProject:i,onOpenTaskDetail:N=>{const M=n.find(w=>w.id===N);M&&d.openDetailTask(M)}}),e.jsx(mi,{children:e.jsx(SP,{isOpen:d.gitManagerOpen,onClose:d.closeGitManager,tasks:n,addToast:r,projectId:t})}),e.jsx(mi,{children:e.jsx(FP,{isOpen:d.workflowStepsOpen,onClose:d.closeWorkflowSteps,addToast:r,projectId:t})}),e.jsx(KP,{isOpen:d.agentsOpen,onClose:d.closeAgents,addToast:r,projectId:t}),d.setupWizardOpen&&e.jsx(a.Suspense,{fallback:null,children:e.jsx(E_,{onProjectRegistered:m.handleSetupComplete,onClose:d.closeSetupWizard})}),d.modelOnboardingOpen&&e.jsx(C_,{onComplete:m.handleModelOnboardingComplete,addToast:r,projectId:t??"",onOpenSetupWizard:m.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:A,firstCreatedTask:b,onViewTask:j}),e.jsx(af,{toasts:l,onRemove:o})]})}function A_({errorMessage:t,isRetrying:n,onRetry:s}){return e.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[e.jsx("h2",{children:"Can't reach the Fusion backend"}),e.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),e.jsxs("p",{className:"settings-muted",children:["Error: ",t]}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const Bo=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function P_(t,n){if(n==="ready")return"done";const s=Bo.findIndex(r=>r.id===n),i=Bo.findIndex(r=>r.id===t);return i<s?"done":i===s?"active":"pending"}function __({stage:t}){return e.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":"Loading Fusion dashboard","data-stage":t,children:e.jsxs("div",{className:"dashboard-loader__content",children:[e.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),e.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),e.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Bo.map(n=>{const s=P_(n.id,t);return e.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${s}`,"data-testid":`dashboard-loader-step-${n.id}`,children:[e.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:s==="done"?"✓":s==="active"?e.jsx(ct,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),e.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const T_=5e3;function R_(t,n,s){return t||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function I_(t,n,s){let i=0,r=0,l=0,o=0,d=0;for(const m of t){switch(m.column){case"in-progress":i++,Ir(m,n,s)&&l++;break;case"todo":o++;break;case"in-review":d++;break}m.blockedBy&&m.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:l,queuedTaskCount:o,inReviewCount:d}}function $_(t,n,s,i){const[r,l]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[o,d]=a.useState(!0),[m,c]=a.useState(null),u=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{d(!0),c(null);const v=await Fy(n);l(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;c(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{d(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(u.current&&clearInterval(u.current),u.current=setInterval(()=>{g()},T_),()=>{u.current&&(clearInterval(u.current),u.current=null)}),[g]);const p=I_(t,s,i),f=R_(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:o,error:m,refresh:g}}const D_={planning:zs,subtask:ki,mission_interview:ns,milestone_interview:ns,slice_interview:ns},F_={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function L_({sessions:t,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const[l,o]=a.useState(!1),[d,m]=a.useState(new Set),c=a.useRef(null),u=a.useRef(new Map),h=a.useRef(null),{activeTabMap:g}=ra(),p=a.useMemo(()=>Ci(),[]);if(a.useEffect(()=>{if(!l)return;const v=y=>{c.current&&!c.current.contains(y.target)&&o(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[l]),a.useEffect(()=>{const v=new Set,y=new Map;for(const k of t){const A=g.get(k.id),j=[k.status,k.updatedAt,A?.tabId??k.lockedByTab??"",A?.stale?"stale":"fresh"].join("|"),_=u.current.get(k.id);_&&_!==j&&v.add(k.id),y.set(k.id,j)}if(u.current=y,v.size!==0)return m(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{m(new Set),h.current=null},500),()=>{h.current&&(clearTimeout(h.current),h.current=null)}},[g,t]),t.length===0)return null;const f=t.length,b=s>0;return e.jsxs("div",{ref:c,className:"background-tasks-indicator",children:[e.jsxs("button",{className:`background-tasks-indicator__pill${b?" background-tasks-indicator__pill--attention":""}`,onClick:()=>o(v=>!v),title:`${f} background AI task${f!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&e.jsx(ct,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&e.jsx(Lc,{size:12}),e.jsxs("span",{children:["AI ",f]})]}),l&&e.jsxs("div",{className:"background-tasks-indicator__popover",children:[e.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),e.jsx("div",{className:"background-tasks-indicator__popover-list",children:t.map(v=>{const y=D_[v.type],k=v.status==="generating",A=v.status==="awaiting_input",j=v.status==="error",_=g.get(v.id),N=_?.tabId??v.lockedByTab??null,M=!!(N&&N!==p&&!_?.stale),w=d.has(v.id);return e.jsxs("div",{className:`background-tasks-indicator__item${w?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:w?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:w?"translateY(-1px)":void 0},onClick:()=>{M&&!window.confirm("This session is active in another tab. Open anyway?")||(i(v),o(!1))},children:[j?e.jsx(is,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):e.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),e.jsxs("div",{className:"background-tasks-indicator__session-content",children:[e.jsx("div",{className:"background-tasks-indicator__session-title",children:v.title}),e.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[j?"Failed":F_[v.type],k&&" — generating...",A&&!M&&" — needs input",A&&M&&" — active in another tab"]})]}),k&&e.jsx(ct,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),A&&!M&&e.jsx(Lc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),A&&M&&e.jsx(Kr,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),e.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:R=>{R.stopPropagation(),r(v.id)},title:"Dismiss",children:e.jsx(Ft,{size:12})})]},v.id)})})]})]})}function z_(t){if(!t)return"no activity";const n=Date.now(),s=new Date(t).getTime(),i=n-s,r=Math.floor(i/1e3),l=Math.floor(r/60),o=Math.floor(l/60),d=Math.floor(o/24);return d>0?`${d}d ago`:o>0?`${o}h ago`:l>0?`${l}m ago`:r>10?`${r}s ago`:"just now"}function O_(t){switch(t){case"running":return{label:"Running",color:"var(--color-success)",icon:an};case"paused":return{label:"Paused",color:"var(--triage)",icon:Ds};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Sn}}}function B_({tasks:t,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:l,onOpenBackgroundSession:o,onDismissBackgroundSession:d,lastFetchTimeMs:m}){const{stats:c,loading:u,error:h}=$_(t,n,s,m),g=a.useMemo(()=>O_(c.executorState),[c.executorState]),p=a.useMemo(()=>z_(c.lastActivityAt),[c.lastActivityAt]),f=g.icon;return h?e.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:e.jsxs("span",{className:"executor-status-bar__error",children:[e.jsx(Wo,{size:14}),h]})}):u&&c.runningTaskCount===0?e.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:e.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):e.jsxs("div",{className:`executor-status-bar ${c.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&o&&d&&e.jsxs(e.Fragment,{children:[e.jsx(L_,{sessions:i,generating:r??0,needsInput:l??0,onOpenSession:o,onDismissSession:d}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),e.jsx("span",{className:"executor-status-bar__count",children:c.queuedTaskCount})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${c.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Running"}),e.jsx("span",{className:"executor-status-bar__count",children:c.runningTaskCount}),e.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),e.jsx("span",{className:"executor-status-bar__max",children:c.maxConcurrent})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),c.stuckTaskCount>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[e.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),e.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:c.stuckTaskCount})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${c.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),e.jsx("span",{className:`executor-status-bar__count ${c.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:c.blockedTaskCount})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),e.jsx("span",{className:"executor-status-bar__count",children:c.inReviewCount})]}),e.jsx("div",{className:"executor-status-bar__spacer"}),e.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[e.jsx(Hi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__time",children:p})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx(f,{size:12,style:{color:g.color},"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__state",style:{color:g.color},children:g.label})]})]})}const U_={planning:zs,subtask:ki,mission_interview:ns,milestone_interview:ns,slice_interview:ns},H_={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},fi=new Set;function q_({sessions:t,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,l]=a.useState(0),o=()=>l(f=>f+1);a.useEffect(()=>{if(fi.size===0)return;const f=new Map(t.map(v=>[v.id,v]));let b=!1;for(const v of fi){const y=f.get(v);y&&y.status!=="awaiting_input"&&y.status!=="error"&&(fi.delete(v),b=!0)}b&&o()},[t]);const d=a.useMemo(()=>t.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!fi.has(f.id)),[t,r]);if(d.length===0)return null;const m=d.filter(f=>f.status==="awaiting_input").length,c=d.filter(f=>f.status==="error").length;let u="";m>0&&c>0?u=`${m} AI session${m===1?"":"s"} need${m===1?"s":""} your input, ${c} failed`:m>0?u=`${m} AI session${m===1?"":"s"} need${m===1?"s":""} your input`:c>0&&(u=`${c} AI session${c===1?"":"s"} failed`);const h=f=>{fi.add(f),o()},g=f=>{fi.delete(f.id),o(),n(f)},p=()=>{for(const f of d)fi.add(f.id);o(),i()};return e.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[e.jsxs("div",{className:"session-notification-banner__header",children:[e.jsxs("div",{className:"session-notification-banner__headline",children:[e.jsx(is,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:u})]}),e.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[e.jsx(Ft,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Dismiss all"})]})]}),e.jsx("div",{className:"session-notification-banner__list",children:d.map(f=>{const b=U_[f.type],v=f.status==="error";return e.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[e.jsxs("div",{className:"session-notification-banner__item-main",children:[v?e.jsx(is,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):e.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),e.jsxs("div",{className:"session-notification-banner__text",children:[e.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),e.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":H_[f.type]})]})]}),e.jsxs("div",{className:"session-notification-banner__actions",children:[e.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),e.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:e.jsx(Ft,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function V_({onResume:t}){const n=e_();if(!n)return null;const s=n.completedSteps.length,i=Xs.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return e.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[e.jsxs("div",{className:"onboarding-resume-card__main",children:[e.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:e.jsx(Ln,{size:20})}),e.jsxs("div",{className:"onboarding-resume-card__content",children:[e.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),e.jsxs("p",{className:"onboarding-resume-card__description",children:[r,e.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),e.jsx("div",{className:"onboarding-resume-card__actions",children:e.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{ks("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),t()},children:[e.jsx(an,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Continue onboarding"})]})})]})}function W_({onOpenSettings:t,onOpenModelOnboarding:n}){const s=na(),i=nf(),[r,l]=a.useState(!0),[o,d]=a.useState(!1),[m,c]=a.useState(!1),[u,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){l(!1);return}let y=!1;return(async()=>{try{l(!0),d(!1);const[A,j]=await Promise.all([wi(),ia()]);if(y)return;const _=A.providers??[],N=_.find(I=>I.id==="github"),w=!_.some(I=>I.id!=="github"&&I.authenticated),R=!j.defaultProvider&&!j.defaultModelId,E=N?!N.authenticated:!1;h({needsAiProvider:w,needsDefaultModel:R,needsGitHub:E})}catch{y||d(!0)}finally{y||l(!1)}})(),()=>{y=!0}},[s,i]);const g=a.useCallback(()=>{XP(),c(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{t("global-models")},[t]),b=a.useCallback(()=>{t("authentication")},[t]),v=a.useMemo(()=>{const y=[];return u.needsAiProvider&&y.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:Sn}),u.needsDefaultModel&&y.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Ym}),u.needsGitHub&&y.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:ts}),y},[u.needsAiProvider,u.needsDefaultModel,u.needsGitHub,b,f,p]);return!s||i||m||r||o||v.length===0?null:e.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[e.jsxs("div",{className:"post-onboarding-recommendations__main",children:[e.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:e.jsx(zs,{size:18,"aria-hidden":!0})}),e.jsxs("div",{className:"post-onboarding-recommendations__content",children:[e.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),e.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),e.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(y=>{const k=y.icon;return e.jsxs("li",{className:"post-onboarding-recommendations__item",children:[e.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[e.jsx(is,{size:14,"aria-hidden":!0}),e.jsx(k,{size:14,"aria-hidden":!0})]}),e.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[e.jsx("strong",{children:y.title}),e.jsx("span",{children:y.description})]}),e.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:y.onAction,children:y.actionLabel})]},y.id)})})]})]}),e.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:e.jsx(Ft,{size:16,"aria-hidden":!0})})]})}function K_({size:t=20}){return e.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.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 ro(t){return t>99?"99+":String(t)}function G_({view:t,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:l,onOpenMailbox:o,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:c,onOpenSchedules:u,onOpenScripts:h,onToggleTerminal:g,onOpenFiles:p,onOpenGitHubImport:f,onOpenPlanning:b,onResumePlanning:v,activePlanningSessionCount:y=0,onOpenUsage:k,onRunScript:A,projectId:j,onViewAllProjects:_,showSkillsTab:N,experimentalFeatures:M}){const w=Xr(),[R,E]=a.useState(!1),[I,L]=a.useState(!1),[ee,$]=a.useState({}),[T,S]=a.useState(!1),Y=a.useMemo(()=>Object.entries(ee).sort(([J],[D])=>J.localeCompare(D)),[ee]);a.useEffect(()=>{if(!I)return;let J=!1;return S(!0),Wa(j).then(D=>{J||$(D)}).catch(()=>{J||$({})}).finally(()=>{J||S(!1)}),()=>{J=!0}},[I,j]);const K=a.useCallback(()=>E(!1),[]),G=a.useCallback(J=>{K(),J?.()},[K]);if(a.useEffect(()=>{if(!R)return;const J=D=>{D.key==="Escape"&&E(!1)};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[R]),w!=="mobile"||i)return null;const P=y>0&&v?v:b,O=!!M?.roadmap,X=!!N,C=O&&(!X||t==="roadmaps"),V=X&&(!O||t!=="roadmaps"),de=X&&!V,B=t==="documents"||t==="insights"||t==="memory"||t==="devserver"||t==="dev-server"||t==="roadmaps"&&!C||t==="skills"&&!V;return e.jsxs(e.Fragment,{children:[e.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="board"||t==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":t==="board"||t==="list",onClick:()=>{n(t==="board"||t==="list"?t:"board")},children:[e.jsx(ji,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":t==="agents",onClick:()=>n("agents"),children:[e.jsx(sn,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":t==="missions",onClick:()=>n("missions"),children:[e.jsx(ns,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":t==="chat",onClick:()=>n("chat"),children:[e.jsx(ei,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":t==="mailbox",onClick:()=>n("mailbox"),children:[e.jsx(Ia,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-nav-tab-badge",children:ro(d)})]}),V&&e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="skills"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-skills",role:"tab","aria-selected":t==="skills",onClick:()=>n("skills"),children:[e.jsx(Sn,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),C&&e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":t==="roadmaps",onClick:()=>n("roadmaps"),children:[e.jsx(fo,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${B?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>E(J=>!J),children:[e.jsx(mo,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),R&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:K}),e.jsxs("div",{className:"mobile-more-sheet",children:[e.jsx("div",{className:"mobile-more-sheet-handle"}),e.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>G(o),children:[e.jsx(Ia,{}),e.jsx("span",{children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:ro(d)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>G(l),children:[e.jsx(Ns,{}),e.jsx("span",{children:"Activity Log"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>G(m),children:[e.jsx(Ls,{}),e.jsx("span",{children:"Git Manager"})]}),e.jsxs("div",{className:"mobile-more-split-row",children:[e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>G(g),children:[e.jsx(Os,{}),e.jsx("span",{children:"Terminal"})]}),e.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>L(J=>!J),"aria-expanded":I,"aria-haspopup":"menu","aria-label":"Show scripts",children:e.jsx(rn,{size:14,className:`mobile-more-chevron${I?" mobile-more-chevron--open":""}`})})]}),I&&e.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:T?e.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[e.jsx(ct,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts…"})]}):Y.length>0?e.jsxs(e.Fragment,{children:[Y.map(([J,D])=>e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${J}`,onClick:()=>{A&&A(J,D),K(),L(!1)},children:[e.jsx(an,{size:14}),e.jsx("span",{children:J})]},J)),h&&e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{K(),L(!1),h()},children:[e.jsx(Ms,{size:14}),e.jsx("span",{children:"Manage Scripts…"})]})]}):h&&e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{K(),L(!1),h()},children:[e.jsx(Ms,{size:14}),e.jsx("span",{children:"No scripts — add one…"})]})}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>G(p),children:[e.jsx(Pn,{}),e.jsx("span",{children:"Files"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>G(P),children:[e.jsx(zs,{}),e.jsx("span",{children:"Planning"}),y>0&&e.jsx("span",{className:"mobile-more-item-badge",children:ro(y)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>G(c),children:[e.jsx(bo,{}),e.jsx("span",{children:"Workflow Steps"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>G(u),children:[e.jsx(Hi,{}),e.jsx("span",{children:"Automation"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>G(f),children:[e.jsx(K_,{}),e.jsx("span",{children:"Import from GitHub"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>G(k),children:[e.jsx(Ns,{}),e.jsx("span",{children:"Usage"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>G(_),children:[e.jsx(Jm,{}),e.jsx("span",{children:"Projects"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>G(()=>n("documents")),children:[e.jsx(vi,{}),e.jsx("span",{children:"Documents"})]}),de&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>G(()=>n("skills")),children:[e.jsx(Sn,{}),e.jsx("span",{children:"Skills"})]}),O&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>G(()=>n("roadmaps")),children:[e.jsx(fo,{}),e.jsx("span",{children:"Roadmaps"})]}),M?.insights&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>G(()=>n("insights")),children:[e.jsx(Ln,{}),e.jsx("span",{children:"Insights"})]}),M?.memoryView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>G(()=>n("memory")),children:[e.jsx(Cr,{}),e.jsx("span",{children:"Memory"})]}),M?.devServerView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{G(()=>n("dev-server"))},children:[e.jsx(Gr,{size:14}),e.jsx("span",{children:"Dev Server"})]}),e.jsx("div",{className:"mobile-more-separator"}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>G(r),children:[e.jsx($a,{}),e.jsx("span",{children:"Settings"})]})]})]})]})}function J_({agents:t,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:l="below"}){const o=a.useMemo(()=>{const d=n.trim().toLowerCase();return d?t.filter(m=>m.name.toLowerCase().includes(d)):t},[t,n]);return i?e.jsx("div",{className:`agent-mention-popup agent-mention-popup--${l}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:o.length===0?e.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):o.map((d,m)=>e.jsxs("button",{type:"button",className:`agent-mention-item${m===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${d.id}`,onMouseDown:c=>c.preventDefault(),onClick:()=>r(d),role:"option","aria-selected":m===s,children:[e.jsx(sn,{size:14,"aria-hidden":"true"}),e.jsx("span",{className:"agent-mention-name",children:d.name}),e.jsx("span",{className:"agent-mention-role",children:d.role})]},d.id))}):null}const yc="__fn_agent__";function of(t,n){const s=typeof t=="string"?t.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Cm(t,n,s){const i=typeof t=="string"?t.trim():"",r=of(n,s),l=i||(r.modelProvider&&r.modelId?yc:"");return l?{agentId:l,...r}:null}function lo(t,n,s){const i=of(n,s),r=i.modelProvider??"",l=i.modelId??"";return`${t}::${r}/${l}`}function Y_(t){const n=t?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,l=typeof r.toolName=="string"?r.toolName:"";if(!l)return null;const o=r.args;return{toolName:l,...o&&typeof o=="object"?{args:o}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(i=>i!==null);return s.length>0?s:void 0}function Em(t){return{id:t.id,sessionId:t.sessionId,role:t.role,content:t.content,thinkingOutput:t.thinkingOutput,toolCalls:Y_(t.metadata),createdAt:t.createdAt}}function Q_(t,n){const[s,i]=a.useState(null),[r,l]=a.useState(!1),[o,d]=a.useState([]),[m,c]=a.useState(!1),[u,h]=a.useState(!1),[g,p]=a.useState(""),[f,b]=a.useState(""),[v,y]=a.useState([]),[k,A]=a.useState(""),j=a.useRef(null),_=a.useRef(!1),N=a.useRef(""),M=a.useRef(""),w=a.useRef(null);a.useEffect(()=>{N.current=k},[k]);const R=a.useCallback(async G=>{const P={agentId:G.agentId};return G.modelProvider&&G.modelId&&(P.modelProvider=G.modelProvider,P.modelId=G.modelId),(await Xk(P,t)).session},[t]),E=a.useCallback(async(G,P,O)=>{const X=Cm(G,P,O);if(!X)return;const C=lo(X.agentId,X.modelProvider,X.modelId);l(!0);try{const{session:V}=await Qk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},t);if(V)i(V),M.current=C;else{const de=await R(X);i(de),M.current=C}}catch(V){console.error("[useQuickChat] Failed to initialize session:",V),n?.("Failed to initialize chat","error")}finally{l(!1)}},[t,n,R]),I=a.useCallback(async()=>{if(s){c(!0);try{const G=await hd(s.id,{limit:50},t);d(G.messages.map(Em))}catch(G){console.error("[useQuickChat] Failed to load messages:",G)}finally{c(!1)}}},[s,t]);a.useEffect(()=>{s?I():d([])},[s,I]);const L=a.useCallback(async()=>{if(s){c(!0);try{const G=await hd(s.id,{limit:50},t);d(G.messages.map(Em))}catch(G){console.error("[useQuickChat] Failed to reload messages:",G)}finally{c(!1)}}},[s,t]),ee=a.useCallback(async(G,P,O)=>{const X=Cm(G,P,O);if(!X)return;const C=lo(X.agentId,X.modelProvider,X.modelId);if(w.current=X,j.current&&(j.current.close(),j.current=null),p(""),b(""),y([]),h(!1),C===M.current&&s){await L();return}d([]),M.current=C,await E(X.agentId,X.modelProvider,X.modelId)},[E,L,s]),$=a.useCallback(async(G,P)=>{await ee(yc,G,P)},[ee]),T=a.useCallback(async()=>{const G=w.current;if(!G)return;const P=lo(G.agentId,G.modelProvider,G.modelId);j.current&&(j.current.close(),j.current=null),p(""),b(""),y([]),h(!1),d([]),l(!0);try{const O=await R(G);i(O),M.current=P}catch(O){console.error("[useQuickChat] Failed to start a fresh session:",O),n?.("Failed to start a new chat","error")}finally{l(!1)}},[n,R]),S=a.useCallback(()=>{s&&(_.current=!0,j.current?.close(),j.current=null,Zk(s.id,t).catch(()=>{}),h(!1),p(""),b(""),y([]))},[s,t]),Y=a.useCallback(()=>{N.current="",A("")},[]),K=a.useCallback(G=>{if(!s||!G.trim())return;if(u){N.current=G,A(G);return}_.current=!1,j.current&&(j.current.close(),j.current=null);const O={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:G,createdAt:new Date().toISOString()};d(B=>[...B,O]),p(""),b(""),y([]),h(!0);let X="",C="",V=[];const de={onThinking:B=>{C+=B,b(C)},onText:B=>{X+=B,p(X)},onToolStart:B=>{V=[...V,{toolName:B.toolName,args:B.args,isError:!1,status:"running"}],y(V)},onToolEnd:B=>{const J=[...V];for(let D=J.length-1;D>=0;D--){const he=J[D];if(he?.toolName===B.toolName&&he.status==="running"){J[D]={...he,status:"completed",isError:B.isError,result:B.result},V=J,y(J);return}}V=[...J,{toolName:B.toolName,isError:B.isError,result:B.result,status:"completed"}],y(V)},onDone:B=>{const J={id:B.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:C||void 0,toolCalls:V.length>0?V:void 0,createdAt:new Date().toISOString()};d(he=>[...he,J]),p(""),b(""),y([]),h(!1),j.current=null;const D=N.current.trim();D&&(N.current="",A(""),K(D))},onError:B=>{if(p(""),b(""),y([]),h(!1),j.current=null,console.error("[useQuickChat] Stream error:",B),n?.("Failed to get response","error"),!_.current){const J=N.current.trim();J&&(N.current="",A(""),K(J))}L()}};j.current=ej(s.id,G,de,t)},[s,u,t,n,L]);return a.useEffect(()=>()=>{j.current&&(j.current.close(),j.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:o,messagesLoading:m,isStreaming:u,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:k,sendMessage:K,stopStreaming:S,clearPendingMessage:Y,switchSession:ee,startModelChat:$,startFreshSession:T,loadMessages:I,reloadMessages:L}),[s,r,o,m,u,g,f,v,k,K,S,Y,ee,$,T,I,L])}function X_(t,n){const[s,i]=a.useState([]),[r,l]=a.useState(null),[o,d]=a.useState(!1),m=a.useCallback(async g=>{d(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await aa({...f,...g,includeEphemeral:g?.includeEphemeral??b},t),y=Array.from(new Map(v.map(k=>[k.id,k])).values());i(y)}catch(p){console.error("Failed to load agents:",p)}finally{d(!1)}},[t,n?.filterState,n?.showSystemAgents]),c=a.useCallback(async()=>{try{const g=await My(t);l(g)}catch(g){console.error("Failed to load agent stats:",g)}},[t]);a.useEffect(()=>{m(),c()},[m,c]),a.useEffect(()=>{const g=t?`?projectId=${encodeURIComponent(t)}`:"",p=()=>{m(),c()};return Bs(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[t,m,c]);const u=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:u||!bj(g));return{agents:s,activeAgents:h,stats:r,isLoading:o,loadAgents:m,loadStats:c}}function Z_({visible:t,position:n,files:s,selectedIndex:i,onSelect:r,loading:l}){return t?e.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:o=>{o.preventDefault()},children:[l&&e.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:e.jsx("span",{className:"spinner"})}),!l&&s.length===0&&e.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!l&&s.length>0&&e.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((o,d)=>{const m=o.path.includes("/")?o.path.slice(0,o.path.lastIndexOf("/")+1):"",c=o.name;return e.jsxs("li",{className:`file-mention-popup-item${d===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(o),onMouseEnter:()=>{},role:"option","aria-selected":d===i,"data-testid":`file-mention-item-${d}`,children:[e.jsx("span",{className:"file-mention-popup-icon",children:e.jsx(Km,{size:14})}),e.jsxs("div",{className:"file-mention-popup-info",children:[e.jsx("span",{className:"file-mention-popup-item-name",children:c}),m&&e.jsx("span",{className:"file-mention-popup-item-path",children:m})]})]},o.path)})})]}):null}const eT=200;function tT(t={}){const{projectId:n,workspace:s="project"}=t,[i,r]=a.useState(!1),[l,o]=a.useState(""),[d,m]=a.useState(-1),[c,u]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const y=a.useCallback((N,M)=>{if(M<0||M>N.length){r(!1);return}const w=R=>/[a-zA-Z0-9/_.-]/.test(R);for(let R=M-1;R>=0;R--){if(N[R]==="#")if(R===0){const E=N.slice(R+1,M);m(R),o(E),f(0),r(!0);return}else{const E=N[R-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const I=N.slice(R+1,M);m(R),o(I),f(0),r(!0);return}r(!1);return}if(!w(N[R])){r(!1);return}}r(!1)},[]),k=a.useCallback(()=>{r(!1),o(""),m(-1),u([]),f(0),g(!1)},[]),A=a.useCallback(async N=>{if(!N.trim()){u([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const M=await Fv(N,s,n);u(M.files),f(0)}catch(M){M.name!=="AbortError"&&u([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{A(l)},eT),()=>{b.current&&clearTimeout(b.current)}},[l,i,A]);const j=a.useCallback((N,M)=>{if(!i||d<0)return M;const w=M.slice(0,d),R=M.slice(d+1),E=R.match(/[\s]|$/),I=E?E.index:R.length,L=R.slice(I);return`${w}#${N.path}${L}`},[i,d]),_=a.useCallback((N,M)=>{if(!i||c.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),f(w=>Math.min(w+1,c.length-1)),!0;case"ArrowUp":return N.preventDefault(),f(w=>Math.max(w-1,0)),!0;case"Enter":case"Tab":return c[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),k(),!0;default:return!1}},[i,c,p,k]);return{mentionActive:i,files:c,loading:h,mentionQuery:l,selectedIndex:p,setSelectedIndex:f,detectMention:y,selectFile:j,dismissMention:k,handleKeyDown:_}}const nT={display:"inline-flex",alignItems:"center",maxWidth:"180px",padding:"var(--space-xs) var(--space-sm)",borderRadius:"var(--radius-pill)",border:"1px solid color-mix(in srgb, var(--todo) 35%, var(--border))",background:"color-mix(in srgb, var(--todo) 14%, transparent)",color:"var(--text)",fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},sT={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function iT(t){return`${t.name?.trim()||t.id} (${t.role})`}function aT(t){const n=t.trim(),s=n.indexOf("/");return!n||s<=0||s>=n.length-1?null:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function rT(t,n){return n?t?.name?.trim()?t.name.trim():n.modelId.replace(/[-_]/g," ").replace(/\s+/g," ").replace(/^\w/,s=>s.toUpperCase()).trim():null}function Sr(t,n){return t.length>n?`${t.slice(0,n)}…`:t}function lT(t){if(!t)return null;const n=Object.entries(t);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${Sr(r,50)}`}).join(", ")}function oT(t){if(t===void 0)return null;if(typeof t=="string")return Sr(t,200);try{return Sr(JSON.stringify(t),200)}catch{return Sr(String(t),200)}}function Mm(t,n=!1){return!t||t.length===0?null:e.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[e.jsxs("div",{className:"chat-tool-calls-header",children:[e.jsx(nx,{size:12,"aria-hidden":"true"}),e.jsx("span",{children:"Tool calls"})]}),t.map((s,i)=>{const r=s.status==="running",l=s.status==="completed"&&s.isError,o=lT(s.args),d=oT(s.result),m=r?o:d?`result: ${d}`:o?`args: ${o}`:null,c=r?"running":l?"error":"completed";return e.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${l?" chat-tool-call--error":""}`,open:r,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),e.jsx("span",{className:"chat-tool-call-name",children:s.toolName}),m&&e.jsx("span",{className:"chat-tool-call-preview",title:m,children:m}),e.jsx("span",{className:"chat-tool-call-status-text",children:c})]}),e.jsxs("div",{className:"chat-tool-call-content",children:[o&&e.jsxs("div",{className:"chat-tool-call-row",children:[e.jsx("span",{className:"chat-tool-call-label",children:"args"}),e.jsx("span",{className:"chat-tool-call-value",children:o})]}),d&&e.jsxs("div",{className:`chat-tool-call-row${l?" chat-tool-call-row--error":""}`,children:[e.jsx("span",{className:"chat-tool-call-label",children:"result"}),e.jsx("span",{className:"chat-tool-call-value",children:d})]})]})]},`${s.toolName}-${i}`)})]})}function cT(t,n){const s=t.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",l=s.length-r.length-1;return{filter:r,start:l,end:n}}function dT(t,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,l]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${t||"default"}`;try{const v=localStorage.getItem(b);if(v){const y=JSON.parse(v);if(typeof y.x=="number"&&typeof y.y=="number"&&!isNaN(y.x)&&!isNaN(y.y))return y}}catch{}return i()}),[o,d]=a.useState(!1),m=a.useRef(null),c=n??a.useRef(!1),u=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,y=window.innerWidth<=768?4:8,k=window.innerWidth<=768?44:0,A=window.innerWidth>768?s():0,j=window.innerWidth-v-y,_=window.innerHeight-v-y-k-A;return{x:Math.max(y,Math.min(j,b.x)),y:Math.max(y,Math.min(_,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${t||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[t]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const y=b.target.closest(".quick-chat-fab");y&&(b.preventDefault(),typeof y.setPointerCapture=="function"&&y.setPointerCapture(b.pointerId),m.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},c.current=!1,d(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!m.current||!o)return;const v=b.clientX-m.current.pointerX,y=b.clientY-m.current.pointerY;if((Math.abs(v)>=5||Math.abs(y)>=5)&&(c.current=!0),c.current){const k=m.current.x-v,A=m.current.y-y,j=u({x:k,y:A});l(j)}},[o,u]),f=a.useCallback(b=>{if(!m.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),d(!1),document.body.style.userSelect="",!c.current){m.current=null;return}h(r),m.current=null,c.current=!1},[r,h]);return{position:r,isDragging:o,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function uT({projectId:t,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:l=[],favoriteModels:o=[],onToggleFavorite:d,onToggleModelFavorite:m}){const{agents:c}=X_(t),[u,h]=a.useState(!1),g=i!==void 0,p=g?i:u,f=g?Fe=>{r?.(typeof Fe=="function"?Fe(p):Fe)}:h,[b,v]=a.useState("agent"),[y,k]=a.useState(""),[A,j]=a.useState([]),[_,N]=a.useState(!1),[M,w]=a.useState(""),[R,E]=a.useState(""),[I,L]=a.useState(""),[ee,$]=a.useState(!1),[T,S]=a.useState(0),[Y,K]=a.useState(-1),[,G]=a.useState(!1),[P,O]=a.useState({top:0,left:0}),X=tT({projectId:t}),C=a.useCallback(Fe=>{if(!Fe||!X.mentionActive)return;const lt=Fe.getBoundingClientRect();O({top:lt.top-260,left:lt.left+8})},[X.mentionActive]),V=a.useRef(!1),de=a.useRef(!1),B=a.useRef(""),J=a.useRef(0),D=a.useRef(null),{position:he,isDragging:q,handlePointerDown:W,handlePointerMove:me,handlePointerUp:Re}=dT(t,V),{activeSession:ve,messages:Me,isStreaming:_e,streamingText:De,streamingThinking:Oe,streamingToolCalls:ze,sessionsLoading:Be,messagesLoading:Ae,sendMessage:Ce,stopStreaming:Ge,pendingMessage:Te,clearPendingMessage:Xe,switchSession:re,startModelChat:Z,startFreshSession:ye}=Q_(t,n),ie=a.useRef(null),Ie=a.useRef(null),pe=a.useRef(null),Ue=a.useRef(null),dt=a.useMemo(()=>aT(M),[M]),ht=a.useMemo(()=>A.find(Fe=>`${Fe.provider}/${Fe.id}`===M)??null,[A,M]),ue=a.useMemo(()=>rT(ht,dt),[ht,dt]),te=a.useMemo(()=>b==="model"?dt?`${yc}::${dt.modelProvider}/${dt.modelId}`:"":y?`${y}::`:"",[b,dt,y]),ke=b==="agent"?!!y:!!dt;a.useEffect(()=>{if(c.length===0){k(""),v("model");return}c.some(lt=>lt.id===y)||k(c[0]?.id??"")},[c,y]),a.useEffect(()=>{!p||de.current||(de.current=!0,N(!0),Kn().then(Fe=>{const lt=Fe.models??[];if(j(lt),c.length===0&<.length>0&&!M){const be=lt[0];be&&w(`${be.provider}/${be.id}`)}}).catch(Fe=>{console.error("[QuickChatFAB] Failed to load models:",Fe),j([])}).finally(()=>{N(!1)}))},[p,c.length,M]),a.useEffect(()=>{if(!p){B.current="";return}if(!te){B.current="";return}if(te!==B.current){if(B.current=te,b==="model"&&dt){Z(dt.modelProvider,dt.modelId);return}b==="agent"&&y&&re(y)}},[p,b,dt,y,te,Z,re]),a.useEffect(()=>{p||($(!1),L(""),K(-1))},[p]);const Ne=a.useCallback(Fe=>{k(Fe)},[]),Ze=a.useCallback(Fe=>{w(Fe)},[]),xe=a.useCallback(()=>{!ke||Be||ye()},[ke,Be,ye]),st=a.useMemo(()=>c.find(Fe=>Fe.id===y)??null,[c,y]),Ee=a.useMemo(()=>{const Fe=I.trim().toLowerCase();return Fe?c.filter(lt=>lt.name.toLowerCase().includes(Fe)):c},[c,I]),He=a.useMemo(()=>{const Fe=new Map;for(const lt of c)Fe.set(lt.name.toLowerCase(),lt);return Fe},[c]);a.useEffect(()=>{S(0)},[I,ee]),a.useEffect(()=>()=>{D.current!==null&&(window.clearTimeout(D.current),D.current=null)},[]),a.useEffect(()=>{if(!p)return;const Fe=be=>{const U=be.target;ie.current?.contains(U)||Ie.current?.contains(U)||U.closest(".model-combobox-dropdown--portal")||f(!1)},lt=be=>{be.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Fe),document.addEventListener("keydown",lt),()=>{document.removeEventListener("mousedown",Fe),document.removeEventListener("keydown",lt)}},[p,f]),a.useEffect(()=>{if(!p)return;const Fe=pe.current;Fe&&(Fe.scrollTop=Fe.scrollHeight)},[Me,De,Oe,p]);const ce=a.useMemo(()=>b==="agent"?st?`Message ${st.name||st.id}`:"Select an agent to start chatting":ue?`Message ${ue}`:"Select a model to start chatting",[b,st,ue]),qe=!ke||!ve||Be,We=Te.length>50?`${Te.slice(0,50)}…`:Te,Pe=a.useCallback(()=>{const Fe=R.trim();!Fe||qe||(E(""),$(!1),L(""),K(-1),Ce(Fe))},[Ce,qe,R]),nt=a.useCallback((Fe,lt)=>{const be=cT(Fe,lt);if(be){$(!0),L(be.filter),K(be.start);return}$(!1),L(""),K(-1)},[]),kt=a.useCallback(Fe=>{const lt=Ue.current;if(!lt||Y<0)return;const be=lt.selectionStart??J.current,U=lt.selectionEnd??be,we=Math.max(be,U),rt=Math.min(Y,we),je=`${`@${Fe.name.replace(/\s+/g,"_")}`} `,Ke=R.slice(0,rt)+je+R.slice(we),pt=rt+je.length;E(Ke),$(!1),L(""),S(0),K(-1),window.requestAnimationFrame(()=>{Ue.current&&(Ue.current.focus(),Ue.current.setSelectionRange(pt,pt))})},[Y,R]),yt=a.useCallback(Fe=>{const lt=Fe.target.value,be=Fe.target.selectionStart??lt.length;J.current=be,E(lt),nt(lt,be),X.detectMention(lt,be),G(X.mentionActive),X.mentionActive&&C(Fe.target)},[nt,X,C]),Ct=a.useCallback(()=>{D.current!==null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{$(!1),L(""),K(-1),G(!1),X.dismissMention(),D.current=null},120)},[X]),Et=a.useCallback(()=>{D.current!==null&&(window.clearTimeout(D.current),D.current=null)},[]),Pt=a.useCallback(Fe=>{const lt=Fe.currentTarget,be=lt.selectionStart??lt.value.length;J.current=be,nt(lt.value,be),X.detectMention(lt.value,be),G(X.mentionActive),X.mentionActive&&C(lt)},[nt,X,C]),It=a.useCallback(Fe=>{Fe.key!=="Escape"&&Pt(Fe)},[Pt]),bt=a.useCallback(Fe=>{const lt=/@([\w-]+)/g,be=[];let U=0,we=lt.exec(Fe);for(;we;){const[rt,xt=""]=we,je=we.index;je>U&&be.push(Fe.slice(U,je));const Ke=xt.replace(/_/g," ").toLowerCase(),pt=He.get(Ke);pt?be.push(e.jsxs("span",{className:"chat-mention-chip",children:["@",pt.name.replace(/\s+/g,"_")]},`${pt.id}-${je}`)):be.push(rt),U=je+rt.length,we=lt.exec(Fe)}return U<Fe.length&&be.push(Fe.slice(U)),be.length===0?Fe:be},[He]),_t=a.useCallback(Fe=>{if(J.current=Fe.currentTarget.selectionStart??J.current,X.mentionActive&&X.files.length>0){if(X.handleKeyDown(Fe,R),Fe.key==="Enter"||Fe.key==="Tab"){const lt=X.files[X.selectedIndex];if(lt){const be=X.selectFile(lt,R);E(be),X.dismissMention(),G(!1)}}return}if(ee&&Fe.key==="ArrowDown"){Fe.preventDefault(),Ee.length>0&&S(lt=>(lt+1)%Ee.length);return}if(ee&&Fe.key==="ArrowUp"){Fe.preventDefault(),Ee.length>0&&S(lt=>lt===0?Ee.length-1:lt-1);return}if(ee&&Fe.key==="Enter"){Fe.preventDefault();const lt=Ee[T]??Ee[0];lt&&kt(lt);return}if(ee&&Fe.key==="Escape"){Fe.preventDefault(),Fe.stopPropagation(),$(!1),L(""),K(-1);return}Fe.key!=="Enter"||Fe.shiftKey||(Fe.preventDefault(),Pe())},[ee,Ee,T,kt,Pe,X,R]),Ve=a.useCallback(()=>{if(V.current){V.current=!1;return}f(Fe=>!Fe)},[f]),ft=he.y+60;return e.jsxs(e.Fragment,{children:[s&&e.jsx("button",{ref:Ie,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":q?"true":"false",style:{right:he.x,bottom:he.y},onPointerDown:W,onPointerMove:me,onPointerUp:Re,onClick:Ve,children:e.jsx(ei,{size:24})}),p&&e.jsxs("div",{className:"quick-chat-panel",ref:ie,"data-testid":"quick-chat-panel",style:{right:he.x,bottom:ft},children:[e.jsxs("div",{className:"quick-chat-panel-header",children:[e.jsxs("div",{style:sT,children:[e.jsx("h3",{children:"Quick Chat"}),ue&&e.jsx("span",{style:nT,"data-testid":"quick-chat-model-tag",title:ue,children:ue})]}),e.jsxs("div",{className:"quick-chat-panel-header-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:xe,disabled:!ke||Be,children:"New chat"}),e.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:e.jsx(Ft,{size:16})})]})]}),c.length>0&&e.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[e.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{v("agent"),w("")},children:"Agent"}),e.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{v("model"),k("")},children:"Model"})]}),b==="agent"&&c.length>0&&e.jsxs("div",{className:"quick-chat-panel-agent-select",children:[e.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),e.jsx("select",{id:"quick-chat-agent-select",value:y,onChange:Fe=>Ne(Fe.target.value),"data-testid":"quick-chat-agent-select",children:c.map(Fe=>e.jsx("option",{value:Fe.id,children:iT(Fe)},Fe.id))})]}),b==="model"&&e.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[e.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),e.jsx(Kt,{id:"quick-chat-model-override",models:A,value:M,onChange:Ze,label:"Select model override",placeholder:_?"Loading models…":"Select a model",disabled:_||A.length===0,favoriteProviders:l,favoriteModels:o,onToggleFavorite:d,onToggleModelFavorite:m})]}),e.jsx("div",{className:"quick-chat-panel-messages",ref:pe,"data-testid":"quick-chat-messages",children:Be||Ae?e.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Me.length===0&&!De&&!Oe&&!_e?e.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):e.jsxs(e.Fragment,{children:[Me.map(Fe=>{const lt=Fe.role==="user";return e.jsxs("div",{className:`quick-chat-panel-message ${lt?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${Fe.id}`,children:[e.jsx("p",{children:bt(Fe.content)}),Mm(Fe.toolCalls,!0)]},Fe.id)}),_e&&e.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[De?e.jsx("p",{"data-testid":"quick-chat-streaming-text",children:bt(De)}):e.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Oe?"Thinking…":"Connecting…"}),Mm(ze,!0),Oe&&e.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[e.jsx("summary",{children:"Thinking"}),e.jsx("pre",{className:"chat-message-thinking-content",children:Oe})]})]})]})}),e.jsxs("div",{className:"quick-chat-panel-input",children:[e.jsxs("div",{className:"quick-chat-input-wrapper",children:[e.jsx("input",{ref:Ue,type:"text",value:R,onChange:yt,onKeyDown:_t,onKeyUp:It,onClick:Pt,onBlur:Ct,onFocus:Et,placeholder:ce,disabled:qe,"data-testid":"quick-chat-input"}),e.jsx(J_,{agents:c,filter:I,highlightedIndex:T,visible:ee,onSelect:kt,position:"above"}),e.jsx(Z_,{visible:X.mentionActive&&!ee,position:P,files:X.files,selectedIndex:X.selectedIndex,onSelect:Fe=>{const lt=X.selectFile(Fe,R);E(lt),X.dismissMention(),G(!1),Ue.current?.focus()},loading:X.loading}),Te&&e.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[e.jsx("span",{children:`Queued: ${We}`}),e.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Xe,children:"×"})]})]}),_e?e.jsx("button",{type:"button",className:"chat-input-stop",onClick:Ge,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:e.jsx(cs,{size:14})}):e.jsx("button",{type:"button",onClick:()=>void Pe(),disabled:qe||R.trim().length===0,"data-testid":"quick-chat-send",children:e.jsx(gi,{size:16})})]})]})]})}function jr(t){if(!t)return 0;const n=Date.parse(t);return Number.isFinite(n)?n:0}function Am(t){return t.status==="generating"||t.status==="awaiting_input"}function mT(t){const[n,s]=a.useState([]),i=a.useRef(new Map),{sessions:r,broadcastUpdate:l,broadcastCompleted:o,requestSync:d}=ra(),m=a.useCallback(()=>{vh(t).then(g=>{const p=new Map;for(const f of g)p.set(f.id,jr(f.updatedAt));i.current=p,s(g)}).catch(g=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",g)})},[t]);a.useEffect(()=>{d(),m()},[m,d]),a.useEffect(()=>{s(g=>{if(r.size===0)return g;let p=!1;const f=new Map(g.map(b=>[b.id,b]));for(const b of r.values()){if(t&&b.projectId&&b.projectId!==t)continue;const v=b.lastEventTimestamp,y=i.current.get(b.sessionId)??0;if(v<y)continue;const k=f.get(b.sessionId),A=b.type??k?.type,j=b.title??k?.title;if(!k&&(!A||!j))continue;const _={id:b.sessionId,type:A??"planning",status:b.status,title:j??"AI Session",projectId:b.projectId??k?.projectId??t??null,lockedByTab:b.owningTabId??k?.lockedByTab??null,updatedAt:b.updatedAt??k?.updatedAt??new Date(v).toISOString()},N=f.get(b.sessionId);(!N||N.status!==_.status||N.title!==_.title||N.type!==_.type||N.projectId!==_.projectId||N.lockedByTab!==_.lockedByTab||N.updatedAt!==_.updatedAt)&&(f.set(b.sessionId,_),i.current.set(b.sessionId,v),p=!0)}return p?[...f.values()].sort((b,v)=>jr(v.updatedAt)-jr(b.updatedAt)):g})},[t,r]),a.useEffect(()=>{const g=t?`?projectId=${encodeURIComponent(t)}`:"",p=b=>{try{const v=JSON.parse(b.data),y=jr(v.updatedAt)||Date.now();s(k=>{const A=i.current.get(v.id)??0;if(y<A)return k;if(i.current.set(v.id,y),v.status==="complete"||v.status==="error")return k.filter(_=>_.id!==v.id);const j=k.findIndex(_=>_.id===v.id);if(j>=0){const _=[...k];return _[j]=v,_}return Am(v)?[v,...k]:k}),l({sessionId:v.id,status:v.status,needsInput:v.status==="awaiting_input",type:v.type,title:v.title,projectId:v.projectId,owningTabId:v.lockedByTab,updatedAt:v.updatedAt,timestamp:y}),(v.status==="complete"||v.status==="error")&&o({sessionId:v.id,status:v.status,timestamp:y})}catch{}},f=b=>{try{const v=JSON.parse(b.data);s(y=>y.filter(k=>k.id!==v)),i.current.delete(v)}catch{}};return Bs(`/api/events${g}`,{events:{"ai_session:updated":p,"ai_session:deleted":f}})},[o,l,t]);const c=a.useCallback(async g=>{const f=n.find(k=>k.id===g)?.type,b=Ci();let v=!1,y=!1;if(f==="planning")try{await dh(g,t,b)}catch(k){v=!0,k instanceof Error&&k.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${g}: locked by another tab`))}else if(f==="subtask")try{await hh(g,t,b)}catch(k){v=!0,k instanceof Error&&k.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${g}: locked by another tab`))}else if(f==="mission_interview")try{await xh(g,t,b)}catch(k){v=!0,k instanceof Error&&k.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${g}: locked by another tab`))}v&&!y&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${g}, attempting delete anyway`);try{await Ok(g)}catch{}s(k=>k.filter(A=>A.id!==g)),i.current.delete(g)},[t,n]),u=a.useMemo(()=>n.filter(g=>Am(g)),[n]),h=a.useMemo(()=>u.filter(g=>g.type==="planning"),[u]);return{sessions:u,generating:u.filter(g=>g.status==="generating").length,needsInput:u.filter(g=>g.status==="awaiting_input").length,planningSessions:h,dismissSession:c,refresh:m}}function Vn(t){return{...t,dependencies:Array.isArray(t.dependencies)?t.dependencies:[],steps:Array.isArray(t.steps)?t.steps:[],log:Array.isArray(t.log)?t.log:[]}}function Pm(t,n){return!t&&!n?0:t?n?t.localeCompare(n):1:-1}function hT(t){const n=t?.projectId,s=t?.searchQuery,i=t?.sseEnabled??!0,[r,l]=a.useState([]),[o,d]=a.useState(!1),m=a.useRef(o);m.current=o;const c=a.useRef(r),u=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);c.current=r,g.current=s,v.current!==n&&(v.current=n,b.current++);const y=1e3,k=a.useCallback(async $=>{const T=++u.current,S=n,Y=$?.searchQueryOverride??s,K=$?.includeArchivedOverride??m.current;try{const G=await jx(void 0,void 0,S,Y,K);if(u.current!==T||n!==S)return;l(G.map(Vn)),f.current=Date.now()}catch{if(u.current!==T||n!==S)return;if($?.clearOnError){l([]);return}l(G=>G)}},[n,s]);p.current=k;const A=a.useCallback(async()=>{m.current||(d(!0),m.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const $=setTimeout(()=>{k({searchQueryOverride:s})},300);return()=>clearTimeout($)},[s]),a.useEffect(()=>{k({clearOnError:!0});const $=()=>{if(document.visibilityState!=="visible")return;const T=Date.now();T-h.current<y||(h.current=T,k())};return document.addEventListener("visibilitychange",$),()=>{document.removeEventListener("visibilitychange",$)}},[k]),a.useEffect(()=>{if(i===!1)return;const $=b.current,T=n?`?projectId=${encodeURIComponent(n)}`:"",S=()=>b.current!==$;let Y=!0;const K=V=>{if(S())return;const de=Vn(JSON.parse(V.data));if(g.current){p.current({searchQueryOverride:g.current});return}l(B=>B.some(J=>J.id===de.id)?B:[...B,de])},G=V=>{if(S())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:de,to:B}=JSON.parse(V.data),J=Vn(de);l(D=>D.map(he=>he.id===J.id?{...J,column:B}:he)),f.current=Date.now()},P=V=>{if(S())return;if(g.current){p.current({searchQueryOverride:g.current});return}const de=Vn(JSON.parse(V.data));l(B=>B.map(J=>{if(J.id!==de.id||Pm(de.updatedAt,J.updatedAt)<0)return J;if(J.column===de.column)return de;const he=Pm(J.columnMovedAt,de.columnMovedAt);return J.columnMovedAt&&!de.columnMovedAt?{...de,column:J.column,columnMovedAt:J.columnMovedAt}:he>0?{...de,column:J.column,columnMovedAt:J.columnMovedAt}:de})),f.current=Date.now()},O=V=>{if(S())return;if(g.current){p.current({searchQueryOverride:g.current});return}const de=Vn(JSON.parse(V.data));l(B=>B.filter(J=>J.id!==de.id))},X=V=>{if(S())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:de}=JSON.parse(V.data),B=Vn(de);l(J=>J.map(D=>D.id===B.id?{...B,column:"done"}:D))},C=Bs(`/api/events${T}`,{events:{"task:created":K,"task:moved":G,"task:updated":P,"task:deleted":O,"task:merged":X},onReconnect:()=>{Y&&(S()||p.current())}});return()=>{Y=!1,C()}},[n,i]);const j=a.useCallback(async $=>{const T=Vn(await sh($,n));return l(S=>S.some(Y=>Y.id===T.id)?S:[...S,T]),T},[n]),_=a.useCallback(async($,T)=>Vn(await Nx($,T,n)),[n]),N=a.useCallback(async $=>Vn(await Sx($,n)),[n]),M=a.useCallback(async $=>Cx($,n),[n]),w=a.useCallback(async $=>Vn(await Ex($,n)),[n]),R=a.useCallback(async $=>{const T=Vn(await Mx($,n));return l(S=>S.some(Y=>Y.id===T.id)?S:[...S,T]),T},[n]),E=a.useCallback(async($,T)=>{const S=c.current.find(K=>K.id===$),Y=S?{...S,...T,updatedAt:new Date().toISOString()}:void 0;Y&&l(K=>K.map(G=>G.id===$?Y:G));try{const K=Vn(await Ws($,T,n));return l(G=>G.map(P=>P.id===$?K:P)),K}catch(K){throw S&&l(G=>G.map(P=>P.id===$?S:P)),K}},[n]),I=a.useCallback(async $=>{const T=Vn(await _x($,n));return l(S=>S.map(Y=>Y.id===$?T:Y)),T},[n]),L=a.useCallback(async $=>{const T=Vn(await Tx($,n));return l(S=>S.map(Y=>Y.id===$?T:Y)),T},[n]),ee=a.useCallback(async()=>{const T=(await Rx(n)).map(Vn);return l(S=>S.map(Y=>T.find(G=>G.id===Y.id)||Y)),T},[n]);return{tasks:r,createTask:j,moveTask:_,deleteTask:N,mergeTask:M,retryTask:w,duplicateTask:R,updateTask:E,archiveTask:I,unarchiveTask:L,archiveAllDone:ee,loadArchivedTasks:A,includeArchived:o,lastFetchTimeMs:f.current}}const pT=5e3,fT=1e3;function gT(){const[t,n]=a.useState([]),[s,i]=a.useState(!0),[r,l]=a.useState(null),o=a.useRef(null),d=a.useRef(0),m=a.useCallback(async()=>{try{l(null);const g=await ld();n(g)}catch(g){l(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const b=performance.now();try{const v=await ld(),k=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${k}`),Ma("[useProjects]",k),g||(n(v),l(null))}catch(v){const k=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${k}`),Ma("[useProjects]",k),g||l(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-d.current<fT||(d.current=b,m())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[m]),a.useEffect(()=>{if(!s)return o.current=setInterval(()=>{m()},pT),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async g=>{const p=await Dy(g);return n(f=>[...f,p]),p},[]),u=a.useCallback(async(g,p)=>{const f=await Uy(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await fh(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:t,loading:s,error:r,refresh:m,register:c,update:u,unregister:h}}const bT="kb-dashboard-current-project";function xT(t){return t??"local"}function vT(t,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[l,o]=a.useState(!0),d=a.useRef(!1),m=a.useRef(!1),c=a.useRef(null),u=xT(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ia();if(p)return;c.current=b.dashboardCurrentProjectIdByNode??{};const v=c.current[u];if(v){const y=t.find(k=>k.id===v);y&&(r(y),d.current=!0)}if(!v)try{const y=localStorage.getItem(bT);if(y){const k=JSON.parse(y);k?.id&&t.some(j=>j.id===k.id)&&(r(k),d.current=!0,c.current={...c.current,[u]:k.id},await Wt({dashboardCurrentProjectIdByNode:c.current}).catch(()=>{}))}}catch{}}catch{}finally{p||o(!1)}}return f(),()=>{p=!0}},[u,t]),a.useEffect(()=>{if(!l){if(i){if(!t.some(b=>b.id===i.id)&&t.length>0){const b=t.find(v=>v.status==="active");r(b||t[0]||null);return}const f={...c.current,[u]:i.id};c.current=f,Wt({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(t.length>0&&!m.current){const p=t.find(f=>f.status==="active");p&&r(p)}}},[i,t,l,u]);const h=a.useCallback(p=>{if(m.current=!1,r(p),p){const f={...c.current,[u]:p.id};c.current=f,Wt({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[u]),g=a.useCallback(()=>{m.current=!0,r(null);const p={...c.current};delete p[u],c.current=p,Wt({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[u]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:l}}const cf=a.createContext(null);function yT({children:t}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),l=a.useCallback(d=>{const m=r.current.get(d);m!==void 0&&(clearTimeout(m),r.current.delete(d)),s(c=>c.filter(u=>u.id!==d))},[]),o=a.useCallback((d,m="info")=>{const c=i.current++;s(h=>[...h,{id:c,message:d,type:m}]);const u=setTimeout(()=>l(c),4e3);r.current.set(c,u)},[l]);return a.useEffect(()=>()=>{r.current.forEach(d=>clearTimeout(d)),r.current.clear()},[]),zm.createElement(cf.Provider,{value:{toasts:n,addToast:o,removeToast:l}},t)}function kT(){const t=a.useContext(cf);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const df="kb-dashboard-theme-mode",uf="kb-dashboard-color-theme",mf=[...fj],Uo="theme-data",oo="theme-data.css";function jT(){const t=document.baseURI||(typeof document.location<"u"?document.location.href:"");return t?t.endsWith("/")?t.slice(0,-1)+`/${oo}`:t.replace(/\/[^/]+$/,`/${oo}`):`/${oo}`}const ws=typeof window<"u",wT=ws?a.useLayoutEffect:a.useEffect;function hf(t){return t==="dark"||t==="light"||t==="system"}function _m(){if(!ws)return"dark";try{const t=localStorage.getItem(df);if(hf(t))return t}catch{}return"dark"}function Tm(){if(!ws)return"default";try{const t=localStorage.getItem(uf);if(t&&mf.includes(t))return t}catch{}return"default"}function Rm(t){if(ws)try{localStorage.setItem(df,t)}catch{}}function Im(t){if(ws)try{localStorage.setItem(uf,t)}catch{}}function NT(t,n){return t==="system"?n?"dark":"light":t}function ST(t,n,s){if(!ws)return;const i=NT(t,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function $m(){if(!ws)return;const t=jT(),n=document.getElementById(Uo);if(n){n.href!==t&&(n.href=t),n.parentNode===document.head&&document.head.lastChild!==n&&document.head.appendChild(n);return}const s=document.createElement("link");s.rel="stylesheet",s.href=t,s.id=Uo,document.head.appendChild(s)}function Dm(){if(!ws)return;const t=document.getElementById(Uo);t&&t.remove()}function CT(){const[t,n]=a.useState(()=>_m()),[s,i]=a.useState(()=>Tm()),[r,l]=a.useState(!0),[o,d]=a.useState(()=>ws?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=a.useRef(t),c=a.useRef(s),u=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{m.current=t},[t]),a.useEffect(()=>{c.current=s},[s]),a.useEffect(()=>{if(!ws||!r)return;let f=!1;return ia().then(b=>{f||(hf(b.themeMode)&&!u.current&&(m.current!==b.themeMode&&(m.current=b.themeMode,n(b.themeMode)),_m()!==b.themeMode&&Rm(b.themeMode)),b.colorTheme&&mf.includes(b.colorTheme)&&!h.current&&(c.current!==b.colorTheme&&(c.current=b.colorTheme,i(b.colorTheme)),Tm()!==b.colorTheme&&Im(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{f||l(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!ws)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{d(v.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),wT(()=>{ST(t,s,o)},[t,s,o]),a.useEffect(()=>{!ws||r||(s!=="default"?$m():Dm())},[s,r]);const g=a.useCallback(f=>{u.current=!0,m.current=f,n(f),Rm(f),Wt({themeMode:f}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(f=>{h.current=!0,c.current=f,i(f),Im(f),f!=="default"?$m():Dm(),Wt({colorTheme:f}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:t,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:o}}function ET(t){const{planningSessions:n}=t,[s,i]=a.useState(!1),[r,l]=a.useState(!1),[o,d]=a.useState(null),[m,c]=a.useState(void 0),[u,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(void 0),[v,y]=a.useState(null),[k,A]=a.useState("definition"),[j,_]=a.useState(!1),[N,M]=a.useState(void 0),[w,R]=a.useState(!1),[E,I]=a.useState(!1),[L,ee]=a.useState(!1),[$,T]=a.useState(!1),[S,Y]=a.useState(void 0),[K,G]=a.useState(!1),[P,O]=a.useState("project"),[X,C]=a.useState(!1),[V,de]=a.useState(!1),[B,J]=a.useState(!1),[D,he]=a.useState(!1),[q,W]=a.useState(!1),[me,Re]=a.useState(!1),[ve,Me]=a.useState(!1),_e=!!(v||j||s||r||u||$||K||X||V||B||q||D||L||w||E||me||ve),De=a.useCallback(()=>i(!0),[]),Oe=a.useCallback(()=>i(!1),[]),ze=a.useCallback(()=>l(!0),[]),Be=a.useCallback(U=>{d(U),l(!0)},[]),Ae=a.useCallback(()=>{const U=n[0];U&&(c(U.id),l(!0))},[n]),Ce=a.useCallback(U=>{c(U),l(!0)},[]),Ge=a.useCallback(()=>{l(!1),d(null),c(void 0)},[]),Te=a.useCallback(U=>{p(U),h(!0)},[]),Xe=a.useCallback(U=>{b(U),h(!0)},[]),re=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),Z=a.useCallback((U,we="definition")=>{y(U),A(we)},[]),ye=a.useCallback(U=>{y(U),A("changes")},[]),ie=a.useCallback(U=>{y(we=>we&&{...we,...U})},[]),Ie=a.useCallback(()=>{y(null)},[]),pe=a.useCallback(U=>{M(U),_(!0)},[]),Ue=a.useCallback(()=>{_(!1),M(void 0)},[]),dt=a.useCallback(()=>R(!0),[]),ht=a.useCallback(()=>R(!1),[]),ue=a.useCallback(()=>I(!0),[]),te=a.useCallback(()=>I(!1),[]),ke=a.useCallback(()=>ee(!0),[]),Ne=a.useCallback(()=>ee(!1),[]),Ze=a.useCallback(()=>{T(U=>!U)},[]),xe=a.useCallback(()=>{T(!1),Y(void 0)},[]),st=a.useCallback(()=>G(!0),[]),Ee=a.useCallback(()=>G(!1),[]),He=a.useCallback(U=>{O(U)},[]),ce=a.useCallback(()=>C(!0),[]),qe=a.useCallback(()=>C(!1),[]),We=a.useCallback(()=>de(!0),[]),Pe=a.useCallback(()=>de(!1),[]),nt=a.useCallback(()=>J(!0),[]),kt=a.useCallback(()=>J(!1),[]),yt=a.useCallback(()=>he(!0),[]),Ct=a.useCallback(()=>he(!1),[]),Et=a.useCallback(()=>W(!0),[]),Pt=a.useCallback(()=>W(!1),[]),It=a.useCallback(async(U,we)=>{W(!1),Y(we),T(!0)},[]),bt=a.useCallback(()=>Re(!0),[]),_t=a.useCallback(()=>Re(!1),[]),Ve=a.useCallback(()=>Me(!0),[]),ft=a.useCallback(()=>Me(!1),[]),Fe=a.useCallback((U,we)=>{we(`Created ${U.id} from planning mode`,"success"),l(!1),d(null)},[]),lt=a.useCallback((U,we)=>{const rt=U.map(xt=>xt.id).join(", ");we(`Created ${rt} from planning mode`,"success"),l(!1),d(null)},[]),be=a.useCallback((U,we)=>{const rt=U.map(xt=>xt.id).join(", ");we(`Created ${rt} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:o,planningResumeSessionId:m,isSubtaskOpen:u,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:k,settingsOpen:j,settingsInitialSection:N,schedulesOpen:w,githubImportOpen:E,usageOpen:L,terminalOpen:$,terminalInitialCommand:S,filesOpen:K,fileBrowserWorkspace:P,activityLogOpen:X,gitManagerOpen:V,workflowStepsOpen:B,agentsOpen:D,scriptsOpen:q,setupWizardOpen:me,modelOnboardingOpen:ve,anyModalOpen:_e,openNewTask:De,closeNewTask:Oe,openPlanning:ze,openPlanningWithInitialPlan:Be,resumePlanning:Ae,openPlanningWithSession:Ce,closePlanning:Ge,openSubtaskBreakdown:Te,openSubtaskWithSession:Xe,closeSubtask:re,openDetailTask:Z,openDetailWithChangesTab:ye,updateDetailTask:ie,closeDetailTask:Ie,openSettings:pe,closeSettings:Ue,openSchedules:dt,closeSchedules:ht,openGitHubImport:ue,closeGitHubImport:te,openUsage:ke,closeUsage:Ne,toggleTerminal:Ze,closeTerminal:xe,openFiles:st,closeFiles:Ee,setFileWorkspace:He,openActivityLog:ce,closeActivityLog:qe,openGitManager:We,closeGitManager:Pe,openWorkflowSteps:nt,closeWorkflowSteps:kt,openAgents:yt,closeAgents:Ct,openScripts:Et,closeScripts:Pt,runScript:It,openSetupWizard:bt,closeSetupWizard:_t,openModelOnboarding:Ve,closeModelOnboarding:ft,onPlanningTaskCreated:Fe,onPlanningTasksCreated:lt,onSubtaskTasksCreated:be}}function MT(t){const[n,s]=a.useState(2),[i,r]=a.useState("."),[l,o]=a.useState(!0),[d,m]=a.useState(!1),[c,u]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[b,v]=a.useState(!1),[y,k]=a.useState({}),[A,j]=a.useState(!1),[_,N]=a.useState(!1),[M,w]=a.useState(!1),[R,E]=a.useState(!1),I=a.useCallback(async()=>{const[S,Y]=await Promise.allSettled([Dx(t),Ki(t)]);if(S.status==="fulfilled"&&(s(S.value.maxConcurrent),r(S.value.rootDir)),Y.status==="fulfilled"){const K=Y.value;o(!!K.autoMerge),m(!!K.globalPause),u(!!K.enginePaused),v(!!K.prAuthAvailable),g(K.taskStuckTimeoutMs),f(K.showQuickChatFAB===!0),k(K.experimentalFeatures??{});const G=K.experimentalFeatures??{};j(G.insights===!0),N(G.roadmap===!0),w(G.memoryView===!0),E(G.devServerView===!0)}},[t]);a.useEffect(()=>{I()},[I]);const L=a.useCallback(async()=>{const S=!l;o(S);try{await Ca({autoMerge:S},t)}catch{o(!S)}},[l,t]),ee=a.useCallback(async()=>{const S=!d;m(S);try{await Ca({globalPause:S,globalPauseReason:S?"manual":void 0},t)}catch{m(!S)}},[d,t]),$=a.useCallback(async()=>{const S=!c;u(S);try{await Ca({enginePaused:S},t)}catch{u(!S)}},[c,t]),T=a.useCallback(async()=>{const S=!p;f(S);try{await Ca({showQuickChatFAB:S},t)}catch{f(!S)}},[p,t]);return{maxConcurrent:n,rootDir:i,autoMerge:l,globalPaused:d,enginePaused:c,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:y,insightsEnabled:A,roadmapEnabled:_,memoryEnabled:M,devServerEnabled:R,toggleAutoMerge:L,toggleGlobalPause:ee,toggleEnginePause:$,toggleShowQuickChatFAB:T,refresh:I}}function AT(t){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:l,addToast:o,openTaskDetail:d,closeTaskDetail:m}=t,c=a.useRef(!1),u=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(y=>y.id===p);if(!v){o(`Project '${p}' not found`,"error");return}r?.id!==v.id&&l(v)}if(c.current)return;c.current=!0,_r(f,p??n).then(v=>{d(v),u.current=f}).catch(()=>{o(`Task ${f} not found`,"error")})},[n,s,i,r,l,o,d]),{handleDetailClose:a.useCallback(()=>{if(u.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),u.current=null}m()},[m])}}function PT(){const[t,n]=a.useState([]),[s,i]=a.useState([]),[r,l]=a.useState([]);a.useEffect(()=>{Kn().then(m=>{n(m.models),i(m.favoriteProviders),l(m.favoriteModels)}).catch(()=>{})},[]);const o=a.useCallback(async m=>{const c=s,h=c.includes(m)?c.filter(g=>g!==m):[m,...c];i(h);try{await Wt({favoriteProviders:h,favoriteModels:r})}catch(g){throw i(c),g}},[s,r]),d=a.useCallback(async m=>{const c=r,h=c.includes(m)?c.filter(g=>g!==m):[m,...c];l(h);try{await Wt({favoriteProviders:s,favoriteModels:h})}catch(g){throw l(c),g}},[r,s]);return{availableModels:t,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:o,toggleFavoriteModel:d}}function _T({projectId:t,openModelOnboarding:n,openSettings:s}){const i=a.useRef(!1);a.useEffect(()=>{if(i.current)return;i.current=!0;let r=!1,l=!1;wi().then(({providers:o})=>{const d=o.some(c=>c.authenticated);if(o.length>0&&!d||o.length>0&&d)return ia().then(c=>{const u=!!(c.defaultProvider&&c.defaultModelId);(c.modelOnboardingComplete===!1||c.modelOnboardingComplete===void 0)&&(!d||!u)&&!na()?r=!0:!d&&!na()&&(l=!0)})}).then(()=>{r?(ks("onboarding:auto-triggered",{trigger:"first-run"}),n()):l&&(ks("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[t,n,s])}const TT=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function Fm(t){return t!==null&&TT.includes(t)}function RT(t){return t==="devserver"?"dev-server":t}function IT(t){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:l,setupWizardOpen:o,openSetupWizard:d,themeMode:m,setThemeMode:c}=t,[u,h]=a.useState(()=>{if(typeof window<"u"){const y=window.localStorage.getItem("kb-dashboard-view-mode");if(y==="overview"||y==="project")return y}return"overview"}),[g,p]=a.useState(()=>{const y=In("kb-dashboard-task-view");return Fm(y)?y:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",u)},[u]),a.useEffect(()=>{const y=In("kb-dashboard-task-view",r?.id);if(Fm(y)){const k=!f.current&&y==="devserver";p(k?"devserver":RT(y))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ms("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&u==="overview"&&h("project")},[n,i,r,u]),a.useEffect(()=>{if(n||i||o||s||l>0||r)return;const y=window.setTimeout(()=>{d()},500);return()=>window.clearTimeout(y)},[n,s,l,i,r,o,d]);const b=a.useCallback(y=>{p(y)},[]),v=a.useCallback(()=>{const y=["dark","light","system"],k=y.indexOf(m),A=y[(k+1)%y.length];c(A)},[m,c]);return{viewMode:u,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function $T(t){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:l,toggleFavoriteProvider:o,toggleFavoriteModel:d,addToast:m,openSettings:c,openSetupWizard:u,closeSetupWizard:h,closeModelOnboarding:g}=t,p=a.useCallback(w=>{n(w),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{c()},[c]),v=a.useCallback(()=>{u()},[u]),y=a.useCallback(w=>{h(),n(w),i("project"),m(`Project ${w.name} registered successfully`,"success"),l()},[h,n,i,m,l]),k=a.useCallback(()=>{g()},[g]),A=a.useCallback(async w=>{try{await Ly(w.id),m(`Project ${w.name} paused`,"success"),await l()}catch{m(`Failed to pause project ${w.name}`,"error")}},[m,l]),j=a.useCallback(async w=>{try{await zy(w.id),m(`Project ${w.name} resumed`,"success"),await l()}catch{m(`Failed to resume project ${w.name}`,"error")}},[m,l]),_=a.useCallback(async w=>{try{await fh(w.id),m(`Project ${w.name} removed`,"success"),r?.id===w.id&&(s(),i("overview")),await l()}catch{m(`Failed to remove project ${w.name}`,"error")}},[r,s,i,m,l]),N=a.useCallback(async w=>{try{await o(w)}catch{m("Failed to update favorites","error")}},[o,m]),M=a.useCallback(async w=>{try{await d(w)}catch{m("Failed to update model favorites","error")}},[d,m]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:y,handleModelOnboardingComplete:k,handlePauseProject:A,handleResumeProject:j,handleRemoveProject:_,handleToggleFavorite:N,handleToggleModelFavorite:M}}function DT(t){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:l}=t,o=a.useCallback(async g=>n({...g,column:"triage"}),[n]),d=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),m=a.useCallback(g=>{s(g,l)},[s,l]),c=a.useCallback(g=>{i(g,l)},[i,l]),u=a.useCallback(g=>{r(g,l)},[r,l]),h=a.useCallback(g=>{l(`Imported ${g.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:o,handleModalCreate:d,handlePlanningTaskCreated:m,handlePlanningTasksCreated:c,handleSubtaskTasksCreated:u,handleGitHubImport:h}}async function FT(t){return Qr("/health",{nodeId:t})}async function LT(t){return Qr("/projects",{nodeId:t})}async function zT(t,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Qr(`/tasks?${i.toString()}`,{nodeId:t})}async function OT(t,n){return Qr(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:t})}async function VI(t){return z(`/nodes/${encodeURIComponent(t)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function WI(t){return z(`/nodes/${encodeURIComponent(t)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function KI(t){return z(`/nodes/${encodeURIComponent(t)}/settings/sync-status`)}async function GI(t){return z(`/nodes/${encodeURIComponent(t)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function BT(t,n){const{projectId:s,searchQuery:i}=n??{},[r,l]=a.useState([]),[o,d]=a.useState([]),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),b=a.useCallback(async()=>{if(!t){l([]),d([]),c(null),h(!1),p(null);return}f.current?.abort();const y=new AbortController;f.current=y,h(!0),p(null);try{const k=[FT(t),LT(t)];s&&(k.push(zT(t,s,i)),k.push(OT(t,s)));const A=await Promise.allSettled(k);if(y.signal.aborted)return;const j=A[0],_=A[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(c(j.value),_.status==="rejected"){p(`Failed to fetch projects: ${_.reason}`),h(!1);return}if(l(_.value),s&&A[2]){const N=A[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&d(N.value)}h(!1)}catch(k){y.signal.aborted||(p(k instanceof Error?k.message:"Unknown error"),h(!1))}},[t,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:o,health:m,loading:u,error:g,refresh:v}}function UT(t){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!t){s(!1),r(null);return}const l=`/api/proxy/${encodeURIComponent(t)}/events`;return Bs(l,{events:{"task:created":o=>{r({type:"task:created",data:o.data})},"task:moved":o=>{r({type:"task:moved",data:o.data})},"task:updated":o=>{r({type:"task:updated",data:o.data})},"task:deleted":o=>{r({type:"task:deleted",data:o.data})},"task:merged":o=>{r({type:"task:merged",data:o.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[t]),{isConnected:n,lastEvent:i}}const HT="fusion-dashboard-current-node",pf=a.createContext(null);function qT({children:t}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),l=a.useRef(!1),o=a.useRef(void 0);a.useEffect(()=>{let u=!1;async function h(){try{const g=await ia();if(u)return;o.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(l.current=!0),!p)try{const f=localStorage.getItem(HT);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(o.current=b.id,await Wt({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{u||r(!1)}}return h(),()=>{u=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const u=n.id;o.current!==u&&(o.current=u,Wt({dashboardCurrentNodeId:u}).catch(()=>{}))}else n===null&&o.current!==void 0&&(o.current=void 0,Wt({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const d=a.useCallback(u=>{s(u)},[]),m=a.useCallback(()=>{s(null),o.current=void 0,Wt({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),c={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:d,clearCurrentNode:m};return e.jsx(pf.Provider,{value:c,children:t})}function VT(){const t=a.useContext(pf);if(t===null)throw new Error("useNodeContext must be used within a NodeProvider");return t}function WT({open:t}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{t&&i.current?.focus()},[t]);const r=a.useCallback(()=>{const o=n.trim();o&&(ux(o),window.location.reload())},[n]),l=a.useCallback(()=>{mx(),window.location.reload()},[]);return t?e.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:o=>{o.key==="Escape"&&(o.preventDefault(),o.stopPropagation())},children:e.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[e.jsx("div",{className:"modal-header auth-token-recovery-header",children:e.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),e.jsxs("div",{className:"auth-token-recovery-content",children:[e.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."}),e.jsxs("div",{className:"auth-token-recovery-field",children:[e.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),e.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:o=>s(o.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),e.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:l,children:"Clear token and retry"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const KT=a.lazy(()=>Zt(()=>import("./AgentsView-DPlnCa_B.js").then(t=>t.A),__vite__mapDeps([13,1,14,3,15])).then(t=>({default:t.AgentsView}))),GT=a.lazy(()=>Zt(()=>import("./DocumentsView-lQwJmc4G.js"),__vite__mapDeps([16,1,4,5,17])).then(t=>({default:t.DocumentsView}))),JT=a.lazy(()=>Zt(()=>import("./InsightsView-DUiZZ0z8.js"),__vite__mapDeps([18,1,4,5,19])).then(t=>({default:t.InsightsView}))),YT=a.lazy(()=>Zt(()=>import("./NodesView-DgyM-ktg.js"),__vite__mapDeps([20,1,14,4,5,21])).then(t=>({default:t.NodesView}))),QT=a.lazy(()=>Zt(()=>import("./ChatView-BXzYysNG.js"),__vite__mapDeps([22,1,4,5])).then(t=>({default:t.ChatView}))),XT=a.lazy(()=>Zt(()=>import("./RoadmapsView-ANn2jmsU.js"),__vite__mapDeps([23,1,4,5,24])).then(t=>({default:t.RoadmapsView}))),ZT=a.lazy(()=>Zt(()=>import("./SkillsView-DEjGh7wW.js"),__vite__mapDeps([25,1,4,5,26])).then(t=>({default:t.SkillsView}))),eR=a.lazy(()=>Zt(()=>import("./MemoryView-DvSmMN6G.js"),__vite__mapDeps([27,1,4,5,28])).then(t=>({default:t.MemoryView}))),tR=a.lazy(()=>Zt(()=>import("./DevServerView-BY5cGz23.js"),__vite__mapDeps([29,1,4,5,30])).then(t=>({default:t.DevServerView})));function nR(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Zt(()=>import("./AgentsView-DPlnCa_B.js").then(n=>n.A),__vite__mapDeps([13,1,14,3,15])),Zt(()=>import("./DocumentsView-lQwJmc4G.js"),__vite__mapDeps([16,1,4,5,17])),Zt(()=>import("./InsightsView-DUiZZ0z8.js"),__vite__mapDeps([18,1,4,5,19])),Zt(()=>import("./NodesView-DgyM-ktg.js"),__vite__mapDeps([20,1,14,4,5,21])),Zt(()=>import("./ChatView-BXzYysNG.js"),__vite__mapDeps([22,1,4,5])),Zt(()=>import("./RoadmapsView-ANn2jmsU.js"),__vite__mapDeps([23,1,4,5,24])),Zt(()=>import("./SkillsView-DEjGh7wW.js"),__vite__mapDeps([25,1,4,5,26])),Zt(()=>import("./MemoryView-DvSmMN6G.js"),__vite__mapDeps([27,1,4,5,28])),Zt(()=>import("./DevServerView-BY5cGz23.js"),__vite__mapDeps([29,1,4,5,30]))})}const co="kb-setup-warning-dismissed";function sR(){const{toasts:t,addToast:n,removeToast:s}=kT(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{nR()},[]);const{projects:r,loading:l,error:o,refresh:d}=gT(),{nodes:m}=p_(),{currentNode:c,currentNodeId:u,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=VT(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:y}=vT(r,{nodeId:u}),{hasAiProvider:k,hasGithub:A,loading:j,hasWarnings:_}=ef(f?.id);a.useEffect(()=>{if(u&&!c&&m.length>0){const Je=m.find(ot=>ot.id===u);if(Je){g(Je);return}}u&&m.length>0&&(m.some(ot=>ot.id===u)||p())},[u,c,m,g,p]);const[N,M]=a.useState(""),w=BT(u,{projectId:f?.id,searchQuery:N||void 0});UT(u);const R=h&&w.projects.length>0?w.projects:r,{themeMode:E,colorTheme:I,setThemeMode:L,setColorTheme:ee}=CT(),{sessions:$,generating:T,needsInput:S,planningSessions:Y,dismissSession:K}=mT(f?.id),G=$.filter(Je=>Je.status==="awaiting_input"||Je.status==="error"),P=ET({projectId:f?.id,planningSessions:Y}),{viewMode:O,setViewMode:X,taskView:C,handleChangeTaskView:V}=IT({projectsLoading:l,projectsError:o,currentProjectLoading:y,currentProject:f,projectsLength:r.length,setupWizardOpen:P.setupWizardOpen,openSetupWizard:P.openSetupWizard,themeMode:E,setThemeMode:L}),de=a.useCallback(Je=>{Je==="missions"&&(te(void 0),Ne(void 0),xe(void 0)),V(Je)},[V]),B=C==="board"||C==="list",{tasks:J,createTask:D,moveTask:he,deleteTask:q,mergeTask:W,retryTask:me,updateTask:Re,duplicateTask:ve,archiveTask:Me,unarchiveTask:_e,archiveAllDone:De,loadArchivedTasks:Oe,lastFetchTimeMs:ze}=hT({...f?{projectId:f.id}:{},searchQuery:N||void 0,sseEnabled:B}),[Be,Ae]=a.useState(!1),Ce=a.useRef(performance.now()),Ge=a.useRef(!1),Te=a.useRef(!1),Xe=a.useMemo(()=>l?"projects":y?"project":"tasks",[l,y]);a.useEffect(()=>{if(!l&&!Ge.current){Ge.current=!0;const Je=`projects loaded at ${Math.round(performance.now()-Ce.current)}ms from mount`;console.log(`[App] ${Je}`),Ma("[App]",Je)}if(!y&&!Te.current){Te.current=!0;const Je=`current-project resolved at ${Math.round(performance.now()-Ce.current)}ms from mount`;console.log(`[App] ${Je}`),Ma("[App]",Je)}},[l,y]),a.useEffect(()=>{if(Be||l||y)return;const Je=performance.now(),ot=window.setTimeout(()=>{const Un=`dashboard ready at ${Math.round(performance.now()-Ce.current)}ms from mount (settle delay=${Math.round(performance.now()-Je)}ms)`;console.log(`[App] ${Un}`),Ma("[App]",Un),Ae(!0)},200);return()=>{window.clearTimeout(ot)}},[Be,l,y]);const Z=Xr()==="mobile",[ye,ie]=a.useState(0),Ie=a.useCallback(()=>{yh(f?.id).then(Je=>{ie(Je.unreadCount)}).catch(Je=>{console.warn("[App] Failed to fetch mailbox unread count:",Je)})},[f?.id]);a.useEffect(()=>{Ie();const Je=new URLSearchParams;f?.id&&Je.set("projectId",f.id);const ot=Je.size>0?`?${Je.toString()}`:"";return Bs(`/api/events${ot}`,{events:{"message:sent":Ie,"message:received":Ie,"message:read":Ie,"message:deleted":Ie}})},[f?.id,Ie]);const[pe,Ue]=a.useState(!1),[dt,ht]=a.useState(!1),[ue,te]=a.useState(void 0),[ke,Ne]=a.useState(void 0),[Ze,xe]=a.useState(void 0),[st,Ee]=a.useState(!1),[He,ce]=a.useState(!1),[qe,We]=a.useState(()=>In(co,f?.id)==="true");a.useEffect(()=>{We(In(co,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const Je=()=>{ce(!0)};return window.addEventListener(xo,Je),()=>{window.removeEventListener(xo,Je)}},[]);const Pe=a.useCallback(()=>{ms(co,"true",f?.id),We(!0)},[f?.id]),{maxConcurrent:nt,autoMerge:kt,globalPaused:yt,enginePaused:Ct,taskStuckTimeoutMs:Et,showQuickChatFAB:Pt,prAuthAvailable:It,experimentalFeatures:bt,insightsEnabled:_t,roadmapEnabled:Ve,memoryEnabled:ft,devServerEnabled:Fe,toggleAutoMerge:lt,toggleGlobalPause:be,toggleEnginePause:U,refresh:we}=MT(f?.id),rt=bt.skillsView===!0,xt=bt.nodesView===!0,je=!0;a.useEffect(()=>{Object.keys(bt).length!==0&&(C==="insights"&&!_t&&V("board"),C==="roadmaps"&&!Ve&&V("board"),C==="memory"&&!ft&&V("board"),(C==="devserver"||C==="dev-server")&&!Fe&&V("board"))},[C,_t,Ve,bt,V,je,ft,Fe]),a.useEffect(()=>{pe&&!xt&&Ue(!1)},[pe,xt]);const{availableModels:Ke,favoriteProviders:pt,favoriteModels:Ht,toggleFavoriteProvider:fn,toggleFavoriteModel:hn}=PT();_T({projectId:f?.id,openModelOnboarding:P.openModelOnboarding,openSettings:P.openSettings});const{handleSelectProject:Jn,handleViewAllProjects:Ot,handleOpenSettings:yn,handleAddProject:tn,handleSetupComplete:dn,handleModelOnboardingComplete:nn,handlePauseProject:Cn,handleResumeProject:kn,handleRemoveProject:jn,handleToggleFavorite:Yn,handleToggleModelFavorite:un}=$T({setCurrentProject:b,clearCurrentProject:v,setViewMode:X,currentProject:f,refreshProjects:d,toggleFavoriteProvider:fn,toggleFavoriteModel:hn,addToast:n,openSettings:P.openSettings,openSetupWizard:P.openSetupWizard,closeSetupWizard:P.closeSetupWizard,closeModelOnboarding:P.closeModelOnboarding}),{handleDetailClose:$t}=AT({projectId:f?.id,projects:r,projectsLoading:l,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:P.openDetailTask,closeTaskDetail:P.closeDetailTask}),{handleBoardQuickCreate:wn,handleModalCreate:On,handlePlanningTaskCreated:Nn,handlePlanningTasksCreated:Bn,handleSubtaskTasksCreated:rs,handleGitHubImport:Vt}=DT({createTask:D,onPlanningTaskCreated:P.onPlanningTaskCreated,onPlanningTasksCreated:P.onPlanningTasksCreated,onSubtaskTasksCreated:P.onSubtaskTasksCreated,addToast:n}),_n=a.useCallback((Je,ot)=>{if(ot==="changes"){P.openDetailWithChangesTab(Je);return}P.openDetailTask(Je,ot)},[P]),x=a.useCallback(()=>{xt&&Ue(Je=>!Je)},[xt]),F=a.useCallback(async()=>{ht(!0);try{await d()}finally{ht(!1)}},[d]),ne=a.useCallback(Je=>{Ne(Je),te(void 0),V("missions")},[V]),ae=a.useCallback(Je=>{Je.type==="planning"?P.openPlanningWithSession(Je.id):Je.type==="subtask"?P.openSubtaskWithSession(Je.id):Je.type==="mission_interview"?(Ne(void 0),te(Je.id),xe(void 0),V("missions")):(Je.type==="milestone_interview"||Je.type==="slice_interview")&&(te(void 0),Ne(void 0),xe(Je.id),V("missions"))},[V,P]),oe=a.useCallback(()=>{for(const Je of G)K(Je.id)},[K,G]),ge=!l&&!y&&r.length===0&&!f&&!!o,et=()=>ge?e.jsx(A_,{errorMessage:o??"Failed to fetch projects",isRetrying:dt,onRetry:F}):pe?e.jsx("div",{className:"nodes-management-overlay",children:e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(YT,{addToast:n,onClose:()=>Ue(!1)})})})}):O==="overview"?e.jsx(Zn,{children:e.jsx(Pw,{projects:r,loading:l,onSelectProject:Jn,onAddProject:tn,onPauseProject:Cn,onResumeProject:kn,onRemoveProject:jn,nodes:m})}):C==="skills"?rt?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(ZT,{addToast:n,projectId:f?.id,onClose:()=>V("board")})})}):(V("board"),null):C==="chat"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(QT,{addToast:n,projectId:f?.id})})}):C==="mailbox"?e.jsx(Zn,{children:e.jsx(wN,{projectId:f?.id,addToast:n,onUnreadCountChange:ie})}):C==="roadmaps"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(XT,{addToast:n,projectId:f?.id})})}):C==="missions"?e.jsx(Zn,{children:e.jsx(xN,{isInline:!0,isOpen:!0,onClose:()=>{Ne(void 0),te(void 0),xe(void 0),V("board")},addToast:n,projectId:f?.id,onSelectTask:Je=>{const ot=J.find(Un=>Un.id===Je);ot&&P.openDetailTask(ot)},availableTasks:J.map(Je=>({id:Je.id,title:Je.title})),resumeSessionId:ue,targetMissionId:ke,milestoneSliceResumeSessionId:Ze,onMilestoneSliceResumeFetchError:()=>xe(void 0)})}):C==="agents"&&je?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(KT,{addToast:n,projectId:f?.id})})}):C==="documents"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(GT,{projectId:f?.id,addToast:n,onOpenDetail:P.openDetailTask})})}):C==="insights"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(JT,{projectId:f?.id,addToast:n,onClose:()=>V("board")})})}):C==="memory"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(eR,{addToast:n,projectId:f?.id})})}):C==="devserver"||C==="dev-server"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(tR,{addToast:n,projectId:f?.id})})}):C==="board"?e.jsx(Zn,{children:e.jsx(xw,{tasks:h&&w.tasks.length>0?w.tasks:J,projectId:f?.id,maxConcurrent:nt,onMoveTask:he,onOpenDetail:P.openDetailTask,addToast:n,onQuickCreate:wn,onNewTask:P.openNewTask,onPlanningMode:P.openPlanningWithInitialPlan,onSubtaskBreakdown:P.openSubtaskBreakdown,autoMerge:kt,onToggleAutoMerge:lt,globalPaused:yt,onUpdateTask:Re,onArchiveTask:Me,onUnarchiveTask:_e,onDeleteTask:q,onArchiveAllDone:De,onLoadArchivedTasks:Oe,searchQuery:N,availableModels:Ke,onOpenDetailWithTab:_n,favoriteProviders:pt,favoriteModels:Ht,onToggleFavorite:Yn,onToggleModelFavorite:un,taskStuckTimeoutMs:Et,onOpenMission:ne,lastFetchTimeMs:ze})}):e.jsx(Zn,{children:e.jsx(yw,{tasks:h&&w.tasks.length>0?w.tasks:J,projectId:f?.id,onMoveTask:he,onOpenDetail:P.openDetailTask,addToast:n,globalPaused:yt,onNewTask:P.openNewTask,onQuickCreate:wn,onPlanningMode:P.openPlanningWithInitialPlan,onSubtaskBreakdown:P.openSubtaskBreakdown,availableModels:Ke,favoriteProviders:pt,favoriteModels:Ht,onToggleFavorite:Yn,onToggleModelFavorite:un,taskStuckTimeoutMs:Et,searchQuery:N,lastFetchTimeMs:ze})});if(!Be)return e.jsxs(e.Fragment,{children:[e.jsx(__,{stage:Xe}),e.jsx(af,{toasts:t,onRemove:s})]});const jt=!P.modelOnboardingOpen&&ZP(),Jt=!P.modelOnboardingOpen&&!jt&&na()&&!nf();return e.jsxs(e.Fragment,{children:[e.jsx(lj,{isElectron:i,onOpenSettings:yn,onOpenGitHubImport:P.openGitHubImport,onOpenPlanning:P.openPlanning,onResumePlanning:P.resumePlanning,activePlanningSessionCount:Y.length,onOpenUsage:P.openUsage,onOpenActivityLog:P.openActivityLog,onOpenMailbox:()=>de("mailbox"),mailboxUnreadCount:ye,onOpenSchedules:P.openSchedules,onOpenGitManager:P.openGitManager,onOpenNodes:x,showNodesButton:xt,onOpenWorkflowSteps:P.openWorkflowSteps,onOpenScripts:P.openScripts,onRunScript:P.runScript,onToggleTerminal:P.toggleTerminal,onOpenFiles:P.openFiles,filesOpen:P.filesOpen,globalPaused:yt,enginePaused:Ct,onToggleGlobalPause:be,onToggleEnginePause:U,view:C,onChangeView:O==="project"&&f?de:void 0,showSkillsTab:rt,showAgentsTab:je,searchQuery:N,onSearchChange:M,projects:R,currentProject:f,onSelectProject:Jn,onViewAllProjects:Ot,projectId:f?.id,mobileNavEnabled:Z,availableNodes:m,currentNode:c,onSelectNode:Je=>{Je===null?p():g(Je)},isRemote:h,experimentalFeatures:{insights:_t,roadmap:Ve,memoryView:ft,devServer:Fe,devServerView:Fe}}),O==="project"&&f&&!pe&&C!=="missions"&&!P.isPlanningOpen&&e.jsx(q_,{sessions:G,onResumeSession:ae,onDismissSession:K,onDismissAll:oe}),O==="project"&&f&&jt&&e.jsx(V_,{onResume:P.openModelOnboarding}),O==="project"&&f&&Jt&&e.jsx(W_,{onOpenModelOnboarding:P.openModelOnboarding,onOpenSettings:Je=>P.openSettings(Je)}),O==="project"&&f&&!j&&_&&!qe&&e.jsx(tf,{hasAiProvider:k,hasGithub:A,onDismiss:Pe}),e.jsx("div",{className:`project-content${O==="project"&&f?" project-content--with-footer":""}${Z?" project-content--with-mobile-nav":""}`,children:et()}),O==="project"&&f&&!pe&&e.jsx(B_,{tasks:h&&w.tasks.length>0?w.tasks:J,projectId:f.id,taskStuckTimeoutMs:Et,backgroundSessions:$,backgroundGenerating:T,backgroundNeedsInput:S,onOpenBackgroundSession:ae,onDismissBackgroundSession:K,lastFetchTimeMs:ze}),e.jsx(G_,{view:C,onChangeView:O==="project"&&f?de:()=>{},footerVisible:O==="project"&&!!f,modalOpen:P.anyModalOpen,onOpenSettings:yn,onOpenActivityLog:P.openActivityLog,onOpenMailbox:()=>de("mailbox"),mailboxUnreadCount:ye,onOpenGitManager:P.openGitManager,onOpenWorkflowSteps:P.openWorkflowSteps,onOpenSchedules:P.openSchedules,onOpenScripts:P.openScripts,onToggleTerminal:P.toggleTerminal,onOpenFiles:P.openFiles,onOpenGitHubImport:P.openGitHubImport,onOpenPlanning:P.openPlanning,onResumePlanning:P.resumePlanning,activePlanningSessionCount:Y.length,onOpenUsage:P.openUsage,onViewAllProjects:Ot,onRunScript:P.runScript,projectId:f?.id,showSkillsTab:rt,experimentalFeatures:{insights:_t,roadmap:Ve,memoryView:ft,devServer:Fe,devServerView:Fe}}),O==="project"&&f&&C!=="chat"&&C!=="mailbox"&&C!=="insights"&&C!=="devserver"&&C!=="dev-server"&&e.jsx(uT,{projectId:f.id,addToast:n,showFAB:Pt,open:st,onOpenChange:Ee,favoriteProviders:pt,favoriteModels:Ht,onToggleFavorite:Yn,onToggleModelFavorite:un}),e.jsx(M_,{projectId:f?.id,tasks:J,projects:r,currentProject:f,addToast:n,toasts:t,removeToast:s,modalManager:P,projectActions:{handleAddProject:tn,handleSetupComplete:dn,handleModelOnboardingComplete:nn},taskHandlers:{handleModalCreate:On,handlePlanningTaskCreated:Nn,handlePlanningTasksCreated:Bn,handleSubtaskTasksCreated:rs,handleGitHubImport:Vt},taskOperations:{moveTask:he,deleteTask:q,mergeTask:W,retryTask:me,duplicateTask:ve},deepLink:{handleDetailClose:$t},settings:{prAuthAvailable:It,themeMode:E,colorTheme:I,setThemeMode:L,setColorTheme:ee},onSettingsClose:()=>{P.closeSettings(),we()},onReopenOnboarding:()=>{P.closeSettings(),P.openModelOnboarding()}}),e.jsx(WT,{open:He})]})}function iR(){return e.jsx(yT,{children:e.jsx(qT,{children:e.jsx(sR,{})})})}vx();Cf.createRoot(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(ax,{children:e.jsx(iR,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(t=>{console.log("SW registered:",t.scope)}).catch(t=>{console.log("SW registration failed:",t)});export{kR as $,Ns as A,sn as B,en as C,rn as D,an as E,vi as F,yi as G,io as H,Ut as I,Ds as J,Lt as K,ct as L,WP as M,Sy as N,zP as O,ss as P,OP as Q,vn as R,Oi as S,Wo as T,Cy as U,BR as V,Ey as W,Ft as X,yR as Y,Sn as Z,Zt as _,ms as a,uI as a$,_r as a0,$v as a1,yg as a2,qo as a3,sa as a4,si as a5,ii as a6,Fs as a7,zI as a8,UI as a9,Xk as aA,FI as aB,LI as aC,Zk as aD,ej as aE,tT as aF,Xr as aG,Ho as aH,J_ as aI,Z_ as aJ,cs as aK,gi as aL,ei as aM,nx as aN,XR as aO,eI as aP,ZR as aQ,tI as aR,nI as aS,sI as aT,iI as aU,aI as aV,rI as aW,lI as aX,oI as aY,cI as aZ,dI as a_,BI as aa,OI as ab,HI as ac,Ln as ad,is as ae,Kb as af,Xb as ag,zs as ah,xg as ai,qr as aj,Hi as ak,KI as al,VI as am,WI as an,GI as ao,Mr as ap,Lb as aq,$a as ar,hg as as,Dn as at,Zm as au,p_ as av,gT as aw,DI as ax,hd as ay,Fa as az,YR as b,xR as b$,hI as b0,pI as b1,mI as b2,An as b3,Vo as b4,qi as b5,II as b6,RI as b7,$I as b8,$M as b9,ty as bA,ny as bB,Zv as bC,jR as bD,Ks as bE,Zs as bF,Gr as bG,Wi as bH,Dy as bI,ux as bJ,mx as bK,NI as bL,Ab as bM,go as bN,PI as bO,_I as bP,EI as bQ,CI as bR,MI as bS,SI as bT,AI as bU,QR as bV,Pn as bW,gR as bX,pR as bY,fR as bZ,Um as b_,Fx as ba,Wc as bb,oR as bc,Lx as bd,Bx as be,Ux as bf,mR as bg,cR as bh,dR as bi,uR as bj,zx as bk,lR as bl,hR as bm,Kp as bn,SR as bo,NR as bp,_R as bq,wR as br,CR as bs,ER as bt,MR as bu,AR as bv,sy as bw,PR as bx,Go as by,ey as bz,Qe as c,vR as c0,bR as c1,fI as c2,bI as c3,yI as c4,xI as c5,gI as c6,vI as c7,kI as c8,ph as c9,Kc as ca,Jg as cb,jI as cc,HR as cd,LR as ce,OR as cf,zR as cg,WR as ch,VR as ci,Wm as cj,DR as ck,$R as cl,LP as cm,UR as cn,Ua as co,J2 as cp,RR as cq,TR as cr,Dv as cs,IR as ct,FR as cu,wI as cv,GR as d,JR as e,TI as f,In as g,Kn as h,aa as i,Kt as j,Ny as k,KR as l,X_ as m,Ki as n,Ca as o,fe as p,bj as q,qR as r,Bs as s,po as t,Wt as u,Ls as v,qt as w,Er as x,BP as y,qI as z};
|