@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
|
@@ -1,644 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-BywTPbLB.js","assets/vendor-react-K0fH_qHe.js","assets/DirectoryPicker-BMJIT7HD.js","assets/folder-open-BVDq27HP.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/PluginManager-D64RIzmL.css","assets/PiExtensionsManager-CriZBkQe.js","assets/PiExtensionsManager-CPgmJgDk.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-CVtmwoJC.js","assets/AgentsView-CWFLMIDP.js","assets/upload-BDvpReDO.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-CjfVl8mZ.js","assets/DocumentsView-Co9to4Zp.css","assets/InsightsView-Rb735C9_.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-BviqBWRA.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-C_T91ebd.js","assets/RoadmapsView-Dhl--4vY.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-CG9y4fsE.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-LLc_uNtG.js","assets/MemoryView-DhinauGs.css","assets/DevServerView-ChWTzTvy.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as a,j as e,a as wa,g as Im,R as $m,c as jf}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 Dm=(...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 wf=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 Nf=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 $c=t=>{const n=Nf(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 ml={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 Sf=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Cf=a.createContext({}),Ef=()=>a.useContext(Cf),Mf=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:f=""}=Ef()??{},p=i??h?Number(s??u)*24/Number(n??c):s??u;return a.createElement("svg",{ref:m,...ml,width:n??c??ml.width,height:n??c??ml.height,stroke:t??g,strokeWidth:p,className:Dm("lucide",f,r),...!l&&!Sf(d)&&{"aria-hidden":"true"},...d},[...o.map(([b,x])=>a.createElement(b,x)),...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 Xe=(t,n)=>{const s=a.forwardRef(({className:i,...r},l)=>a.createElement(Mf,{ref:l,iconNode:n,className:Dm(`lucide-${wf($c(t))}`,`lucide-${t}`,i),...r}));return s.displayName=$c(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 Af=[["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=Xe("activity",Af);/**
|
|
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 Pf=[["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"}]],Ur=Xe("archive",Pf);/**
|
|
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 Rf=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],za=Xe("arrow-down",Rf);/**
|
|
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 Tf=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],na=Xe("arrow-left",Tf);/**
|
|
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 _f=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Oa=Xe("arrow-right",_f);/**
|
|
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 If=[["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"}]],Fm=Xe("arrow-up-down",If);/**
|
|
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 $f=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],gi=Xe("arrow-up",$f);/**
|
|
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 Df=[["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"}]],Lm=Xe("book-open",Df);/**
|
|
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 Ff=[["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"}]],an=Xe("bot",Ff);/**
|
|
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 Lf=[["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"}]],oo=Xe("box",Lf);/**
|
|
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 zf=[["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"}]],Nr=Xe("brain",zf);/**
|
|
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 Of=[["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"}]],zm=Xe("calendar",Of);/**
|
|
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 Bf=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Uf=Xe("check-check",Bf);/**
|
|
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 Hf=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Mn=Xe("check",Hf);/**
|
|
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 qf=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zt=Xe("chevron-down",qf);/**
|
|
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 Vf=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Bo=Xe("chevron-left",Vf);/**
|
|
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 Wf=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ln=Xe("chevron-right",Wf);/**
|
|
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 Kf=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ds=Xe("chevron-up",Kf);/**
|
|
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 Gf=[["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"}]],as=Xe("circle-alert",Gf);/**
|
|
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 Jf=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],nn=Xe("circle-check-big",Jf);/**
|
|
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 Yf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Hr=Xe("circle-dot",Yf);/**
|
|
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 Qf=[["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"}]],Dc=Xe("circle-question-mark",Qf);/**
|
|
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 Xf=[["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"}]],Ba=Xe("circle-x",Xf);/**
|
|
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 Zf=[["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"}]],eg=Xe("clipboard-list",Zf);/**
|
|
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 tg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ui=Xe("clock",tg);/**
|
|
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 ng=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Om=Xe("code",ng);/**
|
|
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 sg=[["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"}]],ig=Xe("columns-3",sg);/**
|
|
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 ag=[["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"}]],Hi=Xe("copy",ag);/**
|
|
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 rg=[["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"}]],lg=Xe("cpu",rg);/**
|
|
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 og=[["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"}]],cg=Xe("download",og);/**
|
|
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 dg=[["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"}]],co=Xe("ellipsis",dg);/**
|
|
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 ug=[["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"}]],mg=Xe("external-link",ug);/**
|
|
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 hg=[["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"}]],pg=Xe("eye-off",hg);/**
|
|
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 fg=[["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"}]],Uo=Xe("eye",fg);/**
|
|
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 gg=[["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=Xe("file-code",gg);/**
|
|
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 bg=[["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"}]],Bm=Xe("file-diff",bg);/**
|
|
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 xg=[["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"}]],vg=Xe("file-minus",xg);/**
|
|
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 yg=[["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"}]],Um=Xe("file-pen",yg);/**
|
|
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 kg=[["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"}]],jg=Xe("file-plus",kg);/**
|
|
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 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:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],Ng=Xe("file-question-mark",wg);/**
|
|
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 Sg=[["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"}]],xi=Xe("file-text",Sg);/**
|
|
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 Cg=[["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"}]],Eg=Xe("file-type",Cg);/**
|
|
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 Mg=[["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"}]],Hm=Xe("file",Mg);/**
|
|
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 Ag=[["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"}]],uo=Xe("folder-git-2",Ag);/**
|
|
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 Pg=[["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"}]],Fc=Xe("folder-root",Pg);/**
|
|
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 Rg=[["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=Xe("folder",Rg);/**
|
|
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 Tg=[["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"}]],Sr=Xe("funnel",Tg);/**
|
|
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 _g=[["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"}]],Fs=Xe("git-branch",_g);/**
|
|
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 Ig=[["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"}]],Ra=Xe("git-commit-horizontal",Ig);/**
|
|
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 $g=[["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"}]],qm=Xe("git-merge",$g);/**
|
|
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 Dg=[["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"}]],ns=Xe("git-pull-request",Dg);/**
|
|
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 Fg=[["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"}]],vi=Xe("globe",Fg);/**
|
|
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 Lg=[["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"}]],Vm=Xe("grid-3x3",Lg);/**
|
|
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 zg=[["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"}]],Ho=Xe("grip-vertical",zg);/**
|
|
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 Og=[["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"}]],Bg=Xe("hard-drive",Og);/**
|
|
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 Ug=[["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"}]],Hg=Xe("heart",Ug);/**
|
|
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 qg=[["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"}]],Ta=Xe("history",qg);/**
|
|
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 Vg=[["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"}]],Na=Xe("inbox",Vg);/**
|
|
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 Wg=[["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"}]],Wm=Xe("key",Wg);/**
|
|
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 Kg=[["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"}]],yi=Xe("layers",Kg);/**
|
|
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 Gg=[["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"}]],ki=Xe("layout-grid",Gg);/**
|
|
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 Jg=[["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"}]],Ls=Xe("lightbulb",Jg);/**
|
|
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 Yg=[["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"}]],qi=Xe("link",Yg);/**
|
|
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 Qg=[["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"}]],Xg=Xe("list-plus",Qg);/**
|
|
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 Zg=[["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"}]],qr=Xe("list-tree",Zg);/**
|
|
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 eb=[["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"}]],mo=Xe("list",eb);/**
|
|
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 tb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ct=Xe("loader-circle",tb);/**
|
|
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 nb=[["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"}]],Vr=Xe("lock",nb);/**
|
|
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 sb=[["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"}]],_a=Xe("mail",sb);/**
|
|
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 ib=[["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"}]],ho=Xe("map",ib);/**
|
|
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 ab=[["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"}]],Xs=Xe("maximize-2",ab);/**
|
|
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 rb=[["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"}]],Zs=Xe("message-square",rb);/**
|
|
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 lb=[["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=Xe("minimize-2",lb);/**
|
|
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 ob=[["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"}]],Wr=Xe("monitor",ob);/**
|
|
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 cb=[["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"}]],Km=Xe("moon",cb);/**
|
|
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 db=[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]],ub=Xe("move",db);/**
|
|
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 mb=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],po=Xe("package",mb);/**
|
|
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 hb=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],pb=Xe("paperclip",hb);/**
|
|
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 fb=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]],$s=Xe("pause",fb);/**
|
|
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 gb=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Ln=Xe("pencil",gb);/**
|
|
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 bb=[["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"}]],rn=Xe("play",bb);/**
|
|
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 xb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ht=Xe("plus",xb);/**
|
|
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 vb=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Gm=Xe("radio",vb);/**
|
|
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 yb=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],An=Xe("refresh-cw",yb);/**
|
|
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 kb=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],jb=Xe("rocket",kb);/**
|
|
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 wb=[["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"}]],Nb=Xe("rotate-ccw",wb);/**
|
|
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 Sb=[["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"}]],Jm=Xe("save",Sb);/**
|
|
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 Cb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],zi=Xe("search",Cb);/**
|
|
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 Eb=[["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"}]],fi=Xe("send",Eb);/**
|
|
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 Mb=[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]],Cr=Xe("server",Mb);/**
|
|
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 Ab=[["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"}]],Pb=Xe("settings-2",Ab);/**
|
|
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 Rb=[["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"}]],Ia=Xe("settings",Rb);/**
|
|
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 Tb=[["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"}]],_b=Xe("shield",Tb);/**
|
|
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 Ib=[["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"}]],On=Xe("sparkles",Ib);/**
|
|
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 $b=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],cs=Xe("square",$b);/**
|
|
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 Db=[["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"}]],Ym=Xe("sun",Db);/**
|
|
518
|
-
* @license lucide-react v1.7.0 - ISC
|
|
519
|
-
*
|
|
520
|
-
* This source code is licensed under the ISC license.
|
|
521
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
522
|
-
*/const Fb=[["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"}]],ss=Xe("target",Fb);/**
|
|
523
|
-
* @license lucide-react v1.7.0 - ISC
|
|
524
|
-
*
|
|
525
|
-
* This source code is licensed under the ISC license.
|
|
526
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
527
|
-
*/const Lb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],zs=Xe("terminal",Lb);/**
|
|
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 zb=[["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"}]],Er=Xe("text-wrap",zb);/**
|
|
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 Ob=[["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=Xe("trash-2",Ob);/**
|
|
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 Bb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Ub=Xe("trending-up",Bb);/**
|
|
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 Hb=[["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"}]],qo=Xe("triangle-alert",Hb);/**
|
|
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 qb=[["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"}]],Lc=Xe("unlink",qb);/**
|
|
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 Vb=[["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"}]],Ai=Xe("user",Vb);/**
|
|
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 Wb=[["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"}]],Kb=Xe("users",Wb);/**
|
|
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 Gb=[["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"}]],Qm=Xe("webhook",Gb);/**
|
|
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 Jb=[["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"}]],fo=Xe("workflow",Jb);/**
|
|
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 Yb=[["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"}]],Qb=Xe("wrench",Yb);/**
|
|
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 Xb=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Lt=Xe("x",Xb);/**
|
|
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 Zb=[["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"}]],jn=Xe("zap",Zb);class Kr 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(qo,{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 es({children:t,onError:n}){return e.jsx(Kr,{level:"page",onError:n,children:t})}function ui({children:t,onError:n}){return e.jsx(Kr,{level:"modal",onError:n,children:t})}function ex({children:t,onError:n}){return e.jsx(Kr,{level:"root",onError:n,children:t})}const tx="modulepreload",nx=function(t){return"/"+t},zc={},tn=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=nx(c),c in zc)return;zc[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":tx,u||(g.as="script"),g.crossOrigin="",g.href=c,m&&g.setAttribute("nonce",m),document.head.appendChild(g),u)return new Promise((f,p)=>{g.addEventListener("load",f),g.addEventListener("error",()=>p(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)})},Vo="fn.authToken",Oc="token",sx="fn_token";let Oi,Bc=!1,Mr=!1;const go="fn:auth-token-recovery-required";function ix(){try{const t=window.localStorage.getItem(Vo);return t&&t.length>0?t:void 0}catch{return}}function Xm(t){try{window.localStorage.setItem(Vo,t)}catch{}}function ax(){if(!(Bc||typeof window>"u")){Bc=!0;try{const t=new URL(window.location.href),n=t.searchParams.get(Oc);if(!n)return;Xm(n),t.searchParams.delete(Oc);const s=t.pathname+(t.search?t.search:"")+t.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Vi(){if(Oi!==void 0)return Oi;const t=ax();if(t)return Oi=t,t;const n=ix();if(n)return Oi=n,n}function rx(t){Oi=t,Mr=!1,Xm(t)}function lx(){Oi=void 0,Mr=!1;try{window.localStorage.removeItem(Vo)}catch{}}function Uc(t){return t==="ws:"?"http:":t==="wss:"?"https:":t}function ox(t){return t==="http:"||t==="https:"||t==="ws:"||t==="wss:"}function cx(t){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!ox(t.protocol))return!1;const s=t.hostname===n.hostname,i=t.port===n.port,r=Uc(t.protocol)===Uc(n.protocol);return s&&i&&r}function dx(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=Vi();if(!n||typeof window>"u")return t;const s=dx(t);return!s||!cx(s.parsed)?t:(s.parsed.searchParams.set(sx,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ii(t){const n=Vi();if(!n)return t;const s=new Headers(t??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function ux(t){if(!t||typeof t!="object")return!1;const n=t;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function mx(){typeof window>"u"||Mr||(Mr=!0,window.dispatchEvent(new CustomEvent(go)))}async function hx(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();ux(i)&&mx()}catch{}}function px(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Vi();const t=window.fetch.bind(window);window.fetch=function(s,i){const r=Vi(),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=>(hx(m),m))}}class fx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function gx(t){const n=t.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Yn(t){return`/api${t}`}async function z(t,n={}){const s=Yn(t),i=Vi(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),ii(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")||gx(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 fx(h?.error||`Request failed for ${s}: ${l.status} ${l.statusText}`,l.status,h?.details)}return u}function bx(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 Ar(t,n){const i=Yn(Y(`/tasks/${t}`,n));for(let r=1;r<=2;r++){const l=await fetch(i,{headers:ii({"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 Zm(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:f,planningModelProvider:p,planningModelId:b,thinkingLevel:x,summarize:v,reviewLevel:y,executionMode:A,priority:j}=t;return z(Y("/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:f,planningModelProvider:p,planningModelId:b,thinkingLevel:x,summarize:v,reviewLevel:y,executionMode:A,priority:j})})}function Ws(t,n,s){return z(Y(`/tasks/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function xx(t,n,s,i,r,l,o,d){return z(Y("/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 vx(t,n,s){return z(Y(`/tasks/${t}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function yx(t,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return z(Y(`/tasks/${t}${r}`,n),{method:"DELETE"})}function kx(t,n){return z(Y(`/tasks/${t}/merge`,n),{method:"POST"})}function jx(t,n){return z(Y(`/tasks/${t}/retry`,n),{method:"POST"})}function wx(t,n){return z(Y(`/tasks/${t}/duplicate`,n),{method:"POST"})}function Nx(t,n){return z(Y(`/tasks/${t}/pause`,n),{method:"POST"})}function Sx(t,n){return z(Y(`/tasks/${t}/unpause`,n),{method:"POST"})}function Cx(t,n){return z(Y(`/tasks/${t}/archive`,n),{method:"POST"})}function Ex(t,n){return z(Y(`/tasks/${t}/unarchive`,n),{method:"POST"})}function Mx(t){return z(Y("/tasks/archive-all-done",t),{method:"POST"}).then(n=>n.archived)}function Ax(t,n){return z(Y(`/tasks/${t}/approve-plan`,n),{method:"POST"})}function Px(t,n){return z(Y(`/tasks/${t}/reject-plan`,n),{method:"POST"})}function Rx(t){return z(Y("/config",t))}function Wi(t){return z(Y("/settings",t))}function Sa(t,n){return z(Y("/settings",n),{method:"PUT",body:JSON.stringify(t)})}function t_(t){return z(Y("/memory",t))}function n_(t,n){return z(Y("/memory",n),{method:"PUT",body:JSON.stringify({content:t})})}function Hc(t){return z(Y("/memory/files",t))}function Tx(t,n){const s=`path=${encodeURIComponent(t)}`;return z(Y(`/memory/file?${s}`,n))}function _x(t,n,s){return z(Y("/memory/file",s),{method:"PUT",body:JSON.stringify({path:t,content:n})})}function Ix(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(Y("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function s_(t){return z(Y("/memory/insights",t))}function i_(t,n){return z(Y("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:t})})}function a_(t){return z(Y("/memory/extract",t),{method:"POST"})}function r_(t){return z(Y("/memory/audit",t))}function l_(t){return z(Y("/memory/stats",t))}function $x(t){return z(Y("/memory/backend",t))}function Dx(t){return z(Y("/memory/install-qmd",t),{method:"POST"})}function Fx(t,n){return z(Y("/memory/test",n),{method:"POST",body:JSON.stringify({query:t})})}function sa(){return z("/settings/global")}function Gt(t){return z("/settings/global",{method:"PUT",body:JSON.stringify(t)})}function Lx(t){return z(Y("/settings/scopes",t))}function o_(t){return z(Y("/settings/pi-extensions",t))}function c_(t,n){return z(Y("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:t})})}function zx(t,n){return z(Y("/settings/test-ntfy",n),{method:"POST",body:t?JSON.stringify(t):void 0})}function d_(){return z("/pi-settings")}async function u_(t){return z("/pi-settings",{method:"PUT",body:JSON.stringify(t)})}async function m_(t){return z("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:t})})}async function h_(t){return z(Y("/pi-settings/reinstall-fusion",t),{method:"POST"})}async function $a(t,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Yn(Y(`/tasks/${t}/attachments`,s)),{method:"POST",headers:ii(),body:i}),l=await r.json();if(!r.ok)throw new Error(l.error||"Upload failed");return l}async function Ox(t,n,s){return z(Y(`/tasks/${t}/attachments/${n}`,s),{method:"DELETE"})}async function qc(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=Y(`/tasks/${t}/logs${r}`,n),o=await fetch(Yn(l),{headers:ii()});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 Bx(t,n,s,i){return z(Y(`/tasks/${t}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Ux(t,n,s){return z(Y(`/tasks/${t}/comments/${n}`,s),{method:"DELETE"})}function Hx(t,n){return z(Y(`/tasks/${t}/documents`,n))}function qx(t,n,s){return z(Y(`/tasks/${t}/documents/${n}/revisions`,s))}async function p_(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(Y(r,n))}function f_(t,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return z(Y(r,t))}function Vc(t,n,s,i,r){return z(Y(`/tasks/${t}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Vx(t,n,s){return z(Y(`/tasks/${t}/documents/${n}`,s),{method:"DELETE"})}function Wx(t,n,s){return z(Y(`/tasks/${t}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Kx(t,n,s){return z(Y(`/tasks/${t}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Gx(t,n){return z(Y(`/tasks/${t}/spec/rebuild`,n),{method:"POST"})}function Jx(t,n,s){return z(Y(`/tasks/${t}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Jn(){return z("/models")}function Yx(){return z("/usage")}function Qx(){return z("/providers/claude-cli/status")}function Xx(t){return z("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:t})})}function ji(){return z("/auth/status")}function eh(t){return z("/auth/login",{method:"POST",body:JSON.stringify({provider:t})})}function th(t){return z("/auth/logout",{method:"POST",body:JSON.stringify({provider:t})})}function nh(t,n){return z("/auth/api-key",{method:"POST",body:JSON.stringify({provider:t,apiKey:n})})}function sh(t){return z("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:t})})}function Zx(t,n,s,i){return z("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s,labels:i})})}function ev(t,n,s,i){return z(Y("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,issueNumber:s})})}function tv(t,n,s){return z("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s})})}function nv(t,n,s,i){return z(Y("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,prNumber:s})})}function sv(t){return z(Y("/git/remotes",t))}function ih(t){return z(Y("/git/remotes/detailed",t))}function iv(t,n,s){return z(Y("/git/remotes",s),{method:"POST",body:JSON.stringify({name:t,url:n})})}function av(t,n){return z(Y(`/git/remotes/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function rv(t,n,s){return z(Y(`/git/remotes/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function lv(t,n,s){return z(Y(`/git/remotes/${encodeURIComponent(t)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function ov(t,n,s){return z(Y(`/tasks/${t}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function cv(t,n){return z(Y(`/tasks/${t}/pr/refresh`,n),{method:"POST"})}async function dv(t,n){return(await z(Y("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:t})})).results}function tr(t,n,s,i){return z(Y("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:t,cols:n,rows:s})})}function Wc(t,n){return z(Y(`/terminal/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function uv(t){return z(Y("/terminal/sessions",t))}function Es(t){return z(Y("/git/status",t))}function mv(t,n){const s=t?`?limit=${t}`:"";return z(Y(`/git/commits${s}`,n))}function Pr(t,n){return z(Y(`/git/commits/${t}/diff`,n))}function hv(t){return z(Y("/git/commits/ahead",t))}function pv(t,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const l=r.size>0?`?${r.toString()}`:"";return z(Y(`/git/remotes/${encodeURIComponent(t)}/commits${l}`,i))}function oa(t){return z(Y("/git/branches",t))}function fv(t,n,s){const i=`?limit=${n}`;return z(Y(`/git/branches/${encodeURIComponent(t)}/commits${i}`,s))}function gv(t){return z(Y("/git/worktrees",t))}function bv(t,n,s){return z(Y("/git/branches",s),{method:"POST",body:JSON.stringify({name:t,base:n})})}function xv(t,n){return z(Y(`/git/branches/${encodeURIComponent(t)}/checkout`,n),{method:"POST"})}function Kc(t,n,s){const i=n?"?force=true":"";return z(Y(`/git/branches/${encodeURIComponent(t)}${i}`,s),{method:"DELETE"})}function vv(t,n){return z(Y("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:t})})}function yv(t){return z(Y("/git/pull",t),{method:"POST"})}function kv(t){return z(Y("/git/push",t),{method:"POST"})}function nr(t){return z(Y("/git/stashes",t))}function jv(t,n){return z(Y("/git/stashes",n),{method:"POST",body:JSON.stringify({message:t})})}function wv(t,n,s){return z(Y(`/git/stashes/${t}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Nv(t,n){return z(Y(`/git/stashes/${t}`,n),{method:"DELETE"})}function Sv(t,n,s){const i=new URLSearchParams;return i.set("path",t),i.set("staged",String(n)),z(Y(`/git/diff/file?${i.toString()}`,s))}function Pi(t){return z(Y("/git/changes",t))}function Gc(t,n){return z(Y("/git/stage",n),{method:"POST",body:JSON.stringify({files:t})})}function Cv(t,n){return z(Y("/git/unstage",n),{method:"POST",body:JSON.stringify({files:t})})}function Jc(t,n){return z(Y("/git/commit",n),{method:"POST",body:JSON.stringify({message:t})})}function Ev(t,n){return z(Y("/git/discard",n),{method:"POST",body:JSON.stringify({files:t})})}function Mv(t){return z(Y("/workspaces",t))}function Av(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 Pv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),z(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Rv(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 Tv(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 _v(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 Iv(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 $v(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 Dv(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 ah(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Fv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Lv(t,n,s){return z(Y("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:t,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function zv(t,n,s,i){return z(Y("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Ov(t,n,s){return z(Y(`/planning/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function rh(t,n,s){return z(Y("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Bv(t,n,s){return z(Y("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Uv(t,n,s){return z(Y("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Hv(t,n,s){return z(Y("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:t,subtasks:n})})}const bo=new Set;if(typeof window<"u"){const t=()=>{for(const n of Array.from(bo))try{n.close()}catch{}};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t)}function qv(t,n){if(n===null||n<=0)return t;const s=t.includes("?")?"&":"?";return`${t}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ua(t,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,l=!1,o=0,d=null,m=null,c=!1;const u=f=>{const p=f.lastEventId;if(!p)return!0;const b=Number.parseInt(p,10);return Number.isFinite(b)?m!==null&&b<=m?!1:(m=b,!0):!0},h=()=>{if(l)return;const f=qv(t,m),p=new EventSource(Ps(f));r=p,p.onopen=()=>{o=0,c=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},p.onmessage=b=>{const x=b;u(x)&&n.onMessage?.(x)};for(const[b,x]of Object.entries(n.events??{}))p.addEventListener(b,v=>{const y=v;u(y)&&x(y)});p.onerror=()=>{if(l||r!==p)return;if(p.readyState===EventSource.CONNECTING){c||(c=!0,s.onConnectionStateChange?.("reconnecting"));return}if(p.close(),o>=i){s.onFatalError?.("Connection lost");return}c=!0,s.onConnectionStateChange?.("reconnecting"),o+=1;const x=Math.min(1e3*2**(o-1),3e4);d=setTimeout(()=>{d=null,h()},x)}};h();const g={close:()=>{l=!0,d&&(clearTimeout(d),d=null),r?.close(),bo.delete(g)},isConnected:()=>!l&&r?.readyState===EventSource.OPEN};return bo.add(g),g}function Yc(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 Ki(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 Vv(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 Wv(t){const s=(Array.isArray(t.lines)?t.lines:[]).map((i,r)=>Vv(i,r+1));return{lines:s,totalLines:typeof t.totalLines=="number"&&Number.isFinite(t.totalLines)?t.totalLines:s.length}}function Kv(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 Qc(t){return Array.isArray(t)?t.map(Yc):(t.candidates??[]).map(Yc)}async function Gv(t){try{const n=await z(Y("/dev-server/candidates",t));return Qc(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await z(Y("/dev-server/detect",t));return Qc(s)}throw n}}function Wo(t){return z(Y("/dev-server/status",t)).then(Ki)}async function g_(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(Y(`/dev-server/logs/history${i}`,n));return Wv(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const l=await Wo(n);return Kv(l.logs,t)}throw r}}function Jv(t,n){const s=t.cwd??t.packagePath??".",i=t.scriptName;return z(Y("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:t.command,scriptName:i,scriptId:i,cwd:s,packagePath:t.packagePath})}).then(Ki)}function Yv(t){return z(Y("/dev-server/stop",t),{method:"POST"}).then(Ki)}function Qv(t){return z(Y("/dev-server/restart",t),{method:"POST"}).then(Ki)}async function Xv(t,n){const s=typeof t=="string"?{url:t}:t;try{const i=await z(Y("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Ki(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await z(Y("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Ki(r)}throw i}}function b_(t){return Yn(Y("/dev-server/logs/stream",t))}async function x_(t){try{return(await z(Y("/devserver",t))).sessions??[]}catch{try{const n=await Wo(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 v_(t,n){try{return await z(Y(`/devserver/${encodeURIComponent(t)}`,n))}catch{try{const s=await Wo(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 y_(t,n){try{return await z(Y(`/devserver/${encodeURIComponent(t)}/start`,n),{method:"POST"})}catch{const s=await Jv({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 k_(t,n){try{return await z(Y(`/devserver/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}catch{const s=await Yv(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 j_(t,n){try{return await z(Y(`/devserver/${encodeURIComponent(t)}/restart`,n),{method:"POST"})}catch{const s=await Qv(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 w_(t,n,s){try{const i=await z(Y(`/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 Xv({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function N_(t){try{return(await z(Y("/devserver/detect",t))).candidates??[]}catch{try{return(await Gv(t)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function S_(t,n){return Yn(Y(`/devserver/${encodeURIComponent(t)}/logs/stream`,n))}function Ha(t,n,s=25e3){const i=setInterval(()=>{Dk(t,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Zv(t,n){return Yn(Y(`/planning/${encodeURIComponent(t)}/stream`,n))}function ey(t,n,s,i){const r=Zv(t,n);let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ua(r,{onOpen:()=>{d(),l=Ha(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 qa(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 ty(t){return z(qa("/routines",t))}function ny(t,n){return z(qa("/routines",n),{method:"POST",body:JSON.stringify(t)})}function Xc(t,n,s){return z(qa(`/routines/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function sy(t,n){await z(qa(`/routines/${t}`,n),{method:"DELETE"})}function iy(t,n){return z(qa(`/routines/${t}/trigger`,n),{method:"POST"})}function Zc(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 ay(t){const n=Y("/activity",t);return z(n,{method:"DELETE"})}function Gr(t){return z(Y("/workflow-steps",t))}function ed(t,n){return z(Y("/workflow-steps",n),{method:"POST",body:JSON.stringify(t)})}function ry(t,n,s){return z(Y(`/workflow-steps/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ly(t,n){return z(Y(`/workflow-steps/${t}`,n),{method:"DELETE"})}function td(t,n){return z(Y(`/workflow-steps/${t}/refine`,n),{method:"POST"})}function oy(t,n){return z(Y(`/tasks/${encodeURIComponent(t)}/workflow-results`,n))}function cy(){return z("/workflow-step-templates")}function dy(t,n){return z(Y(`/workflow-step-templates/${encodeURIComponent(t)}/create`,n),{method:"POST"})}function Va(t){return z(Y("/scripts",t))}function uy(t,n,s){return z(Y("/scripts",s),{method:"POST",body:JSON.stringify({name:t,command:n})})}function my(t,n){return z(Y(`/scripts/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function lh(t,n,s){return(await z(Y("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:t,type:n})})).refined}const sr={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 oh(t){if(!(t instanceof Error))return sr.NETWORK;const n=t.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?sr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?sr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?t.message:sr.NETWORK}function hy(t,n){return z(Y("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:t})})}function py(t,n,s){return z(Y(`/subtasks/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function fy(t,n){return Yn(Y(`/subtasks/${encodeURIComponent(t)}/stream`,n))}function gy(t,n,s,i){let r=null,l=null;const o=()=>{r?.stop(),r=null},d=Ua(fy(t,n),{onOpen:()=>{o(),r=Ha(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 by(t,n,s,i){return z(Y("/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 ch(t,n,s){return z(Y("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Y(t,n){if(!n)return t;const s=t.includes("?")?"&":"?";return`${t}${s}projectId=${encodeURIComponent(n)}`}function xy(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 Jr(t,n){const{nodeId:s,localNodeId:i,...r}=n??{},l=xy(t,s,i);return z(l,r)}function ia(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 dh(t,n){return z(Y(`/agents/${encodeURIComponent(t)}`,n))}function vy(t,n){return z(Y("/agents",n),{method:"POST",body:JSON.stringify(t)})}function yy(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function C_(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function E_(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function M_(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function A_(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/memory/files`,n))}function P_(t,n,s){const i=`path=${encodeURIComponent(n)}`;return z(Y(`/agents/${encodeURIComponent(t)}/memory/file?${i}`,s))}function R_(t,n,s,i){return z(Y(`/agents/${encodeURIComponent(t)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function ky(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function jy(t,n){return z(Y(`/agents/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function T_(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 __(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}`,s))}function I_(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}/logs`,s))}function $_(t,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return z(Y(`/agents/${encodeURIComponent(t)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function D_(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/runs/stop`,n),{method:"POST"})}function wy(t){return z(Y("/agents/stats",t))}function F_(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/chain-of-command`,n))}function L_(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 z_(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function nd(t,n,s){return z(Y(`/tasks/${encodeURIComponent(t)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function O_(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/tasks`,n))}function B_(){return z("/agents/companies")}function U_(t,n){return z(Y("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:t})})}function H_(t,n){return z(Y("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:t})})}function q_(t,n){return z(Y(`/agents/generate/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function sd(t){return z(Y("/backups",t))}function Ny(t){return z(Y("/backups",t),{method:"POST"})}function Sy(t,n){const s=Y("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(t)}`;return z(i)}function Cy(t,n,s){return z(Y("/settings/import",s),{method:"POST",body:JSON.stringify({data:t,scope:n?.scope??"both",merge:n?.merge??!0})})}function id(){return z("/projects/across-nodes")}function Ea(t,n){z("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:t,message:n})}).catch(()=>{})}function ad(){return z("/nodes")}function Ey(t){return z("/nodes",{method:"POST",body:JSON.stringify(t)})}function My(t,n){return z(`/nodes/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ay(t){return z(`/nodes/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Py(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 V_(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=Vi();o&&l.set("fn_token",o);const d=l.toString(),m=`/browse-directory${d?`?${d}`:""}`;return z(m)}function Ry(t){return z("/projects",{method:"POST",body:JSON.stringify(t)})}function uh(t){return z(`/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}function rd(t){return z(`/projects/${encodeURIComponent(t)}/health`)}function Ty(t){return z(Y("/executor/stats",t))}function ld(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 _y(t){return z(`/projects/${encodeURIComponent(t)}/pause`,{method:"POST"})}function Iy(t){return z(`/projects/${encodeURIComponent(t)}/resume`,{method:"POST"})}function $y(){return z("/global-concurrency")}function Dy(t){return z("/global-concurrency",{method:"PUT",body:JSON.stringify(t)})}function Fy(t,n){return z(`/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function mh(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 Ly(t){return z(Y("/missions",t))}function zy(t,n){return z(Y("/missions",n),{method:"POST",body:JSON.stringify(t)})}function hh(t,n){return z(Y(`/missions/${encodeURIComponent(t)}`,n))}function Oy(t,n,s){return z(Y(`/missions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function By(t,n){return z(Y(`/missions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Uy(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(Y(`/missions/${encodeURIComponent(t)}/events${r}`,s))}function Hy(t){return z(Y("/missions/health",t))}function qy(t,n,s){return z(Y(`/missions/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Vy(t,n,s){return z(Y(`/missions/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wy(t,n){return z(Y(`/missions/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Ky(t,n,s){return z(Y(`/missions/milestones/${encodeURIComponent(t)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Gy(t,n,s){return z(Y(`/missions/slices/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Jy(t,n){return z(Y(`/missions/slices/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Yy(t,n){return z(Y(`/missions/slices/${encodeURIComponent(t)}/activate`,n),{method:"POST"})}function Qy(t,n,s){return z(Y(`/missions/slices/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(t,n,s){return z(Y(`/missions/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(t,n){return z(Y(`/missions/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function ek(t,n,s){return z(Y(`/missions/features/${encodeURIComponent(t)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function tk(t,n){return z(Y(`/missions/features/${encodeURIComponent(t)}/unlink-task`,n),{method:"POST"})}function nk(t,n,s,i){return z(Y(`/missions/features/${encodeURIComponent(t)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function sk(t,n){return z(Y(`/missions/slices/${encodeURIComponent(t)}/triage-all`,n),{method:"POST"})}function hl(t,n){return z(Y(`/missions/milestones/${encodeURIComponent(t)}/assertions`,n))}function ik(t,n,s){return z(Y(`/missions/milestones/${encodeURIComponent(t)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function ak(t,n,s){return z(Y(`/missions/assertions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function rk(t,n,s){return z(Y(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function lk(t,n,s){return z(Y(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function ok(t,n){return z(Y(`/missions/assertions/${encodeURIComponent(t)}/features`,n))}function pl(t,n){return z(Y(`/missions/milestones/${encodeURIComponent(t)}/validation`,n))}function od(t,n){return z(Y(`/missions/milestones/${encodeURIComponent(t)}/validation-telemetry`,n))}function ck(t,n){return z(Y(`/missions/features/${encodeURIComponent(t)}/validate`,n),{method:"POST"})}function cd(t,n){return z(Y(`/missions/features/${encodeURIComponent(t)}/validation-loop`,n))}function dk(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(Y(`/missions/features/${encodeURIComponent(t)}/validation-runs${r}`,s)).then(l=>l.runs)}function uk(t,n){return z(Y(`/missions/validation-runs/${encodeURIComponent(t)}`,n))}function mk(t,n){return z(Y(`/missions/${encodeURIComponent(t)}/resume`,n),{method:"POST"})}function hk(t,n){return z(Y(`/missions/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}function pk(t,n){return z(Y(`/missions/${encodeURIComponent(t)}/start`,n),{method:"POST"})}function fk(t,n,s){return z(Y(`/missions/${encodeURIComponent(t)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function gk(t,n,s){return z(Y("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:t,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function bk(t,n,s,i){return z(Y("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function xk(t,n,s){return z(Y(`/missions/interview/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ph(t,n,s){return z(Y("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function vk(t,n,s){return z(Y("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function yk(t,n,s,i){const r=Yn(Y(`/missions/interview/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ua(r,{onOpen:()=>{d(),l=Ha(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 Wa(t,n,s){return Y(`/missions/milestones/${encodeURIComponent(t)}/interview${n}`,s)}function Ka(t,n,s){return Y(`/missions/slices/${encodeURIComponent(t)}/interview${n}`,s)}function kk(t,n){return z(Wa(t,"/start",n),{method:"POST"})}function jk(t,n,s,i){return z(Wa(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function wk(t,n,s,i){const r=Yn(Wa(t,`/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ua(r,{onOpen:()=>{d(),l=Ha(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 Nk(t,n,s){return z(Wa(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function Sk(t,n){return z(Wa(t,"/skip",n),{method:"POST"})}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=Yn(Ka(t,`/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ua(r,{onOpen:()=>{d(),l=Ha(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 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"})}async function Rk(t,n){try{return await z(Y(`/missions/features/${encodeURIComponent(t)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function W_(t){return z(Y("/roadmaps",t))}function K_(t,n){return z(Y("/roadmaps",n),{method:"POST",body:JSON.stringify(t)})}function G_(t,n){return z(Y(`/roadmaps/${encodeURIComponent(t)}`,n))}function J_(t,n,s){return z(Y(`/roadmaps/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Y_(t,n){return z(Y(`/roadmaps/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Q_(t,n,s){return z(Y(`/roadmaps/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function X_(t,n,s){return z(Y(`/roadmaps/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Z_(t,n){return z(Y(`/roadmaps/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function eI(t,n,s){return z(Y(`/roadmaps/milestones/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function tI(t,n,s){return z(Y(`/roadmaps/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function nI(t,n){return z(Y(`/roadmaps/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function sI(t,n,s){return z(Y(`/roadmaps/${encodeURIComponent(t)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function iI(t,n,s){return z(Y(`/roadmaps/milestones/${encodeURIComponent(t)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function aI(t,n,s,i){return z(Y(`/roadmaps/features/${encodeURIComponent(t)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function rI(t,n){return z(Y(`/roadmaps/${encodeURIComponent(t)}/handoff`,n))}function lI(t,n,s,i){return z(Y(`/roadmaps/${encodeURIComponent(t)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function oI(t,n,s){return z(Y(`/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 Gi(t){if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return[]}}async function fh(t){const n=t?`?projectId=${encodeURIComponent(t)}`:"",s=await fetch(Yn(`/ai-sessions${n}`),{headers:ii()});return s.ok?(await s.json()).sessions??[]:[]}async function ti(t){const n=await fetch(Yn(`/ai-sessions/${encodeURIComponent(t)}`),{headers:ii()});return n.ok?n.json():null}async function Tk(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 _k(t,n){return z(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Ik(t,n){return z(`/ai-sessions/${encodeURIComponent(t)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function $k(t){await fetch(Yn(`/ai-sessions/${encodeURIComponent(t)}`),{method:"DELETE",headers:ii()})}function Dk(t,n){return z(Y(`/ai-sessions/${encodeURIComponent(t)}/ping`,n),{method:"POST"})}function Fk(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 Lk(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 gh(t){return z(Y("/messages/unread-count",t))}function zk(t,n){return z(Y("/messages",n),{method:"POST",body:JSON.stringify(t)})}function Ok(t,n){return z(Y(`/messages/${encodeURIComponent(t)}/read`,n),{method:"POST"})}function Bk(t){return z(Y("/messages/read-all",t),{method:"POST"})}function Uk(t,n){return z(Y(`/messages/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Hk(t,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(t)}`;return z(Y(i,s))}function qk(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/mailbox`,n))}function cI(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 dI(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/reflections`,n),{method:"POST"})}function uI(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 mI(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 hI(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function pI(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/ratings/summary`,n))}function fI(t,n,s){return z(Y(`/agents/${encodeURIComponent(t)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function gI(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/budget`,n))}function bI(t,n){return z(Y(`/agents/${encodeURIComponent(t)}/budget/reset`,n),{method:"POST"})}async function xI(t){return z(Y("/plugins",t))}async function vI(t,n){return z(Y("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...t})})}async function yI(t,n){return z(Y(`/plugins/${encodeURIComponent(t)}/enable`,n),{method:"POST"})}async function kI(t,n){return z(Y(`/plugins/${encodeURIComponent(t)}/disable`,n),{method:"POST"})}async function jI(t,n){return z(Y(`/plugins/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function wI(t,n){return z(Y(`/plugins/${encodeURIComponent(t)}/settings`,n))}async function NI(t,n,s){return z(Y(`/plugins/${encodeURIComponent(t)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function SI(t,n){return z(Y(`/plugins/${encodeURIComponent(t)}/reload`,n),{method:"POST"})}async function Vk(t){return z(Y("/plugins/ui-slots",t))}async function CI(t){return(await z(Y("/skills/discovered",t))).skills}async function EI(t,n,s){return z(Y("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:t,enabled:n})})}async function MI(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(Y(`/skills/catalog${r}`,s))}async function AI(t,n){return(await z(Y(`/skills/${encodeURIComponent(t)}/content`,n))).content}function PI(t,n){const s=new URLSearchParams;t&&s.set("projectId",t);const i=s.toString();return z(`/chat/sessions${i?`?${i}`:""}`)}async function Wk(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 Kk(t,n){return z(Y("/chat/sessions",n),{method:"POST",body:JSON.stringify(t)})}function RI(t,n,s){return z(Y(`/chat/sessions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TI(t,n){return z(Y(`/chat/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function dd(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(Y(`/chat/sessions/${encodeURIComponent(t)}/messages${r?`?${r}`:""}`,s))}function Gk(t,n){return z(Y(`/chat/sessions/${encodeURIComponent(t)}/cancel`,n),{method:"POST"})}function Jk(t,n,s,i,r){const l=Yn(Y(`/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:ii({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:o.signal});if(!c.ok){const x=await c.text();let v=`Request failed: ${c.status}`;try{v=JSON.parse(x).error||v}catch{}s.onError?.(v);return}if(!c.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const u=c.body.getReader(),h=new TextDecoder;let g="",f="",p=[];const b=(x,v=!1)=>{g+=x;const y=g.split(`
|
|
588
|
-
`);g=y.pop()||"",v&&g.length>0&&(y.push(g),g="");for(const A of y){const j=A.endsWith("\r")?A.slice(0,-1):A;if(j.startsWith("event:"))f=j.slice(6).trim();else if(j.startsWith("data:")){const P=j.slice(5);p.push(P.startsWith(" ")?P.slice(1):P)}else if(j===""){const P=p.join(`
|
|
589
|
-
`);m(f,P),f="",p=[]}}if(v&&f&&p.length>0){const A=p.join(`
|
|
590
|
-
`);m(f,A),f="",p=[]}};for(;;){const{done:x,value:v}=await u.read();if(x){b(h.decode(),!0);break}b(h.decode(v,{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 _I(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(Y(`/insights${i}`,n))}function II(t,n){return z(Y(`/insights/${encodeURIComponent(t)}/dismiss`,n),{method:"POST"})}function $I(t="manual",n,s){return z(Y("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:t,inputMetadata:n})})}function DI(t){return z(Y("/insights/runs",t))}function FI(t,n){return z(Y(`/insights/${encodeURIComponent(t)}/create-task`,n),{method:"POST"})}function Yk({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),f=a.useRef(null),p=a.useRef(null),b=a.useRef(null),x=a.useCallback(()=>{const T=window.visualViewport;return T&&T.width>0&&T.height>0?{width:T.width,height:T.height,offsetTop:T.offsetTop,offsetLeft:T.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),v=a.useCallback(()=>{const T=p.current;if(!T)return;const C=T.getBoundingClientRect(),$=b.current,{width:F,height:ee,offsetTop:I,offsetLeft:_}=x(),N=16,J=16,K=6,G=$?.offsetWidth||Math.max(C.width,260),M=Math.min(G,Math.max(F-N*2,160)),O=$?.offsetHeight||280,X=Math.min(O,Math.max(ee-J*2,160)),S=C.top-I,V=C.bottom-I,de=C.left-_,L=ee-V,Z=S,D=L<X&&Z>L,me=Math.min(Math.max(de,N),F-N-M)+_,q=D?Math.max(J+I,S-X-K+I):Math.min(V+K+I,ee+I-J-X);g({top:q,left:me,width:M})},[x]),y=a.useMemo(()=>Object.entries(l).sort(([T],[C])=>T.localeCompare(C)),[l]),A=y.length>0,j=y.length+(A?1:0);a.useEffect(()=>{if(!i)return;let T=!1;return m(!0),Va(s).then(C=>{T||o(C)}).catch(()=>{T||o({})}).finally(()=>{T||m(!1)}),()=>{T=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const T=C=>{f.current&&!f.current.contains(C.target)&&p.current&&!p.current.contains(C.target)&&r(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[i]),a.useEffect(()=>{if(!i)return;const T=C=>{C.key==="Escape"&&(r(!1),p.current?.focus())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[i]),a.useEffect(()=>{if(i){u(-1);const T=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(T)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const T=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(T)},[i,d,y.length,A,v]),a.useEffect(()=>{if(!i)return;const T=()=>v();window.addEventListener("resize",T),window.addEventListener("scroll",T,!0);const C=window.visualViewport;return C&&(C.addEventListener("resize",T),C.addEventListener("scroll",T)),()=>{window.removeEventListener("resize",T),window.removeEventListener("scroll",T,!0),C&&(C.removeEventListener("resize",T),C.removeEventListener("scroll",T))}},[i,v]);const P=a.useCallback(T=>{switch(T.key){case"ArrowDown":T.preventDefault(),u(C=>C<j-1?C+1:0);break;case"ArrowUp":T.preventDefault(),u(C=>C>0?C-1:j-1);break;case"Enter":if(T.preventDefault(),c>=0)if(c<y.length){const[C,$]=y[c];E(C,$)}else A&&c===y.length&&k();break;case"Home":T.preventDefault(),u(0);break;case"End":T.preventDefault(),u(j-1);break}},[c,j,y,A]),w=a.useCallback(()=>{r(T=>!T)},[]),E=a.useCallback((T,C)=>{n(T,C),r(!1)},[n]),k=a.useCallback(()=>{t(),r(!1)},[t]);return e.jsxs("div",{className:"quick-scripts-dropdown",ref:f,children:[e.jsxs("button",{ref:p,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick:w,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[e.jsx(zs,{size:16}),e.jsx(zt,{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:P,"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..."})]}):y.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(zs,{size:16})}),e.jsx("p",{children:"No scripts configured"}),e.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:k,children:"Add your first script"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"quick-scripts-dropdown__list",children:y.map(([T,C],$)=>e.jsxs("button",{className:`quick-scripts-dropdown__item ${c===$?"highlighted":""}`,onClick:()=>E(T,C),role:"option","aria-selected":c===$,"data-testid":`quick-script-item-${T}`,children:[e.jsx(rn,{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:T}),e.jsx("span",{className:"quick-scripts-dropdown__item-command",title:C,children:C.length>50?`${C.slice(0,50)}...`:C})]})]},T))}),e.jsx("div",{className:"quick-scripts-dropdown__footer",children:e.jsxs("button",{className:`quick-scripts-dropdown__manage ${A&&c===y.length?"highlighted":""}`,onClick:k,"data-testid":"quick-scripts-manage",children:[e.jsx(Ia,{size:14}),e.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function Qk(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 Xk({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}=Qk(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 ud=new Map,Zk=6e4;function bh(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 f=ud.get(u);if(f&&Date.now()<f.expiresAt){if(h||m.current)return;s(f.slots),r(!1);return}!d.current&&r(!0),o(null);try{const b=await Vk(t);if(h||m.current)return;ud.set(u,{slots:b,expiresAt:Date.now()+Zk}),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 Ga({slotId:t,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=bh(n);if(i||r||!t)return null;const l=s(t);return l.length===0?null:e.jsx(Kr,{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 ej(){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 Yr(){const[t,n]=a.useState(ej);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 xh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function tj({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(zt,{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=xh[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(Mn,{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 md({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 nj({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:f,onOpenScripts:p,onRunScript:b,onToggleTerminal:x,onOpenFiles:v,filesOpen:y,globalPaused:A,enginePaused:j,onToggleGlobalPause:P,onToggleEnginePause:w,view:E="board",onChangeView:k,showSkillsTab:T,showAgentsTab:C,searchQuery:$="",onSearchChange:F,projects:ee=[],currentProject:I,onSelectProject:_,onViewAllProjects:N,projectId:J,isElectron:K=!1,mobileNavEnabled:G,availableNodes:M=[],currentNode:O,onSelectNode:X,isRemote:S=!1,experimentalFeatures:V}){const de=Yr(),L=de==="mobile",D=L||de==="tablet",me=L&&G,[q,W]=a.useState(!1),[ce,Se]=a.useState(!1),[ve,Ee]=a.useState(!1),[Ae,Oe]=a.useState(!1),[Fe,rt]=a.useState(!1),[Pe,Ie]=a.useState(!1),[Be,nt]=a.useState(!1),[De,Qe]=a.useState(!1),[ie,te]=a.useState(!1),[fe,ae]=a.useState({}),[_e,ke]=a.useState(!1),He=a.useRef(null),dt=a.useRef(null),ht=a.useRef(null),he=a.useRef(null),ne=a.useRef(null),ye=a.useRef(null),we=a.useRef(!1),st=a.useRef(null),be=a.useRef(null),it=a.useRef(null),Me=a.useRef(null),qe=a.useMemo(()=>M.filter(Ke=>Ke.type==="remote"),[M]),oe=qe.length>0,Ve=a.useMemo(()=>Object.entries(fe).sort(([Ke],[bt])=>Ke.localeCompare(bt)),[fe]),We=a.useMemo(()=>!!(V?.insights||V?.roadmap||T||V?.memoryView||V?.devServerView),[V,T]);a.useEffect(()=>{we.current=Fe},[Fe]),a.useEffect(()=>{if(!Fe||!D)return;let Ke=!1;return ke(!0),Va(J).then(bt=>{Ke||ae(bt)}).catch(()=>{Ke||ae({})}).finally(()=>{Ke||ke(!1)}),()=>{Ke=!0}},[Fe,D,J]);const Re=q||$.length>0,et=(ce||$.length>0)&&!ve,xt=(E==="board"||E==="list")&&!L&&F&&!ve&&$.length===0,wt=(E==="board"||E==="list")&&!L&&F;a.useEffect(()=>{$===""&&Ee(!1)},[$]),a.useEffect(()=>{if(!Ae)return;const Ke=bt=>{dt.current&&!dt.current.contains(bt.target)&&He.current&&!He.current.contains(bt.target)&&Oe(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[Ae]),a.useEffect(()=>{if(!ie)return;const Ke=bt=>{he.current&&!he.current.contains(bt.target)&&ht.current&&!ht.current.contains(bt.target)&&te(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[ie]),a.useEffect(()=>{if(!Pe)return;const Ke=bt=>{st.current&&!st.current.contains(bt.target)&&Ie(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[Pe]),a.useEffect(()=>{const Ke=bt=>{if(bt.key==="Escape"){if(Qe(!1),te(!1),we.current){rt(!1);return}Oe(!1),W(!1),Ie(!1),nt(!1)}};return document.addEventListener("keydown",Ke),()=>document.removeEventListener("keydown",Ke)},[]),a.useEffect(()=>{if(!Be)return;const Ke=bt=>{be.current&&!be.current.contains(bt.target)&&nt(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[Be]),a.useEffect(()=>{if(!De)return;const Ke=bt=>{it.current&&!it.current.contains(bt.target)&&Me.current&&!Me.current.contains(bt.target)&&Qe(!1)};return document.addEventListener("mousedown",Ke),()=>document.removeEventListener("mousedown",Ke)},[De]);const Et=a.useCallback(()=>{W(Ke=>!Ke)},[]),Rt=a.useCallback(()=>{Se(!0),Ee(!1)},[]),$t=a.useCallback(()=>{Se(!1),Ee(!0),F&&F("")},[F]),_t=a.useCallback(()=>{Oe(Ke=>!Ke)},[]),vt=a.useCallback(Ke=>{Ke&&Ke(),Oe(!1),rt(!1)},[]),Dt=a.useCallback(()=>{W(!1),F&&F("")},[F]);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"})]}),L&&ee.length>=1&&_&&e.jsxs("div",{className:"mobile-project-switch",ref:be,children:[e.jsx("button",{className:`mobile-project-switch-trigger${Be?" mobile-project-switch-trigger--open":""}`,onClick:()=>nt(Ke=>!Ke),title:"Switch project","aria-label":"Switch project","aria-expanded":Be,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:e.jsx(zt,{size:14,className:`mobile-project-switch-chevron${Be?" mobile-project-switch-chevron--open":""}`})}),Be&&e.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:ee.map(Ke=>{const bt=I?.id===Ke.id,Le=xh[Ke.status]?.color;return e.jsxs("button",{className:`mobile-project-switch-item${bt?" mobile-project-switch-item--current":""}`,onClick:()=>{_(Ke),nt(!1)},role:"option","aria-selected":bt,"data-testid":`mobile-project-switch-item-${Ke.id}`,children:[e.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Le||"var(--text-muted)"}}),e.jsxs("div",{className:"mobile-project-switch-info",children:[e.jsx("span",{className:"mobile-project-switch-name",children:Ke.name}),e.jsx("span",{className:"mobile-project-switch-path",children:Ke.path.split("/").slice(-2).join("/")})]}),bt&&e.jsx(Mn,{size:14,className:"mobile-project-switch-check"})]},Ke.id)})})]}),!D&&ee.length>=1&&N&&e.jsx(tj,{projects:ee,currentProject:I??null,onViewAll:N,onSelectProject:_}),oe&&e.jsxs("div",{className:`header-node-selector${L?" header-node-selector--mobile":""}`,ref:L?void 0:st,children:[e.jsx(Xk,{node:O??null,showDetails:!L}),!L&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`btn-icon node-selector-trigger${Pe?" node-selector-trigger--open":""}`,onClick:()=>Ie(Ke=>!Ke),title:"Switch node","aria-label":"Switch node","aria-expanded":Pe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:e.jsx(ln,{size:12,className:`node-selector-chevron${Pe?" node-selector-chevron--open":""}`})}),Pe&&e.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[e.jsxs("button",{className:`node-selector-option${S?"":" node-selector-option--active"}`,onClick:()=>{X?.(null),Ie(!1)},role:"option","aria-selected":!S,"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"})]}),qe.map(Ke=>e.jsxs("button",{className:`node-selector-option${O?.id===Ke.id?" node-selector-option--active":""}`,onClick:()=>{X?.(Ke),Ie(!1)},role:"option","aria-selected":O?.id===Ke.id,"data-testid":`node-option-${Ke.id}`,children:[e.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${Ke.status}`}),e.jsx("span",{className:"node-selector-option-label",children:Ke.name}),e.jsx("span",{className:"node-selector-option-status",children:Ke.status})]},Ke.id))]})]})]})]}),e.jsxs("div",{className:"header-actions",children:[me&&k&&(E==="board"||E==="list")&&e.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>k("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board","data-testid":"mobile-view-toggle-board",children:e.jsx(ki,{size:16})}),e.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>k("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list","data-testid":"mobile-view-toggle-list",children:e.jsx(mo,{size:16})})]}),F&&L&&(me||E==="board"||E==="list")&&!Re&&e.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Et,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:e.jsx(zi,{size:16})}),xt&&e.jsx("button",{className:"btn-icon",onClick:Rt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:e.jsx(zi,{size:16})}),L&&me&&l&&e.jsx("button",{className:"btn-icon",onClick:l,title:"View usage","data-testid":"mobile-header-usage-btn",children:e.jsx(Ns,{size:16})}),!me&&k&&e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>k("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board",children:e.jsx(ki,{size:16})}),e.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>k("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list",children:e.jsx(mo,{size:16})}),C&&e.jsx("button",{className:`view-toggle-btn${E==="agents"?" active":""}`,onClick:()=>k("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":E==="agents",children:e.jsx(an,{size:16})}),e.jsx("button",{className:`view-toggle-btn${E==="missions"?" active":""}`,onClick:()=>k("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":E==="missions",children:e.jsx(ss,{size:16})}),e.jsx("button",{className:`view-toggle-btn${E==="chat"?" active":""}`,onClick:()=>k("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":E==="chat",children:e.jsx(Zs,{size:16})}),e.jsx("button",{className:`view-toggle-btn${E==="documents"?" active":""}`,onClick:()=>k("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":E==="documents",children:e.jsx(xi,{size:16})}),e.jsx("button",{className:`view-toggle-btn${E==="mailbox"?" active":""}`,onClick:()=>k("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":E==="mailbox",children:e.jsx(_a,{size:16})}),We&&e.jsxs(e.Fragment,{children:[e.jsx("button",{ref:Me,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(E)?" active":""}`,onClick:()=>Qe(Ke=>!Ke),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":De,"data-testid":"view-toggle-overflow-trigger",children:e.jsx(zt,{size:12})}),De&&e.jsxs("div",{ref:it,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[V?.insights&&e.jsxs("button",{className:`view-toggle-overflow-item${E==="insights"?" active":""}`,onClick:()=>{k("insights"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[e.jsx(On,{size:14}),e.jsx("span",{children:"Insights"})]}),V?.roadmap&&e.jsxs("button",{className:`view-toggle-overflow-item${E==="roadmaps"?" active":""}`,onClick:()=>{k("roadmaps"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[e.jsx(ho,{size:14}),e.jsx("span",{children:"Roadmaps"})]}),T&&e.jsxs("button",{className:`view-toggle-overflow-item${E==="skills"?" active":""}`,onClick:()=>{k("skills"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[e.jsx(jn,{size:14}),e.jsx("span",{children:"Skills"})]}),V?.memoryView&&e.jsxs("button",{className:`view-toggle-overflow-item${E==="memory"?" active":""}`,onClick:()=>{k("memory"),Qe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[e.jsx(Nr,{size:14}),e.jsx("span",{children:"Memory"})]}),V?.devServerView&&e.jsxs("button",{className:`view-toggle-overflow-item${E==="dev-server"||E==="devserver"?" active":""}`,onClick:()=>{k("devserver"),Qe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[e.jsx(Wr,{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(Ta,{size:16})}),!D&&!K&&e.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:e.jsx(md,{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(Ls,{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:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:e.jsx(zs,{size:16})}),!D&&v&&e.jsx("button",{className:`btn-icon${y?" btn-icon--active":""}`,onClick:v,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(Fs,{size:16})}),!D&&f&&e.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:e.jsx(fo,{size:16})}),!D&&p&&b&&e.jsx(Yk,{onOpenScripts:p,onRunScript:b,projectId:J}),!D&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{ref:ht,className:"btn-icon",onClick:()=>te(Ke=>!Ke),title:"More actions","aria-label":"More actions","aria-expanded":ie,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:e.jsx(co,{size:16})}),ie&&e.jsxs("div",{ref:he,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&e.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),te(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[e.jsx(Cr,{size:14}),e.jsx("span",{children:"Nodes"})]}),e.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{vt(c),te(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[e.jsx(Ui,{size:14}),e.jsx("span",{children:"Automation"})]})]})]}),e.jsx("button",{className:`btn-icon${j?" btn-icon--paused":""}`,onClick:w,title:j?"Resume scheduling":"Pause scheduling",disabled:!!A,children:j?e.jsx(rn,{size:16}):e.jsx($s,{size:16})}),e.jsx("button",{className:`btn-icon${A?" btn-icon--stopped":""}`,onClick:P,title:A?"Start AI engine":"Stop AI engine",children:A?e.jsx(rn,{size:16}):e.jsx(cs,{size:16})}),!D&&e.jsx("button",{className:"btn-icon",onClick:t,title:"Settings",children:e.jsx(Ia,{size:16})}),e.jsx(Ga,{slotId:"header-action",projectId:J}),D&&!me&&e.jsx("button",{ref:He,className:"btn-icon compact-overflow-trigger",onClick:_t,title:"More header actions","aria-label":"More header actions","aria-expanded":Ae,"aria-haspopup":"menu",children:e.jsx(co,{size:16})}),D&&!me&&Ae&&e.jsxs("div",{ref:dt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[ee.length>=1&&N&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(N),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[e.jsx(Vm,{size:16}),e.jsx("span",{children:"Projects"})]}),v&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(v),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:()=>vt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[e.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[e.jsx(Ls,{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:()=>vt(u),role:"menuitem","data-testid":"overflow-git-btn",children:[e.jsx(Fs,{size:16}),e.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[e.jsx(Cr,{size:16}),e.jsx("span",{children:"Nodes"})]}),!K&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(n),role:"menuitem",children:[e.jsx(md,{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:()=>vt(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[e.jsx(zs,{size:16}),e.jsx("span",{children:"Terminal"})]}),e.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>rt(Ke=>!Ke),role:"menuitem","aria-expanded":Fe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:e.jsx(ln,{size:14,className:`mobile-overflow-chevron${Fe?" mobile-overflow-chevron--open":""}`})})]}),Fe&&e.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:_e?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…"})]}):Ve.length>0?e.jsxs(e.Fragment,{children:[Ve.map(([Ke,bt])=>e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Ke,bt),Oe(!1),rt(!1)},role:"menuitem","data-testid":`overflow-script-item-${Ke}`,children:[e.jsx(rn,{size:14}),e.jsx("span",{children:Ke})]},Ke)),p&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>vt(p),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Ms,{size:14}),e.jsx("span",{children:"Manage Scripts…"})]})]}):p&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>vt(p),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:()=>vt(c),role:"menuitem","data-testid":"overflow-schedules-btn",children:[e.jsx(Ui,{size:16}),e.jsx("span",{children:"Automation"})]}),o&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(o),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[e.jsx(Ta,{size:16}),e.jsx("span",{children:"View Activity Log"})]}),d&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[e.jsx(_a,{size:16}),e.jsxs("span",{children:["Mailbox",m>0?` (${m})`:""]})]}),l&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(l),role:"menuitem","data-testid":"overflow-usage-btn",children:[e.jsx(Ns,{size:16}),e.jsx("span",{children:"View Usage"})]}),f&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[e.jsx(fo,{size:16}),e.jsx("span",{children:"Workflow Steps"})]}),e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(t),role:"menuitem",children:[e.jsx(Ia,{size:16}),e.jsx("span",{children:"Settings"})]})]})]})]}),wt&&et&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{className:"header-search",children:[e.jsx(zi,{size:14,className:"header-search-icon"}),e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:$,onChange:Ke=>F(Ke.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:$t,"aria-label":"Close search",children:e.jsx(Lt,{size:14})})]})}),F&&L&&Re&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{ref:ne,className:"header-search mobile-search-expanded",children:[e.jsx(zi,{size:14,className:"header-search-icon"}),e.jsx("input",{ref:ye,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:$,onChange:Ke=>F(Ke.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:Dt,"aria-label":"Close search",children:e.jsx(Lt,{size:14})})]})})]})}const sj={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},ij={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:{}},aj=Object.freeze(Object.keys(sj)),rj=Object.freeze(Object.keys(ij));function lj(t){return aj.includes(t)}function oj(t){return rj.includes(t)}function ge(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}const cj=["off","minimal","low","medium","high"],bi=["triage","todo","in-progress","in-review","done","archived"],Ko=["low","normal","high","urgent"],ds="normal",dj=["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"},uj={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"},xo={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 mj(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 hj(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 pj(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 vh({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(ns,{size:12}),e.jsxs("span",{children:["#",t.number]})]}),n&&e.jsxs("span",{className:`card-github-badge ${pj(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[e.jsx(Hr,{size:12}),e.jsxs("span",{children:["#",n.number]})]})]})}function ir(t,n){return`${t??"default"}:${n}`}class fj{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=ir(this.projectId,l);this.subscriptionsByTask.set(o,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=ir(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=ir(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=ir(this.projectId,o.taskId),m=this.badgeUpdates.get(d);this.badgeUpdates.set(d,{prInfo:hd(o,"prInfo")?o.prInfo??null:m?.prInfo,issueInfo:hd(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 mi=new fj;let gj=0;function hd(t,n){return Object.prototype.hasOwnProperty.call(t,n)}function yh(t){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${gj++}`);const s=a.useSyncExternalStore(l=>mi.subscribe(l),()=>mi.getSnapshot(),()=>mi.getSnapshot()),i=a.useCallback(l=>{mi.subscribeTask(n.current,l)},[]),r=a.useCallback(l=>{mi.unsubscribeTask(n.current,l)},[]);return a.useEffect(()=>{mi.setProjectId(t??null)},[t]),a.useEffect(()=>()=>{mi.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 bj({taskId:t,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:l}){const{badgeUpdates:o,subscribeToBadge:d,unsubscribeFromBadge:m}=yh(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(vh,{prInfo:h,issueInfo:g})}const xj=a.memo(bj);xj.displayName="TaskCardBadge";const ys={data:new Map,pendingPromise:null,lastFetchTime:null},vj=5e3;function kr(t,n){return n?`${n}::${t}`:t}function yj(t,n){const s=ys.data.get(kr(t,n));if(!(!s||Date.now()-s.timestamp>vj))return s}function kj(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 dv(d,t)}catch(h){c=h instanceof Error?h:new Error(String(h));const g=ge(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const f=Math.min(1e3*Math.pow(2,u),3e4);await new Promise(p=>setTimeout(p,f));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 f=ys.data.get(kr(g,t));return f&&f.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,f=Date.now();for(const[p,b]of Object.entries(g))ys.data.set(kr(p,t),{result:b,timestamp:f});ys.lastFetchTime=f}catch{}finally{ys.pendingPromise=null,s(!1)}},[r,t]),o=a.useCallback(d=>ys.data.get(kr(d,t)),[t]);return{fetchBatch:l,isLoading:n,lastFetchTime:ys.lastFetchTime,getBatchData:o}}const vo=new Map,jj=3e4;function kh(t,n,s,i){return`${t}:${n??""}:${s??""}:${i??""}`}function wj(t,n,s,i){const r=kh(t,n,s,i),l=vo.get(r);return l?Date.now()>l.expiresAt?(vo.delete(r),null):l.stats:null}function Nj(t,n,s,i,r){const l=kh(t,n,s,i);vo.set(l,{stats:r,expiresAt:Date.now()+jj})}function Sj(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 f=n==="done"&&!!s,p=(n==="in-progress"||n==="in-review")&&!!o;if(!t||!f&&!p){u(null),g(!1);return}const b=p?o:void 0,x=d!==void 0?String(d):void 0;let v=!1;async function y(j=!1){if(!j){const P=wj(t,i,b,x);if(P){v||(u(P),g(!1));return}}g(!0);try{const P=await mh(t,b,i);v||(u(P.stats),Nj(t,i,b,x,P.stats))}catch{v||u(null)}finally{v||g(!1)}}y();let A;return m&&p&&(A=setInterval(()=>{y(!0)},m)),()=>{v=!0,A&&clearInterval(A)}},[t,n,s,i,l,o,d,m]),{stats:c,loading:h}}const Cj=new Set(["failed","stuck-killed"]);function Tr(t,n,s){if(t.column!=="in-progress"||t.status&&Cj.has(t.status)||!n||n<=0)return!1;const i=new Date(t.updatedAt).getTime();return(s??Date.now())-i>n}function Ej(t){switch(t){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Mj(t){return t==="done"||t==="skipped"}function Aj(t,n,s){const i=s?.get(t)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||t}function jh(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:Aj(m,c,n),status:c?Ej(c.status):"pending",source:"workflow",phase:c?.phase??"pre-merge"}}),l=[...s,...r],o=l.length,d=l.filter(m=>Mj(m.status)).length;return{total:o,completed:d,items:l}}const yo=new Map;async function Pj(t,n){const s=yo.get(t);if(s)return s;try{const i=await hh(t,n);return yo.set(t,i.title),i.title}catch{return t}}const pd=12;function Rj(t){return t.length<=pd?t:t.slice(0,pd-3)+"..."}const ko=new Map;async function Tj(t,n){const s=ko.get(t);if(s)return s;try{const i=await dh(t,n);return ko.set(t,i.name),i.name}catch{return t}}function _j(t){return typeof t=="string"&&Ko.includes(t)?t:ds}function Ij(t,n){return t.length<=n?t:t.slice(0,n-3)+"..."}const $j=new Set(["triage","todo"]),fd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Dj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"};function gd(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 Fj(t,n){return t.length!==n.length?!1:t.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Lj(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function zj(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function Oj(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 Bj(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 Uj(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 Hj(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 qj(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&&Uj(s.attachments,i.attachments)&&Hj(s.comments,i.comments)&&Lj(s.dependencies,i.dependencies)&&Fj(s.steps,i.steps)&&zj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Bj(s.workflowStepResults,i.workflowStepResults)&&gd(s.prInfo,i.prInfo)&&gd(s.issueInfo,i.issueInfo)}function Vj({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:f,lastFetchTimeMs:p,workflowStepNameLookup:b}){const[x,v]=a.useState(!1),[y,A]=a.useState(!1),[j,P]=a.useState(!1),[w,E]=a.useState(t.description||""),[k,T]=a.useState(!1),[C,$]=a.useState(t.column==="in-progress"||t.column==="triage"&&t.steps.some(xe=>xe.status==="done"||xe.status==="skipped")),[F,ee]=a.useState(null),[I,_]=a.useState(null),[N,J]=a.useState(!1),K=a.useRef(null),G=a.useRef(!1),M=a.useRef(null),O=a.useRef(null),[X,S]=a.useState(!1),{badgeUpdates:V,subscribeToBadge:de,unsubscribeFromBadge:L}=yh(n),Z=a.useRef(null),D=a.useRef(!1),me=a.useCallback(xe=>xe instanceof Element?!!xe.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{E(t.description||"")},[t.id,t.description]),a.useEffect(()=>{if(!N)return;const xe=U=>{O.current&&!O.current.contains(U.target)&&J(!1)};return document.addEventListener("click",xe),()=>document.removeEventListener("click",xe)},[N]),a.useEffect(()=>{if(!t.missionId){ee(null);return}const xe=yo.get(t.missionId);if(xe){ee(xe);return}let U=!1;return Pj(t.missionId,n).then(Ne=>{U||ee(Ne)}),()=>{U=!0}},[t.missionId,n]),a.useEffect(()=>{if(!t.assignedAgentId){_(null);return}const xe=ko.get(t.assignedAgentId);if(xe){_(xe);return}_(null);let U=!1;return Tj(t.assignedAgentId,n).then(Ne=>{U||_(Ne)}),()=>{U=!0}},[t.assignedAgentId,n]),a.useEffect(()=>{if(j&&K.current){const xe=K.current;xe.focus(),xe.style.height="auto",xe.style.height=xe.scrollHeight+"px"}},[j]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){S(!0);return}const xe=M.current;if(!xe)return;const U=new IntersectionObserver(([Ne])=>{S(Ne?.isIntersecting??!0)},{rootMargin:"200px"});return U.observe(xe),()=>U.disconnect()},[j,t.id]);const q=a.useCallback(xe=>{xe.dataTransfer.setData("text/plain",t.id),xe.dataTransfer.effectAllowed="move",v(!0)},[t.id]),W=a.useCallback(()=>{v(!1)},[]),ce=a.useCallback(xe=>xe.dataTransfer.types.includes("Files"),[]),Se=a.useCallback(xe=>{ce(xe)&&(xe.preventDefault(),xe.stopPropagation(),xe.dataTransfer.dropEffect="copy",A(!0))},[ce]),ve=a.useCallback(xe=>{ce(xe)&&(xe.preventDefault(),xe.stopPropagation(),A(!1))},[ce]),Ee=a.useCallback(async xe=>{if(!ce(xe))return;xe.preventDefault(),xe.stopPropagation(),A(!1);const U=Array.from(xe.dataTransfer.files);for(const Ne of U)try{await $a(t.id,Ne,n),r(`Attached ${Ne.name} to ${t.id}`,"success")}catch(pt){r(`Failed to attach ${Ne.name}: ${ge(pt)}`,"error")}},[t.id,ce,r]),Ae=a.useCallback(()=>{j||i(t)},[t,i,j]),Oe=a.useCallback(xe=>{if(G.current){G.current=!1;return}me(xe.target)||Ae()},[Ae,me]),Fe=a.useCallback(xe=>{const U=xe.touches[0];U&&(Z.current={x:U.clientX,y:U.clientY,time:Date.now()},D.current=!1)},[]),rt=a.useCallback(xe=>{if(!Z.current)return;const U=xe.touches[0];if(!U)return;const Ne=Math.abs(U.clientX-Z.current.x),pt=Math.abs(U.clientY-Z.current.y);(Ne>bd||pt>bd)&&(D.current=!0)},[]),Pe=a.useCallback(xe=>{if(me(xe.target)||!Z.current)return;const Ne=Date.now()-Z.current.time<Wj,pt=!D.current;Ne&&pt&&(G.current=!0,Ae()),Z.current=null,D.current=!1},[Ae,me]),Ie=a.useCallback(async(xe,U)=>{xe.stopPropagation();try{const Ne=await Ar(U,n);i(Ne)}catch{r(`Failed to load dependency ${U}`,"error")}},[i,r]),Be=t.status==="failed",nt=t.paused===!0,De=_j(t.priority),Qe=De!==ds,ie=Tr(t,h,p),te=t.column==="triage"&&t.status==="awaiting-approval",fe=t.column==="archived",ae=!l&&!s&&!Be&&!nt&&!ie&&!te&&(t.column==="in-progress"||fd.has(t.status)),_e=!s&&!nt&&!j&&!fe,ke=$j.has(t.column)&&!ae&&!nt&&!s&&o,He=!!(t.prInfo||t.issueInfo),dt=!!(t.assignedAgentId&&I===null),ht=a.useMemo(()=>jh(t,b),[t.steps,t.enabledWorkflowSteps,t.workflowStepResults,b]),he=ht.total>0&&(t.status==="executing"||t.column==="in-progress");a.useEffect(()=>{if(!He||!X){L(t.id);return}return de(t.id),()=>{L(t.id)}},[He,X,de,t.id,L]);const ne=V.get(`${n??"default"}:${t.id}`),ye=t.column==="in-progress"||t.column==="in-review",we=a.useMemo(()=>t.steps.map(xe=>`${xe.name}:${xe.status}`).join("|"),[t.steps]),{stats:st}=Sj(t.id,t.column,t.mergeDetails?.commitSha,n,{enabled:X,worktree:t.worktree,stepVersion:ye?we:void 0,pollIntervalMs:ye?3e4:void 0}),be=a.useMemo(()=>yj(t.id,n),[t.id,n]),it=a.useMemo(()=>{const xe=ne?.prInfo,U=ne?.timestamp,Ne=be?.result?.prInfo,pt=be?.timestamp?new Date(be.timestamp).toISOString():void 0,kt=t.prInfo,je=t.prInfo?.lastCheckedAt??t.updatedAt;let Ge=Rr(xe,U,kt,je);const gt=U&&U>=je?U:je;return Ne&&pt&&(!gt||pt>gt)&&(Ge=Ne),Ge},[ne,be,t.prInfo,t.updatedAt]),Me=a.useMemo(()=>{const xe=ne?.issueInfo,U=ne?.timestamp,Ne=be?.result?.issueInfo,pt=be?.timestamp?new Date(be.timestamp).toISOString():void 0,kt=t.issueInfo,je=t.issueInfo?.lastCheckedAt??t.updatedAt;let Ge=Rr(xe,U,kt,je);const gt=U&&U>=je?U:je;return Ne&&pt&&(!gt||pt>gt)&&(Ge=Ne),Ge},[ne,be,t.issueInfo,t.updatedAt]),qe=a.useCallback(xe=>{xe?.stopPropagation(),!(!ke||k)&&(P(!0),E(t.description||""))},[ke,k,t.description]),oe=a.useCallback(()=>{P(!1),E(t.description||"")},[t.description]),Ve=a.useCallback(()=>w!==(t.description||""),[w,t.description]),We=a.useCallback(async()=>{if(!(!o||k)){if(!Ve()){oe();return}T(!0);try{await o(t.id,{description:w.trim()||void 0}),r(`Updated ${t.id}`,"success"),P(!1)}catch(xe){r(`Failed to update ${t.id}: ${ge(xe)}`,"error")}finally{T(!1)}}},[o,t.id,w,k,Ve,oe,r]),Re=a.useCallback(xe=>{xe.key==="Enter"&&!xe.shiftKey?(xe.preventDefault(),We()):xe.key==="Escape"&&(xe.preventDefault(),oe())},[We,oe]),et=a.useCallback(()=>{setTimeout(()=>{const xe=document.activeElement;xe===K.current||xe?.closest(".card-editing-content")||(Ve()?We():oe())},0)},[Ve,We,oe]),xt=a.useCallback(xe=>{ke&&(xe.stopPropagation(),qe(xe))},[ke,qe]),wt=a.useCallback(xe=>{xe.stopPropagation(),qe(xe)},[qe]),Et=a.useCallback(xe=>{E(xe.target.value);const U=xe.target;U.style.height="auto",U.style.height=U.scrollHeight+"px"},[]),Rt=a.useCallback(xe=>{xe.stopPropagation(),d&&d(t.id).then(()=>{r(`Archived ${t.id}`,"success")}).catch(U=>{r(`Failed to archive ${t.id}: ${ge(U)}`,"error")})},[r,d,t.id]),$t=a.useCallback(xe=>{xe.stopPropagation(),m&&m(t.id).then(()=>{r(`Unarchived ${t.id}`,"success")}).catch(U=>{r(`Failed to unarchive ${t.id}: ${ge(U)}`,"error")})},[r,m,t.id]),_t=a.useCallback(xe=>{xe.stopPropagation(),c&&window.confirm(`Delete ${t.id}?`)&&c(t.id).then(()=>{r(`Deleted ${t.id}`,"success")}).catch(U=>{const Ne=Oj(U);if(!Ne||Ne.dependentIds.length===0){r(`Failed to delete ${t.id}: ${ge(U)}`,"error");return}const pt=Ne.dependentIds.join(", ");window.confirm(`${t.id} is a dependency of ${pt}.
|
|
591
|
-
|
|
592
|
-
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}: ${ge(je)}`,"error")})})},[r,c,t.id]),vt=a.useCallback(xe=>{xe.stopPropagation(),u?.(t,"changes")},[t,u]),Dt=a.useCallback(xe=>{xe.stopPropagation(),$(U=>!U)},[]),Ke=a.useCallback(xe=>{xe.stopPropagation(),t.missionId&&g&&g(t.missionId)},[t.missionId,g]),bt=a.useCallback(xe=>{xe.stopPropagation(),J(U=>!U)},[]),Le=a.useCallback((xe,U)=>{xe.stopPropagation(),J(!1),f&&f(t.id,U).then(()=>{r(`Moved ${t.id} to ${us[U]}`,"success")}).catch(Ne=>{r(`Failed to move ${t.id}: ${ge(Ne)}`,"error")})},[r,f,t.id]),lt=`card${x?" dragging":""}${s?" queued":""}${ae?" agent-active":""}${Be?" failed":""}${nt?" paused":""}${ie?" stuck":""}${te?" awaiting-approval":""}${y?" file-drop-target":""}${j?" card-editing":""}${k?" card-saving":""}`;return j?e.jsx("div",{ref:M,className:lt,"data-id":t.id,onDoubleClick:xt,children:e.jsxs("div",{className:"card-editing-content",children:[e.jsx("textarea",{ref:K,className:"card-edit-desc-textarea",placeholder:"Task description",value:w,onChange:Et,onKeyDown:Re,onBlur:et,disabled:k,rows:4}),k&&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:M,className:lt,"data-id":t.id,draggable:_e,onDragStart:_e?q:void 0,onDragEnd:_e?W:void 0,onDragOver:Se,onDragLeave:ve,onDrop:Ee,onClick:Oe,onTouchStart:Fe,onTouchMove:rt,onTouchEnd:Pe,onDoubleClick:xt,children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"card-id",children:t.id}),nt&&e.jsx("span",{className:"card-status-badge paused",children:"paused"}),!nt&&t.status&&t.status!=="queued"&&e.jsx("span",{className:`card-status-badge card-status-badge--${t.column}${te?" awaiting-approval":""}${fd.has(t.status)?" pulsing":""}${Be?" failed":""}${ie?" stuck":""}`,children:ie?"Stuck":te?"Awaiting Approval":t.status}),ie&&(nt||!t.status||t.status==="queued")&&e.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),He&&e.jsx(vh,{prInfo:it,issueInfo:Me}),Qe&&e.jsx("span",{className:`card-priority-badge card-priority-badge--${De}`,children:De}),t.missionId&&e.jsxs("span",{className:"card-mission-badge",onClick:Ke,title:`Mission: ${F??t.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.jsx(ss,{size:11}),Rj(F??t.missionId)]}),e.jsxs("div",{className:"card-header-actions",children:[ke&&e.jsx("button",{className:"card-edit-btn",onClick:wt,title:"Edit task","aria-label":"Edit task",children:e.jsx(Ln,{size:12})}),t.column==="triage"&&c&&e.jsx("button",{className:"card-delete-btn",onClick:_t,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:Rt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),t.column==="archived"&&m&&e.jsx("button",{className:"card-unarchive-btn",onClick:$t,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),t.column==="in-progress"&&f&&e.jsxs("div",{className:"card-send-back",ref:O,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:bt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":N,children:["Send back",e.jsx(zt,{size:10})]}),N&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:xo["in-progress"].filter(xe=>xe!=="in-review").map(xe=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:U=>Le(U,xe),children:us[xe]},xe))})]}),t.column==="in-review"&&f&&e.jsxs("div",{className:"card-send-back",ref:O,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:bt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":N,children:["Move",e.jsx(zt,{size:10})]}),N&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:xo["in-review"].map(xe=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:U=>Le(U,xe),children:xe==="done"?"Done (no merge)":us[xe]},xe))})]}),t.size&&e.jsx("span",{className:`card-size-badge size-${t.size.toLowerCase()}`,children:t.size})]})]}),Be&&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:vd(t.title,xd)||vd(t.description,xd)||t.id}),he&&(()=>{const xe=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:`${xe}%`,backgroundColor:Dj[t.column]}})}),e.jsxs("span",{className:"card-progress-label",children:[ht.completed,"/",ht.total]})]}),e.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Dt,"aria-expanded":C,"aria-label":C?"Hide steps":"Show steps",children:[e.jsxs("span",{children:[ht.total," step",ht.total===1?"":"s"]}),e.jsx(zt,{size:14,className:`card-steps-toggle-icon${C?" expanded":""}`})]}),C&&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 xe=st?.filesChanged;return xe==null||xe===0?null:e.jsxs("button",{type:"button",className:"card-session-files",onClick:vt,disabled:!u,children:[e.jsx(Pn,{size:12}),e.jsxs("span",{children:[xe," ",xe===1?"file":"files"," changed"]})]})})(),t.column==="done"&&(()=>{const xe=st?.filesChanged,U=t.mergeDetails?.filesChanged,Ne=xe??U;if(Ne!=null&&Ne>0)return e.jsxs("button",{type:"button",className:"card-session-files",onClick:vt,disabled:!u,children:[e.jsx(Pn,{size:12}),e.jsxs("span",{children:[Ne," ",Ne===1?"file":"files"," changed"]})]});const pt=t.modifiedFiles?.length;return pt!=null&&pt>0?e.jsxs("button",{type:"button",className:"card-session-files",onClick:vt,disabled:!u,children:[e.jsx(Pn,{size:12}),e.jsxs("span",{children:[pt," ",pt===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(xe=>e.jsxs("span",{className:"card-dep-badge clickable",onClick:U=>void Ie(U,xe),title:`Click to view ${xe}`,children:[e.jsx(qi,{size:12,style:{verticalAlign:"middle"}})," ",xe]},xe))}),t.blockedBy&&e.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${t.blockedBy} (file overlap)`,children:[e.jsx(yi,{size:12,style:{verticalAlign:"middle"}})," ",t.blockedBy]}),(s||t.status==="queued")&&t.column!=="in-progress"&&e.jsxs("span",{className:"queued-badge",children:[e.jsx(Ui,{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 ${I??t.assignedAgentId}`,children:[e.jsx(an,{size:11}),e.jsx("span",{className:"card-agent-badge-text",children:Ij(I??t.assignedAgentId,15)})]})}),e.jsx(Ga,{slotId:"task-card-badge",projectId:n})]})}const bd=10,Wj=300,xd=140;function vd(t,n){return t?t.length>n?t.slice(0,n)+"…":t:""}const _r=a.memo(Vj,qj);_r.displayName="TaskCard";function Kj({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(eg,{size:14}):e.jsx(Fs,{size:14})}),e.jsx("span",{className:"worktree-label",children:t})]}),n.map(f=>e.jsx(_r,{task:f,projectId:i,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g},f.id)),s.map(f=>e.jsx(_r,{task:f,projectId:i,queued:!0,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g},f.id))]})}const wh=a.memo(Kj);wh.displayName="WorktreeGroup";function yd(t){return t.toLowerCase().replace(/[-_./]/g,"")}function Gj(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 Jj(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 Yj(t,n){const s=yd(t),i=yd(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&&Gj(s,l)||s.length>=4&&Jj(s,l,1))return!0;return!1}function Qj(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=>Yj(l,r))})}const Xj={sm:16,md:20,lg:24};function Zj({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 kd({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 jd({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 ew({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 tw({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 nw({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 wd({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 sw({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 iw={anthropic:{component:Zj,color:"#d4a27f"},"claude-cli":{component:sw,color:"#d4a27f",label:"Anthropic — via Claude CLI"},openai:{component:kd,color:"#10a37f"},"openai-codex":{component:kd,color:"#10a37f",label:"OpenAI Codex"},google:{component:jd,color:"#4285f4"},gemini:{component:jd,color:"#4285f4"},ollama:{component:ew,color:"#fff"},minimax:{component:tw,color:"#E73562"},zai:{component:nw,color:"#1A6DFF"},kimi:{component:wd,color:"#6C5CE7"},moonshot:{component:wd,color:"#6C5CE7"}};function is({provider:t,size:n="sm"}){const s=t.toLowerCase(),i=iw[s],r=i?.component,l=i?.color??"var(--text-muted)",o=i?.label,d=Xj[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(lg,{size:d})})}function Jt({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[f,p]=a.useState(!1),[b,x]=a.useState(""),[v,y]=a.useState(0),[A,j]=a.useState(null),[P,w]=a.useState(null),E=a.useRef(null),k=a.useRef(null),T=a.useRef(null),C=a.useRef(null),$=a.useRef(null),F=a.useMemo(()=>Qj(t,b),[t,b]),ee=a.useMemo(()=>F.reduce((W,ce)=>((W[ce.provider]??=[]).push(ce),W),{}),[F]),I=a.useMemo(()=>{const W=[];for(const ce of c){const Se=ce.indexOf("/");if(Se===-1)continue;const ve=ce.slice(0,Se),Ee=ce.slice(Se+1),Ae=F.find(Oe=>Oe.provider===ve&&Oe.id===Ee);Ae&&W.push({model:Ae,fullId:ce})}return W},[c,F]),_=a.useMemo(()=>{const W=Object.entries(ee),ce=new Set(d);return W.sort(([Se],[ve])=>{const Ee=ce.has(Se),Ae=ce.has(ve);if(Ee&&!Ae)return-1;if(!Ee&&Ae)return 1;if(Ee&&Ae){const Oe=d.indexOf(Se),Fe=d.indexOf(ve);if(Oe!==Fe)return Oe-Fe}return Se.localeCompare(ve)})},[ee,d]),N=typeof h=="string"&&h.length>0,J=a.useMemo(()=>{if(!n||N&&n===h)return null;const W=n.indexOf("/");return W===-1?null:n.slice(0,W)},[N,h,n]),K=a.useMemo(()=>{const W=[];return N&&W.push({type:"no-change",value:h,label:g}),W.push({type:"default",value:"",label:"Use default"}),W},[N,g,h]),G=a.useMemo(()=>{const W=[...K];for(const{model:ce,fullId:Se}of I)W.push({type:"favorite",value:Se,label:ce.name,provider:ce.provider});return _.forEach(([ce,Se])=>{W.push({type:"provider",value:`__group_${ce}`,label:ce,provider:ce}),Se.forEach(ve=>{W.push({type:"model",value:`${ve.provider}/${ve.id}`,label:ve.name,provider:ve.provider})})}),W},[I,_,K]),M=a.useMemo(()=>{if(N&&n===h)return g;if(!n)return"Use default";const W=n.indexOf("/");if(W===-1)return n;const ce=n.slice(0,W),Se=n.slice(W+1);return t.find(Ee=>Ee.provider===ce&&Ee.id===Se)?.name||n},[N,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}},[]),S=a.useCallback(()=>{const{height:W}=X(),ce=typeof window.matchMedia=="function",Se=ce?window.matchMedia("(max-width: 640px)").matches:!1,ve=ce?window.matchMedia("(max-width: 768px)").matches:!1;return W<=0?320:Se?Math.min(W*.6,360):ve?Math.min(W*.7,420):320},[X]),V=a.useCallback(()=>{const W=k.current;if(!W)return;const ce=W.getBoundingClientRect(),{width:Se,height:ve,offsetTop:Ee,offsetLeft:Ae}=X(),Oe=16,Fe=16,rt=4,Pe=S(),Ie=ce.bottom-Ee,Be=ce.top-Ee,nt=ce.left-Ae,De=ve-Ie,Qe=Be,ie=Math.max(De-Fe-rt,160),te=Math.max(Qe-Fe-rt,160),fe=De<Pe&&Qe>De,ae=Math.max(Math.min(fe?te:ie,Pe),160),_e=Math.min(ce.width,Se-Oe*2),ke=Math.min(Math.max(nt,Oe),Se-Oe-_e)+Ae,He=fe?Math.max(Fe+Ee,Be-ae-rt+Ee):Math.min(Ie+rt+Ee,ve+Ee-Fe-ae);j({top:He,left:ke,width:_e,maxHeight:ae})},[X,S]);a.useEffect(()=>{w(document.body)},[]),a.useEffect(()=>{if(f){const W=G.findIndex((ce,Se)=>Se>=(O>=0?O:0)&&ce.type!=="provider");y(W>=0?W:0)}},[f,G,O]),a.useEffect(()=>{if(!f)return;V();const W=requestAnimationFrame(()=>C.current?.focus());return()=>cancelAnimationFrame(W)},[f,V]),a.useEffect(()=>{if(!f)return;const W=()=>V();window.addEventListener("resize",W),window.addEventListener("scroll",W,!0);const ce=window.visualViewport;return ce&&(ce.addEventListener("resize",W),ce.addEventListener("scroll",W)),()=>{window.removeEventListener("resize",W),window.removeEventListener("scroll",W,!0),ce&&(ce.removeEventListener("resize",W),ce.removeEventListener("scroll",W))}},[f,V]),a.useEffect(()=>{if(!f)return;const W=ce=>{const Se=ce.target,ve=E.current?.contains(Se),Ee=T.current?.contains(Se);!ve&&!Ee&&(p(!1),x(""))};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[f]);const de=a.useCallback(W=>{switch(W.key){case"ArrowDown":if(W.preventDefault(),!f)p(!0);else{let ce=v;for(let Se=1;Se<=G.length;Se++){const ve=(v+Se)%G.length;if(G[ve]?.type!=="provider"){ce=ve;break}}y(ce)}break;case"ArrowUp":if(W.preventDefault(),f){let ce=v;for(let Se=1;Se<=G.length;Se++){const ve=(v-Se+G.length)%G.length;if(G[ve]?.type!=="provider"){ce=ve;break}}y(ce)}break;case"Enter":if(W.preventDefault(),f){const ce=G[v];ce&&ce.type!=="provider"&&ce.type!=="favorite"&&(s(ce.value),p(!1),x(""))}else p(!0);break;case"Escape":W.preventDefault(),p(!1),x("");break;case"Tab":f&&(p(!1),x(""));break}},[f,v,G,s]),L=a.useCallback(W=>{s(W),p(!1),x("")},[s]),Z=a.useCallback(()=>{x(""),C.current?.focus()},[]),D=a.useCallback(()=>{r||p(W=>!W)},[r]);a.useEffect(()=>{if(f&&$.current){const W=$.current.querySelector(`[data-index="${v}"]`);W&&typeof W.scrollIntoView=="function"&&W.scrollIntoView({block:"nearest"})}},[v,f]);const me=b.length>0,q=f&&A?e.jsxs("div",{ref:T,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:C,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:W=>x(W.target.value),onClick:W=>W.stopPropagation()}),me&&e.jsx("button",{type:"button",className:"model-combobox-clear",onClick:Z,"aria-label":"Clear filter",children:"×"})]}),e.jsxs("div",{className:"model-combobox-results-count",children:[F.length," model",F.length!==1?"s":""]}),e.jsxs("div",{ref:$,className:"model-combobox-list",children:[K.map((W,ce)=>e.jsx("div",{"data-index":ce,className:`model-combobox-option ${v===ce?"model-combobox-option--highlighted":""} ${n===W.value?"model-combobox-option--selected":""}`,onClick:()=>L(W.value),onMouseEnter:()=>y(ce),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}`)),I.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-combobox-divider"}),I.map(({model:W,fullId:ce},Se)=>{const ve=Se+K.length,Ee=v===ve,Ae=n===ce;return e.jsxs("div",{"data-index":ve,className:`model-combobox-option model-combobox-option--favorite ${Ee?"model-combobox-option--highlighted":""} ${Ae?"model-combobox-option--selected":""}`,onClick:()=>L(ce),onMouseEnter:()=>y(ve),role:"option","aria-selected":Ae,children:[e.jsx(is,{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:Oe=>{Oe.stopPropagation(),u(ce)},title:"Remove from favorites","aria-label":`Remove ${W.name} from favorites`,children:"★"})]},ce)}),e.jsx("div",{className:"model-combobox-divider"})]}),_.map(([W,ce])=>{const Se=G.findIndex(Ae=>Ae.value===`__group_${W}`),ve=d.includes(W),Ee=ce.filter(Ae=>{const Oe=`${Ae.provider}/${Ae.id}`;return!c.includes(Oe)});return Ee.length===0?null:e.jsxs("div",{className:"model-combobox-group",children:[e.jsxs("div",{className:"model-combobox-optgroup","data-index":Se,children:[e.jsx(is,{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:Ae=>{Ae.stopPropagation(),m(W)},title:ve?"Remove from favorites":"Add to favorites","aria-label":ve?`Remove ${W} from favorites`:`Add ${W} to favorites`,children:"★"})]}),Ee.map(Ae=>{const Oe=`${Ae.provider}/${Ae.id}`,Fe=G.findIndex(Be=>Be.value===Oe),rt=v===Fe,Pe=n===Oe,Ie=c.includes(Oe);return e.jsxs("div",{"data-index":Fe,className:`model-combobox-option ${rt?"model-combobox-option--highlighted":""} ${Pe?"model-combobox-option--selected":""}`,onClick:()=>L(Oe),onMouseEnter:()=>y(Fe),role:"option","aria-selected":Pe,children:[e.jsx("span",{className:"model-combobox-option-text",children:Ae.name}),e.jsx("span",{className:"model-combobox-option-id",children:Ae.id}),u&&e.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ie?"model-combobox-option-favorite--active":""}`,onClick:Be=>{Be.stopPropagation(),u(Oe)},title:Ie?"Remove from favorites":"Add to favorites","aria-label":Ie?`Remove ${Ae.name} from favorites`:`Add ${Ae.name} to favorites`,children:Ie?"★":"☆"})]},Oe)})]},W)}),F.length===0&&me&&e.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:E,className:"model-combobox",onKeyDown:de,children:e.jsxs("button",{ref:k,type:"button",id:l,className:"model-combobox-trigger",onClick:D,disabled:r,"aria-haspopup":"listbox","aria-expanded":f,"aria-label":o,children:[J&&e.jsx("span",{className:"model-combobox-trigger-icon",children:e.jsx(is,{provider:J,size:"sm"})}),e.jsx("span",{className:"model-combobox-trigger-text",children:M||i}),e.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),P&&q?wa.createPortal(q,P):null]})}function Go(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(Go(t,n))}function ms(t,n,s){typeof window>"u"||window.localStorage.setItem(Go(t,s),n)}function Da(t,n){typeof window>"u"||window.localStorage.removeItem(Go(t,n))}const ca="kb-quick-entry-text",aw=["image/png","image/jpeg","image/gif","image/webp"];function fl(t,n){return t&&n?`${t}/${n}`:""}function gl(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 Nh({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,f]=a.useState(()=>typeof window<"u"&&In(ca,o)||""),[p,b]=a.useState(!1),[x,v]=a.useState(!1),[y,A]=a.useState(!1),j=a.useRef(null),P=a.useRef(null),w=a.useRef(!1),E=a.useRef(o),[k,T]=a.useState([]),C=a.useRef([]),[$,F]=a.useState([]),[ee,I]=a.useState(!1),[_,N]=a.useState(""),[J,K]=a.useState(null),[G,M]=a.useState([]),[O,X]=a.useState(void 0),[S,V]=a.useState(!1),[de,L]=a.useState(!1),[Z,D]=a.useState(!1),[me,q]=a.useState(null),[W,ce]=a.useState(void 0),[Se,ve]=a.useState(void 0),[Ee,Ae]=a.useState(void 0),[Oe,Fe]=a.useState(void 0),[rt,Pe]=a.useState(void 0),[Ie,Be]=a.useState(void 0),nt=a.useRef(null),De=a.useRef(null),Qe=a.useRef(null),ie=a.useRef(null),[te,fe]=a.useState(null),[ae,_e]=a.useState(null),ke=a.useRef(null),He=a.useRef(null),[dt,ht]=a.useState(null),[he]=a.useState(()=>typeof document<"u"?document.body:null),[ne,ye]=a.useState(!1),[we,st]=a.useState(null),[be,it]=a.useState(i??[]),[Me,qe]=a.useState([]),[oe,Ve]=a.useState([]),[We,Re]=a.useState(null),[et,xt]=a.useState(void 0),[wt,Et]=a.useState(!1),[Rt,$t]=a.useState(!1),[_t,vt]=a.useState(!1),Dt=a.useRef(null),Ke=a.useRef(null),[bt,Le]=a.useState(null),lt=m??Me,xe=c??oe,U=!t;a.useEffect(()=>{if(i)it(i),ye(!1),st(null);else{let le=!1;return ye(!0),st(null),Jn().then($e=>{le||(it($e.models),m||qe($e.favoriteProviders),c||Ve($e.favoriteModels))}).catch($e=>{le||st(ge($e)||"Failed to load models")}).finally(()=>{le||ye(!1)}),Wi(o).then($e=>{le||Re($e)}).catch(()=>{}),()=>{le=!0}}},[i,m,c,o]);const Ne=fl(W,Se),pt=fl(Ee,Oe),kt=fl(rt,Ie),je=!!(W&&Se),Ge=!!(Ee&&Oe),gt=!!(rt&&Ie),qt=Number(je)+Number(Ge)+Number(gt),gn=et?We?.modelPresets?.find(le=>le.id===et)?.name??"Models":qt>0?`${qt} model${qt===1?"":"s"}`:"Models",Wt=a.useCallback((le,$e)=>{if(!le||!$e)return"Using default";const mt=be.find(Nt=>Nt.provider===le&&Nt.id===$e);return mt?`${mt.provider}/${mt.id}`:`${le}/${$e}`},[be]);a.useEffect(()=>{f(In(ca,o)||"")},[o]),a.useEffect(()=>{typeof window<"u"&&ms(ca,g,o)},[g,o]),a.useEffect(()=>{E.current!==o&&(E.current=o,M([]),X(void 0),K(null),V(!1),fe(null))},[o]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{C.current=k},[k]),a.useEffect(()=>()=>{C.current.forEach(le=>URL.revokeObjectURL(le.previewUrl))},[]);const Rn=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(()=>{x&&Rn()},[g,x,Rn]),a.useEffect(()=>{if(!p&&g===""&&j.current){const le=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(le)}},[p,g]),a.useEffect(()=>{ee||N("")},[ee]),a.useEffect(()=>{if(!Rt)return;const le=$e=>{const mt=$e.target,Nt=Dt.current?.contains(mt),Ct=Ke.current?.contains(mt);!Nt&&!Ct&&$t(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Rt]),a.useEffect(()=>{if(!Z)return;const le=$e=>{const mt=$e.target,Nt=nt.current?.contains(mt),Ct=De.current?.contains(mt),un=mt instanceof Element&&mt.closest?.(".model-combobox-dropdown--portal")!=null;!Nt&&!Ct&&!un&&(D(!1),q(null))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Z]),a.useEffect(()=>{if(!S)return;const le=$e=>{const mt=$e.target;Qe.current?.contains(mt)||ie.current?.contains(mt)||(V(!1),fe(null))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[S]);const Kt=a.useCallback(()=>{k.forEach(le=>URL.revokeObjectURL(le.previewUrl)),T([]),P.current&&(P.current.value=""),f(""),F([]),K(null),V(!1),fe(null),ce(void 0),ve(void 0),Ae(void 0),Fe(void 0),Pe(void 0),Be(void 0),xt(void 0),Et(!1),I(!1),D(!1),_e(null),q(null),$t(!1),vt(!1),v(!1),A(!1),w.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&Da(ca,o)},[k,o]),$n=a.useCallback(le=>{if(!le||le.length===0)return;const $e=[];for(let mt=0;mt<le.length;mt++){const Nt=le[mt];aw.includes(Nt.type)&&$e.push({file:Nt,previewUrl:URL.createObjectURL(Nt)})}$e.length>0&&T(mt=>[...mt,...$e])},[]),bn=a.useCallback(le=>{p||$n(le.clipboardData?.files)},[$n,p]),on=a.useCallback(le=>{T($e=>{const mt=$e[le];return mt&&URL.revokeObjectURL(mt.previewUrl),$e.filter((Nt,Ct)=>Ct!==le)})},[]),en=a.useCallback(async()=>{const le=g.trim();if(!(!le||p||!t)){b(!0);try{const $e=await t({description:le,column:"triage",dependencies:$.length?$:void 0,...J?{assignedAgentId:J}:{},modelPresetId:et,modelProvider:je?W:void 0,modelId:je?Se:void 0,validatorModelProvider:Ge?Ee:void 0,validatorModelId:Ge?Oe:void 0,planningModelProvider:gt?rt:void 0,planningModelId:gt?Ie:void 0,...wt?{executionMode:"fast"}:{}});if($e&&k.length>0){const mt=[];for(const Nt of k)try{await $a($e.id,Nt.file,o)}catch{mt.push(Nt.file.name)}mt.length>0&&n(`Failed to upload: ${mt.join(", ")}`,"error")}Kt()}catch($e){n(ge($e)||"Failed to create task","error")}finally{b(!1)}}},[g,p,t,$,J,je,W,Se,Ge,Ee,Oe,gt,rt,Ie,k,o,n,Kt,wt]),xn=a.useCallback(le=>{if(le.key==="Enter"){if(le.shiftKey&&x)return;le.preventDefault(),en()}else if(le.key==="Escape"){if(le.preventDefault(),me){q(null);return}if(Z){D(!1),_e(null);return}if(ee){I(!1);return}if(Rt){$t(!1);return}if(S){V(!1),fe(null);return}g.trim()&&(f(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&Da(ca,o)),v(!1),A(!1),j.current?.blur()}},[en,g,x,ee,S,Z,me,Rt,o,A]),wn=a.useCallback(()=>{w.current&&(w.current=!1)},[]),Dn=a.useCallback(()=>{d&&v(!0)},[d]),cn=a.useCallback(le=>{F($e=>$e.includes(le)?$e.filter(mt=>mt!==le):[...$e,le])},[]),sn=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}},[]),Vt=a.useCallback(()=>{const le=nt.current;if(!le)return;const $e=le.getBoundingClientRect(),{width:mt,height:Nt,offsetTop:Ct,offsetLeft:un}=sn(),mn=16,pn=16,fn=4,vn=mt<=768,Cn=Math.min(vn?Nt*.6:Nt*.5,360),ls=vn?Math.min(mt-mn*2,360):Math.max($e.width,240),Vn=Math.min(ls,Math.max(mt-mn*2,200)),En=$e.top-Ct,Tn=$e.bottom-Ct,Xn=$e.left-un,yn=Nt-Tn,Wn=En,fs=Math.max(yn-pn-fn,160),Zn=Math.max(Wn-pn-fn,160),gs=yn<Cn&&Wn>yn,Fn=Math.max(Math.min(gs?Zn:fs,Cn),160),se=Math.min(Math.max(Xn,mn),mt-mn-Vn)+un,tt=gs?Math.max(pn+Ct,En-Fn-fn+Ct):Math.min(Tn+fn+Ct,Nt+Ct-pn-Fn);_e({top:tt,left:se,width:Vn,maxHeight:Fn})},[sn]),Nn=a.useCallback(()=>{const le=Dt.current?.querySelector(".refine-button");if(!le)return;const $e=le.getBoundingClientRect(),{width:mt,height:Nt,offsetTop:Ct,offsetLeft:un}=sn(),mn=8,pn=12,fn=4,vn=Math.min(200,Math.max(Nt-pn*2,160)),Cn=Math.min(200,mt-mn*2),ls=$e.top-Ct,Vn=$e.bottom-Ct,En=$e.left-un,Tn=Nt-Vn,Xn=ls,yn=Tn<vn&&Xn>Tn,Wn=Math.min(Math.max(En,mn),mt-mn-Cn)+un,fs=yn?Math.max(pn+Ct,ls-vn-fn+Ct):Math.min(Vn+fn+Ct,Nt+Ct-pn-vn);Le({top:fs,left:Wn})},[sn]),Un=a.useCallback(()=>{const le=ke.current;if(!le)return;const $e=le.getBoundingClientRect(),{width:mt,height:Nt,offsetTop:Ct,offsetLeft:un}=sn(),mn=16,pn=16,fn=4,vn=mt<=768,Cn=Math.min(vn?Nt*.6:Nt*.5,320),ls=vn?Math.min(mt-mn*2,360):Math.max($e.width,280),Vn=Math.min(ls,Math.max(mt-mn*2,240)),En=$e.top-Ct,Tn=$e.bottom-Ct,Xn=$e.left-un,yn=Nt-Tn,Wn=En,fs=Math.max(yn-pn-fn,200),Zn=Math.max(Wn-pn-fn,200),gs=yn<Cn&&Wn>yn,Fn=Math.max(Math.min(gs?Zn:fs,Cn),200),se=Math.min(Math.max(Xn,mn),mt-mn-Vn)+un,tt=gs?Math.max(pn+Ct,En-Fn-fn+Ct):Math.min(Tn+fn+Ct,Nt+Ct-pn-Fn);ht({top:tt,left:se,width:Vn,maxHeight:Fn})},[sn]),Sn=a.useCallback(()=>{const le=Qe.current?.querySelector("button");if(!le)return;const $e=le.getBoundingClientRect(),{width:mt,height:Nt,offsetTop:Ct,offsetLeft:un}=sn(),mn=16,pn=16,fn=4,vn=mt<=768,Cn=Math.min(vn?Nt*.6:Nt*.5,320),ls=vn?Math.min(mt-mn*2,280):Math.max($e.width,240),Vn=Math.min(ls,Math.max(mt-mn*2,200)),En=$e.top-Ct,Tn=$e.bottom-Ct,Xn=$e.left-un,yn=Nt-Tn,Wn=En,fs=Math.max(yn-pn-fn,160),Zn=Math.max(Wn-pn-fn,160),gs=yn<Cn&&Wn>yn,Fn=Math.max(Math.min(gs?Zn:fs,Cn),160),se=Math.min(Math.max(Xn,mn),mt-mn-Vn)+un,tt=gs?Math.max(pn+Ct,En-Fn-fn+Ct):Math.min(Tn+fn+Ct,Nt+Ct-pn-Fn);fe({top:tt,left:se,width:Vn,maxHeight:Fn})},[sn]);a.useEffect(()=>{if(!Z)return;const le=()=>Vt();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))}},[Z,Vt]),a.useEffect(()=>{if(!Rt)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))}},[Rt,Nn]),a.useEffect(()=>{if(!ee)return;const le=()=>Un();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,Un]),a.useEffect(()=>{if(!S)return;const le=()=>Sn();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))}},[S,Sn]);const Hn=a.useCallback(le=>{const $e=gl(le);Pe($e.provider),Be($e.modelId)},[]),Qn=a.useCallback(le=>{const $e=gl(le);ce($e.provider),ve($e.modelId)},[]),Q=a.useCallback(le=>{const $e=gl(le);Ae($e.provider),Fe($e.modelId)},[]),Ue=a.useCallback(async le=>{if(u){u(le);return}const $e=Me,Nt=$e.includes(le)?$e.filter(Ct=>Ct!==le):[le,...$e];qe(Nt);try{await Gt({favoriteProviders:Nt,favoriteModels:oe})}catch{qe($e)}},[Me,oe,u]),R=a.useCallback(async le=>{if(h){h(le);return}const $e=oe,Nt=$e.includes(le)?$e.filter(Ct=>Ct!==le):[le,...$e];Ve(Nt);try{await Gt({favoriteProviders:Me,favoriteModels:Nt})}catch{Ve($e)}},[oe,Me,h]),B=a.useCallback(()=>{const le=g.trim();if(!le){n("Enter a description first","error");return}r?.(le),Kt()},[g,r,n,Kt]),re=a.useCallback(()=>{const le=g.trim();if(!le){n("Enter a description first","error");return}l?.(le),Kt()},[g,l,n,Kt]),pe=a.useCallback(()=>{en()},[en]),ue=a.useCallback(async le=>{const $e=g.trim();if(!(!$e||_t)){$t(!1),vt(!0);try{const mt=await lh($e,le,o);f(mt),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(mt){const Nt=oh(mt);n(Nt,"error")}finally{vt(!1)}}},[g,_t,n,o]),Te=(le,$e)=>le.length>$e?le.slice(0,$e)+"…":le,ut=a.useCallback(async()=>{if(i){it(i),st(null),ye(!1);return}ye(!0),st(null);try{const le=await Jn();it(le.models),m||qe(le.favoriteProviders),c||Ve(le.favoriteModels)}catch(le){st(ge(le)||"Failed to load models")}finally{ye(!1)}},[i,m,c]),Mt=a.useCallback(async()=>{if(G.length>0&&O===o){V(!0),Sn();return}L(!0);try{const le=await ia(void 0,o);M(le),X(o),V(!0),Sn()}catch(le){const $e=ge(le);n($e?`Failed to load agents: ${$e}`:"Failed to load agents","error"),V(!1)}finally{L(!1)}},[G.length,O,o,n,Sn]),Je=(J?G.find(le=>le.id===J):void 0)?.name??J,ot=y,qn=a.useCallback(()=>{A(le=>{const $e=!le;return v($e),$e})},[]);return e.jsxs("div",{className:`quick-entry-box ${y?"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 ${x?"quick-entry-input--expanded":""}`,placeholder:p?"Creating...":"Add a task...",value:g,onChange:le=>f(le.target.value),onKeyDown:xn,onPaste:bn,onFocus:Dn,onBlur:wn,disabled:p||U,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),e.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:qn,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?e.jsx(Ds,{size:14}):e.jsx(zt,{size:14})})]})}),e.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ot,"aria-hidden":!ot,children:[ot&&!p&&e.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:B,onMouseDown:le=>le.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[e.jsx(Ls,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:re,onMouseDown:le=>le.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[e.jsx(qr,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),e.jsxs("div",{className:"refine-trigger-wrap",ref:Dt,children:[e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${_t?"refine-button--loading":""}`,onClick:()=>{$t(le=>{const $e=!le;return $e?Nn():Le(null),$e})},disabled:!g.trim()||_t,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(On,{size:12,style:{verticalAlign:"middle"}}),_t?"Refining...":"Refine"]}),Rt&&he&&bt&&wa.createPortal(e.jsxs("div",{ref:Ke,className:"refine-menu refine-menu--portal",onMouseDown:le=>le.preventDefault(),style:{position:"fixed",top:`${bt.top}px`,left:`${bt.left}px`},children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>ue("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:()=>ue("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:()=>ue("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:()=>ue("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"})]})]}),he)]}),e.jsx("div",{className:"dep-trigger-wrap",children:e.jsxs("button",{ref:ke,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{I(le=>{const $e=!le;return $e?(D(!1),_e(null),q(null),V(!1),Un()):ht(null),$e})},children:[e.jsx(qi,{size:12,style:{verticalAlign:"middle"}}),$.length>0?`${$.length} deps`:"Deps"]})}),ee&&he&&dt&&(()=>{const le=_.toLowerCase(),$e=(le?s.filter(mt=>mt.id.toLowerCase().includes(le)||mt.title&&mt.title.toLowerCase().includes(le)||mt.description&&mt.description.toLowerCase().includes(le)):[...s]).sort((mt,Nt)=>{const Ct=Nt.createdAt.localeCompare(mt.createdAt);if(Ct!==0)return Ct;const un=parseInt(mt.id.slice(mt.id.lastIndexOf("-")+1),10)||0;return(parseInt(Nt.id.slice(Nt.id.lastIndexOf("-")+1),10)||0)-un});return wa.createPortal(e.jsxs("div",{ref:He,className:"dep-dropdown dep-dropdown--portal",onMouseDown:mt=>mt.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:_,onChange:mt=>N(mt.target.value),onClick:mt=>mt.stopPropagation()}),$e.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):$e.map(mt=>e.jsxs("div",{className:`dep-dropdown-item${$.includes(mt.id)?" selected":""}`,onMouseDown:Nt=>Nt.preventDefault(),onClick:()=>cn(mt.id),children:[e.jsx("span",{className:"dep-dropdown-id",children:mt.id}),e.jsx("span",{className:"dep-dropdown-title",children:Te(mt.title||mt.description||mt.id,60)})]},mt.id))]}),he)})(),e.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>P.current?.click(),children:[e.jsx(pb,{size:12,style:{verticalAlign:"middle"}}),k.length>0?`Attach (${k.length})`:"Attach"]}),e.jsxs("button",{ref:nt,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{I(!1),V(!1),q(null),D(!0),Vt()},children:[e.jsx(Nr,{size:12,style:{verticalAlign:"middle"}}),gn]}),e.jsx("div",{className:"agent-trigger-wrap",ref:Qe,children:e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{S?(V(!1),fe(null)):Mt()},"data-testid":"quick-entry-agent-button",children:[e.jsx(an,{size:12,style:{verticalAlign:"middle"}}),Je?` ${Je}`:" Agent"]})}),S&&he&&te&&wa.createPortal(e.jsxs("div",{ref:ie,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:le=>le.preventDefault(),style:{position:"fixed",top:`${te.top}px`,left:`${te.left}px`,width:`${te.width}px`,maxHeight:te.maxHeight?`${te.maxHeight}px`:void 0,overflowY:te.maxHeight?"auto":void 0},children:[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${J===le.id?" selected":""}`,onMouseDown:$e=>$e.preventDefault(),onClick:()=>{K(le.id===J?null:le.id),V(!1),fe(null)},children:[e.jsx(an,{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"}),J&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:le=>le.preventDefault(),onClick:()=>{K(null),V(!1),fe(null)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),he),e.jsx("button",{type:"button",className:`btn btn-sm ${wt?"btn-primary":""}`,onClick:()=>Et(le=>!le),onMouseDown:le=>le.preventDefault(),"aria-pressed":wt,"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:pe,onMouseDown:le=>le.preventDefault(),disabled:!g.trim()||p,"data-testid":"quick-entry-save",title:"Create task",children:[e.jsx(Jm,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),k.length>0&&e.jsx("div",{className:"inline-create-previews",children:k.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:()=>on($e),disabled:p,title:"Remove image","data-testid":`quick-entry-preview-remove-${$e}`,children:"×"})]},le.previewUrl))}),Z&&he&&ae&&wa.createPortal(e.jsx("div",{ref:De,className:"model-nested-menu model-nested-menu--portal",onMouseDown:le=>le.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ae.top}px`,left:`${ae.left}px`,width:`${ae.width}px`,maxHeight:ae.maxHeight?`${ae.maxHeight}px`:void 0,overflowY:ae.maxHeight?"auto":void 0},children:me===null?e.jsxs("div",{className:"model-menu-items",children:[e.jsxs("button",{type:"button",className:`model-menu-item ${gt?"model-menu-item--active":""}`,onClick:()=>q("plan"),"data-testid":"model-menu-plan",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Ls,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),e.jsx("span",{className:"model-menu-item-value",children:gt?Wt(rt,Ie):"Using default"}),e.jsx(ln,{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(On,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),e.jsx("span",{className:"model-menu-item-value",children:je?Wt(W,Se):"Using default"}),e.jsx(ln,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${Ge?"model-menu-item--active":""}`,onClick:()=>q("validator"),"data-testid":"model-menu-validator",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Nr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Validator"]}),e.jsx("span",{className:"model-menu-item-value",children:Ge?Wt(Ee,Oe):"Using default"}),e.jsx(ln,{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(zt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),e.jsxs("div",{className:"model-submenu-header",children:[me==="plan"&&"Plan Model",me==="executor"&&"Executor Model",me==="validator"&&"Validator Model"]}),e.jsx(Jt,{models:be,value:me==="plan"?kt:me==="executor"?Ne:pt,onChange:me==="plan"?Hn:me==="executor"?Qn:Q,placeholder:"Using default",disabled:ne,id:`model-${me}-select`,label:`${me} model`,favoriteProviders:lt,onToggleFavorite:Ue,favoriteModels:xe,onToggleModelFavorite:R}),we&&e.jsxs("div",{className:"model-submenu-error",children:[e.jsx("span",{children:we}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:ut,children:"Retry"})]})]})}),he)]}),e.jsx("input",{ref:P,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:le=>{$n(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 rw(t){const n=t.replace(/\/+$/,"").split("/");return n[n.length-1]||t}function lw(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 ow(t,n,s){const i=t.filter(p=>p.worktree),r=t.filter(p=>!p.worktree),l=new Map;for(const p of i){const b=p.worktree,x=l.get(b)||[];x.push(p),l.set(b,x)}const o=new Map(n.map(p=>[p.id,p])),m=n.filter(p=>p.column==="todo").filter(p=>!p.paused&&(p.dependencies||[]).every(b=>{const x=o.get(b);return x&&(x.column==="done"||x.column==="in-review"||x.column==="archived")})),u=lw(m).map(p=>o.get(p)).filter(p=>p!==void 0&&m.includes(p)),h=[],g=Array.from(l.keys());for(const p of g)h.push({label:rw(p),activeTasks:l.get(p),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const f=u.slice(0,s);return f.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:f}),h}const Nd=100,bl=50,Sd=25;function cw({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:f,onUnarchiveTask:p,onDeleteTask:b,onArchiveAllDone:x,collapsed:v,onToggleCollapse:y,allTasks:A,availableModels:j,onPlanningMode:P,onSubtaskBreakdown:w,onOpenDetailWithTab:E,favoriteProviders:k,favoriteModels:T,onToggleFavorite:C,onToggleModelFavorite:$,isSearchActive:F,taskStuckTimeoutMs:ee,onOpenMission:I,lastFetchTimeMs:_,workflowStepNameLookup:N}){const[J,K]=a.useState(!1),[G,M]=a.useState(bl),O=hj(n.length),X=t==="archived",S=X&&v,V=!X&&!F&&t!=="in-progress"&&n.length>Nd;a.useEffect(()=>{M(Se=>t==="in-progress"||X||n.length<=Nd?bl:Math.min(Math.max(Se,bl),n.length))},[t,X,n.length]);const de=a.useCallback(Se=>{X||(Se.preventDefault(),Se.dataTransfer.dropEffect="move",K(!0))},[X]),L=a.useCallback(Se=>{Se.currentTarget.contains(Se.relatedTarget)||K(!1)},[]),Z=a.useCallback(async Se=>{Se.preventDefault(),K(!1);const ve=Se.dataTransfer.getData("text/plain");if(!ve)return;const Ee=n.find(Ae=>Ae.id===ve);if(!(Ee&&Ee.column===t))try{await r(ve,t)}catch(Ae){o(ge(Ae),"error")}},[t,r,o,n]),D=a.useMemo(()=>t!=="in-progress"?[]:ow(n,n,i),[t,n,i]),me=a.useMemo(()=>V?n.slice(0,G):n,[V,n,G]),q=Math.max(0,n.length-me.length),W=a.useCallback(()=>{M(Se=>Math.min(Se+Sd,n.length))},[n.length]),ce=a.useCallback(async()=>{if(!(!x||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const ve=await x();o(`Archived ${ve.length} tasks`,"success")}catch(ve){o(ge(ve)||"Failed to archive tasks","error")}},[x,n.length,o]);return e.jsxs("div",{className:`column${J?" drag-over":""}${X?" column-archived":""}${S?" column-collapsed":""}`,"data-column":t,onDragOver:de,onDragLeave:L,onDrop:Z,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${O?" 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"&&x&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:ce,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:e.jsx(Ur,{size:16})}),X&&y&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:y,title:v?"Expand archived tasks":"Collapse archived tasks","aria-label":v?"Expand archived tasks":"Collapse archived tasks",children:v?e.jsx(zt,{size:16}):e.jsx(Ds,{size:16})})]}),!S&&e.jsx("p",{className:"column-desc",children:uj[t]}),!S&&e.jsxs("div",{className:"column-body",children:[t==="triage"&&d&&e.jsx(Nh,{onCreate:d,addToast:o,tasks:A??[],availableModels:j,onPlanningMode:P,onSubtaskBreakdown:w,projectId:s,autoExpand:!1,favoriteProviders:k,favoriteModels:T,onToggleFavorite:C,onToggleModelFavorite:$}),t==="in-progress"?D.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):D.map(Se=>e.jsx(wh,{label:Se.label,activeTasks:Se.activeTasks,queuedTasks:Se.queuedTasks,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onOpenDetailWithTab:E,taskStuckTimeoutMs:ee,onOpenMission:I,lastFetchTimeMs:_,workflowStepNameLookup:N},Se.label)):n.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):e.jsxs(e.Fragment,{children:[me.map(Se=>e.jsx(_r,{task:Se,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onArchiveTask:f,onUnarchiveTask:p,onDeleteTask:b,onOpenDetailWithTab:E,taskStuckTimeoutMs:ee,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:_,workflowStepNameLookup:N},Se.id)),V&&q>0&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:W,children:["Load ",Math.min(Sd,q)," more (",q," remaining)"]})]}),e.jsx(Ga,{slotId:"board-column-footer",projectId:s})]})]})}const Sh=a.memo(cw);Sh.displayName="Column";function dw(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 uw(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}const Cd=new Map;function mw(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 hw({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:f,onDeleteTask:p,onArchiveAllDone:b,onLoadArchivedTasks:x,searchQuery:v="",availableModels:y,onPlanningMode:A,onSubtaskBreakdown:j,onOpenDetailWithTab:P,favoriteProviders:w,favoriteModels:E,onToggleFavorite:k,onToggleModelFavorite:T,taskStuckTimeoutMs:C,onOpenMission:$,lastFetchTimeMs:F}){const[ee,I]=a.useState(!0),_=a.useRef(!1),{fetchBatch:N}=kj(n),J=a.useRef(null),[K,G]=a.useState(Cd),M=v.trim()!=="",O=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),X=a.useCallback(()=>{I(de=>{const L=!de;return!L&&!_.current&&x&&(_.current=!0,x()),L})},[x]),S=a.useMemo(()=>{const de=Object.fromEntries(bi.map(D=>[D,[]]));for(const D of t)de[D.column].push(D);const L=O.current,Z={};for(const D of bi){const me=dw(de[D]);Z[D]=uw(L[D],me)?L[D]:me}return O.current=Z,Z},[t]);a.useEffect(()=>{let de=!1;return Gr(n).then(L=>{if(de)return;const Z=new Map(L.map(D=>[D.id,D.name]));G(D=>mw(D,Z)?D:Z)}).catch(()=>{de||G(L=>L.size===0?L:Cd)}),()=>{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 J.current&&clearTimeout(J.current),J.current=setTimeout(()=>{const de=[];for(let L=0;L<V.length;L+=50)de.push(V.slice(L,L+50));de.forEach(L=>{N(L)})},500),()=>{J.current&&clearTimeout(J.current)}},[V,N]),e.jsx(e.Fragment,{children:e.jsx("main",{className:"board",id:"board",children:bi.map(de=>e.jsx(Sh,{column:de,tasks:S[de],projectId:n,maxConcurrent:s,onMoveTask:i,onOpenDetail:r,addToast:l,globalPaused:u,onUpdateTask:h,onArchiveTask:g,onUnarchiveTask:f,onDeleteTask:p,allTasks:t,availableModels:y,onOpenDetailWithTab:P,favoriteProviders:w,favoriteModels:E,onToggleFavorite:k,onToggleModelFavorite:T,isSearchActive:M,taskStuckTimeoutMs:C,onOpenMission:$,lastFetchTimeMs:F,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 da={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Ed=new Set(["planning","researching","executing","finalizing","merging","specifying"]),jo=["id","title","status","column","dependencies","progress"];function Md(t){try{const n=In("kb-dashboard-list-columns",t);if(n){const i=JSON.parse(n).filter(r=>jo.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(jo)}function Ad(t){try{const n=In("kb-dashboard-hide-done",t);if(n!==null)return n==="true"}catch{}return!1}function Pd(t){try{const n=In("kb-dashboard-list-collapsed",t);if(n){const i=JSON.parse(n).filter(r=>bi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Rd(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 pw(t){return t.status==="executing"||t.column==="in-progress"}function Td(t){const n=jh(t);return n.total===0||!pw(t)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function fw({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:f,onTasksUpdated:p,projectId:b,projectName:x,taskStuckTimeoutMs:v,searchQuery:y="",lastFetchTimeMs:A}){const[j,P]=a.useState("id"),[w,E]=a.useState("desc"),[k,T]=a.useState(null),[C,$]=a.useState(null),[F,ee]=a.useState(null),_=Yr()==="mobile",[N,J]=a.useState(()=>Md(b)),[K,G]=a.useState(()=>Ad(b)),[M,O]=a.useState(()=>Pd(b));a.useEffect(()=>{typeof window<"u"&&ms("kb-dashboard-list-columns",JSON.stringify([...N]),b)},[b,N]),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([...M]),b)},[M,b]);const[X,S]=a.useState(!1),V=a.useRef(null),[de,L]=a.useState(()=>Rd(b));a.useEffect(()=>{J(Md(b)),G(Ad(b)),O(Pd(b)),L(Rd(b))},[b]),a.useEffect(()=>{typeof window<"u"&&ms("kb-dashboard-selected-tasks",JSON.stringify([...de]),b)},[b,de]);const Z=a.useCallback(ne=>{L(ye=>{const we=new Set(ye);return we.has(ne)?we.delete(ne):we.add(ne),we})},[]),D=a.useCallback(()=>{L(new Set)},[]),me=a.useCallback(ne=>{J(ye=>{const we=new Set(ye);return we.has(ne)?we.size>1&&we.delete(ne):we.add(ne),we})},[]);a.useEffect(()=>{if(!X)return;const ne=we=>{V.current&&!V.current.contains(we.target)&&S(!1)},ye=we=>{we.key==="Escape"&&S(!1)};return document.addEventListener("mousedown",ne),document.addEventListener("keydown",ye),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",ye)}},[X]);const q={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},W=a.useCallback(ne=>{j===ne?E(ye=>ye==="asc"?"desc":"asc"):(P(ne),E("asc"))},[j]),ce=a.useCallback(ne=>{ee(ye=>ye===ne?null:ne)},[]),Se=a.useCallback(ne=>{O(ye=>{const we=new Set(ye);return we.has(ne)?we.delete(ne):we.add(ne),we})},[]),ve=a.useCallback(()=>{ee(null)},[]),Ee=a.useMemo(()=>{let ne=y?t.filter(be=>be.id.toLowerCase().includes(y.toLowerCase())||be.title&&be.title.toLowerCase().includes(y.toLowerCase())||be.description.toLowerCase().includes(y.toLowerCase())):[...t];K&&!F&&(ne=ne.filter(be=>be.column!=="done"&&be.column!=="archived"));const we=[...F?ne.filter(be=>be.column===F):ne].sort((be,it)=>{let Me=0;switch(j){case"id":Me=be.id.localeCompare(it.id);break;case"title":Me=(be.title||be.description).localeCompare(it.title||it.description);break;case"status":Me=(be.status||"").localeCompare(it.status||"");break;case"column":Me=be.column.localeCompare(it.column);break}return w==="asc"?Me:-Me}),st={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return we.forEach(be=>st[be.column].push(be)),st},[t,y,j,w,K,F]),Ae=a.useMemo(()=>Object.values(Ee).reduce((ne,ye)=>ne+ye.length,0),[Ee]),Oe=a.useMemo(()=>t.filter(ne=>ne.column==="done"||ne.column==="archived").length,[t]),Fe=a.useMemo(()=>K?Oe:0,[K,Oe]),rt=a.useCallback(()=>{const ne=Object.values(Ee).flat().filter(ye=>ye.column!=="archived").map(ye=>ye.id);L(ye=>{if(ne.every(st=>ye.has(st))){const st=new Set(ye);return ne.forEach(be=>st.delete(be)),st}else return new Set([...ye,...ne])})},[Ee]),Pe=a.useMemo(()=>{const ne=Object.values(Ee).flat().filter(ye=>ye.column!=="archived");return ne.length===0?!1:ne.every(ye=>de.has(ye.id))},[Ee,de]),Ie=a.useMemo(()=>{const ne=Object.values(Ee).flat().filter(we=>we.column!=="archived");if(ne.length===0)return!1;const ye=ne.filter(we=>de.has(we.id)).length;return ye>0&&ye<ne.length},[Ee,de]),[Be,nt]=a.useState("__no_change__"),[De,Qe]=a.useState("__no_change__"),[ie,te]=a.useState(!1),fe=a.useCallback(async()=>{if(de.size===0)return;const ne=Array.from(de).filter(we=>{const st=t.find(be=>be.id===we);return st&&st.column!=="archived"});if(ne.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ye={taskIds:ne};if(Be!=="__no_change__")if(Be==="")ye.modelProvider=null,ye.modelId=null;else{const we=Be.indexOf("/");we!==-1&&(ye.modelProvider=Be.slice(0,we),ye.modelId=Be.slice(we+1))}if(De!=="__no_change__")if(De==="")ye.validatorModelProvider=null,ye.validatorModelId=null;else{const we=De.indexOf("/");we!==-1&&(ye.validatorModelProvider=De.slice(0,we),ye.validatorModelId=De.slice(we+1))}if(Object.keys(ye).length===1){i("No changes to apply","info");return}te(!0);try{const we=await xx(ye.taskIds,ye.modelProvider,ye.modelId,ye.validatorModelProvider,ye.validatorModelId,void 0,void 0,b);p&&we.updated.length>0&&p(we.updated),i(`Updated ${we.count} task${we.count===1?"":"s"}`,"success"),D(),nt("__no_change__"),Qe("__no_change__")}catch(we){i(ge(we)||"Failed to update models","error")}finally{te(!1)}},[de,t,Be,De,b,i,D,p]),ae=a.useCallback(ne=>{s(ne)},[s]),_e=a.useCallback((ne,ye)=>{if(ye.paused){ne.preventDefault();return}ne.dataTransfer.setData("text/plain",ye.id),ne.dataTransfer.effectAllowed="move",T(ye.id)},[]),ke=a.useCallback(()=>{T(null),$(null)},[]),He=a.useCallback((ne,ye)=>{ne.preventDefault(),ne.dataTransfer.dropEffect="move",$(ye)},[]),dt=a.useCallback(()=>{$(null)},[]),ht=a.useCallback(async(ne,ye)=>{ne.preventDefault(),$(null);const we=ne.dataTransfer.getData("text/plain");if(we){if(ye==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(we,ye)}catch(st){i(ge(st),"error")}}},[n,i]),he=ne=>j!==ne?e.jsx(Fm,{size:14,className:"sort-icon"}):w==="asc"?e.jsx(gi,{size:14,className:"sort-icon active"}):e.jsx(za,{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:()=>S(ne=>!ne),"aria-expanded":X,"aria-haspopup":"menu",children:[e.jsx(ig,{size:14}),"Columns"]}),X&&e.jsx("div",{className:"list-column-dropdown",role:"menu",children:jo.map(ne=>{const ye=N.has(ne),we=ye&&N.size===1;return e.jsxs("label",{className:`list-column-dropdown-item${we?" disabled":""}`,role:"menuitem",title:we?"At least one column must be visible":"",children:[e.jsx("input",{type:"checkbox",checked:ye,onChange:()=>me(ne),disabled:we}),e.jsx("span",{children:q[ne]})]},ne)})})]}),e.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>G(ne=>!ne),"aria-pressed":K,title:K?"Show done tasks":"Hide done tasks",children:[K?e.jsx(Uo,{size:14}):e.jsx(pg,{size:14}),K?"Show Done":"Hide Done"]}),e.jsxs("div",{className:"list-stats",children:[F?`${Ae} of ${t.length} tasks in ${us[F]}`:`${Ae} of ${t.length} tasks`,Fe>0&&!F&&e.jsxs("span",{className:"list-stats-hidden",children:[" (",Fe," hidden)"]}),F&&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(Jt,{models:d,value:Be,onChange:nt,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(Jt,{models:d,value:De,onChange:Qe,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:fe,disabled:ie||Be==="__no_change__"&&De==="__no_change__",children:ie?"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:bi.map(ne=>{const ye=t.filter(it=>it.column===ne).length,we=ne==="done"||ne==="archived",st=K&&we?0:ye,be=K&&we&&ye>0;return e.jsxs("div",{className:`list-drop-zone${C===ne?" drag-over":""}${F===ne?" active":""}`,onClick:()=>ce(ne),onDragOver:it=>He(it,ne),onDragLeave:dt,onDrop:it=>ht(it,ne),"data-column":ne,children:[e.jsx("span",{className:"drop-zone-dot",style:{background:da[ne]}}),e.jsx("span",{className:"drop-zone-label",children:us[ne]}),e.jsx("span",{className:"drop-zone-count",children:be?`${st} of ${ye}`:ye})]},ne)})}),e.jsxs("div",{className:"list-table-container",children:[e.jsx("div",{className:"list-quick-entry-above-table",children:e.jsx(Nh,{onCreate:o??(async()=>i("Task creation not available","error")),addToast:i,tasks:t,availableModels:d,onPlanningMode:g,onSubtaskBreakdown:f,projectId:b,autoExpand:!1,favoriteProviders:m,favoriteModels:c,onToggleFavorite:u,onToggleModelFavorite:h})}),Ae===0?e.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):_?e.jsx("div",{className:"list-cards",children:bi.map(ne=>{if(F&&ne!==F||K&&(ne==="done"||ne==="archived")&&!F)return null;const ye=Ee[ne],we=ye.length===0;if(y&&we)return null;const st=M.has(ne);return e.jsxs(a.Fragment,{children:[e.jsxs("div",{className:`list-card-section-header${st?" list-section-header--collapsed":""}`,onClick:()=>Se(ne),"aria-expanded":!st,role:"button",tabIndex:0,onKeyDown:be=>{(be.key==="Enter"||be.key===" ")&&(be.preventDefault(),Se(ne))},children:[e.jsx(ln,{size:14,className:`list-section-chevron${st?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${ne}`}),e.jsx("span",{className:"list-section-title",children:us[ne]}),e.jsx("span",{className:"list-section-count",children:ye.length})]}),!st&&e.jsx(e.Fragment,{children:we?e.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ye.map(be=>{const it=be.status==="failed",Me=be.paused===!0,qe=Tr(be,v,A),oe=!r&&!it&&!Me&&!qe&&(be.column==="in-progress"||Ed.has(be.status)),Ve=typeof be.status=="string"&&be.status.trim().length>0,We=!!(be.dependencies&&be.dependencies.length>0),Re=Td(be),et=Re.hasProgress,xt=de.size>0;return e.jsxs("div",{className:`list-card${oe?" agent-active":""}${xt?" list-card--selectable":""}`,onClick:()=>ae(be),"data-id":be.id,children:[xt&&e.jsx("label",{className:"list-card-checkbox",onClick:wt=>wt.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:de.has(be.id),onChange:wt=>{wt.stopPropagation(),Z(be.id)},onClick:wt=>wt.stopPropagation(),disabled:be.column==="archived","aria-label":`Select ${be.id}`})}),e.jsxs("div",{className:"list-card-row",children:[e.jsx("span",{className:"list-card-id",children:be.id}),e.jsx("span",{className:"list-card-spacer"}),qe?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ve?e.jsx("span",{className:`list-status-badge list-status-badge--${be.column}${it?" failed":""}${oe?" pulsing":""}`,children:be.status}):null]}),e.jsx("div",{className:"list-card-row",children:e.jsx("div",{className:"list-card-title",children:be.title||be.description})}),(We||et)&&e.jsxs("div",{className:"list-card-row list-card-meta",children:[We&&e.jsxs("span",{className:"list-dep-badge",title:be.dependencies.join(", "),children:[e.jsx(qi,{size:12})," ",be.dependencies.length]}),et&&e.jsxs("div",{className:"list-progress",children:[e.jsx("div",{className:"list-progress-bar",children:e.jsx("div",{className:"list-progress-fill",style:{width:`${Re.percent}%`,backgroundColor:da[be.column]}})}),e.jsx("span",{className:"list-progress-label",children:Re.label})]})]})]},be.id)})})]},ne)})}):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:Pe,ref:ne=>{ne&&(ne.indeterminate=Ie)},onChange:rt,"aria-label":"Select all visible tasks"})}),N.has("id")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("id"),children:["ID ",he("id")]}),N.has("title")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("title"),children:["Title ",he("title")]}),N.has("status")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("status"),children:["Status ",he("status")]}),N.has("column")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>W("column"),children:["Column ",he("column")]}),N.has("dependencies")&&e.jsx("th",{className:"list-header-cell",children:"Dependencies"}),N.has("progress")&&e.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),e.jsx("tbody",{children:bi.map(ne=>{if(F&&ne!==F||K&&(ne==="done"||ne==="archived")&&!F)return null;const ye=Ee[ne],we=ye.length===0;if(y&&we)return null;const st=M.has(ne);return e.jsxs(a.Fragment,{children:[e.jsx("tr",{className:`list-section-header${st?" list-section-header--collapsed":""}`,onClick:()=>Se(ne),"aria-expanded":!st,children:e.jsxs("th",{colSpan:N.size+1,className:"list-section-cell",children:[e.jsx(ln,{size:14,className:`list-section-chevron${st?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${ne}`}),e.jsx("span",{className:"list-section-title",children:us[ne]}),e.jsx("span",{className:"list-section-count",children:ye.length})]})}),!st&&e.jsx(e.Fragment,{children:we?e.jsx("tr",{className:"list-section-empty",children:e.jsx("td",{colSpan:N.size+1,className:"list-empty-cell",children:"No tasks"})}):ye.map(be=>{const it=be.status==="failed",Me=be.paused===!0,qe=Tr(be,v,A),oe=!r&&!it&&!Me&&!qe&&(be.column==="in-progress"||Ed.has(be.status)),Ve=k===be.id;return e.jsxs("tr",{className:`list-row${it?" failed":""}${Me?" paused":""}${qe?" stuck":""}${oe?" agent-active":""}${Ve?" dragging":""}`,onClick:()=>ae(be),draggable:!Me,onDragStart:We=>_e(We,be),onDragEnd:ke,"data-id":be.id,children:[e.jsx("td",{className:"list-cell list-cell-checkbox",children:e.jsx("input",{type:"checkbox",checked:de.has(be.id),onChange:We=>{We.stopPropagation(),Z(be.id)},onClick:We=>We.stopPropagation(),disabled:be.column==="archived","aria-label":`Select ${be.id}`})}),N.has("id")&&e.jsx("td",{className:"list-cell list-cell-id",children:be.id}),N.has("title")&&e.jsx("td",{className:"list-cell list-cell-title",children:be.title||be.description}),N.has("status")&&e.jsx("td",{className:"list-cell",children:qe?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):be.status?e.jsx("span",{className:`list-status-badge list-status-badge--${be.column}${it?" failed":""}${oe?" pulsing":""}`,children:be.status}):e.jsx("span",{className:"list-status-badge",children:"-"})}),N.has("column")&&e.jsx("td",{className:"list-cell",children:e.jsx("span",{className:"list-column-badge",style:{background:`${da[be.column]}20`,color:da[be.column]},children:us[be.column]})}),N.has("dependencies")&&e.jsx("td",{className:"list-cell list-cell-deps",children:be.dependencies&&be.dependencies.length>0?e.jsxs("span",{className:"list-dep-badge",title:be.dependencies.join(", "),children:[e.jsx(qi,{size:12})," ",be.dependencies.length]}):"-"}),N.has("progress")&&e.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const We=Td(be);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:da[be.column]}})}),e.jsx("span",{className:"list-progress-label",children:We.label})]}):"-"})()})]},be.id)})})]},ne)})})]})]})]})}const gw={active:{label:"Active",color:"var(--success)",icon:rn},paused:{label:"Paused",color:"var(--warning)",icon:$s},errored:{label:"Error",color:"var(--color-error)",icon:as},initializing:{label:"Initializing",color:"var(--info)",icon:ct}};function bw(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 xw(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 vw(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 yw({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=gw[t.status],g=h.icon,f=a.useCallback(()=>{s(t)},[s,t]),p=a.useCallback(j=>{j.stopPropagation(),i(t)},[i,t]),b=a.useCallback(j=>{j.stopPropagation(),r(t)},[r,t]),x=a.useCallback(j=>{if(j.stopPropagation(),!c){u(!0);return}l(t),u(!1)},[c,l,t]),v=t.status==="paused",y=t.status==="errored",A=t.status==="initializing";return e.jsxs("div",{className:`project-card ${m?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:f,"data-project-id":t.id,role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),f())},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:xw(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:bw(t.lastActivityAt||n?.lastActivityAt)})]}),e.jsxs("div",{className:"project-card-actions",children:[v?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(rn,{size:14}),e.jsx("span",{children:"Resume"})]}):e.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:m||A,title:A?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[e.jsx($s,{size:14}),e.jsx("span",{children:"Pause"})]}),e.jsxs("button",{className:"project-card-action project-card-action-open",onClick:f,disabled:m,title:"Open project","aria-label":"Open project",children:[e.jsx(Oa,{size:14}),e.jsx("span",{children:"Open"})]}),e.jsxs("button",{className:`project-card-action project-card-action-remove ${c?"is-armed":""}`,onClick:x,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 kw=a.memo(yw,vw);function jw(){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(nn,{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(as,{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 ww=1e4,_d=5;function Nw(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 f={};for(let p=0;p<t.length;p+=_d){const b=t.slice(p,p+_d),x=await Promise.allSettled(b.map(async v=>{try{return await rd(v)}catch{return null}}));if(b.forEach((v,y)=>{const A=x[y];f[v]=A.status==="fulfilled"?A.value:null}),m.current?.signal.aborted)return}s(f),c.current=!0}catch(f){if(f instanceof Error&&f.name==="AbortError")return;o(f instanceof Error?f.message:"Failed to fetch health data"),c.current=!0}finally{r(!1)}},[t]),h=a.useCallback(async g=>{try{const f=await rd(g);s(p=>({...p,[g]:f}))}catch(f){console.error(`Failed to fetch health for project ${g}:`,f)}},[]);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()},ww),()=>{d.current&&(clearInterval(d.current),d.current=null)}},[u,t.length]),{healthMap:n,loading:i,error:l,refresh:u,refreshProject:h}}function Sw({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,f]=a.useState("activity"),[p,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const ee=localStorage.getItem("kb-dashboard-recent-projects");if(ee)try{const I=JSON.parse(ee);v(I)}catch{}},[]);const[x,v]=a.useState([]),y=a.useMemo(()=>t.map(ee=>ee.id),[t]),{healthMap:A,loading:j}=Nw(y),P=a.useMemo(()=>t.map(ee=>({project:ee,health:A[ee.id]||null})),[t,A]),w=a.useMemo(()=>{let ee=[...P];return m!=="all"&&(ee=ee.filter(({project:I})=>I.status===m)),u!==null&&(ee=ee.filter(({project:I})=>I.nodeId===u)),ee},[P,m,u]),E=a.useMemo(()=>{const ee=[...w];return ee.sort((I,_)=>{let N=0;switch(g){case"name":N=I.project.name.localeCompare(_.project.name);break;case"activity":{const J=I.project.lastActivityAt||I.health?.lastActivityAt||I.project.updatedAt,K=_.project.lastActivityAt||_.health?.lastActivityAt||_.project.updatedAt;N=new Date(K).getTime()-new Date(J).getTime();break}case"status":{const J={errored:0,initializing:1,paused:2,active:3};N=J[I.project.status]-J[_.project.status];break}}return p==="asc"?N:-N}),ee},[w,g,p]),k=a.useMemo(()=>{const ee=t.length,I=t.filter(O=>O.status==="active").length,_=t.filter(O=>O.status==="errored").length,N=new Set;t.forEach(O=>{O.nodeId&&N.add(O.nodeId)});const J=N.size||(ee>0?1:0);let K=0,G=0,M=0;return Object.values(A).forEach(O=>{O&&(K+=O.activeTaskCount,G+=O.totalTasksCompleted,M+=O.inFlightAgentCount)}),{totalProjects:ee,activeProjects:I,erroredProjects:_,totalNodes:J,totalActiveTasks:K,totalCompletedTasks:G,totalInFlightAgents:M}},[t,A]),T=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]),C=a.useMemo(()=>{const ee=new Map;return t.forEach(I=>{const _=I.nodeId,N=ee.get(_);if(N)N.count++;else{const K=d.find(G=>G.id===_)?.name??I._sourceNodeName??"Local";ee.set(_,{name:K,count:1})}}),Array.from(ee.entries()).map(([I,{name:_,count:N}])=>({nodeId:I??null,name:_,count:N}))},[t,d]),$=a.useCallback(ee=>{const I=[ee.id,...x.filter(_=>_!==ee.id)].slice(0,3);v(I),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(I)),s(ee)},[s,x]);return n||j&&t.length>0&&Object.keys(A).length===0?e.jsx(jw,{}):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(Na,{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(Ht,{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(ki,{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:k.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:k.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(nn,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:k.totalCompletedTasks}),e.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),k.erroredProjects>0&&e.jsxs("div",{className:"project-stat project-stat--error",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(as,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:k.erroredProjects}),e.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),k.totalNodes>1&&e.jsxs("div",{className:"project-stat project-stat--nodes",children:[e.jsx("div",{className:"project-stat__icon",children:e.jsx(Cr,{size:16})}),e.jsxs("div",{className:"project-stat__content",children:[e.jsx("span",{className:"project-stat__value",children:k.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(Ht,{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:T.all})]}),e.jsxs("button",{className:`project-filter-tab ${m==="active"?"active":""}`,onClick:()=>c("active"),children:["Active",e.jsx("span",{className:"project-filter-count",children:T.active})]}),e.jsxs("button",{className:`project-filter-tab ${m==="paused"?"active":""}`,onClick:()=>c("paused"),children:["Paused",e.jsx("span",{className:"project-filter-count",children:T.paused})]}),e.jsxs("button",{className:`project-filter-tab ${m==="errored"?"active":""} ${T.errored>0?"has-errors":""}`,onClick:()=>c("errored"),children:["Errored",e.jsx("span",{className:"project-filter-count",children:T.errored})]})]}),C.length>1&&e.jsxs("div",{className:"project-node-filter",children:[e.jsx(Cr,{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"}),C.map(({nodeId:ee,name:I,count:_})=>e.jsxs("option",{value:ee??"",children:[I," (",_,")"]},ee??"local"))]})]}),e.jsxs("div",{className:"project-sort",children:[e.jsx(Sr,{size:14}),e.jsxs("select",{value:`${g}-${p}`,onChange:ee=>{const[I,_]=ee.target.value.split("-");f(I),b(_)},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(Fm,{size:14})]})]}),e.jsx("div",{className:"project-grid",children:E.map(({project:ee,health:I})=>{const _=d.find(J=>J.id===ee.nodeId),N=_?void 0:ee._sourceNodeName;return e.jsx(kw,{project:ee,health:I,node:_,nodeNameFallback:N,onSelect:$,onPause:r,onResume:l,onRemove:o},ee.id)})}),E.length===0&&e.jsxs("div",{className:"project-overview__no-results",children:[e.jsx(Sr,{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 Cw=45e3,Ew=3e3,Mw=2e3,Aw=1500,Id="fusion:sse-client-id";let Ri=null;const ei=new Map;function $d(){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 Ch(){if(!(typeof window>"u")){if(Ri)return Ri;try{const t=window.sessionStorage.getItem(Id);if(t)return Ri=t,t;const n=$d();return window.sessionStorage.setItem(Id,n),Ri=n,n}catch{return Ri=$d(),Ri}}}function Eh(t){if(!(typeof window>"u"))try{return{parsed:new URL(t,window.location.origin),preserveRelativePath:t.startsWith("/")}}catch{return}}function Mh(t){return t.origin===window.location.origin&&t.pathname==="/api/events"}function Pw(t){const n=Ch();if(!n)return t;const s=Eh(t);return!s||!Mh(s.parsed)?t:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Jo(t,n){const s=Ch();if(!s)return;const i=Eh(t);if(!i||!Mh(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 Rw(t){if(typeof window>"u")return;const n=Jo(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 Qr(t){t.keepaliveTimer&&(clearInterval(t.keepaliveTimer),t.keepaliveTimer=null)}function Dd(t){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Jo(t.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),Aw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function Tw(t){Qr(t),Jo(t.url,"keepalive")&&(Dd(t),t.keepaliveTimer=window.setInterval(()=>{Dd(t)},Mw))}if(typeof window<"u"){const t=()=>{for(const s of Array.from(ei.values()))if(!s.closed){if(Qr(s),Rw(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(ei.values()))i.subscribers.size!==0&&(i.closed=!1,Yo(i))};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t),window.addEventListener("pageshow",n)}function Ca(t){t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),t.heartbeatTimer=setTimeout(()=>{Ah(t)},Cw)}function Ah(t){if(t.heartbeatTimer&&(clearTimeout(t.heartbeatTimer),t.heartbeatTimer=null),t.es&&(t.es.close(),t.es=null),Qr(t),t.nativeListeners.clear(),t.closed||t.subscribers.size===0||t.reconnectTimer)return;const n=ei.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=ei.get(t.url);s&&s===t&&t.subscribers.size>0&&Yo(t)},Ew)}}function Yo(t){if(t.es||t.closed)return;t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=null);const n=new EventSource(Ps(Pw(t.url)));t.es=n,Tw(t),n.addEventListener("open",()=>{Ca(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);Ah(t)}),n.addEventListener("message",()=>Ca(t)),n.addEventListener("heartbeat",()=>Ca(t)),Ph(t),Ca(t)}function Ph(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=>{Ca(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 _w(t){t.closed=!0,t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),Qr(t),t.reconnectTimer&&clearTimeout(t.reconnectTimer),t.es&&t.es.close(),t.es=null,t.nativeListeners.clear(),ei.delete(t.url)}function Os(t,n={}){let s=ei.get(t);s||(s={url:t,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ei.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),Yo(s),Ph(s);let r=!0;return()=>{if(!r)return;r=!1;const l=ei.get(t);l&&(l.subscribers.delete(i),l.subscribers.size===0&&_w(l))}}const Qo="kb-planning-last-description",Xo="kb-subtask-last-description",Zo="kb-mission-last-goal";function Iw(t,n){ms(Qo,t,n)}function $w(t){return In(Qo,t)||""}function Ti(t){Da(Qo,t)}function Dw(t,n){ms(Xo,t,n)}function Fw(t){return In(Xo,t)||""}function xl(t){Da(Xo,t)}function Lw(t,n){ms(Zo,t,n)}function zw(t){return In(Zo,t)||""}function Ys(t){Da(Zo,t)}function Ow(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 Bw(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 Uw(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=Uw(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?Ow(l):void 0,h=l.question&&u!==void 0?Bw(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 Fd="fusion-tab-id";function Hw(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Si(){if(typeof window>"u")return"server-tab";const t=window.sessionStorage.getItem(Fd);if(t)return t;const n=Hw();return window.sessionStorage.setItem(Fd,n),n}function Xr(t){const n=a.useMemo(()=>Si(),[]),[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(Tk(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=_k(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:Os("/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(Ik(t,n)),i(!1),l(null)}finally{d(!1)}}},[t,n]);return{isLockedByOther:s,currentHolder:r,takeControl:m,isLoading:o}}const qw="fusion:ai-session-sync",Ld="fusion:ai-session-sync",Vw=3e4,Ww=6e4;function Ts(){return Date.now()}function Kw(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function zd(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 Gw{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=Kw(),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(qw),this.channel.onmessage=s=>{const i=zd(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Ld||!s.newValue))try{const i=JSON.parse(s.newValue),r=zd(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})},Vw)}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(Ld,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>Ww;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 _s=new Gw;function aa(){const t=a.useSyncExternalStore(d=>_s.subscribe(d),()=>_s.getSnapshot(),()=>_s.getSnapshot());a.useEffect(()=>{_s.requestSync()},[]);const n=a.useCallback(d=>{_s.broadcastUpdate(d)},[]),s=a.useCallback(d=>{_s.broadcastCompleted(d)},[]),i=a.useCallback((d,m)=>{_s.broadcastLock(d,m)},[]),r=a.useCallback((d,m)=>{_s.broadcastUnlock(d,m)},[]),l=a.useCallback(d=>{_s.broadcastHeartbeat(d)},[]),o=a.useCallback(()=>{_s.requestSync()},[]);return{tabId:t.tabId,sessions:t.sessions,activeTabMap:t.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:l,requestSync:o}}function Jw(t,n){return t&&n?`${t}/${n}`:""}function Yw(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 Qw=["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 Xw({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,f]=a.useState([]),[p,b]=a.useState([]),[x,v]=a.useState(null),[y,A]=a.useState(!1),j=a.useRef(!1),[P,w]=a.useState(""),[E,k]=a.useState(!0),[T,C]=a.useState(!1),[$,F]=a.useState(!1),[ee,I]=a.useState(!1),_=a.useRef(null),N=a.useRef(null),J=a.useRef(null),K=a.useRef(null),[G,M]=a.useState(l??null),O=a.useMemo(()=>Si(),[]),{isLockedByOther:X,takeControl:S,isLoading:V}=Xr(t?G:null),{activeTabMap:de,broadcastUpdate:L,broadcastCompleted:Z,broadcastLock:D,broadcastUnlock:me,broadcastHeartbeat:q}=aa(),[W,ce]=a.useState(void 0),[Se,ve]=a.useState(void 0),[Ee,Ae]=a.useState([]),[Oe,Fe]=a.useState(!0),[rt,Pe]=a.useState(null),[Ie,Be]=a.useState([]),[nt,De]=a.useState([]),Qe=Jw(W,Se);a.useEffect(()=>{(async()=>{try{Fe(!0);const qe=await Jn();Ae(qe.models),Be(qe.favoriteProviders),De(qe.favoriteModels)}catch(qe){Pe(ge(qe)||"Failed to load models")}finally{Fe(!1)}})()},[]);const ie=a.useCallback(Me=>{Be(qe=>{const oe=qe,We=oe.includes(Me)?oe.filter(Re=>Re!==Me):[Me,...oe];return Gt({favoriteProviders:We,favoriteModels:nt}).catch(()=>{Be(oe)}),We})},[nt]),te=a.useCallback(Me=>{De(qe=>{const oe=qe,We=oe.includes(Me)?oe.filter(Re=>Re!==Me):[Me,...oe];return Gt({favoriteProviders:Ie,favoriteModels:We}).catch(()=>{De(oe)}),We})},[Ie]),fe=a.useCallback((Me,qe)=>{if(!Me||!qe)return"Using default";const oe=Ee.find(Ve=>Ve.provider===Me&&Ve.id===qe);return oe?`${oe.provider}/${oe.id}`:`${Me}/${qe}`},[Ee]),ae=a.useCallback(Me=>{N.current?.close();const qe=yk(Me,i,{onThinking:oe=>{w(Ve=>Ve+oe),L({sessionId:Me,status:"generating",needsInput:!1,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onQuestion:oe=>{C(!1),F(!1),Ys(i),c({type:"question",sessionId:Me,question:oe}),w(""),A(!0),L({sessionId:Me,status:"awaiting_input",needsInput:!0,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onSummary:oe=>{C(!1),F(!1),Ys(i),c({type:"summary",sessionId:Me,summary:oe}),v(oe),w(""),A(!0),L({sessionId:Me,status:"complete",needsInput:!1,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onError:oe=>{const Ve=oe||"Session failed while contacting the AI.";C(!1),F(!1),h(null),c({type:"error",sessionId:Me,errorMessage:Ve}),w(""),A(!0),J.current=Me,L({sessionId:Me,status:"error",needsInput:!1,owningTabId:O,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null}),Z({sessionId:Me,status:"error"})},onComplete:()=>{C(!1),F(!1),J.current=null,Z({sessionId:Me,status:"complete"})},onConnectionStateChange:oe=>{C(oe==="reconnecting")}});N.current=qe},[Z,L,o,i,O]),_e=a.useCallback(async Me=>{const qe=Me??o;if(qe.trim()){h(null),w(""),f([]),b([]),C(!1),c({type:"loading"});try{const{sessionId:oe}=await gk(qe.trim(),i,W&&Se?{modelProvider:W,modelId:Se}:void 0);J.current=oe,M(oe),Ys(i),ae(oe),f([])}catch(oe){C(!1),h(ge(oe)||"Failed to start interview session"),c({type:"initial"}),J.current=null,M(null)}}},[ae,o,W,Se,i]);a.useEffect(()=>{t&&m.type==="initial"&&_.current?.focus()},[t,m.type]),a.useEffect(()=>{if(t&&r&&!j.current&&m.type==="initial"){d(r);const Me=setTimeout(()=>{j.current=!0,_e(r)},0);return()=>clearTimeout(Me)}else if(t&&!r&&!j.current&&m.type==="initial"){const Me=zw(i);Me&&d(Me)}},[t,r,m.type,_e]),a.useEffect(()=>{t||(j.current=!1,C(!1),F(!1),M(null))},[t]),a.useEffect(()=>{if(!t||!l||m.type!=="initial")return;let Me=!1;return ti(l).then(qe=>{if(Me||!qe)return;const oe=Gi(qe.conversationHistory);if(b(oe),M(qe.id),f(oe.map(Ve=>Ve.response).filter(Ve=>!!(Ve&&typeof Ve=="object"&&!Array.isArray(Ve)))),qe.status==="awaiting_input"&&qe.currentQuestion)try{Ys(i);const Ve=JSON.parse(qe.currentQuestion);J.current=qe.id,A(!0),c({type:"question",sessionId:qe.id,question:Ve})}catch{h("Failed to restore session question.")}else if(qe.status==="complete"&&qe.result)try{Ys(i);const Ve=JSON.parse(qe.result);J.current=qe.id,A(!0),v(Ve),c({type:"summary",sessionId:qe.id,summary:Ve})}catch{h("Failed to restore session result.")}else qe.status==="generating"?(J.current=qe.id,A(!0),qe.thinkingOutput&&w(qe.thinkingOutput),c({type:"loading"}),ae(qe.id)):qe.status==="error"&&(J.current=qe.id,A(!0),h(null),c({type:"error",sessionId:qe.id,errorMessage:qe.error??"The session encountered an error."}))}).catch(()=>{Me||h("Failed to resume session.")}),()=>{Me=!0}},[ae,t,l,m.type,i]),a.useEffect(()=>{if(!t){K.current&&(me(K.current,O),K.current=null);return}if(G&&K.current!==G){K.current&&me(K.current,O),D(G,O),K.current=G;return}!G&&K.current&&(me(K.current,O),K.current=null)},[D,me,t,G,O]),a.useEffect(()=>{if(!t||!G||K.current!==G)return;q(O);const Me=setInterval(()=>{q(O)},3e4);return()=>{clearInterval(Me)}},[q,t,G,O]),a.useEffect(()=>()=>{N.current?.close(),N.current=null,K.current&&(me(K.current,O),K.current=null)},[me,O]),a.useEffect(()=>{if(!t)return;const Me=qe=>{(m.type==="question"||m.type==="summary")&&(qe.preventDefault(),qe.returnValue=""),N.current?.close()};return window.addEventListener("beforeunload",Me),()=>window.removeEventListener("beforeunload",Me)},[t,m]);const ke=a.useCallback(()=>{N.current?.close(),N.current=null,n()},[n]),He=a.useCallback(async()=>{if(o&&Lw(o,i),!(y&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(N.current?.close(),N.current=null,m.type==="question"||m.type==="summary"||m.type==="error")try{await ph(m.sessionId,i,O)}catch{}d(""),c({type:"initial"}),h(null),f([]),b([]),v(null),w(""),C(!1),F(!1),A(!1),I(!1),ce(void 0),ve(void 0),J.current=null,M(null),n()}},[o,y,m,n,i,O]);a.useEffect(()=>{if(!t)return;const Me=qe=>{qe.key==="Escape"&&(y?confirm("Are you sure you want to close? Your interview progress will be lost.")&&He():He())};return document.addEventListener("keydown",Me),()=>document.removeEventListener("keydown",Me)},[t,y,He]);const dt=a.useCallback(async Me=>{if(m.type!=="question")return;const{sessionId:qe}=m;h(null),f(oe=>[...oe,Me]),b(oe=>[...oe,{question:m.question,response:Me}]),c({type:"loading"}),w("");try{ae(qe),await bk(qe,Me,i,O),A(!0)}catch(oe){N.current?.close(),N.current=null,h(ge(oe)||"Failed to submit response"),c({type:"question",sessionId:qe,question:m.question})}},[m,i,O,ae]),ht=a.useCallback(async()=>{if(m.type!=="error")return;const Me=m.sessionId;h(null),F(!0),w(""),c({type:"loading"}),ae(Me);try{J.current=Me,M(Me),await xk(Me,i,O)}catch(qe){let oe=qe;if((ge(qe)||"").includes("not in an error state"))try{const We=await ti(Me);if(!We)throw new Error("Failed to refresh interview session.");const Re=Gi(We.conversationHistory);if(b(Re),f(Re.map(et=>et.response).filter(et=>!!(et&&typeof et=="object"&&!Array.isArray(et)))),J.current=We.id,M(We.id),A(!0),We.status==="generating")w(We.thinkingOutput??""),c({type:"loading"}),N.current?.isConnected()||ae(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 et=JSON.parse(We.currentQuestion);c({type:"question",sessionId:We.id,question:et}),N.current?.isConnected()||ae(We.id)}else if(We.status==="complete"){if(!We.result)throw new Error("Interview session is complete but has no result.");Ys(i);const et=JSON.parse(We.result);v(et),c({type:"summary",sessionId:We.id,summary:et})}else We.status==="error"&&c({type:"error",sessionId:We.id,errorMessage:We.error??"Retry failed. Please try again."});C(!1);return}catch(We){oe=We}N.current?.close(),N.current=null,c({type:"error",sessionId:Me,errorMessage:ge(oe)||"Retry failed. Please try again."}),C(!1)}finally{F(!1)}},[ae,i,O,m]),he=a.useCallback(async()=>{if(m.type==="summary"){h(null),I(!0);try{const Me=await vk(m.sessionId,x||void 0,i);s(Me),Ys(i),N.current?.close(),N.current=null,d(""),c({type:"initial"}),h(null),f([]),b([]),v(null),w(""),C(!1),F(!1),A(!1),I(!1),J.current=null,M(null),n()}catch(Me){h(ge(Me)||"Failed to create mission"),I(!1)}}},[m,x,s,n,i]),ne=()=>m.type==="question"?Math.min(g.length+1,6):6,ye=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",we=G?de.get(G):null,st=we&&we.tabId!==O,be=!!(st&&!we.stale),it=X&&(!st||we.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:Me=>Me.target===Me.currentTarget&&He(),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(ss,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Plan Mission with AI"})]}),e.jsxs("div",{className:"modal-header-actions",children:[ye&&e.jsx("button",{className:"modal-send-to-background",onClick:ke,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:He,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[u&&e.jsx("div",{className:"form-error planning-error",children:u}),T&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),be&&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(On,{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:_,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:Me=>d(Me.target.value),onKeyDown:Me=>{Me.key==="Enter"&&!Me.shiftKey&&o.trim()&&(Me.preventDefault(),_e())}})]}),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:Qw.map((Me,qe)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>d(Me),children:Me.length>45?Me.slice(0,45)+"...":Me},qe))})]}),e.jsxs("div",{className:"planning-model-select-group",children:[e.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Oe&&e.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),e.jsx(Jt,{id:"mission-interview-modal-model",label:"Planning Model",value:Qe,onChange:Me=>{const{provider:qe,modelId:oe}=Yw(Me);ce(qe),ve(oe)},models:Ee,disabled:Oe,favoriteProviders:Ie,onToggleFavorite:ie,favoriteModels:nt,onToggleModelFavorite:te}),rt&&e.jsxs("div",{className:"form-hint form-hint-error",children:[rt," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Fe(!0);const Me=await Jn();Ae(Me.models),Be(Me.favoriteProviders),De(Me.favoriteModels),Pe(null)}catch(Me){Pe(ge(Me)||"Failed to load models")}finally{Fe(!1)}})()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${W&&Se?"model-badge-custom":"model-badge-default"}`,children:fe(W,Se)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>_e(),disabled:!o.trim(),children:[e.jsx(ss,{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:P?"AI is thinking...":"Preparing next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>k(!E),type:"button",children:E?"Hide thinking":"Show thinking"}),E&&P&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:P})})]})]}),m.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[p.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:p}),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:$,children:[$?e.jsx(ct,{size:14,className:"spin"}):e.jsx(An,{size:14}),e.jsx("span",{className:"icon-ml-6",children:$?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:He,disabled:$,children:"Cancel"})]})]})]})}),m.type==="question"&&e.jsx(Zw,{question:m.question,progress:ne(),historyEntries:p,onSubmit:dt}),m.type==="summary"&&x&&e.jsx(eN,{summary:x,historyEntries:p,onSummaryChange:v,onApprove:he,onStartOver:()=>{c({type:"initial"}),A(!1),v(null),f([]),b([]),M(null),N.current?.close(),N.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(Vr,{size:16}),e.jsx("span",{children:it?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),it&&e.jsx("button",{type:"button",onClick:()=>{S()},disabled:V,className:"btn btn-primary session-lock-take-control",children:V?"Taking control...":"Take Control"})]})})]})]})}):null}function Zw({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 f=g.target.checked?[...h,u.id]:h.filter(p=>p!==u.id);l({[t.id]:f})}}),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(nn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Lt,{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(Oa,{size:16,className:"icon-ml-4"})]})})]})}function eN({summary:t,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:l}){const[o,d]=a.useState(()=>new Set(t.milestones.map((j,P)=>P))),[m,c]=a.useState(()=>{const j=new Set;return t.milestones.forEach((P,w)=>{P.slices.forEach((E,k)=>j.add(`${w}-${k}`))}),j}),u=j=>{d(P=>{const w=new Set(P);return w.has(j)?w.delete(j):w.add(j),w})},h=j=>{c(P=>{const w=new Set(P);return w.has(j)?w.delete(j):w.add(j),w})},g=(j,P)=>{const w=[...t.milestones];w[j]={...w[j],...P},s({...t,milestones:w})},f=(j,P,w)=>{const E=[...t.milestones],k=[...E[j].slices];k[P]={...k[P],...w},E[j]={...E[j],slices:k},s({...t,milestones:E})},p=(j,P,w,E)=>{const k=[...t.milestones],T=[...k[j].slices],C=[...T[P].features];C[w]={...C[w],...E},T[P]={...T[P],features:C},k[j]={...k[j],slices:T},s({...t,milestones:k})},b=j=>{const P=t.milestones.filter((w,E)=>E!==j);s({...t,milestones:P})},x=(j,P)=>{const w=[...t.milestones];w[j]={...w[j],slices:w[j].slices.filter((E,k)=>k!==P)},s({...t,milestones:w})},v=(j,P,w)=>{const E=[...t.milestones],k=[...E[j].slices];k[P]={...k[P],features:k[P].features.filter((T,C)=>C!==w)},E[j]={...E[j],slices:k},s({...t,milestones:E})},y=(j,P)=>{const w=[...t.milestones],E=[...w[j].slices];E[P]={...E[P],features:[...E[P].features,{title:"New feature",description:""}]},w[j]={...w[j],slices:E},s({...t,milestones:w})},A=t.milestones.reduce((j,P)=>j+P.slices.reduce((w,E)=>w+E.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(nn,{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,P)=>e.jsxs("div",{className:"roadmap-card",children:[e.jsxs("div",{className:"roadmap-card-header",onClick:()=>u(P),children:[o.has(P)?e.jsx(zt,{size:16,className:"icon-text-secondary"}):e.jsx(ln,{size:16,className:"icon-text-secondary"}),e.jsx(yi,{size:16,className:"icon-milestone"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:w=>g(P,{title:w.target.value}),onClick:w=>w.stopPropagation()}),t.milestones.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),b(P)},title:"Remove milestone",children:e.jsx(Ut,{size:14,className:"icon-text-secondary"})})]}),o.has(P)&&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:w=>g(P,{description:w.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:w=>g(P,{verification:w.target.value})})]}),j.slices.map((w,E)=>{const k=`${P}-${E}`;return e.jsxs("div",{className:"roadmap-slice-card",children:[e.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(k),children:[m.has(k)?e.jsx(zt,{size:14,className:"icon-text-secondary"}):e.jsx(ln,{size:14,className:"icon-text-secondary"}),e.jsx(po,{size:14,className:"icon-slice"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:T=>f(P,E,{title:T.target.value}),onClick:T=>T.stopPropagation()}),j.slices.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:T=>{T.stopPropagation(),x(P,E)},title:"Remove slice",children:e.jsx(Ut,{size:12,className:"icon-text-secondary"})})]}),m.has(k)&&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:w.verification||"",onChange:T=>f(P,E,{verification:T.target.value})})]}),w.features.map((T,C)=>e.jsxs("div",{className:"roadmap-feature-row",children:[e.jsx(oo,{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:T.title,onChange:$=>p(P,E,C,{title:$.target.value})}),T.description&&e.jsx("p",{className:"roadmap-feature-text",children:T.description}),T.acceptanceCriteria&&e.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",T.acceptanceCriteria]})]}),e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>v(P,E,C),title:"Remove feature",children:e.jsx(Ut,{size:12,className:"icon-text-secondary"})})]},C)),e.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(P,E),children:[e.jsx(Ht,{size:12}),"Add Feature"]})]})]},E)})]})]},P))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:r,disabled:l,children:[e.jsx(na,{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(nn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function tN({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),[f,p]=a.useState([]),[b,x]=a.useState([]),[v,y]=a.useState(null),[A,j]=a.useState(""),[P,w]=a.useState(!0),[E,k]=a.useState(!1),[T,C]=a.useState(!1),$=a.useRef(null),F=a.useRef(null),ee=a.useRef(null),I=a.useRef(null),[_,N]=a.useState(null),J=a.useMemo(()=>Si(),[]);Xr(t?_:null);const{activeTabMap:K,broadcastUpdate:G,broadcastCompleted:M,broadcastLock:O,broadcastUnlock:X,broadcastHeartbeat:S}=aa(),V=i==="milestone"?kk:Ck,de=i==="milestone"?jk:Ek,L=i==="milestone"?wk:Mk,Z=i==="milestone"?Nk:Ak,D=i==="milestone"?Sk:Pk,me=i==="milestone"?"Milestone":"Slice",q=i==="milestone"?"milestone_interview":"slice_interview",W=a.useCallback(De=>{F.current?.close();const Qe=L(De,d,{onThinking:ie=>{j(te=>te+ie),G({sessionId:De,status:"generating",needsInput:!1,owningTabId:J,type:q,title:l,projectId:d??null})},onQuestion:ie=>{k(!1),ce(),u({type:"question",sessionId:De,question:ie}),j(""),G({sessionId:De,status:"awaiting_input",needsInput:!0,owningTabId:J,type:q,title:l,projectId:d??null})},onSummary:ie=>{k(!1),ce(),u({type:"summary",sessionId:De,summary:ie}),y(ie),j(""),G({sessionId:De,status:"complete",needsInput:!1,owningTabId:J,type:q,title:l,projectId:d??null})},onError:ie=>{const te=ie||"Session failed while contacting the AI.";k(!1),g(null),u({type:"error",sessionId:De,errorMessage:te}),j(""),ee.current=De,G({sessionId:De,status:"error",needsInput:!1,owningTabId:J,type:q,title:l,projectId:d??null}),M({sessionId:De,status:"error"})},onComplete:()=>{k(!1),ee.current=null,M({sessionId:De,status:"complete"})},onConnectionStateChange:ie=>{k(ie==="reconnecting")}});F.current=Qe},[M,G,L,q,d,J,l]),ce=()=>{y(null),p([]),x([]),j("")},Se=a.useCallback(async()=>{g(null),ce(),k(!1),u({type:"loading"});try{const{sessionId:De}=await V(r,d);ee.current=De,N(De),W(De)}catch(De){k(!1),g(ge(De)||`Failed to start ${me.toLowerCase()} interview`),u({type:"initial"}),ee.current=null,N(null)}},[W,d,V,r,me]),ve=a.useCallback(async()=>{g(null),C(!0);try{await D(r,d),s(),u({type:"applied"})}catch(De){g(ge(De)||`Failed to skip ${me.toLowerCase()} interview`),C(!1)}},[s,d,D,r,me]);a.useEffect(()=>{t&&c.type==="initial"&&$.current?.focus()},[t,c.type]),a.useEffect(()=>{if(!t||!m||c.type!=="initial")return;let De=!1;return ti(m).then(Qe=>{if(De||!Qe)return;const ie=Gi(Qe.conversationHistory);if(x(ie),N(Qe.id),p(ie.map(te=>te.response).filter(te=>!!(te&&typeof te=="object"&&!Array.isArray(te)))),Qe.status==="awaiting_input"&&Qe.currentQuestion)try{const te=JSON.parse(Qe.currentQuestion);ee.current=Qe.id,u({type:"question",sessionId:Qe.id,question:te})}catch{g("Failed to restore session question.")}else if(Qe.status==="complete"&&Qe.result)try{const te=JSON.parse(Qe.result);ee.current=Qe.id,y(te),u({type:"summary",sessionId:Qe.id,summary:te})}catch{g("Failed to restore session result.")}else Qe.status==="generating"?(ee.current=Qe.id,Qe.thinkingOutput&&j(Qe.thinkingOutput),u({type:"loading"}),W(Qe.id)):Qe.status==="error"&&(ee.current=Qe.id,g(null),u({type:"error",sessionId:Qe.id,errorMessage:Qe.error??"The session encountered an error."}))}).catch(()=>{De||g("Failed to resume session.")}),()=>{De=!0}},[W,t,m,c.type]),a.useEffect(()=>{t||(k(!1),N(null))},[t]),a.useEffect(()=>{if(!(!t||!_)){if(I.current!==_){I.current&&X(I.current,J),O(_,J),I.current=_;return}!_&&I.current&&(X(I.current,J),I.current=null)}},[O,X,t,_,J]),a.useEffect(()=>{if(!t||!_||I.current!==_)return;S(J);const De=setInterval(()=>{S(J)},3e4);return()=>{clearInterval(De)}},[S,t,_,J]),a.useEffect(()=>()=>{F.current?.close(),F.current=null,I.current&&(X(I.current,J),I.current=null)},[X,J]);const Ee=a.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),Ae=a.useCallback(async()=>{F.current?.close(),F.current=null,ce(),u({type:"initial"}),g(null),ee.current=null,N(null),n()},[n]),Oe=a.useCallback(async De=>{if(c.type!=="question")return;const{sessionId:Qe}=c;g(null),p(ie=>[...ie,De]),x(ie=>[...ie,{question:c.question,response:De}]),u({type:"loading"}),j("");try{W(Qe),await de(Qe,De,d,J)}catch(ie){F.current?.close(),F.current=null,g(ge(ie)||"Failed to submit response"),u({type:"question",sessionId:Qe,question:c.question})}},[W,d,de,J,c]),Fe=a.useCallback(async()=>{if(c.type==="summary"){g(null),C(!0);try{await Z(c.sessionId,v||void 0,d),s(),u({type:"applied"})}catch(De){g(ge(De)||"Failed to apply interview results"),C(!1)}}},[Z,v,s,d,c]),rt=()=>c.type==="question"?Math.min(f.length+1,6):6,Pe=c.type==="loading"||c.type==="question"||c.type==="summary"||c.type==="error",Ie=_?K.get(_):null,nt=!!(Ie&&Ie.tabId!==J&&!Ie.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:De=>De.target===De.currentTarget&&Ae(),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(On,{size:20,className:"icon-triage"}),e.jsxs("h3",{children:["Plan ",me,": ",l]})]}),e.jsxs("div",{className:"modal-header-actions",children:[Pe&&e.jsx("button",{className:"modal-send-to-background",onClick:Ee,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:Ae,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[h&&e.jsx("div",{className:"form-error planning-error",children:h}),E&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),nt&&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(On,{size:32,className:"icon-triage-lg"}),e.jsxs("h4",{children:["Refine ",me," 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 Se(),children:[e.jsx(On,{size:16,className:"icon-mr-8"}),"Start Interview"]}),e.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ve(),disabled:T,children:[T?e.jsx(ct,{size:16,className:"spin"}):null,"Use Mission Context"]}),e.jsx("button",{className:"btn",onClick:Ae,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:()=>w(!P),type:"button",children:P?"Hide thinking":"Show thinking"}),P&&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:Ae,children:"Cancel"})})]})]})}),c.type==="question"&&e.jsx(nN,{question:c.question,progress:rt(),historyEntries:b,onSubmit:Oe}),c.type==="summary"&&v&&e.jsx(sN,{summary:v,historyEntries:b,onSummaryChange:y,onApply:Fe,onCancel:Ae,isApplying:T}),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(nn,{size:48,className:"icon-success"}),e.jsxs("h4",{children:[me," 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 nN({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 f=g.target.checked?[...h,u.id]:h.filter(p=>p!==u.id);l({[t.id]:f})}}),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(nn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Lt,{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(Oa,{size:16,className:"icon-ml-4"})]})})]})}function sN({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 f={...o,[h]:g};d(f),s(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-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(zt,{size:16}):e.jsx(ln,{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 ua={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)"}},Od={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)"}},Bd={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)"}},ar={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)"}},rr={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)"}},lr={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)"}},Ud={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)"}},iN=3;function aN(t){return t==="completed"?"planned":t==="needs_update"?"needs_update":"not_started"}function Hd({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 qd(t){return t?t.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const vl={title:"",description:"",status:"planning",autopilotEnabled:!1},yl={title:"",description:"",status:"planning",dependencies:[]},kl={title:"",description:"",status:"pending"},jl={title:"",description:"",acceptanceCriteria:"",status:"defined"},rN=3600*1e3;function Ir(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 lN(t){if(!t)return"healthy";const n=typeof t.lastErrorAt=="string"&&Date.now()-new Date(t.lastErrorAt).getTime()<=rN,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 oN(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 cN(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 wl(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 Rh=["feature_triaged","feature_completed"],Th=["slice_activated","slice_completed","milestone_completed"],_h=["mission_started","mission_paused","mission_resumed","mission_completed"],Ih=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Vd(t,n){switch(n){case"errors":return t==="error"||t==="warning";case"state_changes":return _h.includes(t);case"tasks":return Rh.includes(t);case"slices":return Th.includes(t);case"autopilot":return Ih.includes(t);default:return!0}}function dN(t){return t==="error"||t==="warning"?"mission-event__type--error":_h.includes(t)?"mission-event__type--state":Rh.includes(t)?"mission-event__type--task":Th.includes(t)?"mission-event__type--slice":Ih.includes(t)?"mission-event__type--autopilot":"mission-event__type--default"}function uN(t){return t.replace(/_/g," ")}function mN(t,n){return n?t==="watching"?`Watching since ${Ir(n)}`:`Last activation ${Ir(n)}`:null}function hN({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,f]=a.useState([]),[p,b]=a.useState(null),[x,v]=a.useState(!0),[y,A]=a.useState(!1),[j,P]=a.useState(!1),[w,E]=a.useState(null),[k,T]=a.useState(vl),[C,$]=a.useState(!1),[F,ee]=a.useState(new Set),[I,_]=a.useState(new Set),[N,J]=a.useState(null),[K,G]=a.useState(yl),[M,O]=a.useState(!1),[X,S]=a.useState(null),[V,de]=a.useState(kl),[L,Z]=a.useState(!1),[D,me]=a.useState(null),[q,W]=a.useState(null),[ce,Se]=a.useState(jl),[ve,Ee]=a.useState(!1),[Ae,Oe]=a.useState(null),[Fe,rt]=a.useState(null),[Pe,Ie]=a.useState(""),[Be,nt]=a.useState(!1),[De,Qe]=a.useState([]),[ie,te]=a.useState(void 0),fe=ie??d,[ae,_e]=a.useState(null),[ke,He]=a.useState(null),[dt,ht]=a.useState(null);a.useEffect(()=>{h&&fe&&nt(!0)},[h,fe]),a.useEffect(()=>{if(!h||fe)return;let H=!1;return fh(r).then(Ce=>{if(H)return;const ze=Ce.filter(yt=>yt.type==="mission_interview"&&(yt.status==="awaiting_input"||yt.status==="error"));Qe(ze)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{H=!0}},[h,r,fe]),a.useEffect(()=>{if(!h||!c)return;let H=!1;return ti(c).then(Ce=>{if(!(H||!Ce))try{const ze=JSON.parse(Ce.inputPayload||"{}");ze.targetId&&ze.targetType&&_e({type:ze.targetType,id:ze.targetId,title:ze.targetTitle||Ce.title,resumeSessionId:c})}catch{_e({type:"milestone",id:"",title:Ce.title,resumeSessionId:c})}}).catch(Ce=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),u?.())}),()=>{H=!0}},[h,c,u]);const[he,ne]=a.useState(null),[ye,we]=a.useState(new Map),[st,be]=a.useState(null),[it,Me]=a.useState({title:"",assertion:"",status:"pending"}),[qe,oe]=a.useState(!1),[Ve,We]=a.useState(null),[Re,et]=a.useState(new Map),[xt,wt]=a.useState(new Set),[Et,Rt]=a.useState(new Set),[$t,_t]=a.useState(null),[vt,Dt]=a.useState(new Map),[Ke,bt]=a.useState(null),[Le,lt]=a.useState(null),[xe,U]=a.useState(!0),[Ne,pt]=a.useState(new Set),[kt,je]=a.useState(new Map),[Ge,gt]=a.useState(null),[qt,gn]=a.useState(new Map),[Wt,Rn]=a.useState(null),[Kt,$n]=a.useState(new Map),[bn,on]=a.useState(new Map),[en,xn]=a.useState("structure"),[wn,Dn]=a.useState([]),cn=a.useRef([]),sn=a.useRef([]),Vt=a.useRef(null),Nn=a.useRef(null),Un=a.useRef("structure"),Sn=a.useRef("all"),[Hn,Qn]=a.useState(!1),[Q,Ue]=a.useState(0),[R,B]=a.useState("all"),[re,pe]=a.useState(new Set),ue=a.useRef(null),Te=a.useRef(null);sn.current=g,Vt.current=p,Nn.current=Ke,Un.current=en,Sn.current=R;const ut=a.useCallback((H="auto")=>{const Ce=Te.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:H});return}const ze=ue.current;ze&&(ze.scrollTop=ze.scrollHeight)},[]),Mt=a.useCallback(()=>{const H=ue.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),dn=a.useCallback(async H=>{if(H.length===0){on(new Map);return}const Ce=await Hy(r);on(ze=>{const yt=new Map(ze);for(const[Qt,At]of Object.entries(Ce))oN(At)&&yt.set(Qt,At);return yt})},[r]),Je=a.useCallback(async()=>{try{v(!0);const H=await Ly(r);f(H),dn(H)}catch(H){i(ge(H)||"Failed to load missions","error")}finally{v(!1)}},[i,r,dn]),ot=a.useCallback(async H=>{try{A(!0);const Ce=await hh(H,r);if(b(Ce),Ce.milestones.length>0){const ze=Ce.milestones[0].id;bt(ze),U(!0),ee(new Set([ze])),hl(ze,r).then(yt=>{we(Qt=>{const At=new Map(Qt);return At.set(ze,yt),At})}).catch(()=>{}),pl(ze,r).then(yt=>{Dt(Qt=>{const At=new Map(Qt);return At.set(ze,yt),At})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&_(new Set([Ce.milestones[0].slices[0].id]))}else bt(null),lt(null)}catch(Ce){i(ge(Ce)||"Failed to load mission details","error")}finally{A(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Ke){lt(null);return}let H=!1;return lt(null),od(Ke,r).then(Ce=>{if(!H){if(!wl(Ce)){lt(null);return}lt(Ce),Dt(ze=>{const yt=new Map(ze);return yt.set(Ke,Ce.rollup),yt})}}).catch(()=>{H||lt(null)}),()=>{H=!0}},[h,Ke,r]),a.useEffect(()=>{U(!0)},[Ke]);const qn=a.useCallback(H=>{!H||H!==Nn.current||od(H,r).then(Ce=>{Nn.current!==H||!wl(Ce)||(lt(Ce),Dt(ze=>{const yt=new Map(ze);return yt.set(H,Ce.rollup),yt}))}).catch(()=>{})},[r]),le=a.useCallback(async(H,Ce)=>{const ze=Ce?.append??!1,yt=ze?cn.current.length:0;ze||(Qn(!0),pe(new Set));try{const Qt=await Uy(H,{limit:50,offset:yt,eventType:void 0},r),At=Qt.events.filter(Bt=>Vd(Bt.eventType,R));Dn(Bt=>{if(!ze)return At;const Ye=new Set(Bt.map(jt=>jt.id)),Ze=[...Bt];for(const jt of At)Ye.has(jt.id)||Ze.push(jt);return Ze}),Ue(Qt.total),ze||requestAnimationFrame(()=>{ut("auto")})}catch(Qt){i(ge(Qt)||"Failed to load mission activity","error")}finally{ze||Qn(!1)}},[i,R,r,ut]);a.useEffect(()=>{cn.current=wn},[wn]),a.useEffect(()=>{h&&(Je(),b(null),bt(null),lt(null),Dn([]),Ue(0),xn("structure"),B("all"),pe(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||!p||en!=="activity"||le(p.id)},[en,h,le,p,R]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const Ce=`/api/events${H.size>0?`?${H.toString()}`:""}`,ze=()=>{dn(sn.current)},yt=_n=>{ze();const hn=_n;if(hn.data)try{const Tt=JSON.parse(hn.data);Tt?.id&&f(di=>di.map(vs=>vs.id===Tt.id?{...vs,...Tt}:vs))}catch{}Vt.current&&ot(Vt.current.id)},Qt=_n=>{ze(),Vt.current&&ot(Vt.current.id)},At=()=>{ze(),Vt.current&&ot(Vt.current.id)},Bt=_n=>{ze(),Vt.current&&ot(Vt.current.id)},Ye=_n=>{const hn=_n;if(hn.data)try{const Tt=JSON.parse(hn.data);Tt&&Tt.featureId&&(oi(Tt.featureId),Ei(Tt.featureId),Tt.milestoneId&&qn(Tt.milestoneId))}catch{}},Ze=_n=>{const hn=_n;if(hn.data)try{const Tt=JSON.parse(hn.data);Tt&&Tt.featureId&&(oi(Tt.featureId),Ei(Tt.featureId),Tt.milestoneId&&qn(Tt.milestoneId),Vt.current&&ot(Vt.current.id))}catch{}},jt=_n=>{const hn=_n;if(hn.data)try{const Tt=JSON.parse(hn.data);Tt&&Tt.milestoneId&&(Js(Tt.milestoneId),qn(Tt.milestoneId))}catch{}},Xt=_n=>{const hn=_n;if(hn.data)try{const Tt=JSON.parse(hn.data);Tt&&Tt.milestoneId&&(ri(Tt.milestoneId),Js(Tt.milestoneId),qn(Tt.milestoneId))}catch{}};return Os(Ce,{events:{"mission:updated":yt,"slice:updated":Qt,"feature:updated":At,"milestone:updated":Bt,"mission:event":_n=>{ze();const hn=Vt.current;if(!hn||Un.current!=="activity")return;const Tt=Mt(),di=_n;if(di.data)try{const vs=JSON.parse(di.data);if(!cN(vs)||vs.missionId!==hn.id||!Vd(vs.eventType,Sn.current))return;Dn(Hs=>{const dl=Hs.filter(ul=>ul.id!==vs.id);return[vs,...dl].slice(0,100)}),Ue(Hs=>Hs+1),Tt&&requestAnimationFrame(()=>{const Hs=ue.current;Hs&&(Hs.scrollTop=0)})}catch{}},"validator-run:started":Ye,"validator-run:completed":Ze,"milestone:validation:updated":jt,"assertion:created":Xt,"assertion:updated":Xt,"assertion:deleted":Xt,"assertion:linked":Xt,"assertion:unlinked":Xt,"fix-feature:created":_n=>{const hn=_n;if(hn.data)try{const Tt=JSON.parse(hn.data);if(Tt&&Tt.sourceFeatureId){oi(Tt.sourceFeatureId);const di=Tt?.feature?.sliceId,vs=Vt.current;if(di&&vs){const Hs=vs.milestones.find(dl=>dl.slices.some(ul=>ul.id===di));Hs&&qn(Hs.id)}Vt.current&&ot(Vt.current.id)}}catch{}}}})},[h,Mt,ot,dn,r,qn]);const mt=a.useCallback(()=>{P(!0),E(null),T(vl)},[]),Nt=a.useCallback(H=>{E(H.id),P(!1),T({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),Ct=a.useCallback(()=>{E(null),P(!1),T(vl)},[]),un=a.useCallback(async()=>{if(!k.title.trim()){i("Mission title is required","error");return}try{if($(!0),j)await zy({title:k.title.trim(),description:k.description.trim()||void 0,autopilotEnabled:k.autopilotEnabled},r),i("Mission created","success");else if(w){const H={title:k.title.trim(),description:k.description.trim()||void 0,status:k.status,autopilotEnabled:k.autopilotEnabled};k.autopilotEnabled&&(H.autoAdvance=!0),await Oy(w,H,r),i("Mission updated","success"),p?.id===w&&await ot(w)}await Je(),Ct()}catch(H){i(ge(H)||"Failed to save mission","error")}finally{$(!1)}},[k,j,w,i,Je,ot,p,Ct,r]),mn=a.useCallback(async H=>{try{await By(H,r),i("Mission deleted","success"),p?.id===H&&b(null),await Je(),ne(null)}catch(Ce){i(ge(Ce)||"Failed to delete mission","error")}},[i,Je,p,r]),pn=a.useCallback(()=>{O(!0),J(null),G(yl)},[]),fn=a.useCallback(H=>{J(H.id),O(!1),G({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),vn=a.useCallback(()=>{J(null),O(!1),G(yl)},[]),Cn=a.useCallback(async()=>{if(!K.title.trim()){i("Milestone title is required","error");return}try{$(!0),M&&p?(await qy(p.id,{title:K.title.trim(),description:K.description.trim()||void 0,dependencies:K.dependencies},r),i("Milestone created","success")):N&&(await Vy(N,{title:K.title.trim(),description:K.description.trim()||void 0,status:K.status,dependencies:K.dependencies},r),i("Milestone updated","success")),await ot(p.id),vn()}catch(H){i(ge(H)||"Failed to save milestone","error")}finally{$(!1)}},[K,M,N,p,i,ot,vn,k.title,r]),ls=a.useCallback(async H=>{try{await Wy(H,r),i("Milestone deleted","success"),await ot(p.id),ne(null)}catch(Ce){i(ge(Ce)||"Failed to delete milestone","error")}},[i,ot,p,r]),Vn=a.useCallback(H=>{bt(H),U(!0),ee(Ce=>{const ze=new Set(Ce);return!ze.has(H)?(ze.add(H),hl(H,r).then(Qt=>{we(At=>{const Bt=new Map(At);return Bt.set(H,Qt),Bt})}).catch(()=>{}),pl(H,r).then(Qt=>{Dt(At=>{const Bt=new Map(At);return Bt.set(H,Qt),Bt})}).catch(()=>{})):ze.delete(H),ze})},[r]),En=a.useCallback(H=>{me(H),Z(!0),S(null),de(kl)},[]),Tn=a.useCallback(H=>{S(H.id),Z(!1),de({title:H.title,description:H.description||"",status:H.status})},[]),Xn=a.useCallback(()=>{S(null),Z(!1),me(null),de(kl)},[]),yn=a.useCallback(async()=>{if(!V.title.trim()){i("Slice title is required","error");return}try{$(!0),L&&D?(await Ky(D,{title:V.title.trim(),description:V.description.trim()||void 0},r),i("Slice created","success")):X&&(await Gy(X,{title:V.title.trim(),description:V.description.trim()||void 0,status:V.status},r),i("Slice updated","success")),await ot(p.id),Xn()}catch(H){i(ge(H)||"Failed to save slice","error")}finally{$(!1)}},[V,L,X,D,p,i,ot,Xn,r]),Wn=a.useCallback(async H=>{try{await Jy(H,r),i("Slice deleted","success"),await ot(p.id),ne(null)}catch(Ce){i(ge(Ce)||"Failed to delete slice","error")}},[i,ot,p,r]),fs=a.useCallback(async H=>{try{await Yy(H,r),i("Slice activated","success"),await ot(p.id)}catch(Ce){i(ge(Ce)||"Failed to activate slice","error")}},[i,ot,p,r]),Zn=a.useCallback(H=>{_(Ce=>{const ze=new Set(Ce);return ze.has(H)?ze.delete(H):ze.add(H),ze})},[]),gs=a.useCallback(H=>{Oe(H),Ee(!0),W(null),Se(jl)},[]),Fn=a.useCallback(H=>{W(H.id),Ee(!1),Se({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),se=a.useCallback(()=>{W(null),Ee(!1),Oe(null),Se(jl)},[]),tt=a.useCallback(async()=>{if(!ce.title.trim()){i("Feature title is required","error");return}try{$(!0),ve&&Ae?(await Qy(Ae,{title:ce.title.trim(),description:ce.description.trim()||void 0,acceptanceCriteria:ce.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):q&&(await Xy(q,{title:ce.title.trim(),description:ce.description.trim()||void 0,acceptanceCriteria:ce.acceptanceCriteria.trim()||void 0,status:ce.status},r),i("Feature updated","success")),await ot(p.id),se()}catch(H){i(ge(H)||"Failed to save feature","error")}finally{$(!1)}},[ce,ve,q,Ae,p,i,ot,se,r]),ft=a.useCallback(async H=>{try{await Zy(H,r),i("Feature deleted","success"),await ot(p.id),ne(null)}catch(Ce){i(ge(Ce)||"Failed to delete feature","error")}},[i,ot,p,r]),It=a.useCallback(async()=>{if(!Fe||!Pe.trim()){i("Task ID is required","error");return}try{await ek(Fe,Pe.trim(),r),i("Feature linked to task","success"),await ot(p.id),rt(null),Ie("")}catch(H){i(ge(H)||"Failed to link feature to task","error")}},[Fe,Pe,i,ot,p,r]),Cs=a.useCallback(async H=>{try{await tk(H,r),i("Feature unlinked from task","success"),await ot(p.id)}catch(Ce){i(ge(Ce)||"Failed to unlink feature","error")}},[i,ot,p,r]),bs=a.useCallback(async H=>{try{$(!0),await nk(H,void 0,void 0,r),i("Feature triaged — task created","success"),await ot(p.id)}catch(Ce){i(ge(Ce)||"Failed to triage feature","error")}finally{$(!1)}},[i,ot,p,r]),il=a.useCallback(async H=>{ht(H);try{const Ce=await Rk(H,r);He({featureId:H,enrichedDescription:Ce.description})}catch{await bs(H)}finally{ht(null)}},[bs,r]),Xa=a.useCallback(async()=>{ke&&(He(null),await bs(ke.featureId))},[bs,ke]),al=a.useCallback(()=>{He(null)},[]),rl=a.useCallback(async H=>{try{$(!0);const Ce=await sk(H,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await ot(p.id)}catch(Ce){i(ge(Ce)||"Failed to triage slice features","error")}finally{$(!1)}},[i,ot,p,r]),ri=a.useCallback(async H=>{try{const Ce=await hl(H,r);we(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch{}},[r]),Js=a.useCallback(async H=>{try{const Ce=await pl(H,r);Dt(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch{}},[r]),vc=a.useCallback(async H=>{if(!it.title.trim()||!it.assertion.trim()){i("Title and assertion text are required","error");return}try{$(!0),await ik(H,{title:it.title.trim(),assertion:it.assertion.trim(),status:it.status},r),i("Assertion created","success"),await ri(H),await Js(H),oe(!1),Me({title:"",assertion:"",status:"pending"})}catch(Ce){i(ge(Ce)||"Failed to create assertion","error")}finally{$(!1)}},[it,i,ri,Js,r]),Us=a.useCallback(H=>{be(H.id),Me({title:H.title,assertion:H.assertion,status:H.status})},[]),li=a.useCallback(()=>{be(null),oe(!1),Me({title:"",assertion:"",status:"pending"})},[]),ll=a.useCallback(async(H,Ce)=>{if(!it.title.trim()||!it.assertion.trim()){i("Title and assertion text are required","error");return}try{$(!0),await ak(H,{title:it.title.trim(),assertion:it.assertion.trim(),status:it.status},r),i("Assertion updated","success"),await ri(Ce),await Js(Ce),li()}catch(ze){i(ge(ze)||"Failed to update assertion","error")}finally{$(!1)}},[it,i,ri,Js,li,r]),Rs=a.useCallback(async H=>{try{const Ce=await ok(H,r);et(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch{}},[r]),yc=a.useCallback(async H=>{const Ce=Ve!==H;We(ze=>ze===H?null:H),Ce&&await Rs(H)},[Ve,Rs]),kc=a.useCallback(H=>{We(H),Rs(H),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${H}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Rs]),uf=a.useCallback(async(H,Ce)=>{try{wt(ze=>new Set(ze).add(Ce)),await rk(H,Ce,r),i("Feature linked to assertion","success"),await Rs(Ce),_t(null)}catch(ze){i(ge(ze)||"Failed to link feature","error")}finally{wt(ze=>{const yt=new Set(ze);return yt.delete(Ce),yt})}},[i,Rs,r]),mf=a.useCallback(async(H,Ce)=>{const ze=`${H}-${Ce}`;try{Rt(yt=>new Set(yt).add(ze)),await lk(H,Ce,r),i("Feature unlinked from assertion","success"),await Rs(Ce)}catch(yt){i(ge(yt)||"Failed to unlink feature","error")}finally{Rt(yt=>{const Qt=new Set(yt);return Qt.delete(ze),Qt})}},[i,Rs,r]),hf=a.useCallback(async H=>{try{pt(ze=>new Set(ze).add(H)),await ck(H,r),i("Validation triggered","success");const Ce=await cd(H,r);je(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch(Ce){i(ge(Ce)||"Failed to trigger validation","error")}finally{pt(Ce=>{const ze=new Set(Ce);return ze.delete(H),ze})}},[i,r]),oi=a.useCallback(async H=>{try{const Ce=await cd(H,r);je(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch{}},[r]),Ei=a.useCallback(async H=>{try{const Ce=await dk(H,{limit:10},r);gn(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch{}},[r]),Za=a.useCallback(H=>{const Ce=Vt.current;if(Ce){for(const ze of Ce.milestones)for(const yt of ze.slices)if(yt.features.find(At=>At.id===H)){ee(At=>{const Bt=new Set(At);return Bt.add(ze.id),Bt}),_(At=>{const Bt=new Set(At);return Bt.add(yt.id),Bt}),gt(H),bt(ze.id),oi(H),Ei(H),requestAnimationFrame(()=>{const At=document.querySelector(`[data-mission-feature-id="${H}"]`);At instanceof HTMLElement&&typeof At.scrollIntoView=="function"&&At.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[oi,Ei]),jc=a.useCallback(async H=>{try{const Ce=await uk(H,r);$n(ze=>{const yt=new Map(ze);return yt.set(H,Ce),yt})}catch{}},[r]),pf=a.useCallback(async H=>{Ge===H?gt(null):(gt(H),await oi(H),await Ei(H))},[Ge,oi,Ei]),ff=a.useCallback(async H=>{Wt===H?Rn(null):(Rn(H),await jc(H))},[Wt,jc]),wc=a.useCallback(async H=>{try{await mk(H,r),i("Mission resumed","success"),await ot(H),Je()}catch(Ce){i(ge(Ce)||"Failed to resume mission","error")}},[i,ot,Je,r]),Nc=a.useCallback(async H=>{try{const ze=(await hk(H,r)).pausedTaskIds?.length??0;i(`Mission stopped (${ze} task${ze!==1?"s":""} paused)`,"success"),await ot(H),Je()}catch(Ce){i(ge(Ce)||"Failed to stop mission","error")}},[i,ot,Je,r]),Sc=a.useCallback(async H=>{try{await pk(H,r),i("Mission started — first slice activated","success"),await ot(H),Je()}catch(Ce){i(ge(Ce)||"Failed to start mission","error")}},[i,ot,Je,r]),gf=a.useCallback(async(H,Ce)=>{try{await fk(H,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await ot(H),Je()}catch(ze){i(ge(ze)||"Failed to update autopilot","error")}},[i,ot,Je,r]),Cc=a.useCallback(H=>{xn("structure"),bt(null),lt(null),Dn([]),Ue(0),B("all"),pe(new Set),ot(H.id)},[ot]),bf=a.useCallback(()=>{b(null),bt(null),lt(null),xn("structure"),Dn([]),Ue(0),B("all"),pe(new Set),Je()},[Je]),ol=wn.length<Q,Mi=p?.autopilotState??"inactive",Ec=Mi==="watching"||Mi==="activating",Mc=mN(Mi,p?.lastAutopilotActivityAt),er=a.useMemo(()=>!Le||!Ke||!wl(Le)?null:Le.rollup.milestoneId===Ke?Le:null,[Ke,Le]),xf=a.useMemo(()=>{const H=new Map;for(const Ce of er?.validationTelemetry.validationRounds??[]){const ze=H.get(Ce.featureId);(!ze||Ce.startedAt>ze.startedAt)&&H.set(Ce.featureId,Ce)}return H},[er]),vf=a.useCallback(()=>{!p||Hn||!ol||le(p.id,{append:!0})},[Hn,ol,le,p]),yf=a.useCallback(H=>{pe(Ce=>{const ze=new Set(Ce);return ze.has(H)?ze.delete(H):ze.add(H),ze})},[]),cl=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),un())},[un]),Ac=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Cn())},[Cn]),Pc=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),yn())},[yn]),Rc=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),tt())},[tt]),kf=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const H=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const Tc=e.jsxs("div",{ref:kf,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:[p?e.jsx("button",{className:"mission-manager__back-btn",onClick:bf,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:e.jsx(Bo,{size:18})}):null,e.jsx(ss,{size:18,className:"mission-manager__header-icon"}),e.jsx("h2",{className:"mission-manager__title",children:p?p.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(Lt,{size:18})})]}),e.jsx("div",{className:"mission-manager__body",children:x?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(ct,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading missions..."})]}):y?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(ct,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading mission details..."})]}):p?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:[Ec&&e.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),e.jsx("h3",{className:"mission-detail__title",children:p.title})]}),e.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(ua[p.status]||ua.planning).bg,color:(ua[p.status]||ua.planning).text},children:p.status})]}),p.description&&e.jsx("p",{className:"mission-detail__description",children:p.description}),e.jsx("div",{className:"mission-detail__meta",children:e.jsxs("span",{className:"mission-detail__meta-info",children:[p.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:p.autopilotEnabled??!1,onChange:H=>gf(p.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(jn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),e.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(rr[Mi]||rr.inactive).bg,color:(rr[Mi]||rr.inactive).text},"data-testid":"autopilot-state-badge",children:[Ec&&e.jsx("span",{className:"mission-detail__autopilot-pulse"}),Mi]})]}),Mc&&e.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Mc})]}),e.jsxs("div",{className:"mission-detail__actions",children:[p.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Nc(p.id),title:"Stop mission","aria-label":"Stop mission",children:e.jsx(cs,{size:14})}),p.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>wc(p.id),title:"Resume mission","aria-label":"Resume mission",children:e.jsx(rn,{size:14})}),p.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Sc(p.id),title:"Start mission","aria-label":"Start mission",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Nt(p),title:"Edit mission","aria-label":"Edit mission",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ne({type:"mission",id:p.id}),title:"Delete mission","aria-label":"Delete mission",children:e.jsx(Ut,{size:14})})]})]}),w===p.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:H=>T({...k,title:H.target.value}),onKeyDown:cl,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:H=>T({...k,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:k.status,onChange:H=>T({...k,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:k.autopilotEnabled,onChange:H=>T({...k,autopilotEnabled:H.target.checked})}),e.jsx(jn,{size:12})," Autopilot"]})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:un,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ct,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[e.jsx("button",{className:`mission-btn ${en==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>xn("structure"),role:"tab","aria-selected":en==="structure","data-testid":"mission-tab-structure",children:"Structure"}),e.jsxs("button",{className:`mission-btn ${en==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>xn("activity"),role:"tab","aria-selected":en==="activity","data-testid":"mission-tab-activity",children:["Activity (",Q,")"]})]}),en==="structure"?e.jsxs("div",{className:"mission-detail__milestones",children:[p.milestones.map(H=>{const Ce=er?.rollup.milestoneId===H.id?er:null,ze=Ce?.rollup??vt.get(H.id),yt=Ce?.validationTelemetry.validationRounds??[],Qt=Ce?.fixFeatures??[],At=Ud[ze?.state??"not_started"]??Ud.not_started,Bt=ze&&(ze.state==="blocked"||ze.state==="failed")?Ce?.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:()=>Vn(H.id),children:[e.jsx("button",{className:"mission-milestone__expand",children:F.has(H.id)?e.jsx(zt,{size:16}):e.jsx(ln,{size:16})}),e.jsx(yi,{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:Od[H.status].bg,color:Od[H.status].text},children:H.status}),e.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),e.jsx(Hd,{state:aN(H.interviewState)}),ze&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:At.bg,color:At.text},title:"Validation state",children:qd(ze.state)}),ze.totalAssertions>0&&e.jsx("div",{className:"mission-milestone__coverage-bar",title:`${ze.passedAssertions??0} of ${ze.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(ze.passedAssertions??0)/ze.totalAssertions*100}%`,backgroundColor:(ze.passedAssertions??0)===ze.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>_e({type:"milestone",id:H.id,title:H.title}),title:"Plan milestone","aria-label":"Plan milestone",children:e.jsx(xi,{size:14})}),e.jsxs("div",{className:"mission-milestone__actions",onClick:Ye=>Ye.stopPropagation(),children:[e.jsx("button",{className:"mission-icon-btn",onClick:()=>En(H.id),title:"Add slice",children:e.jsx(Ht,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>fn(H),title:"Edit milestone",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ne({type:"milestone",id:H.id}),title:"Delete milestone",children:e.jsx(Ut,{size:14})})]})]}),F.has(H.id)&&e.jsxs("div",{className:"mission-milestone__body",children:[(M||N===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:Ac,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:Cn,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),N?"Update":"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vn,children:"Cancel"})]})]}),Ce&&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:[Ce.validationTelemetry.totalRuns," rounds",Ce.validationTelemetry.lastValidatorStatus?` · Last ${Ce.validationTelemetry.lastValidatorStatus}`:""]})]}),Bt&&e.jsxs("div",{className:"mission-blocked-reason",children:[e.jsx("strong",{children:"Blocked reason:"})," ",Bt]}),yt.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:xe?"Hide validation rounds":"Show validation rounds",children:[xe?e.jsx(zt,{size:12}):e.jsx(ln,{size:12}),"Validation rounds (",yt.length,")"]}),xe&&e.jsx("div",{className:"mission-validation-rounds__list",children:yt.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(Ze=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>kc(Ze),title:`Jump to assertion ${Ze}`,children:Ze},`${Ye.roundId}-${Ze}`))}):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(Ze=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Za(Ze),title:`Jump to fix feature ${Ze}`,children:Ze},`${Ye.roundId}-${Ze}`))}):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))})]}),Qt.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:Qt.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:()=>Za(Ye.id),title:`Jump to feature ${Ye.id}`,children:Ye.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ar[Ye.status].bg,color:ar[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:()=>Za(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(Ze=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>kc(Ze),title:`Jump to assertion ${Ze}`,children:Ze},`${Ye.id}-${Ze}`))})]})]},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:()=>Zn(Ye.id),children:[e.jsx("button",{className:"mission-slice__expand",children:I.has(Ye.id)?e.jsx(zt,{size:16}):e.jsx(ln,{size:16})}),e.jsx(po,{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:Bd[Ye.status].bg,color:Bd[Ye.status].text},children:Ye.status}),e.jsxs("span",{className:"mission-slice__count",children:[Ye.features?.length||0," features"]}),e.jsx(Hd,{state:Ye.planState??"not_started"}),Ye.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>_e({type:"slice",id:Ye.id,title:Ye.title}),title:"Plan slice","aria-label":"Plan slice",children:e.jsx(xi,{size:14})}),e.jsxs("div",{className:"mission-slice__actions",onClick:Ze=>Ze.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(rn,{size:14})}),Ye.status==="active"&&Ye.features?.some(Ze=>Ze.status==="defined")&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>rl(Ye.id),title:"Triage all features",disabled:C,children:C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(jn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>gs(Ye.id),title:"Add feature",children:e.jsx(Ht,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Tn(Ye),title:"Edit slice",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ne({type:"slice",id:Ye.id}),title:"Delete slice",children:e.jsx(Ut,{size:14})})]})]}),I.has(Ye.id)&&e.jsxs("div",{className:"mission-slice__body",children:[L&&D===H.id&&!X&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:V.title,onChange:Ze=>de({...V,title:Ze.target.value}),onKeyDown:Pc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:Ze=>de({...V,description:Ze.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:yn,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Xn,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:Ze=>de({...V,title:Ze.target.value}),onKeyDown:Pc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:Ze=>de({...V,description:Ze.target.value}),rows:2}),e.jsxs("select",{value:V.status,onChange:Ze=>de({...V,status:Ze.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:yn,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Xn,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-features",children:[Ye.features?.map(Ze=>e.jsxs("div",{className:"mission-feature","data-mission-feature-id":Ze.id,children:[e.jsxs("div",{className:"mission-feature__header",children:[e.jsx("button",{className:"mission-feature__expand",onClick:()=>pf(Ze.id),title:Ge===Ze.id?"Collapse details":"Expand to show run history",children:Ge===Ze.id?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})}),e.jsx(oo,{size:14,className:"mission-feature__icon"}),e.jsx("span",{className:"mission-feature__title",children:Ze.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ar[Ze.status].bg,color:ar[Ze.status].text},children:Ze.status}),Ze.loopState&&Ze.loopState!=="idle"&&e.jsxs("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,title:`Loop state: ${Ze.loopState}`,children:[Ze.loopState==="implementing"&&"⏳",Ze.loopState==="validating"&&"🔄",Ze.loopState==="needs_fix"&&"🔧",Ze.loopState==="passed"&&"✅",Ze.loopState==="blocked"&&"🚫"]}),Ze.generatedFromFeatureId&&e.jsx("button",{className:"mission-feature__lineage",onClick:()=>Za(Ze.generatedFromFeatureId),title:`Generated from feature: ${Ze.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ze.loopState==="validating"||Ze.loopState==="needs_fix")&&(()=>{const jt=kt.get(Ze.id),Xt=xf.get(Ze.id),xs=jt?.implementationAttemptCount??Xt?.implementationAttempt??Ze.implementationAttemptCount??0,ci=jt?.retryBudgetRemaining??Math.max(0,iN-xs);return e.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",xs," · ",ci," ",ci===1?"retry":"retries"," left"]})})(),Ze.loopState==="implementing"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>hf(Ze.id),title:"Validate feature",disabled:Ne.has(Ze.id),children:Ne.has(Ze.id)?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(On,{size:14})}),Ze.taskId&&e.jsx("span",{className:"mission-feature__task-link",onClick:()=>l?.(Ze.taskId),title:"Click to view task",children:Ze.taskId}),e.jsxs("div",{className:"mission-feature__actions",children:[Ze.status==="defined"&&!Ze.taskId&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>il(Ze.id),title:"Triage — create task",disabled:C||dt===Ze.id,children:dt===Ze.id?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(jn,{size:14})}),Ze.taskId?e.jsx("button",{className:"mission-icon-btn",onClick:()=>Cs(Ze.id),title:"Unlink task",children:e.jsx(Lc,{size:14})}):Ze.status!=="defined"?e.jsx("button",{className:"mission-icon-btn",onClick:()=>rt(Ze.id),title:"Link to task",children:e.jsx(qi,{size:14})}):null,e.jsx("button",{className:"mission-icon-btn",onClick:()=>Fn(Ze),title:"Edit feature",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ne({type:"feature",id:Ze.id}),title:"Delete feature",children:e.jsx(Ut,{size:14})})]})]}),Ze.description&&e.jsx("p",{className:"mission-feature__description",children:Ze.description}),Ze.acceptanceCriteria&&e.jsxs("p",{className:"mission-feature__criteria",children:[e.jsx("strong",{children:"Acceptance:"})," ",Ze.acceptanceCriteria]}),ke?.featureId===Ze.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:ke.enrichedDescription}),e.jsxs("div",{className:"mission-triage-preview__actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:Xa,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):null,"Create Task"]}),e.jsx("button",{className:"btn",onClick:al,disabled:C,children:"Cancel"})]})]}),q===Ze.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:ce.title,onChange:jt=>Se({...ce,title:jt.target.value}),onKeyDown:Rc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:ce.description,onChange:jt=>Se({...ce,description:jt.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ce.acceptanceCriteria,onChange:jt=>Se({...ce,acceptanceCriteria:jt.target.value}),rows:2}),e.jsxs("select",{value:ce.status,onChange:jt=>Se({...ce,status:jt.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:tt,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:se,children:"Cancel"})]})]}),Ge===Ze.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"})}),(qt.get(Ze.id)??[]).map(jt=>e.jsxs("div",{className:"mission-run",children:[e.jsxs("div",{className:"mission-run__header",onClick:()=>ff(jt.id),children:[e.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${jt.status}`,title:jt.status,children:jt.status}),e.jsx("span",{className:"mission-run__time",children:new Date(jt.startedAt).toLocaleString()}),jt.completedAt&&e.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(jt.completedAt).getTime()-new Date(jt.startedAt).getTime())/1e3),"s"]}),jt.triggerType&&e.jsx("span",{className:"mission-run__trigger",children:jt.triggerType}),e.jsx("button",{className:"mission-icon-btn",title:Wt===jt.id?"Hide details":"Show details",children:Wt===jt.id?e.jsx(zt,{size:12}):e.jsx(ln,{size:12})})]}),Wt===jt.id&&Kt.get(jt.id)&&e.jsxs("div",{className:"mission-run__details",children:[jt.summary&&e.jsx("p",{className:"mission-run__summary",children:jt.summary}),jt.blockedReason&&e.jsxs("p",{className:"mission-run__blocked-reason",children:[e.jsx("strong",{children:"Blocked:"})," ",jt.blockedReason]}),Kt.get(jt.id)?.failures&&Kt.get(jt.id).failures.length>0&&e.jsxs("div",{className:"mission-run__failures",children:[e.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Kt.get(jt.id).failures.map(Xt=>e.jsxs("div",{className:"mission-run__failure",children:[e.jsx("span",{className:"mission-run__failure-message",children:Xt.message}),Xt.expected&&e.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Xt.expected]}),Xt.actual&&e.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Xt.actual]})]},Xt.id))]}),(!Kt.get(jt.id)?.failures||Kt.get(jt.id).failures.length===0)&&e.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},jt.id)),(!qt.get(Ze.id)||qt.get(Ze.id).length===0)&&e.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ze.id)),ve&&Ae===Ye.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:ce.title,onChange:Ze=>Se({...ce,title:Ze.target.value}),onKeyDown:Rc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:ce.description,onChange:Ze=>Se({...ce,description:Ze.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ce.acceptanceCriteria,onChange:Ze=>Se({...ce,acceptanceCriteria:Ze.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:tt,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{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(oo,{size:16}),e.jsx("span",{children:"No fix features generated."})]})]})]})]},Ye.id)),H.slices.length===0&&!L&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(po,{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"}),ze&&e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:At.bg,color:At.text},children:qd(ze.state)}),ze&&ze.totalAssertions>0&&e.jsx("div",{className:"mission-assertions__coverage-bar",title:`${ze.passedAssertions??0} of ${ze.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(ze.passedAssertions??0)/ze.totalAssertions*100}%`,backgroundColor:(ze.passedAssertions??0)===ze.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>{oe(!0),be(null),Me({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:e.jsx(Ht,{size:14})})]}),qe&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:it.title,onChange:Ye=>Me({...it,title:Ye.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:it.assertion,onChange:Ye=>Me({...it,assertion:Ye.target.value}),rows:2}),e.jsxs("select",{value:it.status,onChange:Ye=>Me({...it,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:()=>vc(H.id),disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:li,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(ye.get(H.id))?ye.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:st===Ye.id?e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:it.title,onChange:Ze=>Me({...it,title:Ze.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text",value:it.assertion,onChange:Ze=>Me({...it,assertion:Ze.target.value}),rows:2}),e.jsxs("select",{value:it.status,onChange:Ze=>Me({...it,status:Ze.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:()=>ll(Ye.id,H.id),disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Save"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:li,children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(lr[Ye.status]??lr.pending).bg,color:(lr[Ye.status]??lr.pending).text},children:Ye.status}),e.jsx("span",{className:"mission-assertion__title",children:Ye.title}),(()=>{const jt=Re.get(Ye.id)?.length??0;return jt>0?e.jsxs("span",{className:"mission-assertion__linked-count",title:`${jt} linked feature${jt!==1?"s":""}`,children:["(",jt," linked)"]}):null})(),e.jsx("button",{className:"mission-icon-btn",onClick:()=>yc(Ye.id),title:"Toggle details",children:Ve===Ye.id?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Us(Ye),title:"Edit assertion",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ne({type:"assertion",id:Ye.id}),title:"Delete assertion",children:e.jsx(Ut,{size:14})})]})}),Ve===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()=>{Ve!==Ye.id&&await yc(Ye.id),_t($t===Ye.id?null:Ye.id)},title:"Link a feature",children:[e.jsx(qi,{size:12}),"Link Feature"]})]}),$t===Ye.id&&e.jsx("div",{className:"mission-assertion__feature-picker",children:e.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ze=new Set((Re.get(Ye.id)??[]).map(Xt=>Xt.id)),jt=[];return p?.milestones.forEach(Xt=>Xt.slices.forEach(xs=>jt.push(...xs.features.filter(ci=>!Ze.has(ci.id))))),jt.length===0?e.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):jt.map(Xt=>e.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>uf(Xt.id,Ye.id),disabled:xt.has(Ye.id),children:[e.jsx("span",{className:"mission-assertion__feature-picker-title",children:Xt.title}),xt.has(Ye.id)&&e.jsx(ct,{size:12,className:"spinner"})]},Xt.id))})()})}),(()=>{const Ze=Re.get(Ye.id)??[];return Ze.length===0?e.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ze.map(jt=>{const Xt=`${jt.id}-${Ye.id}`,xs=Et.has(Xt);return e.jsxs("div",{className:"mission-assertion__linked-feature",children:[e.jsx("span",{className:"mission-assertion__linked-feature-title",children:jt.title}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>mf(jt.id,Ye.id),disabled:xs,title:"Unlink feature",children:xs?e.jsx(ct,{size:12,className:"spinner"}):e.jsx(Lc,{size:12})})]},jt.id)})})()]})]})]},Ye.id)),(!ye.get(H.id)||ye.get(H.id)?.length===0)&&!qe&&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)}),p&&!M&&N===null&&e.jsxs("button",{className:"mission-add-btn",onClick:pn,children:[e.jsx(Ht,{size:16}),"Add Milestone"]}),M&&N===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:Ac,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:Cn,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vn,children:"Cancel"})]})]}),p.milestones.length===0&&!M&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(yi,{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:R,onChange:H=>B(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:[wn.length," of ",Q]})]}),!Hn&&ol&&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:vf,"data-testid":"mission-activity-load-more",children:"Load more"})}),Hn?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..."})]}):wn.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:ue,className:"mission-events","data-testid":"mission-activity-events",children:[wn.map(H=>{const Ce=!!(H.metadata&&Object.keys(H.metadata).length>0),ze=re.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 ${dN(H.eventType)}`,children:uN(H.eventType)}),e.jsx("span",{className:"mission-event__time",children:Ir(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()}),Ce&&e.jsxs("div",{className:"mission-event__metadata",children:[e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>yf(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[ze?"Hide":"Show"," metadata"]}),ze&&e.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),e.jsx("div",{ref:Te})]})]})]}):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:k.title,onChange:H=>T({...k,title:H.target.value}),onKeyDown:cl,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:H=>T({...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:un,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ct,children:"Cancel"})]})]}),g.map(H=>{const Ce=H,ze=p,yt=ze&&ze.id===Ce.id,Qt=ua[Ce.status]||{bg:"",text:""},At=Ce.summary,Bt=bn.get(Ce.id),Ye=lN(Bt),Ze=!!(At&&(At.totalMilestones>0||At.totalFeatures>0)),jt=Bt?.totalTasks??0,Xt=Bt?.tasksCompleted??0,xs=Bt?.tasksFailed??0,ci=Bt?.estimatedCompletionPercent??At?.progressPercent??0,_n=Ze||jt>0||xs>0||!!Bt?.lastActivityAt,hn=Ce.status==="active"&&(Bt?.currentMilestoneId||Bt?.currentSliceId)?"Current milestone/slice in progress":null;return e.jsxs("div",{className:`mission-list__item ${yt?"mission-list__item--selected":""}`,onClick:()=>Cc(H),children:[e.jsxs("div",{className:"mission-list__item-content",children:[e.jsxs("div",{className:"mission-list__item-header",children:[e.jsx(ss,{size:16,className:"mission-list__item-icon"}),e.jsx("span",{className:"mission-list__item-title",children:Ce.title}),H.autopilotEnabled&&e.jsx("span",{title:"Autopilot enabled",children:e.jsx(jn,{size:12,className:"mission-list__item-autopilot-icon"})}),e.jsx("span",{className:`mission-health-badge mission-health-badge--${Ye}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${Ye}`}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Qt.bg,color:Qt.text},children:Ce.status})]}),Ce.description&&e.jsx("p",{className:"mission-list__item-description",children:Ce.description}),hn&&e.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",hn]}),_n&&e.jsxs("div",{className:"mission-list__item-summary",children:[Ze&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"mission-list__item-stat",children:[At.completedMilestones,"/",At.totalMilestones," milestones"]}),e.jsxs("span",{className:"mission-list__item-stat",children:[At.completedFeatures,"/",At.totalFeatures," features"]})]}),e.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[Xt,"/",jt," tasks"]}),xs>0&&e.jsxs("button",{className:"mission-list__item-failed",onClick:Tt=>{Tt.stopPropagation(),Cc(H)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[xs," failed"]}),e.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",Ir(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:`${ci}%`}})})]})]}),e.jsxs("div",{className:"mission-list__item-actions",onClick:Tt=>Tt.stopPropagation(),children:[Ce.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Nc(Ce.id),title:"Stop mission",children:e.jsx(cs,{size:14})}),Ce.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>wc(Ce.id),title:"Resume mission",children:e.jsx(rn,{size:14})}),Ce.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Sc(Ce.id),title:"Start mission",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Nt(H),title:"Edit mission",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ne({type:"mission",id:Ce.id}),title:"Delete mission",children:e.jsx(Ut,{size:14})})]})]},Ce.id)}),w&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:H=>T({...k,title:H.target.value}),onKeyDown:cl,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:H=>T({...k,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:k.status,onChange:H=>T({...k,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:k.autopilotEnabled,onChange:H=>T({...k,autopilotEnabled:H.target.checked})}),e.jsx(jn,{size:12})," Autopilot"]})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:un,disabled:C,children:[C?e.jsx(ct,{size:14,className:"spinner"}):e.jsx(Mn,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ct,children:"Cancel"})]})]}),g.length===0&&!j&&e.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[e.jsx(ss,{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:[De.length>0&&e.jsxs("div",{className:"mission-resume-prompt",children:[e.jsx(as,{size:16}),e.jsx("span",{children:De.length===1?`Resume "${De[0].title}"?`:`${De.length} interview sessions pending`}),e.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:De.map(H=>e.jsxs("button",{className:"mission-add-btn",onClick:()=>{te(H.id),nt(!0),Qe([])},children:[H.status==="error"?e.jsx(An,{size:14}):e.jsx(On,{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:()=>nt(!0),children:[e.jsx(On,{size:16}),"Plan with AI"]}),e.jsxs("button",{className:"mission-add-btn",onClick:mt,children:[e.jsx(Ht,{size:16}),"New Mission"]})]})]})]})}),he&&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 ",he.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()=>{he.type==="mission"?await mn(he.id):he.type==="milestone"?await ls(he.id):he.type==="slice"?await Wn(he.id):he.type==="feature"&&await ft(he.id)},children:"Delete"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ne(null),children:"Cancel"})]})]})}),Fe&&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:Pe,onChange:H=>Ie(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:()=>Ie(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:It,children:"Link"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{rt(null),Ie("")},children:"Cancel"})]})]})})]}),_c=e.jsx(Xw,{isOpen:Be,onClose:()=>nt(!1),onMissionCreated:()=>{Je(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:fe}),Ic=ae?e.jsx(tN,{isOpen:!0,onClose:()=>_e(null),onApplied:()=>{_e(null),p&&ot(p.id)},targetType:ae.type,targetId:ae.id,targetTitle:ae.title,missionContext:p?.title,projectId:r,resumeSessionId:ae.resumeSessionId}):null;return n?e.jsxs(e.Fragment,{children:[Tc,_c,Ic]}):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:Tc}),_c,Ic]})}const or=2e3;function pN({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,f]=a.useState(""),[p,b]=a.useState(!1),[x,v]=a.useState(null),y=m.trim()!==""&&g.trim().length>0&&g.length<=or,A=a.useCallback(async()=>{if(!(!y||p)){b(!0),v(null);try{const P=u==="agent"?"user-to-agent":"system";await zk({toId:m.trim(),toType:u,content:g.trim(),type:P,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(P){const w=ge(P)||"Failed to send message";v(w),o?.(w,"error")}finally{b(!1)}}},[y,p,m,u,g,n,i,r,o]),j=a.useCallback(P=>{c(P),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(Lt,{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:P=>j(P.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(P=>e.jsx("option",{value:P.id,children:P.name||P.id},P.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(an,{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=>f(P.target.value),maxLength:or,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>or?"over-limit":"",children:[g.length,"/",or]})})]}),x&&e.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[e.jsx(as,{size:14}),e.jsx("span",{children:x})]})]}),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:!y||p,"data-testid":"message-composer-send",children:p?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:14,className:"spin"}),e.jsx("span",{children:"Sending…"})]}):e.jsxs(e.Fragment,{children:[e.jsx(fi,{size:14}),e.jsx("span",{children:"Send"})]})})]})]})}function _i(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 fN(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 gN(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 Wd(t,n=80){return t.length<=n?t:`${t.slice(0,n)}…`}function bN(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 xN({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),[f,p]=a.useState(null),[b,x]=a.useState([]),[v,y]=a.useState(!1),[A,j]=a.useState(null),[P,w]=a.useState(null),[E,k]=a.useState(null),[T,C]=a.useState("inbox"),[$,F]=a.useState(null),[ee,I]=a.useState([]),_=a.useMemo(()=>new Map(ee.map(q=>[q.id,q.name??""])),[ee]),N=a.useCallback((q,W)=>fN(q,W,_),[_]),J=a.useCallback(async()=>{g(!0);try{const q=await Fk({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 Lk({limit:50},t);m(q)}catch{}finally{g(!1)}},[t]),G=a.useCallback(async q=>{g(!0);try{const W=await qk(q,t);F(W)}catch{}finally{g(!1)}},[t]),M=a.useCallback(async()=>{try{const q=await ia(void 0,t);I(q)}catch{}},[t]),O=a.useCallback(async()=>{try{const q=await gh(t);u(q.unreadCount),s?.(q.unreadCount)}catch{}},[t,s]);a.useEffect(()=>{i==="inbox"?J():i==="outbox"?K():i==="agents"&&M()},[i,J,K,M]),a.useEffect(()=>{E&&G(E)},[E,G]),a.useEffect(()=>{O()},[O]),a.useEffect(()=>{M()},[M]),a.useEffect(()=>{if(typeof EventSource>"u")return;const q=t?`?projectId=${encodeURIComponent(t)}`:"",W=()=>{O(),i==="inbox"?J():i==="outbox"&&K(),E&&G(E)};return Os(`/api/events${q}`,{events:{"message:sent":W,"message:received":W,"message:read":W,"message:deleted":W}})},[t,i,E,O,J,K,G]);const X=a.useCallback(async q=>{if(p(q),!q.read)try{const W=await Ok(q.id,t);W&&o(Se=>Se&&{...Se,messages:Se.messages.map(ve=>ve.id===W.id?W:ve),unreadCount:Math.max(0,Se.unreadCount-1)});const ce=Math.max(0,c-1);u(ce),s?.(ce)}catch{}try{const W=await Hk(q.fromId,q.fromType,t);x(W)}catch{x([q])}},[t,c,s]),S=a.useCallback(()=>{p(null),x([])},[]),V=a.useCallback(async()=>{try{const q=await Bk(t);u(0),s?.(0),o(W=>W&&{...W,messages:W.messages.map(ce=>({...ce,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 Uk(q,t),p(null),x([]),i==="inbox"?J():i==="outbox"?K():E&&G(E),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[t,i,E,J,K,G,n]),L=a.useCallback(q=>{j({id:q.fromId,type:q.fromType}),w({messageId:q.id,preview:Wd(q.content,120)}),y(!0)},[]),Z=a.useCallback(()=>{y(!1),j(null),w(null),n?.("Message sent","success"),i==="outbox"?K():i==="agents"&&E&&G(E),O()},[i,K,E,G,n,O]),D=a.useCallback(()=>{j(i==="agents"&&E?{id:E,type:"agent"}:null),w(null),y(!0)},[i,E]),me=a.useCallback(()=>{y(!1),j(null),w(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(_a,{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(Zs,{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(Uf,{size:14}),e.jsx("span",{children:"Mark all read"})]}),e.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?J():i==="outbox"?K():E&&G(E)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?e.jsx(ct,{size:14,className:"spin"}):e.jsx(An,{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"),p(null)},"data-testid":"mailbox-tab-inbox",children:[e.jsx(Na,{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"),p(null)},"data-testid":"mailbox-tab-outbox",children:[e.jsx(fi,{size:14}),e.jsx("span",{children:"Outbox"})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),p(null)},"data-testid":"mailbox-tab-agents",children:[e.jsx(an,{size:14}),e.jsx("span",{children:"Agents"})]})]}),e.jsxs("div",{className:"mailbox-content","data-testid":"mailbox-content",children:[f&&!v&&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:S,"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:gN(f.type)}),e.jsx("span",{className:"mailbox-message-time",children:_i(f.createdAt)})]}),e.jsxs("div",{className:"mailbox-message-detail-actions",children:[f.fromType==="agent"&&e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>L(f),"data-testid":"mailbox-reply",children:[e.jsx(Zs,{size:14}),e.jsx("span",{children:"Reply"})]}),e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>de(f.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:[f.fromType==="agent"?e.jsx(an,{size:14}):e.jsx(Ai,{size:14}),N(f.fromId,f.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:[f.toType==="agent"?e.jsx(an,{size:14}):e.jsx(Ai,{size:14}),N(f.toId,f.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,ce=W?b.find(Se=>Se.id===W):void 0;return e.jsxs("div",{className:`mailbox-conversation-msg ${q.id===f.id?"current":""}`,children:[e.jsxs("div",{className:"mailbox-conversation-msg-header",children:[e.jsx("span",{children:N(q.fromId,q.fromType)}),e.jsx("span",{className:"mailbox-message-time",children:_i(q.createdAt)})]}),W&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${q.id}`,children:["↪ Replying to ",ce?Wd(ce.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:[f.metadata?.replyTo?.messageId&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",f.metadata.replyTo.messageId]}),e.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:f.content})]})]}),v&&e.jsx(pN,{recipient:A,replyContext:P,agents:ee,projectId:t,onSend:Z,onCancel:me,addToast:n}),!f&&!v&&e.jsxs(e.Fragment,{children:[i==="inbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!l&&e.jsx(Nl,{}),l&&l.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[e.jsx(Na,{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:bN(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(an,{size:16}):e.jsx(Ai,{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:N(q.fromId,q.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:_i(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(Nl,{}),d&&d.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[e.jsx(fi,{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(an,{size:16}):e.jsx(Ai,{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: ",N(q.toId,q.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:_i(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(an,{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:E??"",onChange:q=>{k(q.target.value||null),C("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(Zs,{size:14}),e.jsx("span",{children:"Compose"})]})]}),E&&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 ${T==="inbox"?"active":""}`,onClick:()=>C("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[e.jsx(Na,{size:12}),e.jsx("span",{children:"Inbox"}),$&&$.unreadCount>0&&e.jsx("span",{className:"mailbox-tab-badge",children:$.unreadCount})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${T==="outbox"?"active":""}`,onClick:()=>C("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[e.jsx(fi,{size:12}),e.jsx("span",{children:"Outbox"})]})]}),e.jsxs("div",{className:"mailbox-agents-content",children:[!E&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(an,{size:32}),e.jsx("p",{children:"Select an agent to view their mailbox"})]}),E&&h&&!$&&e.jsx(Nl,{}),E&&$&&T==="inbox"&&$.inbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(Na,{size:32}),e.jsx("p",{children:"No received messages for this agent"})]}),E&&$&&T==="outbox"&&$.outbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(fi,{size:32}),e.jsx("p",{children:"No sent messages for this agent"})]}),E&&$&&T==="inbox"&&$.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(an,{size:16}):e.jsx(Ai,{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:N(q.fromId,q.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:_i(q.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[q.content.slice(0,80),q.content.length>80?"…":""]})]})]},q.id)),E&&$&&T==="outbox"&&$.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(an,{size:16}):e.jsx(Ai,{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: ",N(q.toId,q.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:_i(q.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[q.content.slice(0,80),q.content.length>80?"…":""]})]})]},q.id))]})]})})]})]})]})}function Nl(){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 vN(t,n){const s={};return(t[t.length-1]===""?[...t,""]:t).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const yN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,kN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,jN={};function Kd(t,n){return(jN.jsx?kN:yN).test(t)}const wN=/[ \t\n\f\r]/g;function NN(t){return typeof t=="object"?t.type==="text"?Gd(t.value):!1:Gd(t)}function Gd(t){return t.replace(wN,"")===""}class Ja{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}Ja.prototype.normal={};Ja.prototype.property={};Ja.prototype.space=void 0;function $h(t,n){const s={},i={};for(const r of t)Object.assign(s,r.property),Object.assign(i,r.normal);return new Ja(s,i,n)}function wo(t){return t.toLowerCase()}class rs{constructor(n,s){this.attribute=s,this.property=n}}rs.prototype.attribute="";rs.prototype.booleanish=!1;rs.prototype.boolean=!1;rs.prototype.commaOrSpaceSeparated=!1;rs.prototype.commaSeparated=!1;rs.prototype.defined=!1;rs.prototype.mustUseProperty=!1;rs.prototype.number=!1;rs.prototype.overloadedBoolean=!1;rs.prototype.property="";rs.prototype.spaceSeparated=!1;rs.prototype.space=void 0;let SN=0;const Pt=Ci(),kn=Ci(),No=Ci(),at=Ci(),Zt=Ci(),Bi=Ci(),os=Ci();function Ci(){return 2**++SN}const So=Object.freeze(Object.defineProperty({__proto__:null,boolean:Pt,booleanish:kn,commaOrSpaceSeparated:os,commaSeparated:Bi,number:at,overloadedBoolean:No,spaceSeparated:Zt},Symbol.toStringTag,{value:"Module"})),Sl=Object.keys(So);class ec extends rs{constructor(n,s,i,r){let l=-1;if(super(n,s),Jd(this,"space",r),typeof i=="number")for(;++l<Sl.length;){const o=Sl[l];Jd(this,Sl[l],(i&So[o])===So[o])}}}ec.prototype.defined=!0;function Jd(t,n,s){s&&(t[n]=s)}function ra(t){const n={},s={};for(const[i,r]of Object.entries(t.properties)){const l=new ec(i,t.transform(t.attributes||{},i),r,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(l.mustUseProperty=!0),n[i]=l,s[wo(i)]=i,s[wo(l.attribute)]=i}return new Ja(n,s,t.space)}const Dh=ra({properties:{ariaActiveDescendant:null,ariaAtomic:kn,ariaAutoComplete:null,ariaBusy:kn,ariaChecked:kn,ariaColCount:at,ariaColIndex:at,ariaColSpan:at,ariaControls:Zt,ariaCurrent:null,ariaDescribedBy:Zt,ariaDetails:null,ariaDisabled:kn,ariaDropEffect:Zt,ariaErrorMessage:null,ariaExpanded:kn,ariaFlowTo:Zt,ariaGrabbed:kn,ariaHasPopup:null,ariaHidden:kn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Zt,ariaLevel:at,ariaLive:null,ariaModal:kn,ariaMultiLine:kn,ariaMultiSelectable:kn,ariaOrientation:null,ariaOwns:Zt,ariaPlaceholder:null,ariaPosInSet:at,ariaPressed:kn,ariaReadOnly:kn,ariaRelevant:null,ariaRequired:kn,ariaRoleDescription:Zt,ariaRowCount:at,ariaRowIndex:at,ariaRowSpan:at,ariaSelected:kn,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 Fh(t,n){return n in t?t[n]:n}function Lh(t,n){return Fh(t,n.toLowerCase())}const CN=ra({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Bi,acceptCharset:Zt,accessKey:Zt,action:null,allow:null,allowFullScreen:Pt,allowPaymentRequest:Pt,allowUserMedia:Pt,alt:null,as:null,async:Pt,autoCapitalize:null,autoComplete:Zt,autoFocus:Pt,autoPlay:Pt,blocking:Zt,capture:null,charSet:null,checked:Pt,cite:null,className:Zt,cols:at,colSpan:null,content:null,contentEditable:kn,controls:Pt,controlsList:Zt,coords:at|Bi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Pt,defer:Pt,dir:null,dirName:null,disabled:Pt,download:No,draggable:kn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Pt,formTarget:null,headers:Zt,height:at,hidden:No,high:at,href:null,hrefLang:null,htmlFor:Zt,httpEquiv:Zt,id:null,imageSizes:null,imageSrcSet:null,inert:Pt,inputMode:null,integrity:null,is:null,isMap:Pt,itemId:null,itemProp:Zt,itemRef:Zt,itemScope:Pt,itemType:Zt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Pt,low:at,manifest:null,max:null,maxLength:at,media:null,method:null,min:null,minLength:at,multiple:Pt,muted:Pt,name:null,nonce:null,noModule:Pt,noValidate:Pt,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:Pt,optimum:at,pattern:null,ping:Zt,placeholder:null,playsInline:Pt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Pt,referrerPolicy:null,rel:Zt,required:Pt,reversed:Pt,rows:at,rowSpan:at,sandbox:Zt,scope:null,scoped:Pt,seamless:Pt,selected:Pt,shadowRootClonable:Pt,shadowRootDelegatesFocus:Pt,shadowRootMode:null,shape:null,size:at,sizes:null,slot:null,span:at,spellCheck:kn,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:Pt,useMap:null,value:kn,width:at,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Zt,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:Pt,declare:Pt,event:null,face:null,frame:null,frameBorder:null,hSpace:at,leftMargin:at,link:null,longDesc:null,lowSrc:null,marginHeight:at,marginWidth:at,noResize:Pt,noHref:Pt,noShade:Pt,noWrap:Pt,object:null,profile:null,prompt:null,rev:null,rightMargin:at,rules:null,scheme:null,scrolling:kn,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:Pt,disableRemotePlayback:Pt,prefix:null,property:null,results:at,security:null,unselectable:null},space:"html",transform:Lh}),EN=ra({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:Zt,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:Pt,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:Bi,g2:Bi,glyphName:Bi,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:Zt,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:Fh}),zh=ra({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()}}),Oh=ra({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Lh}),Bh=ra({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),MN={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"},AN=/[A-Z]/g,Yd=/-[a-z]/g,PN=/^data[-\w.:]+$/i;function RN(t,n){const s=wo(n);let i=n,r=rs;if(s in t.normal)return t.property[t.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&PN.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(Yd,_N);i="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!Yd.test(l)){let o=l.replace(AN,TN);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}r=ec}return new r(i,n)}function TN(t){return"-"+t.toLowerCase()}function _N(t){return t.charAt(1).toUpperCase()}const IN=$h([Dh,CN,zh,Oh,Bh],"html"),tc=$h([Dh,EN,zh,Oh,Bh],"svg");function $N(t){return t.join(" ").trim()}var Ii={},Cl,Qd;function DN(){if(Qd)return Cl;Qd=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=`
|
|
593
|
-
`,c="/",u="*",h="",g="comment",f="declaration";function p(x,v){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];v=v||{};var y=1,A=1;function j(I){var _=I.match(n);_&&(y+=_.length);var N=I.lastIndexOf(m);A=~N?I.length-N:A+I.length}function P(){var I={line:y,column:A};return function(_){return _.position=new w(I),T(),_}}function w(I){this.start=I,this.end={line:y,column:A},this.source=v.source}w.prototype.content=x;function E(I){var _=new Error(v.source+":"+y+":"+A+": "+I);if(_.reason=I,_.filename=v.source,_.line=y,_.column=A,_.source=x,!v.silent)throw _}function k(I){var _=I.exec(x);if(_){var N=_[0];return j(N),x=x.slice(N.length),_}}function T(){k(s)}function C(I){var _;for(I=I||[];_=$();)_!==!1&&I.push(_);return I}function $(){var I=P();if(!(c!=x.charAt(0)||u!=x.charAt(1))){for(var _=2;h!=x.charAt(_)&&(u!=x.charAt(_)||c!=x.charAt(_+1));)++_;if(_+=2,h===x.charAt(_-1))return E("End of comment missing");var N=x.slice(2,_-2);return A+=2,j(N),x=x.slice(_),A+=2,I({type:g,comment:N})}}function F(){var I=P(),_=k(i);if(_){if($(),!k(r))return E("property missing ':'");var N=k(l),J=I({type:f,property:b(_[0].replace(t,h)),value:N?b(N[0].replace(t,h)):h});return k(o),J}}function ee(){var I=[];C(I);for(var _;_=F();)_!==!1&&(I.push(_),C(I));return I}return T(),ee()}function b(x){return x?x.replace(d,h):h}return Cl=p,Cl}var Xd;function FN(){if(Xd)return Ii;Xd=1;var t=Ii&&Ii.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.default=s;const n=t(DN());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 Ii}var ma={},Zd;function LN(){if(Zd)return ma;Zd=1,Object.defineProperty(ma,"__esModule",{value:!0}),ma.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 ma.camelCase=m,ma}var ha,eu;function zN(){if(eu)return ha;eu=1;var t=ha&&ha.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=t(FN()),s=LN();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,ha=i,ha}var ON=zN();const BN=Im(ON),Uh=Hh("end"),nc=Hh("start");function Hh(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 UN(t){const n=nc(t),s=Uh(t);if(n&&s)return{start:n,end:s}}function Ma(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?tu(t.position):"start"in t||"end"in t?tu(t):"line"in t||"column"in t?Co(t):""}function Co(t){return nu(t&&t.line)+":"+nu(t&&t.column)}function tu(t){return Co(t&&t.start)+"-"+Co(t&&t.end)}function nu(t){return t&&typeof t=="number"?t:1}class Bn 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=Ma(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}}Bn.prototype.file="";Bn.prototype.name="";Bn.prototype.reason="";Bn.prototype.message="";Bn.prototype.stack="";Bn.prototype.column=void 0;Bn.prototype.line=void 0;Bn.prototype.ancestors=void 0;Bn.prototype.cause=void 0;Bn.prototype.fatal=void 0;Bn.prototype.place=void 0;Bn.prototype.ruleId=void 0;Bn.prototype.source=void 0;const sc={}.hasOwnProperty,HN=new Map,qN=/[A-Z]/g,VN=new Set(["table","tbody","thead","tfoot","tr"]),WN=new Set(["td","th"]),qh="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function KN(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=t1(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=e1(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"?tc:IN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},l=Vh(r,t,void 0);return l&&typeof l!="string"?l:r.create(t,r.Fragment,{children:l||void 0},void 0)}function Vh(t,n,s){if(n.type==="element")return GN(t,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return JN(t,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return QN(t,n,s);if(n.type==="mdxjsEsm")return YN(t,n);if(n.type==="root")return XN(t,n,s);if(n.type==="text")return ZN(t,n)}function GN(t,n,s){const i=t.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=tc,t.schema=r),t.ancestors.push(n);const l=Kh(t,n.tagName,!1),o=n1(t,n);let d=ac(t,n);return VN.has(n.tagName)&&(d=d.filter(function(m){return typeof m=="string"?!NN(m):!0})),Wh(t,o,l,n),ic(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function JN(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)}Fa(t,n.position)}function YN(t,n){if(n.data&&n.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(n.data.estree);Fa(t,n.position)}function QN(t,n,s){const i=t.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=tc,t.schema=r),t.ancestors.push(n);const l=n.name===null?t.Fragment:Kh(t,n.name,!0),o=s1(t,n),d=ac(t,n);return Wh(t,o,l,n),ic(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function XN(t,n,s){const i={};return ic(i,ac(t,n)),t.create(n,t.Fragment,i,s)}function ZN(t,n){return n.value}function Wh(t,n,s,i){typeof s!="string"&&s!==t.Fragment&&t.passNode&&(n.node=i)}function ic(t,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(t.children=s)}}function e1(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 t1(t,n){return s;function s(i,r,l,o){const d=Array.isArray(l.children),m=nc(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 n1(t,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&sc.call(n.properties,r)){const l=i1(t,r,n.properties[r]);if(l){const[o,d]=l;t.tableCellAlignToStyle&&o==="align"&&typeof d=="string"&&WN.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 s1(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 Fa(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 Fa(t,n.position);else l=i.value===null?!0:i.value;s[r]=l}return s}function ac(t,n){const s=[];let i=-1;const r=t.passKeys?new Map:HN;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=Vh(t,l,o);d!==void 0&&s.push(d)}return s}function i1(t,n,s){const i=RN(t.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?vN(s):$N(s)),i.property==="style"){let r=typeof s=="object"?s:a1(t,String(s));return t.stylePropertyNameCase==="css"&&(r=r1(r)),["style",r]}return[t.elementAttributeNameCase==="react"&&i.space?MN[i.property]||i.property:i.attribute,s]}}function a1(t,n){try{return BN(n,{reactCompat:!0})}catch(s){if(t.ignoreInvalidStyle)return{};const i=s,r=new Bn("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=qh+"#cannot-parse-style-attribute",r}}function Kh(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=Kd(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=Kd(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return sc.call(t.components,r)?t.components[r]:r}if(t.evaluater)return t.evaluater.evaluateExpression(i);Fa(t)}function Fa(t,n){const s=new Bn("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=qh+"#cannot-handle-mdx-estrees-without-createevaluater",s}function r1(t){const n={};let s;for(s in t)sc.call(t,s)&&(n[l1(s)]=t[s]);return n}function l1(t){let n=t.replace(qN,o1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function o1(t){return"-"+t.toLowerCase()}const El={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},c1={};function rc(t,n){const s=c1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Gh(t,i,r)}function Gh(t,n,s){if(d1(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 su(t.children,n,s)}return Array.isArray(t)?su(t,n,s):""}function su(t,n,s){const i=[];let r=-1;for(;++r<t.length;)i[r]=Gh(t[r],n,s);return i.join("")}function d1(t){return!!(t&&typeof t=="object")}const iu=document.createElement("i");function lc(t){const n="&"+t+";";iu.innerHTML=n;const s=iu.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 au={}.hasOwnProperty;function Jh(t){const n={};let s=-1;for(;++s<t.length;)u1(n,t[s]);return n}function u1(t,n){let s;for(s in n){const r=(au.call(t,s)?t[s]:void 0)||(t[s]={}),l=n[s];let o;if(l)for(o in l){au.call(r,o)||(r[o]=[]);const d=l[o];m1(r[o],Array.isArray(d)?d:d?[d]:[])}}}function m1(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 Yh(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 Gn=ai(/[A-Za-z]/),zn=ai(/[\dA-Za-z]/),h1=ai(/[#-'*+\--9=?A-Z^-~]/);function $r(t){return t!==null&&(t<32||t===127)}const Eo=ai(/\d/),p1=ai(/[\dA-Fa-f]/),f1=ai(/[!-/:-@[-`{-~]/);function St(t){return t!==null&&t<-2}function Yt(t){return t!==null&&(t<0||t===32)}function Ft(t){return t===-2||t===-1||t===32}const Zr=ai(/\p{P}|\p{S}/u),wi=ai(/\s/);function ai(t){return n;function n(s){return s!==null&&s>-1&&t.test(String.fromCharCode(s))}}function la(t){const n=[];let s=-1,i=0,r=0;for(;++s<t.length;){const l=t.charCodeAt(s);let o="";if(l===37&&zn(t.charCodeAt(s+1))&&zn(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 Ot(t,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let l=0;return o;function o(m){return Ft(m)?(t.enter(s),d(m)):n(m)}function d(m){return Ft(m)&&l++<r?(t.consume(m),d):(t.exit(s),n(m))}}const g1={tokenize:b1};function b1(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"),Ot(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 St(d)?(t.consume(d),t.exit("chunkText"),l):(t.consume(d),o)}}const x1={tokenize:v1},ru={tokenize:y1};function v1(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&&y();const j=n.events.length;let P=j,w;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){w=n.events[P][1].end;break}v(i);let E=j;for(;E<n.events.length;)n.events[E][1].end={...w},E++;return hs(n.events,P+1,0,n.events.slice(j)),n.events.length=E,c(A)}return d(A)}function c(A){if(i===s.length){if(!r)return g(A);if(r.currentConstruct&&r.currentConstruct.concrete)return p(A);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},t.check(ru,u,h)(A)}function u(A){return r&&y(),v(i),g(A)}function h(A){return n.parser.lazy[n.now().line]=i!==s.length,o=n.now().offset,p(A)}function g(A){return n.containerState={},t.attempt(ru,f,p)(A)}function f(A){return i++,s.push([n.currentConstruct,n.containerState]),g(A)}function p(A){if(A===null){r&&y(),v(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){x(t.exit("chunkFlow"),!0),v(0),t.consume(A);return}return St(A)?(t.consume(A),x(t.exit("chunkFlow")),i=0,n.interrupt=void 0,d):(t.consume(A),b)}function x(A,j){const P=n.sliceStream(A);if(j&&P.push(null),A.previous=l,l&&(l.next=A),l=A,r.defineSkip(A.start),r.write(P),n.parser.lazy[A.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<o&&(!r.events[w][1].end||r.events[w][1].end.offset>o))return;const E=n.events.length;let k=E,T,C;for(;k--;)if(n.events[k][0]==="exit"&&n.events[k][1].type==="chunkFlow"){if(T){C=n.events[k][1].end;break}T=!0}for(v(i),w=E;w<n.events.length;)n.events[w][1].end={...C},w++;hs(n.events,k+1,0,n.events.slice(E)),n.events.length=w}}function v(A){let j=s.length;for(;j-- >A;){const P=s[j];n.containerState=P[1],P[0].exit.call(n,t)}s.length=A}function y(){r.write([null]),l=void 0,r=void 0,n.containerState._closeFlow=void 0}}function y1(t,n,s){return Ot(t,t.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ji(t){if(t===null||Yt(t)||wi(t))return 1;if(Zr(t))return 2}function el(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 Mo={name:"attention",resolveAll:k1,tokenize:j1};function k1(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};lu(h,-m),lu(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,el(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 j1(t,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Ji(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=Ji(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 lu(t,n){t.column+=n,t.offset+=n,t._bufferIndex+=n}const w1={name:"autolink",tokenize:N1};function N1(t,n,s){let i=0;return r;function r(f){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),l}function l(f){return Gn(f)?(t.consume(f),o):f===64?s(f):c(f)}function o(f){return f===43||f===45||f===46||zn(f)?(i=1,d(f)):c(f)}function d(f){return f===58?(t.consume(f),i=0,m):(f===43||f===45||f===46||zn(f))&&i++<32?(t.consume(f),d):(i=0,c(f))}function m(f){return f===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),n):f===null||f===32||f===60||$r(f)?s(f):(t.consume(f),m)}function c(f){return f===64?(t.consume(f),u):h1(f)?(t.consume(f),c):s(f)}function u(f){return zn(f)?h(f):s(f)}function h(f){return f===46?(t.consume(f),i=0,u):f===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(f),t.exit("autolinkMarker"),t.exit("autolink"),n):g(f)}function g(f){if((f===45||zn(f))&&i++<63){const p=f===45?g:h;return t.consume(f),p}return s(f)}}const Ya={partial:!0,tokenize:S1};function S1(t,n,s){return i;function i(l){return Ft(l)?Ot(t,r,"linePrefix")(l):r(l)}function r(l){return l===null||St(l)?n(l):s(l)}}const Qh={continuation:{tokenize:E1},exit:M1,name:"blockQuote",tokenize:C1};function C1(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 Ft(o)?(t.enter("blockQuotePrefixWhitespace"),t.consume(o),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),n):(t.exit("blockQuotePrefix"),n(o))}}function E1(t,n,s){const i=this;return r;function r(o){return Ft(o)?Ot(t,l,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):l(o)}function l(o){return t.attempt(Qh,n,s)(o)}}function M1(t){t.exit("blockQuote")}const Xh={name:"characterEscape",tokenize:A1};function A1(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 f1(l)?(t.enter("characterEscapeValue"),t.consume(l),t.exit("characterEscapeValue"),t.exit("characterEscape"),n):s(l)}}const Zh={name:"characterReference",tokenize:P1};function P1(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=zn,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=p1,u):(t.enter("characterReferenceValue"),l=7,o=Eo,u(h))}function u(h){if(h===59&&r){const g=t.exit("characterReferenceValue");return o===zn&&!lc(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 ou={partial:!0,tokenize:T1},cu={concrete:!0,name:"codeFenced",tokenize:R1};function R1(t,n,s){const i=this,r={partial:!0,tokenize:P};let l=0,o=0,d;return m;function m(w){return c(w)}function c(w){const E=i.events[i.events.length-1];return l=E&&E[1].type==="linePrefix"?E[2].sliceSerialize(E[1],!0).length:0,d=w,t.enter("codeFenced"),t.enter("codeFencedFence"),t.enter("codeFencedFenceSequence"),u(w)}function u(w){return w===d?(o++,t.consume(w),u):o<3?s(w):(t.exit("codeFencedFenceSequence"),Ft(w)?Ot(t,h,"whitespace")(w):h(w))}function h(w){return w===null||St(w)?(t.exit("codeFencedFence"),i.interrupt?n(w):t.check(ou,b,j)(w)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||St(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),h(w)):Ft(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ot(t,f,"whitespace")(w)):w===96&&w===d?s(w):(t.consume(w),g)}function f(w){return w===null||St(w)?h(w):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),p(w))}function p(w){return w===null||St(w)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),h(w)):w===96&&w===d?s(w):(t.consume(w),p)}function b(w){return t.attempt(r,j,x)(w)}function x(w){return t.enter("lineEnding"),t.consume(w),t.exit("lineEnding"),v}function v(w){return l>0&&Ft(w)?Ot(t,y,"linePrefix",l+1)(w):y(w)}function y(w){return w===null||St(w)?t.check(ou,b,j)(w):(t.enter("codeFlowValue"),A(w))}function A(w){return w===null||St(w)?(t.exit("codeFlowValue"),y(w)):(t.consume(w),A)}function j(w){return t.exit("codeFenced"),n(w)}function P(w,E,k){let T=0;return C;function C(_){return w.enter("lineEnding"),w.consume(_),w.exit("lineEnding"),$}function $(_){return w.enter("codeFencedFence"),Ft(_)?Ot(w,F,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):F(_)}function F(_){return _===d?(w.enter("codeFencedFenceSequence"),ee(_)):k(_)}function ee(_){return _===d?(T++,w.consume(_),ee):T>=o?(w.exit("codeFencedFenceSequence"),Ft(_)?Ot(w,I,"whitespace")(_):I(_)):k(_)}function I(_){return _===null||St(_)?(w.exit("codeFencedFence"),E(_)):k(_)}}}function T1(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 Ml={name:"codeIndented",tokenize:I1},_1={partial:!0,tokenize:$1};function I1(t,n,s){const i=this;return r;function r(c){return t.enter("codeIndented"),Ot(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):St(c)?t.attempt(_1,o,m)(c):(t.enter("codeFlowValue"),d(c))}function d(c){return c===null||St(c)?(t.exit("codeFlowValue"),o(c)):(t.consume(c),d)}function m(c){return t.exit("codeIndented"),n(c)}}function $1(t,n,s){const i=this;return r;function r(o){return i.parser.lazy[i.now().line]?s(o):St(o)?(t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),r):Ot(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):St(o)?r(o):s(o)}}const D1={name:"codeText",previous:L1,resolve:F1,tokenize:z1};function F1(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 L1(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function z1(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)):St(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||St(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 O1{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&&pa(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),pa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),pa(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);pa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);pa(this.left,s.reverse())}}}function pa(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 ep(t){const n={};let s=-1,i,r,l,o,d,m,c;const u=new O1(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,B1(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 B1(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,f=s,p=0,b=0;const x=[b];for(;f;){for(;t.get(++r)[1]!==f;);l.push(r),f._tokenizer||(u=i.sliceStream(f),f.next||u.push(null),h&&o.defineSkip(f.start),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),f._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),h=f,f=f.next}for(f=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,x.push(b),f._tokenizer=void 0,f.previous=void 0,f=f.next);for(o.events=[],f?(f._tokenizer=void 0,f.previous=void 0):x.pop(),g=x.length;g--;){const v=d.slice(x[g],x[g+1]),y=l.pop();m.push([y,y+v.length-1]),t.splice(y,2,v)}for(m.reverse(),g=-1;++g<m.length;)c[p+m[g][0]]=p+m[g][1],p+=m[g][1]-m[g][0]-1;return c}const U1={resolve:q1,tokenize:V1},H1={partial:!0,tokenize:W1};function q1(t){return ep(t),t}function V1(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):St(d)?t.check(H1,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 W1(t,n,s){const i=this;return r;function r(o){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),Ot(t,l,"linePrefix")}function l(o){if(o===null||St(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 tp(t,n,s,i,r,l,o,d,m){const c=m||Number.POSITIVE_INFINITY;let u=0;return h;function h(v){return v===60?(t.enter(i),t.enter(r),t.enter(l),t.consume(v),t.exit(l),g):v===null||v===32||v===41||$r(v)?s(v):(t.enter(i),t.enter(o),t.enter(d),t.enter("chunkString",{contentType:"string"}),b(v))}function g(v){return v===62?(t.enter(l),t.consume(v),t.exit(l),t.exit(r),t.exit(i),n):(t.enter(d),t.enter("chunkString",{contentType:"string"}),f(v))}function f(v){return v===62?(t.exit("chunkString"),t.exit(d),g(v)):v===null||v===60||St(v)?s(v):(t.consume(v),v===92?p:f)}function p(v){return v===60||v===62||v===92?(t.consume(v),f):f(v)}function b(v){return!u&&(v===null||v===41||Yt(v))?(t.exit("chunkString"),t.exit(d),t.exit(o),t.exit(i),n(v)):u<c&&v===40?(t.consume(v),u++,b):v===41?(t.consume(v),u--,b):v===null||v===32||v===40||$r(v)?s(v):(t.consume(v),v===92?x:b)}function x(v){return v===40||v===41||v===92?(t.consume(v),b):b(v)}}function np(t,n,s,i,r,l){const o=this;let d=0,m;return c;function c(f){return t.enter(i),t.enter(r),t.consume(f),t.exit(r),t.enter(l),u}function u(f){return d>999||f===null||f===91||f===93&&!m||f===94&&!d&&"_hiddenFootnoteSupport"in o.parser.constructs?s(f):f===93?(t.exit(l),t.enter(r),t.consume(f),t.exit(r),t.exit(i),n):St(f)?(t.enter("lineEnding"),t.consume(f),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),h(f))}function h(f){return f===null||f===91||f===93||St(f)||d++>999?(t.exit("chunkString"),u(f)):(t.consume(f),m||(m=!Ft(f)),f===92?g:h)}function g(f){return f===91||f===92||f===93?(t.consume(f),d++,h):h(f)}}function sp(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):St(g)?(t.enter("lineEnding"),t.consume(g),t.exit("lineEnding"),Ot(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===o||g===null||St(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 Aa(t,n){let s;return i;function i(r){return St(r)?(t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),s=!0,i):Ft(r)?Ot(t,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const K1={name:"definition",tokenize:J1},G1={partial:!0,tokenize:Y1};function J1(t,n,s){const i=this;let r;return l;function l(f){return t.enter("definition"),o(f)}function o(f){return np.call(i,t,d,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(f)}function d(f){return r=As(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),f===58?(t.enter("definitionMarker"),t.consume(f),t.exit("definitionMarker"),m):s(f)}function m(f){return Yt(f)?Aa(t,c)(f):c(f)}function c(f){return tp(t,u,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(f)}function u(f){return t.attempt(G1,h,h)(f)}function h(f){return Ft(f)?Ot(t,g,"whitespace")(f):g(f)}function g(f){return f===null||St(f)?(t.exit("definition"),i.parser.defined.push(r),n(f)):s(f)}}function Y1(t,n,s){return i;function i(d){return Yt(d)?Aa(t,r)(d):s(d)}function r(d){return sp(t,l,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function l(d){return Ft(d)?Ot(t,o,"whitespace")(d):o(d)}function o(d){return d===null||St(d)?n(d):s(d)}}const Q1={name:"hardBreakEscape",tokenize:X1};function X1(t,n,s){return i;function i(l){return t.enter("hardBreakEscape"),t.consume(l),r}function r(l){return St(l)?(t.exit("hardBreakEscape"),n(l)):s(l)}}const Z1={name:"headingAtx",resolve:eS,tokenize:tS};function eS(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 tS(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||Yt(u)?(t.exit("atxHeadingSequence"),d(u)):s(u)}function d(u){return u===35?(t.enter("atxHeadingSequence"),m(u)):u===null||St(u)?(t.exit("atxHeading"),n(u)):Ft(u)?Ot(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||Yt(u)?(t.exit("atxHeadingText"),d(u)):(t.consume(u),c)}}const nS=["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"],du=["pre","script","style","textarea"],sS={concrete:!0,name:"htmlFlow",resolveTo:rS,tokenize:lS},iS={partial:!0,tokenize:cS},aS={partial:!0,tokenize:oS};function rS(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 lS(t,n,s){const i=this;let r,l,o,d,m;return c;function c(S){return u(S)}function u(S){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(S),h}function h(S){return S===33?(t.consume(S),g):S===47?(t.consume(S),l=!0,b):S===63?(t.consume(S),r=3,i.interrupt?n:M):Gn(S)?(t.consume(S),o=String.fromCharCode(S),x):s(S)}function g(S){return S===45?(t.consume(S),r=2,f):S===91?(t.consume(S),r=5,d=0,p):Gn(S)?(t.consume(S),r=4,i.interrupt?n:M):s(S)}function f(S){return S===45?(t.consume(S),i.interrupt?n:M):s(S)}function p(S){const V="CDATA[";return S===V.charCodeAt(d++)?(t.consume(S),d===V.length?i.interrupt?n:F:p):s(S)}function b(S){return Gn(S)?(t.consume(S),o=String.fromCharCode(S),x):s(S)}function x(S){if(S===null||S===47||S===62||Yt(S)){const V=S===47,de=o.toLowerCase();return!V&&!l&&du.includes(de)?(r=1,i.interrupt?n(S):F(S)):nS.includes(o.toLowerCase())?(r=6,V?(t.consume(S),v):i.interrupt?n(S):F(S)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(S):l?y(S):A(S))}return S===45||zn(S)?(t.consume(S),o+=String.fromCharCode(S),x):s(S)}function v(S){return S===62?(t.consume(S),i.interrupt?n:F):s(S)}function y(S){return Ft(S)?(t.consume(S),y):C(S)}function A(S){return S===47?(t.consume(S),C):S===58||S===95||Gn(S)?(t.consume(S),j):Ft(S)?(t.consume(S),A):C(S)}function j(S){return S===45||S===46||S===58||S===95||zn(S)?(t.consume(S),j):P(S)}function P(S){return S===61?(t.consume(S),w):Ft(S)?(t.consume(S),P):A(S)}function w(S){return S===null||S===60||S===61||S===62||S===96?s(S):S===34||S===39?(t.consume(S),m=S,E):Ft(S)?(t.consume(S),w):k(S)}function E(S){return S===m?(t.consume(S),m=null,T):S===null||St(S)?s(S):(t.consume(S),E)}function k(S){return S===null||S===34||S===39||S===47||S===60||S===61||S===62||S===96||Yt(S)?P(S):(t.consume(S),k)}function T(S){return S===47||S===62||Ft(S)?A(S):s(S)}function C(S){return S===62?(t.consume(S),$):s(S)}function $(S){return S===null||St(S)?F(S):Ft(S)?(t.consume(S),$):s(S)}function F(S){return S===45&&r===2?(t.consume(S),N):S===60&&r===1?(t.consume(S),J):S===62&&r===4?(t.consume(S),O):S===63&&r===3?(t.consume(S),M):S===93&&r===5?(t.consume(S),G):St(S)&&(r===6||r===7)?(t.exit("htmlFlowData"),t.check(iS,X,ee)(S)):S===null||St(S)?(t.exit("htmlFlowData"),ee(S)):(t.consume(S),F)}function ee(S){return t.check(aS,I,X)(S)}function I(S){return t.enter("lineEnding"),t.consume(S),t.exit("lineEnding"),_}function _(S){return S===null||St(S)?ee(S):(t.enter("htmlFlowData"),F(S))}function N(S){return S===45?(t.consume(S),M):F(S)}function J(S){return S===47?(t.consume(S),o="",K):F(S)}function K(S){if(S===62){const V=o.toLowerCase();return du.includes(V)?(t.consume(S),O):F(S)}return Gn(S)&&o.length<8?(t.consume(S),o+=String.fromCharCode(S),K):F(S)}function G(S){return S===93?(t.consume(S),M):F(S)}function M(S){return S===62?(t.consume(S),O):S===45&&r===2?(t.consume(S),M):F(S)}function O(S){return S===null||St(S)?(t.exit("htmlFlowData"),X(S)):(t.consume(S),O)}function X(S){return t.exit("htmlFlow"),n(S)}}function oS(t,n,s){const i=this;return r;function r(o){return St(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 cS(t,n,s){return i;function i(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),t.attempt(Ya,n,s)}}const dS={name:"htmlText",tokenize:uS};function uS(t,n,s){const i=this;let r,l,o;return d;function d(M){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(M),m}function m(M){return M===33?(t.consume(M),c):M===47?(t.consume(M),P):M===63?(t.consume(M),A):Gn(M)?(t.consume(M),k):s(M)}function c(M){return M===45?(t.consume(M),u):M===91?(t.consume(M),l=0,p):Gn(M)?(t.consume(M),y):s(M)}function u(M){return M===45?(t.consume(M),f):s(M)}function h(M){return M===null?s(M):M===45?(t.consume(M),g):St(M)?(o=h,J(M)):(t.consume(M),h)}function g(M){return M===45?(t.consume(M),f):h(M)}function f(M){return M===62?N(M):M===45?g(M):h(M)}function p(M){const O="CDATA[";return M===O.charCodeAt(l++)?(t.consume(M),l===O.length?b:p):s(M)}function b(M){return M===null?s(M):M===93?(t.consume(M),x):St(M)?(o=b,J(M)):(t.consume(M),b)}function x(M){return M===93?(t.consume(M),v):b(M)}function v(M){return M===62?N(M):M===93?(t.consume(M),v):b(M)}function y(M){return M===null||M===62?N(M):St(M)?(o=y,J(M)):(t.consume(M),y)}function A(M){return M===null?s(M):M===63?(t.consume(M),j):St(M)?(o=A,J(M)):(t.consume(M),A)}function j(M){return M===62?N(M):A(M)}function P(M){return Gn(M)?(t.consume(M),w):s(M)}function w(M){return M===45||zn(M)?(t.consume(M),w):E(M)}function E(M){return St(M)?(o=E,J(M)):Ft(M)?(t.consume(M),E):N(M)}function k(M){return M===45||zn(M)?(t.consume(M),k):M===47||M===62||Yt(M)?T(M):s(M)}function T(M){return M===47?(t.consume(M),N):M===58||M===95||Gn(M)?(t.consume(M),C):St(M)?(o=T,J(M)):Ft(M)?(t.consume(M),T):N(M)}function C(M){return M===45||M===46||M===58||M===95||zn(M)?(t.consume(M),C):$(M)}function $(M){return M===61?(t.consume(M),F):St(M)?(o=$,J(M)):Ft(M)?(t.consume(M),$):T(M)}function F(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(t.consume(M),r=M,ee):St(M)?(o=F,J(M)):Ft(M)?(t.consume(M),F):(t.consume(M),I)}function ee(M){return M===r?(t.consume(M),r=void 0,_):M===null?s(M):St(M)?(o=ee,J(M)):(t.consume(M),ee)}function I(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||Yt(M)?T(M):(t.consume(M),I)}function _(M){return M===47||M===62||Yt(M)?T(M):s(M)}function N(M){return M===62?(t.consume(M),t.exit("htmlTextData"),t.exit("htmlText"),n):s(M)}function J(M){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(M),t.exit("lineEnding"),K}function K(M){return Ft(M)?Ot(t,G,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):G(M)}function G(M){return t.enter("htmlTextData"),o(M)}}const oc={name:"labelEnd",resolveAll:fS,resolveTo:gS,tokenize:bS},mS={tokenize:xS},hS={tokenize:vS},pS={tokenize:yS};function fS(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 gS(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,el(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 bS(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(mS,u,o?u:h)(g):g===91?t.attempt(hS,u,o?c:h)(g):o?u(g):h(g)}function c(g){return t.attempt(pS,u,h)(g)}function u(g){return n(g)}function h(g){return l._balanced=!0,s(g)}}function xS(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 Yt(h)?Aa(t,l)(h):l(h)}function l(h){return h===41?u(h):tp(t,o,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function o(h){return Yt(h)?Aa(t,m)(h):u(h)}function d(h){return s(h)}function m(h){return h===34||h===39||h===40?sp(t,c,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):u(h)}function c(h){return Yt(h)?Aa(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 vS(t,n,s){const i=this;return r;function r(d){return np.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 yS(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 kS={name:"labelStartImage",resolveAll:oc.resolveAll,tokenize:jS};function jS(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 wS={name:"labelStartLink",resolveAll:oc.resolveAll,tokenize:NS};function NS(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 Al={name:"lineEnding",tokenize:SS};function SS(t,n){return s;function s(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),Ot(t,n,"linePrefix")}}const jr={name:"thematicBreak",tokenize:CS};function CS(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||St(c))?(t.exit("thematicBreak"),n(c)):s(c)}function m(c){return c===r?(t.consume(c),i++,m):(t.exit("thematicBreakSequence"),Ft(c)?Ot(t,d,"whitespace")(c):d(c))}}const ts={continuation:{tokenize:PS},exit:TS,name:"list",tokenize:AS},ES={partial:!0,tokenize:_S},MS={partial:!0,tokenize:RS};function AS(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(f){const p=i.containerState.type||(f===42||f===43||f===45?"listUnordered":"listOrdered");if(p==="listUnordered"?!i.containerState.marker||f===i.containerState.marker:Eo(f)){if(i.containerState.type||(i.containerState.type=p,t.enter(p,{_container:!0})),p==="listUnordered")return t.enter("listItemPrefix"),f===42||f===45?t.check(jr,s,c)(f):c(f);if(!i.interrupt||f===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),m(f)}return s(f)}function m(f){return Eo(f)&&++o<10?(t.consume(f),m):(!i.interrupt||o<2)&&(i.containerState.marker?f===i.containerState.marker:f===41||f===46)?(t.exit("listItemValue"),c(f)):s(f)}function c(f){return t.enter("listItemMarker"),t.consume(f),t.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||f,t.check(Ya,i.interrupt?s:u,t.attempt(ES,g,h))}function u(f){return i.containerState.initialBlankLine=!0,l++,g(f)}function h(f){return Ft(f)?(t.enter("listItemPrefixWhitespace"),t.consume(f),t.exit("listItemPrefixWhitespace"),g):s(f)}function g(f){return i.containerState.size=l+i.sliceSerialize(t.exit("listItemPrefix"),!0).length,n(f)}}function PS(t,n,s){const i=this;return i.containerState._closeFlow=void 0,t.check(Ya,r,l);function r(d){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Ot(t,n,"listItemIndent",i.containerState.size+1)(d)}function l(d){return i.containerState.furtherBlankLines||!Ft(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(MS,n,o)(d))}function o(d){return i.containerState._closeFlow=!0,i.interrupt=void 0,Ot(t,t.attempt(ts,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function RS(t,n,s){const i=this;return Ot(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 TS(t){t.exit(this.containerState.type)}function _S(t,n,s){const i=this;return Ot(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!Ft(l)&&o&&o[1].type==="listItemPrefixWhitespace"?n(l):s(l)}}const uu={name:"setextUnderline",resolveTo:IS,tokenize:$S};function IS(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 $S(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"),Ft(c)?Ot(t,m,"lineSuffix")(c):m(c))}function m(c){return c===null||St(c)?(t.exit("setextHeadingLine"),n(c)):s(c)}}const DS={tokenize:FS};function FS(t){const n=this,s=t.attempt(Ya,i,t.attempt(this.parser.constructs.flowInitial,r,Ot(t,t.attempt(this.parser.constructs.flow,r,t.attempt(U1,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 LS={resolveAll:ap()},zS=ip("string"),OS=ip("text");function ip(t){return{resolveAll:ap(t==="text"?BS: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 f=h[g];if(!f.previous||f.previous.call(i,i.previous))return!0}return!1}}}function ap(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 BS(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 US={42:ts,43:ts,45:ts,48:ts,49:ts,50:ts,51:ts,52:ts,53:ts,54:ts,55:ts,56:ts,57:ts,62:Qh},HS={91:K1},qS={[-2]:Ml,[-1]:Ml,32:Ml},VS={35:Z1,42:jr,45:[uu,jr],60:sS,61:uu,95:jr,96:cu,126:cu},WS={38:Zh,92:Xh},KS={[-5]:Al,[-4]:Al,[-3]:Al,33:kS,38:Zh,42:Mo,60:[w1,dS],91:wS,92:[Q1,Xh],93:oc,95:Mo,96:D1},GS={null:[Mo,LS]},JS={null:[42,95]},YS={null:[]},QS=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:JS,contentInitial:HS,disable:YS,document:US,flow:VS,flowInitial:qS,insideSpan:GS,string:WS,text:KS},Symbol.toStringTag,{value:"Module"}));function XS(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:E(P),check:E(w),consume:y,enter:A,exit:j,interrupt:E(w,{interrupt:!0})},c={code:null,containerState:{},defineSkip:b,events:[],now:p,parser:t,previous:null,sliceSerialize:g,sliceStream:f,write:h};let u=n.tokenize.call(c,m);return n.resolveAll&&l.push(n),c;function h($){return o=js(o,$),x(),o[o.length-1]!==null?[]:(k(n,0),c.events=el(l,c.events,c),c.events)}function g($,F){return e0(f($),F)}function f($){return ZS(o,$)}function p(){const{_bufferIndex:$,_index:F,line:ee,column:I,offset:_}=i;return{_bufferIndex:$,_index:F,line:ee,column:I,offset:_}}function b($){r[$.line]=$.column,C()}function x(){let $;for(;i._index<o.length;){const F=o[i._index];if(typeof F=="string")for($=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===$&&i._bufferIndex<F.length;)v(F.charCodeAt(i._bufferIndex));else v(F)}}function v($){u=u($)}function y($){St($)?(i.line++,i.column=1,i.offset+=$===-3?2:1,C()):$!==-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=$}function A($,F){const ee=F||{};return ee.type=$,ee.start=p(),c.events.push(["enter",ee,c]),d.push(ee),ee}function j($){const F=d.pop();return F.end=p(),c.events.push(["exit",F,c]),F}function P($,F){k($,F.from)}function w($,F){F.restore()}function E($,F){return ee;function ee(I,_,N){let J,K,G,M;return Array.isArray(I)?X(I):"tokenize"in I?X([I]):O(I);function O(L){return Z;function Z(D){const me=D!==null&&L[D],q=D!==null&&L.null,W=[...Array.isArray(me)?me:me?[me]:[],...Array.isArray(q)?q:q?[q]:[]];return X(W)(D)}}function X(L){return J=L,K=0,L.length===0?N:S(L[K])}function S(L){return Z;function Z(D){return M=T(),G=L,L.partial||(c.currentConstruct=L),L.name&&c.parser.constructs.disable.null.includes(L.name)?de():L.tokenize.call(F?Object.assign(Object.create(c),F):c,m,V,de)(D)}}function V(L){return $(G,M),_}function de(L){return M.restore(),++K<J.length?S(J[K]):N}}}function k($,F){$.resolveAll&&!l.includes($)&&l.push($),$.resolve&&hs(c.events,F,c.events.length-F,$.resolve(c.events.slice(F),c)),$.resolveTo&&(c.events=$.resolveTo(c.events,c))}function T(){const $=p(),F=c.previous,ee=c.currentConstruct,I=c.events.length,_=Array.from(d);return{from:I,restore:N};function N(){i=$,c.previous=F,c.currentConstruct=ee,c.events.length=I,d=_,C()}}function C(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function ZS(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 e0(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=`
|
|
594
|
-
`;break}case-3:{o=`\r
|
|
595
|
-
`;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 t0(t){const i={constructs:Jh([QS,...(t||{}).extensions||[]]),content:r(g1),defined:[],document:r(x1),flow:r(DS),lazy:{},string:r(zS),text:r(OS)};return i;function r(l){return o;function o(d){return XS(i,l,d)}}}function n0(t){for(;!ep(t););return t}const mu=/[\0\t\n\r]/g;function s0(){let t=1,n="",s=!0,i;return r;function r(l,o,d){const m=[];let c,u,h,g,f;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(mu.lastIndex=h,c=mu.exec(l),g=c&&c.index!==void 0?c.index:l.length,f=l.charCodeAt(g),!c){n=l.slice(h);break}if(f===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),f){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 i0=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function a0(t){return t.replace(i0,r0)}function r0(t,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),l=r===120||r===88;return Yh(s.slice(l?2:1),l?16:10)}return lc(s)||t}const rp={}.hasOwnProperty;function l0(t,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),o0(s)(n0(t0(s).document().write(s0()(t,n,!0))))}function o0(t){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(rt),autolinkProtocol:T,autolinkEmail:T,atxHeading:l(Ee),blockQuote:l(q),characterEscape:T,characterReference:T,codeFenced:l(W),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:l(W,o),codeText:l(ce,o),codeTextData:T,data:T,codeFlowValue:T,definition:l(Se),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:l(ve),hardBreakEscape:l(Ae),hardBreakTrailing:l(Ae),htmlFlow:l(Oe,o),htmlFlowData:T,htmlText:l(Oe,o),htmlTextData:T,image:l(Fe),label:o,link:l(rt),listItem:l(Ie),listItemValue:g,listOrdered:l(Pe,h),listUnordered:l(Pe),paragraph:l(Be),reference:S,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:l(Ee),strong:l(nt),thematicBreak:l(Qe)},exit:{atxHeading:m(),atxHeadingSequence:P,autolink:m(),autolinkEmail:me,autolinkProtocol:D,blockQuote:m(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:de,characterReferenceMarkerNumeric:de,characterReferenceValue:L,characterReference:Z,codeFenced:m(x),codeFencedFence:b,codeFencedFenceInfo:f,codeFencedFenceMeta:p,codeFlowValue:C,codeIndented:m(v),codeText:m(_),codeTextData:C,data:C,definition:m(),definitionDestinationString:j,definitionLabelString:y,definitionTitleString:A,emphasis:m(),hardBreakEscape:m(F),hardBreakTrailing:m(F),htmlFlow:m(ee),htmlFlowData:C,htmlText:m(I),htmlTextData:C,image:m(J),label:G,labelText:K,lineEnding:$,link:m(N),listItem:m(),listOrdered:m(),listUnordered:m(),paragraph:m(),referenceString:V,resourceDestinationString:M,resourceTitleString:O,resource:X,setextHeading:m(k),setextHeadingLineSequence:E,setextHeadingText:w,strong:m(),thematicBreak:m()}};lp(n,(t||{}).mdastExtensions||[]);const s={};return i;function i(ie){let te={type:"root",children:[]};const fe={stack:[te],tokenStack:[],config:n,enter:d,exit:c,buffer:o,resume:u,data:s},ae=[];let _e=-1;for(;++_e<ie.length;)if(ie[_e][1].type==="listOrdered"||ie[_e][1].type==="listUnordered")if(ie[_e][0]==="enter")ae.push(_e);else{const ke=ae.pop();_e=r(ie,ke,_e)}for(_e=-1;++_e<ie.length;){const ke=n[ie[_e][0]];rp.call(ke,ie[_e][1].type)&&ke[ie[_e][1].type].call(Object.assign({sliceSerialize:ie[_e][2].sliceSerialize},fe),ie[_e][1])}if(fe.tokenStack.length>0){const ke=fe.tokenStack[fe.tokenStack.length-1];(ke[1]||hu).call(fe,void 0,ke[0])}for(te.position={start:Qs(ie.length>0?ie[0][1].start:{line:1,column:1,offset:0}),end:Qs(ie.length>0?ie[ie.length-2][1].end:{line:1,column:1,offset:0})},_e=-1;++_e<n.transforms.length;)te=n.transforms[_e](te)||te;return te}function r(ie,te,fe){let ae=te-1,_e=-1,ke=!1,He,dt,ht,he;for(;++ae<=fe;){const ne=ie[ae];switch(ne[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ne[0]==="enter"?_e++:_e--,he=void 0;break}case"lineEndingBlank":{ne[0]==="enter"&&(He&&!he&&!_e&&!ht&&(ht=ae),he=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:he=void 0}if(!_e&&ne[0]==="enter"&&ne[1].type==="listItemPrefix"||_e===-1&&ne[0]==="exit"&&(ne[1].type==="listUnordered"||ne[1].type==="listOrdered")){if(He){let ye=ae;for(dt=void 0;ye--;){const we=ie[ye];if(we[1].type==="lineEnding"||we[1].type==="lineEndingBlank"){if(we[0]==="exit")continue;dt&&(ie[dt][1].type="lineEndingBlank",ke=!0),we[1].type="lineEnding",dt=ye}else if(!(we[1].type==="linePrefix"||we[1].type==="blockQuotePrefix"||we[1].type==="blockQuotePrefixWhitespace"||we[1].type==="blockQuoteMarker"||we[1].type==="listItemIndent"))break}ht&&(!dt||ht<dt)&&(He._spread=!0),He.end=Object.assign({},dt?ie[dt][1].start:ne[1].end),ie.splice(dt||ae,0,["exit",He,ne[2]]),ae++,fe++}if(ne[1].type==="listItemPrefix"){const ye={type:"listItem",_spread:!1,start:Object.assign({},ne[1].start),end:void 0};He=ye,ie.splice(ae,0,["enter",ye,ne[2]]),ae++,fe++,ht=void 0,he=!0}}}return ie[te][1]._spread=ke,fe}function l(ie,te){return fe;function fe(ae){d.call(this,ie(ae),ae),te&&te.call(this,ae)}}function o(){this.stack.push({type:"fragment",children:[]})}function d(ie,te,fe){this.stack[this.stack.length-1].children.push(ie),this.stack.push(ie),this.tokenStack.push([te,fe||void 0]),ie.position={start:Qs(te.start),end:void 0}}function m(ie){return te;function te(fe){ie&&ie.call(this,fe),c.call(this,fe)}}function c(ie,te){const fe=this.stack.pop(),ae=this.tokenStack.pop();if(ae)ae[0].type!==ie.type&&(te?te.call(this,ie,ae[0]):(ae[1]||hu).call(this,ie,ae[0]));else throw new Error("Cannot close `"+ie.type+"` ("+Ma({start:ie.start,end:ie.end})+"): it’s not open");fe.position.end=Qs(ie.end)}function u(){return rc(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(ie){if(this.data.expectingFirstListItemValue){const te=this.stack[this.stack.length-2];te.start=Number.parseInt(this.sliceSerialize(ie),10),this.data.expectingFirstListItemValue=void 0}}function f(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.lang=ie}function p(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.meta=ie}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.value=ie.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function v(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.value=ie.replace(/(\r?\n|\r)$/g,"")}function y(ie){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.label=te,fe.identifier=As(this.sliceSerialize(ie)).toLowerCase()}function A(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.title=ie}function j(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.url=ie}function P(ie){const te=this.stack[this.stack.length-1];if(!te.depth){const fe=this.sliceSerialize(ie).length;te.depth=fe}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function E(ie){const te=this.stack[this.stack.length-1];te.depth=this.sliceSerialize(ie).codePointAt(0)===61?1:2}function k(){this.data.setextHeadingSlurpLineEnding=void 0}function T(ie){const fe=this.stack[this.stack.length-1].children;let ae=fe[fe.length-1];(!ae||ae.type!=="text")&&(ae=De(),ae.position={start:Qs(ie.start),end:void 0},fe.push(ae)),this.stack.push(ae)}function C(ie){const te=this.stack.pop();te.value+=this.sliceSerialize(ie),te.position.end=Qs(ie.end)}function $(ie){const te=this.stack[this.stack.length-1];if(this.data.atHardBreak){const fe=te.children[te.children.length-1];fe.position.end=Qs(ie.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(te.type)&&(T.call(this,ie),C.call(this,ie))}function F(){this.data.atHardBreak=!0}function ee(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.value=ie}function I(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.value=ie}function _(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.value=ie}function N(){const ie=this.stack[this.stack.length-1];if(this.data.inReference){const te=this.data.referenceType||"shortcut";ie.type+="Reference",ie.referenceType=te,delete ie.url,delete ie.title}else delete ie.identifier,delete ie.label;this.data.referenceType=void 0}function J(){const ie=this.stack[this.stack.length-1];if(this.data.inReference){const te=this.data.referenceType||"shortcut";ie.type+="Reference",ie.referenceType=te,delete ie.url,delete ie.title}else delete ie.identifier,delete ie.label;this.data.referenceType=void 0}function K(ie){const te=this.sliceSerialize(ie),fe=this.stack[this.stack.length-2];fe.label=a0(te),fe.identifier=As(te).toLowerCase()}function G(){const ie=this.stack[this.stack.length-1],te=this.resume(),fe=this.stack[this.stack.length-1];if(this.data.inReference=!0,fe.type==="link"){const ae=ie.children;fe.children=ae}else fe.alt=te}function M(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.url=ie}function O(){const ie=this.resume(),te=this.stack[this.stack.length-1];te.title=ie}function X(){this.data.inReference=void 0}function S(){this.data.referenceType="collapsed"}function V(ie){const te=this.resume(),fe=this.stack[this.stack.length-1];fe.label=te,fe.identifier=As(this.sliceSerialize(ie)).toLowerCase(),this.data.referenceType="full"}function de(ie){this.data.characterReferenceType=ie.type}function L(ie){const te=this.sliceSerialize(ie),fe=this.data.characterReferenceType;let ae;fe?(ae=Yh(te,fe==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ae=lc(te);const _e=this.stack[this.stack.length-1];_e.value+=ae}function Z(ie){const te=this.stack.pop();te.position.end=Qs(ie.end)}function D(ie){C.call(this,ie);const te=this.stack[this.stack.length-1];te.url=this.sliceSerialize(ie)}function me(ie){C.call(this,ie);const te=this.stack[this.stack.length-1];te.url="mailto:"+this.sliceSerialize(ie)}function q(){return{type:"blockquote",children:[]}}function W(){return{type:"code",lang:null,meta:null,value:""}}function ce(){return{type:"inlineCode",value:""}}function Se(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ve(){return{type:"emphasis",children:[]}}function Ee(){return{type:"heading",depth:0,children:[]}}function Ae(){return{type:"break"}}function Oe(){return{type:"html",value:""}}function Fe(){return{type:"image",title:null,url:"",alt:null}}function rt(){return{type:"link",title:null,url:"",children:[]}}function Pe(ie){return{type:"list",ordered:ie.type==="listOrdered",start:null,spread:ie._spread,children:[]}}function Ie(ie){return{type:"listItem",spread:ie._spread,checked:null,children:[]}}function Be(){return{type:"paragraph",children:[]}}function nt(){return{type:"strong",children:[]}}function De(){return{type:"text",value:""}}function Qe(){return{type:"thematicBreak"}}}function Qs(t){return{line:t.line,column:t.column,offset:t.offset}}function lp(t,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?lp(t,i):c0(t,i)}}function c0(t,n){let s;for(s in n)if(rp.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 hu(t,n){throw t?new Error("Cannot close `"+t.type+"` ("+Ma({start:t.start,end:t.end})+"): a different token (`"+n.type+"`, "+Ma({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Ma({start:n.start,end:n.end})+") is still open")}function d0(t){const n=this;n.parser=s;function s(i){return l0(i,{...n.data("settings"),...t,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function u0(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 m0(t,n){const s={type:"element",tagName:"br",properties:{},children:[]};return t.patch(n,s),[t.applyData(n,s),{type:"text",value:`
|
|
596
|
-
`}]}function h0(t,n){const s=n.value?n.value+`
|
|
597
|
-
`:"",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 p0(t,n){const s={type:"element",tagName:"del",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function f0(t,n){const s={type:"element",tagName:"em",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function g0(t,n){const s=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=la(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 b0(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 x0(t,n){if(t.options.allowDangerousHtml){const s={type:"raw",value:n.value};return t.patch(n,s),t.applyData(n,s)}}function op(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 v0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return op(t,n);const r={src:la(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 y0(t,n){const s={src:la(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 k0(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 j0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return op(t,n);const r={href:la(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 w0(t,n){const s={href:la(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 N0(t,n,s){const i=t.all(n),r=s?S0(s):cp(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:`
|
|
598
|
-
`}),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:`
|
|
599
|
-
`});const c={type:"element",tagName:"li",properties:l,children:o};return t.patch(n,c),t.applyData(n,c)}function S0(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=cp(s[i])}return n}function cp(t){const n=t.spread;return n??t.children.length>1}function C0(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 E0(t,n){const s={type:"element",tagName:"p",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function M0(t,n){const s={type:"root",children:t.wrap(t.all(n))};return t.patch(n,s),t.applyData(n,s)}function A0(t,n){const s={type:"element",tagName:"strong",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function P0(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=nc(n.children[1]),m=Uh(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 R0(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={},f=o?o[m]:void 0;f&&(g.align=f);let p={type:"element",tagName:l,properties:g,children:[]};h&&(p.children=t.all(h),t.patch(h,p),p=t.applyData(h,p)),c.push(p)}const u={type:"element",tagName:"tr",properties:{},children:t.wrap(c,!0)};return t.patch(n,u),t.applyData(n,u)}function T0(t,n){const s={type:"element",tagName:"td",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}const pu=9,fu=32;function _0(t){const n=String(t),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const l=[];for(;i;)l.push(gu(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return l.push(gu(n.slice(r),r>0,!1)),l.join("")}function gu(t,n,s){let i=0,r=t.length;if(n){let l=t.codePointAt(i);for(;l===pu||l===fu;)i++,l=t.codePointAt(i)}if(s){let l=t.codePointAt(r-1);for(;l===pu||l===fu;)r--,l=t.codePointAt(r-1)}return r>i?t.slice(i,r):""}function I0(t,n){const s={type:"text",value:_0(String(n.value))};return t.patch(n,s),t.applyData(n,s)}function $0(t,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(n,s),t.applyData(n,s)}const D0={blockquote:u0,break:m0,code:h0,delete:p0,emphasis:f0,footnoteReference:g0,heading:b0,html:x0,imageReference:v0,image:y0,inlineCode:k0,linkReference:j0,link:w0,listItem:N0,list:C0,paragraph:E0,root:M0,strong:A0,table:P0,tableCell:T0,tableRow:R0,text:I0,thematicBreak:$0,toml:cr,yaml:cr,definition:cr,footnoteDefinition:cr};function cr(){}const dp=-1,tl=0,Pa=1,Dr=2,cc=3,dc=4,uc=5,mc=6,up=7,mp=8,bu=typeof self=="object"?self:globalThis,F0=(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 tl:case dp:return s(o,r);case Pa:{const d=s([],r);for(const m of o)d.push(i(m));return d}case Dr:{const d=s({},r);for(const[m,c]of o)d[i(m)]=i(c);return d}case cc:return s(new Date(o),r);case dc:{const{source:d,flags:m}=o;return s(new RegExp(d,m),r)}case uc:{const d=s(new Map,r);for(const[m,c]of o)d.set(i(m),i(c));return d}case mc:{const d=s(new Set,r);for(const m of o)d.add(i(m));return d}case up:{const{name:d,message:m}=o;return s(new bu[d](m),r)}case mp: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 bu[l](o),r)};return i},xu=t=>F0(new Map,t)(0),$i="",{toString:L0}={},{keys:z0}=Object,fa=t=>{const n=typeof t;if(n!=="object"||!t)return[tl,n];const s=L0.call(t).slice(8,-1);switch(s){case"Array":return[Pa,$i];case"Object":return[Dr,$i];case"Date":return[cc,$i];case"RegExp":return[dc,$i];case"Map":return[uc,$i];case"Set":return[mc,$i];case"DataView":return[Pa,s]}return s.includes("Array")?[Pa,s]:s.includes("Error")?[up,s]:[Dr,s]},dr=([t,n])=>t===tl&&(n==="function"||n==="symbol"),O0=(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]=fa(o);switch(d){case tl:{let u=o;switch(m){case"bigint":d=mp,u=o.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+m);u=null;break;case"undefined":return r([dp],o)}return r([d,u],o)}case Pa:{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 Dr:{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 z0(o))(t||!dr(fa(o[g])))&&u.push([l(g),l(o[g])]);return h}case cc:return r([d,o.toISOString()],o);case dc:{const{source:u,flags:h}=o;return r([d,{source:u,flags:h}],o)}case uc:{const u=[],h=r([d,u],o);for(const[g,f]of o)(t||!(dr(fa(g))||dr(fa(f))))&&u.push([l(g),l(f)]);return h}case mc:{const u=[],h=r([d,u],o);for(const g of o)(t||!dr(fa(g)))&&u.push(l(g));return h}}const{message:c}=o;return r([d,{name:m,message:c}],o)};return l},vu=(t,{json:n,lossy:s}={})=>{const i=[];return O0(!(n||s),!!n,new Map,i)(t),i},Fr=typeof structuredClone=="function"?(t,n)=>n&&("json"in n||"lossy"in n)?xu(vu(t,n)):structuredClone(t):(t,n)=>xu(vu(t,n));function B0(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 U0(t,n){return"Back to reference "+(t+1)+(n>1?"-"+n:"")}function H0(t){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",s=t.options.footnoteBackContent||B0,i=t.options.footnoteBackLabel||U0,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=la(h.toLowerCase());let f=0;const p=[],b=t.footnoteCounts.get(h);for(;b!==void 0&&++f<=b;){p.length>0&&p.push({type:"text",value:" "});let y=typeof s=="string"?s:s(m,f);typeof y=="string"&&(y={type:"text",value:y}),p.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(f>1?"-"+f:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(m,f),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const x=u[u.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const y=x.children[x.children.length-1];y&&y.type==="text"?y.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...p)}else u.push(...p);const v={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:t.wrap(u,!0)};t.patch(c,v),d.push(v)}if(d.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:l,properties:{...Fr(o),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
600
|
-
`},{type:"element",tagName:"ol",properties:{},children:t.wrap(d,!0)},{type:"text",value:`
|
|
601
|
-
`}]}}const nl=(function(t){if(t==null)return K0;if(typeof t=="function")return sl(t);if(typeof t=="object")return Array.isArray(t)?q0(t):V0(t);if(typeof t=="string")return W0(t);throw new Error("Expected function, string, or object as test")});function q0(t){const n=[];let s=-1;for(;++s<t.length;)n[s]=nl(t[s]);return sl(i);function i(...r){let l=-1;for(;++l<n.length;)if(n[l].apply(this,r))return!0;return!1}}function V0(t){const n=t;return sl(s);function s(i){const r=i;let l;for(l in t)if(r[l]!==n[l])return!1;return!0}}function W0(t){return sl(n);function n(s){return s&&s.type===t}}function sl(t){return n;function n(s,i,r){return!!(G0(s)&&t.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function K0(){return!0}function G0(t){return t!==null&&typeof t=="object"&&"type"in t}const hp=[],J0=!0,Ao=!1,Y0="skip";function pp(t,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const l=nl(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 f=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(m.type+(f?"<"+f+">":""))+")"})}return g;function g(){let f=hp,p,b,x;if((!n||l(m,c,u[u.length-1]||void 0))&&(f=Q0(s(m,u)),f[0]===Ao))return f;if("children"in m&&m.children){const v=m;if(v.children&&f[0]!==Y0)for(b=(i?v.children.length:-1)+o,x=u.concat(v);b>-1&&b<v.children.length;){const y=v.children[b];if(p=d(y,b,x)(),p[0]===Ao)return p;b=typeof p[1]=="number"?p[1]:b+o}}return f}}}function Q0(t){return Array.isArray(t)?t:typeof t=="number"?[J0,t]:t==null?hp:[t]}function hc(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),pp(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 Po={}.hasOwnProperty,X0={};function Z0(t,n){const s=n||X0,i=new Map,r=new Map,l=new Map,o={...D0,...s.handlers},d={all:c,applyData:tC,definitionById:i,footnoteById:r,footnoteCounts:l,footnoteOrder:[],handlers:o,one:m,options:s,patch:eC,wrap:sC};return hc(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,f=d.handlers[g];if(Po.call(d.handlers,g)&&f)return f(d,u,h);if(d.options.passThrough&&d.options.passThrough.includes(g)){if("children"in u){const{children:b,...x}=u,v=Fr(x);return v.children=d.all(u),v}return Fr(u)}return(d.options.unknownHandler||nC)(d,u,h)}function c(u){const h=[];if("children"in u){const g=u.children;let f=-1;for(;++f<g.length;){const p=d.one(g[f],u);if(p){if(f&&g[f-1].type==="break"&&(!Array.isArray(p)&&p.type==="text"&&(p.value=yu(p.value)),!Array.isArray(p)&&p.type==="element")){const b=p.children[0];b&&b.type==="text"&&(b.value=yu(b.value))}Array.isArray(p)?h.push(...p):h.push(p)}}}return h}}function eC(t,n){t.position&&(n.position=UN(t))}function tC(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,Fr(l)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function nC(t,n){const s=n.data||{},i="value"in n&&!(Po.call(s,"hProperties")||Po.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 sC(t,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
|
|
602
|
-
`});++i<t.length;)i&&s.push({type:"text",value:`
|
|
603
|
-
`}),s.push(t[i]);return n&&t.length>0&&s.push({type:"text",value:`
|
|
604
|
-
`}),s}function yu(t){let n=0,s=t.charCodeAt(n);for(;s===9||s===32;)n++,s=t.charCodeAt(n);return t.slice(n)}function ku(t,n){const s=Z0(t,n),i=s.one(t,void 0),r=H0(s),l=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&l.children.push({type:"text",value:`
|
|
605
|
-
`},r),l}function iC(t,n){return t&&"run"in t?async function(s,i){const r=ku(s,{file:i,...n});await t.run(r,i)}:function(s,i){return ku(s,{file:i,...t||n})}}function ju(t){if(t)throw t}var Pl,wu;function aC(){if(wu)return Pl;wu=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 Pl=function m(){var c,u,h,g,f,p,b=arguments[0],x=1,v=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});x<v;++x)if(c=arguments[x],c!=null)for(u in c)h=d(b,u),g=d(c,u),b!==g&&(y&&g&&(l(g)||(f=r(g)))?(f?(f=!1,p=h&&r(h)?h:[]):p=h&&l(h)?h:{},o(b,{name:u,newValue:m(y,p,g)})):typeof g<"u"&&o(b,{name:u,newValue:g}));return b},Pl}var rC=aC();const Rl=Im(rC);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 lC(){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?oC(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 oC(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:cC,dirname:dC,extname:uC,join:mC,sep:"/"};function cC(t,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Qa(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 dC(t){if(Qa(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 uC(t){Qa(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 mC(...t){let n=-1,s;for(;++n<t.length;)Qa(t[n]),t[n]&&(s=s===void 0?t[n]:s+"/"+t[n]);return s===void 0?".":hC(s)}function hC(t){Qa(t);const n=t.codePointAt(0)===47;let s=pC(t,!n);return s.length===0&&!n&&(s="."),s.length>0&&t.codePointAt(t.length-1)===47&&(s+="/"),n?"/"+s:s}function pC(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 Qa(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const fC={cwd:gC};function gC(){return"/"}function To(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function bC(t){if(typeof t=="string")t=new URL(t);else if(!To(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 xC(t)}function xC(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 Tl=["history","path","basename","stem","extname","dirname"];class fp{constructor(n){let s;n?To(n)?s={path:n}:typeof n=="string"||vC(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":fC.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Tl.length;){const l=Tl[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)Tl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Is.basename(this.path):void 0}set basename(n){Il(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){Nu(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"),Nu(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){To(n)&&(n=bC(n)),Il(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){Il(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 Bn(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 Il(t,n){if(!t)throw new Error("`"+n+"` cannot be empty")}function Nu(t,n){if(!t)throw new Error("Setting `"+n+"` requires `path` to be set too")}function vC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const yC=(function(t){const i=this.constructor.prototype,r=i[t],l=function(){return r.apply(l,arguments)};return Object.setPrototypeOf(l,i),l}),kC={}.hasOwnProperty;class pc extends yC{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=lC()}copy(){const n=new pc;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?(Fl("data",this.frozen),this.namespace[n]=s,this):kC.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Fl("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=ur(n),i=this.parser||this.Parser;return $l("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),$l("process",this.parser||this.Parser),Dl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(l,o){const d=ur(n),m=i.parse(d);i.run(m,d,function(u,h,g){if(u||!h||!g)return c(u);const f=h,p=i.stringify(f,g);NC(p)?g.value=p:g.result=p,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(),$l("processSync",this.parser||this.Parser),Dl("processSync",this.compiler||this.Compiler),this.process(n,r),Cu("processSync","process",s),i;function r(l,o){s=!0,ju(l),i=o}}run(n,s,i){Su(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=ur(s);r.run(n,m,c);function c(u,h,g){const f=h||n;u?d(u):o?o(f):i(void 0,f,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,l),Cu("runSync","run",i),r;function l(o,d){ju(o),r=d,i=!0}}stringify(n,s){this.freeze();const i=ur(s),r=this.compiler||this.Compiler;return Dl("stringify",r),Su(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Fl("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[f,...p]=u;const b=i[g][1];Ro(b)&&Ro(f)&&(f=Rl(!0,b,f)),i[g]=[c,f,...p]}}}}const jC=new pc().freeze();function $l(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Dl(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Fl(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 Su(t){if(!Ro(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Cu(t,n,s){if(!s)throw new Error("`"+t+"` finished async. Use `"+n+"` instead")}function ur(t){return wC(t)?t:new fp(t)}function wC(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function NC(t){return typeof t=="string"||SC(t)}function SC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const CC="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Eu=[],Mu={allowDangerousHtml:!0},EC=/^(https?|ircs?|mailto|xmpp)$/i,MC=[{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 ni(t){const n=AC(t),s=PC(t);return RC(n.runSync(n.parse(s),s),t)}function AC(t){const n=t.rehypePlugins||Eu,s=t.remarkPlugins||Eu,i=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...Mu}:Mu;return jC().use(d0).use(s).use(iC,i).use(n)}function PC(t){const n=t.children||"",s=new fp;return typeof n=="string"&&(s.value=n),s}function RC(t,n){const s=n.allowedElements,i=n.allowElement,r=n.components,l=n.disallowedElements,o=n.skipHtml,d=n.unwrapDisallowed,m=n.urlTransform||TC;for(const u of MC)Object.hasOwn(n,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+CC+u.id,void 0);return hc(t,c),KN(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 f;for(f in El)if(Object.hasOwn(El,f)&&Object.hasOwn(u.properties,f)){const p=u.properties[f],b=El[f];(b===null||b.includes(u.tagName))&&(u.properties[f]=m(String(p||""),f,u))}}if(u.type==="element"){let f=s?!s.includes(u.tagName):l?l.includes(u.tagName):!1;if(!f&&i&&typeof h=="number"&&(f=!i(u,h,g)),f&&g&&typeof h=="number")return d&&u.children?g.children.splice(h,1,...u.children):g.children.splice(h,1),h}}}function TC(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||EC.test(t.slice(0,n))?t:""}function Au(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 _C(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function IC(t,n,s){const r=nl((s||{}).ignore||[]),l=$C(n);let o=-1;for(;++o<l.length;)pp(t,"text",d);function d(c,u){let h=-1,g;for(;++h<u.length;){const f=u[h],p=g?g.children:void 0;if(r(f,p?p.indexOf(f):void 0,g))return;g=f}if(g)return m(c,u)}function m(c,u){const h=u[u.length-1],g=l[o][0],f=l[o][1];let p=0;const x=h.children.indexOf(c);let v=!1,y=[];g.lastIndex=0;let A=g.exec(c.value);for(;A;){const j=A.index,P={index:A.index,input:A.input,stack:[...u,c]};let w=f(...A,P);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=j+1:(p!==j&&y.push({type:"text",value:c.value.slice(p,j)}),Array.isArray(w)?y.push(...w):w&&y.push(w),p=j+A[0].length,v=!0),!g.global)break;A=g.exec(c.value)}return v?(p<c.value.length&&y.push({type:"text",value:c.value.slice(p)}),h.children.splice(x,1,...y)):y=[c],x+y.length}}function $C(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([DC(r[0]),FC(r[1])])}return n}function DC(t){return typeof t=="string"?new RegExp(_C(t),"g"):t}function FC(t){return typeof t=="function"?t:function(){return t}}const Ll="phrasing",zl=["autolink","link","image","label"];function LC(){return{transforms:[VC],enter:{literalAutolink:OC,literalAutolinkEmail:Ol,literalAutolinkHttp:Ol,literalAutolinkWww:Ol},exit:{literalAutolink:qC,literalAutolinkEmail:HC,literalAutolinkHttp:BC,literalAutolinkWww:UC}}}function zC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ll,notInConstruct:zl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ll,notInConstruct:zl},{character:":",before:"[ps]",after:"\\/",inConstruct:Ll,notInConstruct:zl}]}}function OC(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function Ol(t){this.config.enter.autolinkProtocol.call(this,t)}function BC(t){this.config.exit.autolinkProtocol.call(this,t)}function UC(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 HC(t){this.config.exit.autolinkEmail.call(this,t)}function qC(t){this.exit(t)}function VC(t){IC(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,WC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,KC]],{ignore:["link","linkReference"]})}function WC(t,n,s,i,r){let l="";if(!gp(r)||(/^w/i.test(n)&&(s=n+s,n="",l="http://"),!GC(s)))return!1;const o=JC(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 KC(t,n,s,i){return!gp(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function GC(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 JC(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=Au(t,"(");let l=Au(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 gp(t,n){const s=t.input.charCodeAt(t.index-1);return(t.index===0||wi(s)||Zr(s))&&(!n||s!==47)}bp.peek=iE;function YC(){this.buffer()}function QC(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function XC(){this.buffer()}function ZC(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function eE(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 tE(t){this.exit(t)}function nE(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 sE(t){this.exit(t)}function iE(){return"["}function bp(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 aE(){return{enter:{gfmFootnoteCallString:YC,gfmFootnoteCall:QC,gfmFootnoteDefinitionLabelString:XC,gfmFootnoteDefinition:ZC},exit:{gfmFootnoteCallString:eE,gfmFootnoteCall:tE,gfmFootnoteDefinitionLabelString:nE,gfmFootnoteDefinition:sE}}}function rE(t){let n=!1;return t&&t.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:bp},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?`
|
|
606
|
-
`:" ")+l.indentLines(l.containerFlow(i,d.current()),n?xp:lE))),c(),m}}function lE(t,n,s){return n===0?t:xp(t,n,s)}function xp(t,n,s){return(s?"":" ")+t}const oE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];vp.peek=hE;function cE(){return{canContainEols:["delete"],enter:{strikethrough:uE},exit:{strikethrough:mE}}}function dE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:oE}],handlers:{delete:vp}}}function uE(t){this.enter({type:"delete",children:[]},t)}function mE(t){this.exit(t)}function vp(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 hE(){return"~"}function pE(t){return t.length}function fE(t,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||pE,l=[],o=[],d=[],m=[];let c=0,u=-1;for(;++u<t.length;){const b=[],x=[];let v=-1;for(t[u].length>c&&(c=t[u].length);++v<t[u].length;){const y=gE(t[u][v]);if(s.alignDelimiters!==!1){const A=r(y);x[v]=A,(m[v]===void 0||A>m[v])&&(m[v]=A)}b.push(y)}o[u]=b,d[u]=x}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<c;)l[h]=Pu(i[h]);else{const b=Pu(i);for(;++h<c;)l[h]=b}h=-1;const g=[],f=[];for(;++h<c;){const b=l[h];let x="",v="";b===99?(x=":",v=":"):b===108?x=":":b===114&&(v=":");let y=s.alignDelimiters===!1?1:Math.max(1,m[h]-x.length-v.length);const A=x+"-".repeat(y)+v;s.alignDelimiters!==!1&&(y=x.length+y+v.length,y>m[h]&&(m[h]=y),f[h]=y),g[h]=A}o.splice(1,0,g),d.splice(1,0,f),u=-1;const p=[];for(;++u<o.length;){const b=o[u],x=d[u];h=-1;const v=[];for(;++h<c;){const y=b[h]||"";let A="",j="";if(s.alignDelimiters!==!1){const P=m[h]-(x[h]||0),w=l[h];w===114?A=" ".repeat(P):w===99?P%2?(A=" ".repeat(P/2+.5),j=" ".repeat(P/2-.5)):(A=" ".repeat(P/2),j=A):j=" ".repeat(P)}s.delimiterStart!==!1&&!h&&v.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&v.push(" "),s.alignDelimiters!==!1&&v.push(A),v.push(y),s.alignDelimiters!==!1&&v.push(j),s.padding!==!1&&v.push(" "),(s.delimiterEnd!==!1||h!==c-1)&&v.push("|")}p.push(s.delimiterEnd===!1?v.join("").replace(/ +$/,""):v.join(""))}return p.join(`
|
|
607
|
-
`)}function gE(t){return t==null?"":String(t)}function Pu(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 bE(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()),xE);return r(),o}function xE(t,n,s){return">"+(s?"":" ")+t}function vE(t,n){return Ru(t,n.inConstruct,!0)&&!Ru(t,n.notInConstruct,!1)}function Ru(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 Tu(t,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
608
|
-
`&&vE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
|
|
609
|
-
`}function yE(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 kE(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 jE(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 wE(t,n,s,i){const r=jE(s),l=t.value||"",o=r==="`"?"GraveAccent":"Tilde";if(kE(t,s)){const h=s.enter("codeIndented"),g=s.indentLines(l,NE);return h(),g}const d=s.createTracker(i),m=r.repeat(Math.max(yE(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:`
|
|
610
|
-
`,encode:["`"],...d.current()})),h()}return u+=d.move(`
|
|
611
|
-
`),l&&(u+=d.move(l+`
|
|
612
|
-
`)),u+=d.move(m),c(),u}function NE(t,n,s){return(s?"":" ")+t}function fc(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 SE(t,n,s,i){const r=fc(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?" ":`
|
|
613
|
-
`,...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 CE(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 La(t){return"&#x"+t.toString(16).toUpperCase()+";"}function Lr(t,n,s){const i=Ji(t),r=Ji(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}}yp.peek=EE;function yp(t,n,s,i){const r=CE(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=Lr(i.before.charCodeAt(i.before.length-1),c,r);u.inside&&(m=La(c)+m.slice(1));const h=m.charCodeAt(m.length-1),g=Lr(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+La(h));const f=o.move(r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+f}function EE(t,n,s){return s.options.emphasis||"*"}function ME(t,n){let s=!1;return hc(t,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Ao}),!!((!t.depth||t.depth<3)&&rc(t)&&(n.options.setext||s))}function AE(t,n,s,i){const r=Math.max(Math.min(6,t.depth||1),1),l=s.createTracker(i);if(ME(t,s)){const u=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(t,{...l.current(),before:`
|
|
614
|
-
`,after:`
|
|
615
|
-
`});return h(),u(),g+`
|
|
616
|
-
`+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
|
|
617
|
-
`))+1))}const o="#".repeat(r),d=s.enter("headingAtx"),m=s.enter("phrasing");l.move(o+" ");let c=s.containerPhrasing(t,{before:"# ",after:`
|
|
618
|
-
`,...l.current()});return/^[\t ]/.test(c)&&(c=La(c.charCodeAt(0))+c.slice(1)),c=c?o+" "+c:o,s.options.closeAtx&&(c+=" "+o),m(),d(),c}kp.peek=PE;function kp(t){return t.value||""}function PE(){return"<"}jp.peek=RE;function jp(t,n,s,i){const r=fc(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 RE(){return"!"}wp.peek=TE;function wp(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 TE(){return"!"}Np.peek=_E;function Np(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 _E(){return"`"}function Sp(t,n){const s=rc(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))}Cp.peek=IE;function Cp(t,n,s,i){const r=fc(s),l=r==='"'?"Quote":"Apostrophe",o=s.createTracker(i);let d,m;if(Sp(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 IE(t,n,s){return Sp(t,s)?"<":"["}Ep.peek=$E;function Ep(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 $E(){return"["}function gc(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 DE(t){const n=gc(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 FE(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 Mp(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 LE(t,n,s,i){const r=s.enter("list"),l=s.bulletCurrent;let o=t.ordered?FE(s):gc(s);const d=t.ordered?o==="."?")":".":DE(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),Mp(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 zE(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 OE(t,n,s,i){const r=zE(s);let l=s.bulletCurrent||gc(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,f){return g?(f?"":" ".repeat(o))+h:(f?l:l+" ".repeat(o-l.length))+h}}function BE(t,n,s,i){const r=s.enter("paragraph"),l=s.enter("phrasing"),o=s.containerPhrasing(t,i);return l(),r(),o}const UE=nl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function HE(t,n,s,i){return(t.children.some(function(o){return UE(o)})?s.containerPhrasing:s.containerFlow).call(s,t,i)}function qE(t){const n=t.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Ap.peek=VE;function Ap(t,n,s,i){const r=qE(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=Lr(i.before.charCodeAt(i.before.length-1),c,r);u.inside&&(m=La(c)+m.slice(1));const h=m.charCodeAt(m.length-1),g=Lr(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+La(h));const f=o.move(r+r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+f}function VE(t,n,s){return s.options.strong||"*"}function WE(t,n,s,i){return s.safe(t.value,i)}function KE(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 GE(t,n,s){const i=(Mp(s)+(s.options.ruleSpaces?" ":"")).repeat(KE(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Pp={blockquote:bE,break:Tu,code:wE,definition:SE,emphasis:yp,hardBreak:Tu,heading:AE,html:kp,image:jp,imageReference:wp,inlineCode:Np,link:Cp,linkReference:Ep,list:LE,listItem:OE,paragraph:BE,root:HE,strong:Ap,text:WE,thematicBreak:GE};function JE(){return{enter:{table:YE,tableData:_u,tableHeader:_u,tableRow:XE},exit:{codeText:ZE,table:QE,tableData:Bl,tableHeader:Bl,tableRow:Bl}}}function YE(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 QE(t){this.exit(t),this.data.inTable=void 0}function XE(t){this.enter({type:"tableRow",children:[]},t)}function Bl(t){this.exit(t)}function _u(t){this.enter({type:"tableCell",children:[]},t)}function ZE(t){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,e2));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(t)}function e2(t,n){return n==="|"?n:t}function t2(t){const n=t||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,l=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
619
|
-
`,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(f,p,b,x){return c(u(f,b,x),f.align)}function d(f,p,b,x){const v=h(f,b,x),y=c([v]);return y.slice(0,y.indexOf(`
|
|
620
|
-
`))}function m(f,p,b,x){const v=b.enter("tableCell"),y=b.enter("phrasing"),A=b.containerPhrasing(f,{...x,before:l,after:l});return y(),v(),A}function c(f,p){return fE(f,{align:p,alignDelimiters:i,padding:s,stringLength:r})}function u(f,p,b){const x=f.children;let v=-1;const y=[],A=p.enter("table");for(;++v<x.length;)y[v]=h(x[v],p,b);return A(),y}function h(f,p,b){const x=f.children;let v=-1;const y=[],A=p.enter("tableRow");for(;++v<x.length;)y[v]=m(x[v],f,p,b);return A(),y}function g(f,p,b){let x=Pp.inlineCode(f,p,b);return b.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function n2(){return{exit:{taskListCheckValueChecked:Iu,taskListCheckValueUnchecked:Iu,paragraph:i2}}}function s2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:a2}}}function Iu(t){const n=this.stack[this.stack.length-2];n.type,n.checked=t.type==="taskListCheckValueChecked"}function i2(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 a2(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=Pp.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 r2(){return[LC(),aE(),cE(),JE(),n2()]}function l2(t){return{extensions:[zC(),rE(t),dE(),t2(t),s2()]}}const o2={tokenize:p2,partial:!0},Rp={tokenize:f2,partial:!0},Tp={tokenize:g2,partial:!0},_p={tokenize:b2,partial:!0},c2={tokenize:x2,partial:!0},Ip={name:"wwwAutolink",tokenize:m2,previous:Dp},$p={name:"protocolAutolink",tokenize:h2,previous:Fp},Gs={name:"emailAutolink",tokenize:u2,previous:Lp},Bs={};function d2(){return{text:Bs}}let hi=48;for(;hi<123;)Bs[hi]=Gs,hi++,hi===58?hi=65:hi===91&&(hi=97);Bs[43]=Gs;Bs[45]=Gs;Bs[46]=Gs;Bs[95]=Gs;Bs[72]=[Gs,$p];Bs[104]=[Gs,$p];Bs[87]=[Gs,Ip];Bs[119]=[Gs,Ip];function u2(t,n,s){const i=this;let r,l;return o;function o(h){return!_o(h)||!Lp.call(i,i.previous)||bc(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(c2,u,c)(h):h===45||h===95||zn(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&&Gn(i.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),n(h)):s(h)}}function m2(t,n,s){const i=this;return r;function r(o){return o!==87&&o!==119||!Dp.call(i,i.previous)||bc(i.events)?s(o):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(o2,t.attempt(Rp,t.attempt(Tp,l),s),s)(o))}function l(o){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),n(o)}}function h2(t,n,s){const i=this;let r="",l=!1;return o;function o(h){return(h===72||h===104)&&Fp.call(i,i.previous)&&!bc(i.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),t.consume(h),d):s(h)}function d(h){if(Gn(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||$r(h)||Yt(h)||wi(h)||Zr(h)?s(h):t.attempt(Rp,t.attempt(Tp,u),s)(h)}function u(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),n(h)}}function p2(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 f2(t,n,s){let i,r,l;return o;function o(c){return c===46||c===95?t.check(_p,m,d)(c):c===null||Yt(c)||wi(c)||c!==45&&Zr(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 g2(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(_p,n,l)(o):o===null||Yt(o)||wi(o)?n(o):(t.consume(o),r)}function l(o){return o===41&&i++,t.consume(o),r}}function b2(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||Yt(d)||wi(d)?n(d):s(d)}function r(d){return d===null||d===40||d===91||Yt(d)||wi(d)?n(d):i(d)}function l(d){return Gn(d)?o(d):s(d)}function o(d){return d===59?(t.consume(d),i):Gn(d)?(t.consume(d),o):s(d)}}function x2(t,n,s){return i;function i(l){return t.consume(l),r}function r(l){return zn(l)?s(l):n(l)}}function Dp(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Yt(t)}function Fp(t){return!Gn(t)}function Lp(t){return!(t===47||_o(t))}function _o(t){return t===43||t===45||t===46||t===95||zn(t)}function bc(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 v2={tokenize:E2,partial:!0};function y2(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:N2,continuation:{tokenize:S2},exit:C2}},text:{91:{name:"gfmFootnoteCall",tokenize:w2},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:k2,resolveTo:j2}}}}function k2(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 j2(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 w2(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||Yt(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 Yt(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 N2(t,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l,o=0,d;return m;function m(p){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(p),t.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(p){return p===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(p),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",u):s(p)}function u(p){if(o>999||p===93&&!d||p===null||p===91||Yt(p))return s(p);if(p===93){t.exit("chunkString");const b=t.exit("gfmFootnoteDefinitionLabelString");return l=As(i.sliceSerialize(b)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(p),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),g}return Yt(p)||(d=!0),o++,t.consume(p),p===92?h:u}function h(p){return p===91||p===92||p===93?(t.consume(p),o++,u):u(p)}function g(p){return p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),r.includes(l)||r.push(l),Ot(t,f,"gfmFootnoteDefinitionWhitespace")):s(p)}function f(p){return n(p)}}function S2(t,n,s){return t.check(Ya,n,t.attempt(v2,n,s))}function C2(t){t.exit("gfmFootnoteDefinition")}function E2(t,n,s){const i=this;return Ot(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 M2(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]],f=d.parser.constructs.insideSpan.null;f&&hs(g,g.length,0,el(f,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(p){return c===126&&u[u.length-1][1].type!=="characterEscape"?m(p):(o.enter("strikethroughSequenceTemporary"),f(p))}function f(p){const b=Ji(c);if(p===126)return h>1?m(p):(o.consume(p),h++,f);if(h<2&&!s)return m(p);const x=o.exit("strikethroughSequenceTemporary"),v=Ji(p);return x._open=!v||v===2&&!!b,x._close=!b||b===2&&!!v,d(p)}}}class A2{constructor(){this.map=[]}add(n,s,i){P2(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 P2(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 R2(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 T2(){return{flow:{null:{name:"table",tokenize:_2,resolveAll:I2}}}}function _2(t,n,s){const i=this;let r=0,l=0,o;return d;function d(C){let $=i.events.length-1;for(;$>-1;){const I=i.events[$][1].type;if(I==="lineEnding"||I==="linePrefix")$--;else break}const F=$>-1?i.events[$][1].type:null,ee=F==="tableHead"||F==="tableRow"?w:m;return ee===w&&i.parser.lazy[i.now().line]?s(C):ee(C)}function m(C){return t.enter("tableHead"),t.enter("tableRow"),c(C)}function c(C){return C===124||(o=!0,l+=1),u(C)}function u(C){return C===null?s(C):St(C)?l>1?(l=0,i.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(C),t.exit("lineEnding"),f):s(C):Ft(C)?Ot(t,u,"whitespace")(C):(l+=1,o&&(o=!1,r+=1),C===124?(t.enter("tableCellDivider"),t.consume(C),t.exit("tableCellDivider"),o=!0,u):(t.enter("data"),h(C)))}function h(C){return C===null||C===124||Yt(C)?(t.exit("data"),u(C)):(t.consume(C),C===92?g:h)}function g(C){return C===92||C===124?(t.consume(C),h):h(C)}function f(C){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(C):(t.enter("tableDelimiterRow"),o=!1,Ft(C)?Ot(t,p,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):p(C))}function p(C){return C===45||C===58?x(C):C===124?(o=!0,t.enter("tableCellDivider"),t.consume(C),t.exit("tableCellDivider"),b):P(C)}function b(C){return Ft(C)?Ot(t,x,"whitespace")(C):x(C)}function x(C){return C===58?(l+=1,o=!0,t.enter("tableDelimiterMarker"),t.consume(C),t.exit("tableDelimiterMarker"),v):C===45?(l+=1,v(C)):C===null||St(C)?j(C):P(C)}function v(C){return C===45?(t.enter("tableDelimiterFiller"),y(C)):P(C)}function y(C){return C===45?(t.consume(C),y):C===58?(o=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(C),t.exit("tableDelimiterMarker"),A):(t.exit("tableDelimiterFiller"),A(C))}function A(C){return Ft(C)?Ot(t,j,"whitespace")(C):j(C)}function j(C){return C===124?p(C):C===null||St(C)?!o||r!==l?P(C):(t.exit("tableDelimiterRow"),t.exit("tableHead"),n(C)):P(C)}function P(C){return s(C)}function w(C){return t.enter("tableRow"),E(C)}function E(C){return C===124?(t.enter("tableCellDivider"),t.consume(C),t.exit("tableCellDivider"),E):C===null||St(C)?(t.exit("tableRow"),n(C)):Ft(C)?Ot(t,E,"whitespace")(C):(t.enter("data"),k(C))}function k(C){return C===null||C===124||Yt(C)?(t.exit("data"),E(C)):(t.consume(C),C===92?T:k)}function T(C){return C===92||C===124?(t.consume(C),k):k(C)}}function I2(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 A2;for(;++s<t.length;){const f=t[s],p=f[1];f[0]==="enter"?p.type==="tableHead"?(d=!1,m!==0&&($u(g,n,m,c,u),u=void 0,m=0),c={type:"table",start:Object.assign({},p.start),end:Object.assign({},p.end)},g.add(s,0,[["enter",c,n]])):p.type==="tableRow"||p.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({},p.start),end:Object.assign({},p.end)},g.add(s,0,[["enter",u,n]])),r=p.type==="tableDelimiterRow"?2:u?3:1):r&&(p.type==="data"||p.type==="tableDelimiterMarker"||p.type==="tableDelimiterFiller")?(i=!1,o[2]===0&&(l[1]!==0&&(o[0]=o[1],h=mr(g,n,l,r,void 0,h),l=[0,0,0,0]),o[2]=s)):p.type==="tableCellDivider"&&(i?i=!1:(l[1]!==0&&(o[0]=o[1],h=mr(g,n,l,r,void 0,h)),l=o,o=[l[1],s,0,0])):p.type==="tableHead"?(d=!0,m=s):p.type==="tableRow"||p.type==="tableDelimiterRow"?(m=s,l[1]!==0?(o[0]=o[1],h=mr(g,n,l,r,s,h)):o[1]!==0&&(h=mr(g,n,o,r,s,h)),r=0):r&&(p.type==="data"||p.type==="tableDelimiterMarker"||p.type==="tableDelimiterFiller")&&(o[3]=s)}for(m!==0&&$u(g,n,m,c,u),g.consume(n.events),s=-1;++s<n.events.length;){const f=n.events[s];f[0]==="enter"&&f[1].type==="table"&&(f[1]._align=R2(n.events,s))}return t}function mr(t,n,s,i,r,l){const o=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",d="tableContent";s[0]!==0&&(l.end=Object.assign({},Fi(n.events,s[0])),t.add(s[0],0,[["exit",l,n]]));const m=Fi(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=Fi(n.events,s[2]),u=Fi(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]],f=n.events[s[3]];if(g[1].end=Object.assign({},f[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const p=s[2]+1,b=s[3]-s[2]-1;t.add(p,b,[])}}t.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(l.end=Object.assign({},Fi(n.events,r)),t.add(r,0,[["exit",l,n]]),l=void 0),l}function $u(t,n,s,i,r){const l=[],o=Fi(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 Fi(t,n){const s=t[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const $2={name:"tasklistCheck",tokenize:F2};function D2(){return{text:{91:$2}}}function F2(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 Yt(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 St(m)?n(m):Ft(m)?t.check({tokenize:L2},n,s)(m):s(m)}}function L2(t,n,s){return Ot(t,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function z2(t){return Jh([d2(),y2(),M2(t),T2(),D2()])}const O2={};function si(t){const n=this,s=t||O2,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),l=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),o=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(z2(s)),l.push(r2()),o.push(l2(s))}const Du=500,Fu=100;function Ul(t){return t.length>Du?t.slice(-Du):t}function zp(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),f=a.useRef(null),p=a.useRef(!1),b=a.useRef(0),x=a.useRef(t),v=a.useRef(s),y=a.useRef(n),A=a.useRef(0);(x.current!==t||v.current!==s||y.current!==n)&&(x.current=t,v.current=s,y.current=n,b.current++,p.current=!0,r([]),o(!1),m(!1),u(null),g(!1),f.current&&(f.current(),f.current=null)),a.useEffect(()=>{if(!t||!n){f.current&&(f.current(),f.current=null);return}const E=b.current,k=++A.current;p.current=!1;const T=t,C=s;async function $(){if(!T)return;o(!0),g(!1);try{const ee=await qc(T,C,{limit:Fu});if(p.current||b.current!==E||A.current!==k)return;r(Ul(ee.entries)),m(ee.hasMore),u(ee.total)}catch{if(p.current||b.current!==E||A.current!==k)return;r([]),m(!1),u(null)}finally{!p.current&&b.current===E&&A.current===k&&o(!1)}const F=C?`?projectId=${encodeURIComponent(C)}`:"";f.current=Os(`/api/tasks/${T}/logs/stream${F}`,{events:{"agent:log":ee=>{if(!(p.current||b.current!==E))try{const I=JSON.parse(ee.data);r(_=>Ul([..._,I])),u(_=>_!==null?_+1:null)}catch{}}}})}return $(),()=>{p.current=!0,f.current&&(f.current(),f.current=null)}},[t,n,s]);const P=a.useCallback(async()=>{if(!t||h)return;const E=b.current,k=i.length,T=t;g(!0);try{const C=await qc(T,s,{limit:Fu,offset:k});if(p.current||b.current!==E)return;r($=>{const F=[...C.entries,...$];return Ul(F)}),m(C.hasMore),u(C.total)}catch{}finally{g(!1)}},[t,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:l,clear:w,loadMore:P,hasMore:d,total:c,loadingMore:h}}function B2(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 Lu={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})},U2=50;function Op(t){return[t.taskId,t.timestamp,t.agent??"",t.type,t.text,t.detail??""].join("|")}function H2(t){const n=new Map;return t.map(s=>{const i=Op(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function q2({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),[f,p]=a.useState(!0),[b,x]=a.useState(!1),v=a.useMemo(()=>H2(t),[t]);a.useLayoutEffect(()=>{const k=c.current;if(!k)return;const T=t.length,C=u.current,$=h.current,F=v[v.length-1]??null,ee=g.current!==F;if(T>C){const I=k.scrollTop<=U2;if(ee)if(I)k.scrollTop=0;else{const _=k.scrollHeight-$;_>0&&(k.scrollTop+=_)}}u.current=T,h.current=k.scrollHeight,g.current=F},[t,v]);const y=a.useCallback(k=>{k.key==="Escape"&&b&&x(!1)},[b]);if(a.useEffect(()=>{if(b)return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[b,y]),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=[...v].reverse(),P=s?.provider&&s?.modelId,w=i?.provider&&i?.modelId,E=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:"}),P?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(is,{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:"}),w?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(is,{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:"}),E?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(is,{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:()=>p(k=>!k),"aria-label":f?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":f,"data-testid":"agent-log-mode-toggle",title:f?"Show raw text":"Show formatted markdown",children:f?"Markdown":"Plain"}),e.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(k=>!k),"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(Xs,{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((k,T)=>{const C=j[T]??`${Op(k)}|fallback`,$=A[T-1],F=k.type==="tool"||k.type==="tool_result"||k.type==="tool_error",ee=k.agent?F||T===0||$&&($.agent!==k.agent||$.type!==k.type):!1,I=ee?e.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:B2(k.timestamp)}):null,_=ee?e.jsxs("span",{className:"agent-log-badge-row",children:[e.jsxs("span",{className:"agent-log-agent-badge",children:["[",k.agent,"]"]}),I]}):null;return k.type==="tool"?e.jsxs("div",{className:"agent-log-tool",children:[_,"⚡ ",k.text,k.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",k.detail]})]},C):k.type==="thinking"?e.jsxs("span",{className:"agent-log-thinking",children:[_,f?e.jsx(ni,{remarkPlugins:[si],components:Lu,children:k.text}):k.text]},C):k.type==="tool_result"?e.jsxs("div",{className:"agent-log-tool-result",children:[_,"✓ ",k.text,k.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",k.detail]})]},C):k.type==="tool_error"?e.jsxs("div",{className:"agent-log-tool-error",children:[_,"✗ ",k.text,k.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",k.detail]})]},C):e.jsxs("span",{className:"agent-log-text",children:[_,f?e.jsx(ni,{remarkPlugins:[si],components:Lu,children:k.text}):k.text]},C)}),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 Yi(t){return t??void 0}function hr(t){return{provider:Yi(t.modelProvider),modelId:Yi(t.modelId)}}function pr(t){return{provider:Yi(t.validatorModelProvider),modelId:Yi(t.validatorModelId)}}function fr(t){return{provider:Yi(t.planningModelProvider),modelId:Yi(t.planningModelId)}}function V2(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function W2(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 K2(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 Hl(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 ql(t){return t.provider&&t.modelId?`${t.provider}/${t.modelId}`:""}function Vl(t,n){return t.provider===n.provider&&t.modelId===n.modelId}function G2(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 J2({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,f]=a.useState(null),[p,b]=a.useState(()=>hr(t)),[x,v]=a.useState(()=>hr(t)),[y,A]=a.useState(()=>pr(t)),[j,P]=a.useState(()=>pr(t)),[w,E]=a.useState(()=>fr(t)),[k,T]=a.useState(()=>fr(t)),[C,$]=a.useState(()=>t.thinkingLevel??null),[F,ee]=a.useState(()=>t.thinkingLevel??null),[I,_]=a.useState(null),N=a.useRef(t.id);a.useEffect(()=>{h(!0),f(null),Jn().then(ve=>{l(ve.models),d(ve.favoriteProviders),c(ve.favoriteModels)}).catch(ve=>{f(ve.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const J=a.useCallback(async ve=>{const Ee=o,Oe=Ee.includes(ve)?Ee.filter(Fe=>Fe!==ve):[ve,...Ee];d(Oe);try{await Gt({favoriteProviders:Oe,favoriteModels:m})}catch{d(Ee),n("Failed to update favorites","error")}},[o,m,n]),K=a.useCallback(async ve=>{const Ee=m,Oe=Ee.includes(ve)?Ee.filter(Fe=>Fe!==ve):[ve,...Ee];c(Oe);try{await Gt({favoriteProviders:o,favoriteModels:Oe})}catch{c(Ee),n("Failed to update model favorites","error")}},[m,o,n]);a.useEffect(()=>{N.current=t.id;const ve=hr(t),Ee=pr(t),Ae=fr(t);b(ve),v(ve),A(Ee),P(Ee),E(Ae),T(Ae);const Oe=t.thinkingLevel??null;$(Oe),ee(Oe),_(null)},[t.id,t.modelProvider,t.modelId,t.validatorModelProvider,t.validatorModelId,t.planningModelProvider,t.planningModelId,t.thinkingLevel]);const G=a.useMemo(()=>ql(p),[p]),M=a.useMemo(()=>ql(y),[y]),O=a.useMemo(()=>ql(w),[w]),X=a.useMemo(()=>V2(t,i),[t,i]),S=a.useMemo(()=>W2(t,i),[t,i]),V=a.useMemo(()=>K2(t,i),[t,i]),de=I!==null,L=a.useCallback(async(ve,Ee)=>{const Ae=t.id,Oe=x,Fe=j,rt=k;_(ve);try{const Pe=s?ve==="executor"?{modelProvider:Ee.provider??null,modelId:Ee.modelId??null}:ve==="validator"?{validatorModelProvider:Ee.provider??null,validatorModelId:Ee.modelId??null}:{planningModelProvider:Ee.provider??null,planningModelId:Ee.modelId??null}:{modelProvider:(ve==="executor"?Ee:x).provider??null,modelId:(ve==="executor"?Ee:x).modelId??null,validatorModelProvider:(ve==="validator"?Ee:j).provider??null,validatorModelId:(ve==="validator"?Ee:j).modelId??null,planningModelProvider:(ve==="planning"?Ee:k).provider??null,planningModelId:(ve==="planning"?Ee:k).modelId??null},Ie=await Ws(Ae,Pe);if(N.current!==Ae)return;const Be=hr(Ie),nt=pr(Ie),De=fr(Ie);v(Be),b(Be),P(nt),A(nt),T(De),E(De),s?.(Ie),n(G2(ve,{executor:Be,validator:nt,planning:De}[ve]),"success")}catch(Pe){if(N.current!==Ae)return;ve==="executor"?b(Oe):ve==="validator"?A(Fe):E(rt),n(ge(Pe)||"Failed to save model settings","error")}finally{N.current===Ae&&_(null)}},[t.id,x,j,k,n,s]),Z=a.useCallback(ve=>{const Ee=Hl(ve);b(Ee),!Vl(Ee,x)&&L("executor",Ee)},[x,L]),D=a.useCallback(ve=>{const Ee=Hl(ve);A(Ee),!Vl(Ee,j)&&L("validator",Ee)},[j,L]),me=a.useCallback(ve=>{const Ee=Hl(ve);E(Ee),!Vl(Ee,k)&&L("planning",Ee)},[k,L]),q=a.useCallback(async ve=>{const Ee=t.id,Ae=F,Oe=ve===""?null:ve;$(Oe),_("thinking");try{const Fe=await Ws(Ee,{thinkingLevel:Oe});if(N.current!==Ee)return;const rt=Fe.thinkingLevel??null;ee(rt),$(rt),s?.(Fe);const Pe=i?.defaultThinkingLevel??"off";n(rt===null?`Thinking level set to default (${Pe})`:`Thinking level set to ${rt}`,"success")}catch(Fe){if(N.current!==Ee)return;$(Ae),n(ge(Fe)||"Failed to save thinking level","error")}finally{N.current===Ee&&_(null)}},[t.id,F,i,n,s]),W=!x.provider&&!x.modelId,ce=!j.provider&&!j.modelId,Se=!k.provider&&!k.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),f(null),Jn().then(ve=>{l(ve.models),d(ve.favoriteProviders),c(ve.favoriteModels)}).catch(ve=>f(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:[x.provider&&e.jsx(is,{provider:x.provider,size:"sm"}),x.provider,"/",x.modelId]})}),e.jsx(Jt,{id:"executorModel",label:"Executor Model",value:G,onChange:Z,models:r,disabled:de,placeholder:"Select executor model…",favoriteProviders:o,onToggleFavorite:J,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:ce?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",S.provider&&S.modelId?` (${S.provider}/${S.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&e.jsx(is,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),e.jsx(Jt,{id:"validatorModel",label:"Validator Model",value:M,onChange:D,models:r,disabled:de,placeholder:"Select validator model…",favoriteProviders:o,onToggleFavorite:J,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:Se?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:[k.provider&&e.jsx(is,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),e.jsx(Jt,{id:"planningModel",label:"Planning Model",value:O,onChange:me,models:r,disabled:de,placeholder:"Select planning model…",favoriteProviders:o,onToggleFavorite:J,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:F===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:F})}),e.jsxs("select",{id:"thinkingLevel",value:C??"",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&&ce&&Se&&F===null?"Using global default models.":"Model settings are up to date."})]})]})}const Y2={open:e.jsx(Hr,{size:16}),closed:e.jsx(Ba,{size:16}),merged:e.jsx(qm,{size:16})};function Q2({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(""),[f,p]=a.useState(""),[b,x]=a.useState(!1),[v,y]=a.useState(!1),[A,j]=a.useState(null),P=a.useCallback(async()=>{if(h.trim()){x(!0);try{const T=await ov(t,{title:h.trim(),body:f.trim()||void 0},n);o(T),u(!1),g(""),p(""),m(`Created PR #${T.number}`,"success")}catch(T){m(ge(T)||"Failed to create PR","error")}finally{x(!1)}}},[t,h,f,n,o,m]),w=a.useCallback(async()=>{if(s){y(!0);try{const T=await cv(t,n);j(T),d(T.prInfo),m("PR status refreshed","success")}catch(T){m(ge(T)||"Failed to refresh PR","error")}finally{y(!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(ns,{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(ns,{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(ns,{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:T=>g(T.target.value),disabled:b,className:"pr-input"}),e.jsx("textarea",{placeholder:"PR description (optional)",value:f,onChange:T=>p(T.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:P,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ns,{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(Ht,{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 E=Y2[s.status]??e.jsx(Hr,{size:16}),k=A?.blockingReasons??[];return e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ns,{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:E}),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:w,disabled:v,title:"Refresh PR status",children:e.jsx(An,{size:14,style:{verticalAlign:"middle",opacity:v?.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:k.length>0?`Waiting for: ${k.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(Zs,{size:14}),s.commentCount]}),e.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[e.jsx(mg,{size:14}),"View on GitHub"]})]})]})]})}const zu=2e3;function X2(t){const n=t.updatedAt||t.createdAt,s=new Date(n).toLocaleString();return t.updatedAt?`${s} (edited)`:s}function Z2(t){return t==="agent"||t==="system"}function eM({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),[f,p]=a.useState(null),b=a.useMemo(()=>[...t.comments||[]].sort((E,k)=>new Date(k.createdAt).getTime()-new Date(E.createdAt).getTime()),[t.comments]),x=l.length>zu;async function v(){const E=l.trim();if(E){g(!0);try{const k=await Wx(t.id,E,r);o(""),n?.(k),s("Comment added","success")}catch(k){s(ge(k)||"Failed to add comment","error")}finally{g(!1)}}}async function y(E){const k=c.trim();if(k){g(!0);try{const T=await Bx(t.id,E,k,r);m(null),u(""),n?.(T),s("Comment updated","success")}catch(T){s(ge(T)||"Failed to update comment","error")}finally{g(!1)}}}async function A(E){p(E);try{const k=await Ux(t.id,E,r);n?.(k),s("Comment deleted","success")}catch(k){s(ge(k)||"Failed to delete comment","error")}finally{p(null)}}function j(E){E.key==="Enter"&&(E.ctrlKey||E.metaKey)&&(E.preventDefault(),v())}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(E=>{const k=E.author===i,T=d===E.id,C=Z2(E.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:[C?e.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):e.jsx("strong",{children:E.author}),e.jsx("span",{className:"detail-log-timestamp",children:X2(E)})]}),k&&!T?e.jsxs("div",{className:"comments-actions-row",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{m(E.id),u(E.text)},children:"Edit"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void A(E.id),disabled:f===E.id,children:f===E.id?"Deleting…":"Delete"})]}):null]}),T?e.jsxs("div",{className:"comments-edit-form",children:[e.jsx("textarea",{value:c,onChange:$=>u($.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 y(E.id),disabled:h||!c.trim(),children:"Save"})]})]}):e.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:E.text})]},E.id)})}),e.jsxs("div",{className:"comments-compose-form",children:[e.jsx("textarea",{value:l,onChange:E=>o(E.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${x?" comments-char-count--over":""}`,children:[l.length," / ",zu]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void v(),disabled:h||!l.trim()||x,children:h?"Posting…":"Add Comment"})]})]})]})}function tM(t){return t?t.slice(0,7):"Unknown"}function nM({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:tM(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 Bp(t){return t.split(`
|
|
621
|
-
`).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}
|
|
622
|
-
`},i):e.jsx($m.Fragment,{children:`${s}
|
|
623
|
-
`},i)})}function Ou(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 f=l-g.length;for(let p=0;p<r.length;p++){const b=r[p],x=t.slice(0,b);x.length<=f&&x.length+s.length+g.length<=n&&x.length+g.length>d&&(d=x.length+g.length,o=x+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 sM(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function iM({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(x=>x!==null&&x>0?x-1:x)},[]),f=a.useCallback(()=>{c(x=>x!==null&&x<s.length-1?x+1:x)},[]);if(a.useEffect(()=>{if(!t)return;const x=v=>{if(v.key==="Escape"){o();return}v.key==="ArrowUp"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),g()),v.key==="ArrowDown"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),f())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t,o,g,f]),!t)return null;const p=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:x=>x.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(Bo,{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:f,disabled:m===null||m>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:e.jsx(ln,{size:14})})]}),e.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:()=>h(x=>!x),title:u?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:e.jsx(Er,{size:14})}),d&&e.jsxs("button",{className:"btn btn-sm",onClick:d,children:[e.jsx(An,{size:14}),"Refresh"]}),e.jsx("button",{className:"modal-close",onClick:o,"aria-label":"Close",children:e.jsx(Lt,{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(Ra,{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((x,v)=>e.jsxs("button",{className:`changes-diff-file-item ${m===v?"selected":""}`,onClick:()=>c(v),title:x.path,children:[e.jsx("span",{className:`changes-file-status changes-file-status--${x.status}`,children:sM(x.status)}),e.jsx("span",{className:"changes-diff-file-path",children:x.path}),e.jsxs("span",{className:"changes-diff-file-stat",children:["+",x.additions," -",x.deletions]})]},x.path))})]}),e.jsx("div",{className:"changes-diff-content",children:p?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:p.path}),e.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",p.additions," -",p.deletions]})]}),p.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:Bp(p.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 Bu(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function aM({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,f]=a.useState(null),[p,b]=a.useState(new Set),[x,v]=a.useState(null),[y,A]=a.useState(!0),[j,P]=a.useState(!1),w=i==="done",E=w&&!!r?.commitSha,k=i==="in-progress"||i==="in-review"||E,T=a.useCallback(async()=>{if(!k){h(!1);return}try{h(!0),f(null);const I=await mh(t,void 0,s),_=I.files.map(N=>({path:N.path,status:N.status,additions:N.additions,deletions:N.deletions,patch:N.patch}));d(_),c(I.stats),_.length>0&&(b(new Set([_[0].path])),v(0))}catch(I){f(ge(I)||"Failed to load diff")}finally{h(!1)}},[t,s,k]);a.useEffect(()=>{T()},[T]);const C=I=>{b(_=>{const N=new Set(_);if(N.has(I))N.delete(I);else{N.add(I);const J=o.findIndex(K=>K.path===I);J!==-1&&v(J)}return N})},$=I=>{if(I<0||I>=o.length)return;const _=o[I].path;b(new Set([_])),v(I)},F=x!==null&&x>0,ee=x!==null&&x<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(as,{size:16}),e.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!w&&!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(w&&!E){const I=r?.filesChanged,_=r?.insertions,N=r?.deletions,J=I!=null||_!=null||N!=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:J?`Merge summary: ${I??0} file${(I??0)===1?"":"s"} changed, +${_??0} additions, -${N??0} deletions.`:"No merge commit was recorded for this task."})]})})}return o.length===0?w&&l&&l.length>0?e.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Ra,{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(I=>e.jsx("div",{className:"changes-file-item",children:e.jsxs("div",{className:"changes-file-header",children:[e.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Bu("unknown")}),e.jsx("span",{className:"changes-file-path",title:I,children:Ou(I)})]})},I))})]}):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:w?"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:[w&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Ra,{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:()=>F&&$(x-1),disabled:!F,title:"Previous file","aria-label":"Previous file",children:e.jsx(Bo,{size:14})}),e.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:x!==null?`${x+1}/${o.length}`:`—/${o.length}`}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>ee&&$(x+1),disabled:!ee,title:"Next file","aria-label":"Next file",children:e.jsx(ln,{size:14})})]}),e.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>A(I=>!I),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:e.jsx(Er,{size:14})})]}),e.jsxs("div",{className:"changes-header-actions-secondary",children:[e.jsx("button",{className:"btn btn-sm",onClick:T,disabled:u,children:"Refresh"}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>P(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:e.jsx(Xs,{size:14})})]})]})]}),e.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map(I=>{const _=p.has(I.path);return e.jsxs("div",{className:`changes-file-item ${_?"expanded":""}`,children:[e.jsxs("button",{className:"changes-file-header",onClick:()=>C(I.path),children:[e.jsx("span",{className:"changes-file-toggle",children:_?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})}),e.jsx("span",{className:`changes-file-status changes-file-status--${I.status}`,title:I.status,children:Bu(I.status)}),e.jsx("span",{className:"changes-file-path",title:I.path,children:Ou(I.path)}),e.jsxs("span",{className:"changes-file-stat",title:`+${I.additions} -${I.deletions}`,children:["+",I.additions," -",I.deletions]})]}),_&&I.patch&&e.jsx("div",{className:"changes-file-content",children:e.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:e.jsx("code",{children:Bp(I.patch)})})})]},I.path)})}),e.jsx(iM,{isOpen:j,taskId:t,files:o,stats:m,mergeDetails:r,column:i,onClose:()=>P(!1),onRefresh:T})]})}function Io(t){return{executorValue:t?.executorProvider&&t?.executorModelId?`${t.executorProvider}/${t.executorModelId}`:"",validatorValue:t?.validatorProvider&&t?.validatorModelId?`${t.validatorProvider}/${t.validatorModelId}`:""}}function rM(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function lM(t,n){const s=rM(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 Uu=["image/png","image/jpeg","image/gif","image/webp"];function oM(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 Up({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:f,onPlanningModelChange:p,thinkingLevel:b,onThinkingLevelChange:x,presetMode:v,onPresetModeChange:y,selectedPresetId:A,onSelectedPresetIdChange:j,selectedWorkflowSteps:P,onWorkflowStepsChange:w,onDefaultOnApplied:E,pendingImages:k,onImagesChange:T,tasks:C,projectId:$,disabled:F=!1,addToast:ee,isActive:I=!0,onAutoSaveDescription:_,onPlanningMode:N,onSubtaskBreakdown:J,onClose:K,renderBelowPrimary:G,hideDependencies:M,reviewLevel:O,onReviewLevelChange:X}){const S=(M?!1:l.length>0)||k.length>0||P.length>0||v!=="default"||(d??ds)!==ds||c!==""||h!==""||(f||"")!==""||(b||"")!==""||O!==void 0,[V,de]=a.useState(!1),[L,Z]=a.useState(S),[D,me]=a.useState(""),[q,W]=a.useState([]),[ce,Se]=a.useState([]),[ve,Ee]=a.useState([]),[Ae,Oe]=a.useState(!1),[Fe,rt]=a.useState(null),[Pe,Ie]=a.useState([]),[Be,nt]=a.useState("idle"),[De,Qe]=a.useState(!1),[ie,te]=a.useState(!1),[fe,ae]=a.useState(!1),_e=a.useRef(null),ke=a.useRef(null),He=a.useRef(null),dt=a.useRef(null),ht=a.useRef(null),he=a.useRef(null),ne=a.useRef(null),ye=a.useRef(!1),we=a.useRef(S),st=a.useRef(n.trim()),be=a.useRef(n.trim());a.useEffect(()=>{I&&(Oe(!0),Jn().then(U=>{W(U.models),Se(U.favoriteProviders),Ee(U.favoriteModels)}).catch(()=>{}).finally(()=>Oe(!1)),Wi($).then(U=>rt(U)).catch(()=>rt(null)),Gr($).then(U=>Ie(U.filter(Ne=>Ne.enabled))).catch(()=>Ie([])))},[I,$]);const it=Fe?.modelPresets||[],Me=it.find(U=>U.id===A),qe=(M?!1:l.length>0)||k.length>0||P.length>0||v!=="default"||(d??ds)!==ds||c!==""||h!==""||(f||"")!==""||(b||"")!==""||O!==void 0;a.useEffect(()=>{if(t!=="create"||!I||!Fe?.autoSelectModelPreset)return;const U=(Fe.defaultPresetBySize,void 0);if(U){const Ne=Io(U);j(U.id),y("preset"),u(Ne.executorValue),g(Ne.validatorValue)}},[I,Fe,it,t]);const oe=a.useRef(!1);a.useEffect(()=>{if(t!=="create"||!I||oe.current||Pe.length===0)return;const U=Pe.filter(pt=>pt.defaultOn);if(U.length===0)return;oe.current=!0;const Ne=U.map(pt=>pt.id);w(Ne),E?.(Ne)},[t,I,Pe]),a.useEffect(()=>{I||(oe.current=!1)},[I]),a.useEffect(()=>{qe&&!we.current&&Z(!0),we.current=qe},[qe]),a.useEffect(()=>{L||(de(!1),me(""))},[L]),a.useEffect(()=>{t!=="edit"||!I||dt.current&&(dt.current.focus(),dt.current.select())},[t,I]),a.useEffect(()=>{if(!V)return;const U=Ne=>{ke.current&&!ke.current.contains(Ne.target)&&de(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[V]),a.useEffect(()=>{(t!=="edit"||F)&&ae(!1)},[t,F]),a.useEffect(()=>{if(t!=="edit"){nt("idle");return}const U=n.trim();st.current=U,be.current=U,nt("idle")},[t]),a.useEffect(()=>{if(t!=="edit"||!_||!I)return;const U=n.trim(),Ne=st.current;if(U===Ne||U===be.current){he.current&&(clearTimeout(he.current),he.current=null),ye.current||nt("idle");return}return he.current&&clearTimeout(he.current),he.current=setTimeout(async()=>{if(!ye.current){ye.current=!0,nt("saving");try{await _(U),be.current=U,nt("saved"),ne.current&&clearTimeout(ne.current),ne.current=setTimeout(()=>{nt("idle"),ne.current=null},2e3)}catch{nt("idle")}finally{ye.current=!1,he.current=null}}},1500),()=>{he.current&&(clearTimeout(he.current),he.current=null)}},[t,n,_,I]),a.useEffect(()=>()=>{he.current&&clearTimeout(he.current),ne.current&&clearTimeout(ne.current)},[]),a.useEffect(()=>{if(!De)return;const U=Ne=>{_e.current&&!_e.current.contains(Ne.target)&&Qe(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[De]);const Ve=a.useCallback(U=>{const Ne=U.clipboardData?.items;if(Ne)for(let pt=0;pt<Ne.length;pt++){const kt=Ne[pt];if(kt.type.startsWith("image/")){const je=kt.getAsFile();if(je&&Uu.includes(je.type)){U.preventDefault(),T([...k,{file:je,previewUrl:URL.createObjectURL(je)}]);return}}}},[k,T]),We=a.useCallback(U=>{U.preventDefault();const Ne=U.dataTransfer.files;for(let pt=0;pt<Ne.length;pt++){const kt=Ne[pt];if(Uu.includes(kt.type)){T([...k,{file:kt,previewUrl:URL.createObjectURL(kt)}]);return}}},[k,T]),Re=a.useCallback(U=>{const Ne=k[U];Ne&&URL.revokeObjectURL(Ne.previewUrl),T(k.filter((pt,kt)=>kt!==U))},[k,T]),et=a.useCallback(U=>{o(l.includes(U)?l.filter(Ne=>Ne!==U):[...l,U])},[l,o]),xt=(U,Ne)=>U.length>Ne?U.slice(0,Ne)+"…":U,wt=a.useCallback(U=>{s(U.target.value);const Ne=U.target;Ne.style.height="auto",Ne.style.height=Ne.scrollHeight+"px"},[s]),Et=a.useCallback(()=>{ae(U=>!U)},[]),Rt=a.useCallback(U=>{!fe||U.key!=="Escape"||(U.preventDefault(),U.stopPropagation(),ae(!1))},[fe]),$t=a.useCallback(async U=>{const Ne=n.trim();if(!(!Ne||ie)){te(!0);try{const pt=await lh(Ne,U,$);s(pt),Qe(!1),ee("Description refined with AI","success"),He.current&&(He.current.style.height="auto",He.current.style.height=He.current.scrollHeight+"px")}catch(pt){const kt=oh(pt);ee(kt,"error")}finally{te(!1)}}},[n,ie,ee,s,$]),_t=a.useCallback(async U=>{const Ne=ce,kt=Ne.includes(U)?Ne.filter(je=>je!==U):[U,...Ne];Se(kt);try{await Gt({favoriteProviders:kt,favoriteModels:ve})}catch{Se(Ne)}},[ce,ve]),vt=a.useCallback(async U=>{const Ne=ve,kt=Ne.includes(U)?Ne.filter(je=>je!==U):[U,...Ne];Ee(kt);try{await Gt({favoriteProviders:ce,favoriteModels:kt})}catch{Ee(Ne)}},[ve,ce]),Dt=a.useCallback(U=>{if(U<=0)return;const Ne=[...P];[Ne[U-1],Ne[U]]=[Ne[U],Ne[U-1]],w(Ne)},[P,w]),Ke=a.useCallback(U=>{if(U>=P.length-1)return;const Ne=[...P];[Ne[U],Ne[U+1]]=[Ne[U+1],Ne[U]],w(Ne)},[P,w]),bt=a.useCallback(U=>{w(P.filter(Ne=>Ne!==U))},[P,w]),Le=new Map;for(const U of Pe)Le.set(U.id,{name:U.name,description:U.description});const lt=C.filter(U=>!l.includes(U.id)).sort((U,Ne)=>{const pt=Ne.createdAt.localeCompare(U.createdAt);if(pt!==0)return pt;const kt=parseInt(U.id.slice(U.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ne.id.slice(Ne.id.lastIndexOf("-")+1),10)||0)-kt}),xe=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:Ve,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:F})]}),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${Be==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Be==="saving"?"Saving...":Be==="saved"?"Saved":""})]}),e.jsxs("div",{className:`description-with-refine${fe?" description--fullscreen":""}`,ref:_e,onKeyDown:Rt,children:[fe&&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:Et,"aria-label":"Collapse description",title:"Collapse description",children:e.jsx(Ks,{size:14})})]}),e.jsx("textarea",{ref:He,autoFocus:t==="create",id:"task-form-description",value:n,onChange:wt,placeholder:"What needs to be done?",rows:t==="edit"?8:5,disabled:F||ie}),(()=>{const U=!!n.trim()&&!F;return e.jsxs(e.Fragment,{children:[!fe&&e.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${U?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Et,"aria-label":"Expand description",title:"Expand description",children:e.jsx(Xs,{size:14})}),U&&e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ie?"refine-button--loading":""}`,onClick:()=>Qe(Ne=>!Ne),disabled:ie,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(On,{size:12,style:{verticalAlign:"middle"}}),ie?"Refining...":"Refine"]})]})})(),De&&e.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:U=>U.preventDefault(),children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>$t("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:()=>$t("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:()=>$t("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:()=>$t("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"&&(N||J)&&e.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[N&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const U=n.trim();if(!U){ee("Enter a description first","error");return}K?.(),N(U)},disabled:F||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),J&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const U=n.trim();if(!U){ee("Enter a description first","error");return}K?.(),J(U)},disabled:F||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),G,e.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Z(U=>!U),"aria-expanded":L,"aria-controls":"task-form-more-options",disabled:F,"data-testid":"task-form-more-options-toggle",children:[e.jsx("span",{children:"More options"}),L?e.jsx(Ds,{size:14}):e.jsx(zt,{size:14})]}),e.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${L?"":" collapsed"}`,"aria-hidden":!L,"data-testid":"task-form-more-options",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Attachments"}),k.length>0&&e.jsx("div",{className:"inline-create-previews",children:k.map((U,Ne)=>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:()=>Re(Ne),disabled:F,title:"Remove image",children:"×"})]},U.previewUrl))}),e.jsx("input",{ref:ht,type:"file",accept:"image/*",onChange:U=>{const Ne=U.target.files?.[0];Ne&&(T([...k,{file:Ne,previewUrl:URL.createObjectURL(Ne)}]),U.target.value="")},style:{display:"none"}}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ht.current?.click(),disabled:F,children:"Attach Screenshot"}),e.jsx("small",{children:"You can also paste images or drag & drop"})]}),!M&&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:ke,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(U=>!U),disabled:F,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=>me(U.target.value),onClick:U=>U.stopPropagation()}),xe.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):xe.map(U=>e.jsxs("div",{className:`dep-dropdown-item${l.includes(U.id)?" selected":""}`,onClick:()=>et(U.id),onMouseDown:Ne=>Ne.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:U.id}),e.jsx("span",{className:"dep-dropdown-title",children:xt(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:()=>et(U),disabled:F,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:F,children:Ko.map(U=>e.jsx("option",{value:U,children:U[0].toUpperCase()+U.slice(1)},U))})]}),Ae?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:v==="preset"?A:v,onChange:U=>{const Ne=U.target.value;if(Ne==="default"){y("default"),j(""),u(""),g("");return}if(Ne==="custom"){y("custom"),j("");return}const pt=it.find(je=>je.id===Ne),kt=Io(pt);y("preset"),j(Ne),u(kt.executorValue),g(kt.validatorValue)},disabled:F,children:[e.jsx("option",{value:"default",children:"Use default"}),it.length>0?e.jsx("option",{disabled:!0,children:"──────────"}):null,it.map(U=>e.jsx("option",{value:U.id,children:U.name},U.id)),e.jsx("option",{value:"custom",children:"Custom"})]})]}),v==="preset"&&Me?e.jsxs("small",{children:["Using preset: ",Me.name]}):null,v==="preset"?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>y("custom"),disabled:F,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(Jt,{id:"executor-model",label:"Executor Model",value:c,onChange:U=>{y("custom"),j(""),u(U)},models:q,disabled:F||v==="preset",favoriteProviders:ce,onToggleFavorite:_t,favoriteModels:ve,onToggleModelFavorite:vt})]}),e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Validator"}),e.jsx(Jt,{id:"validator-model",label:"Validator Model",value:h,onChange:U=>{y("custom"),j(""),g(U)},models:q,disabled:F||v==="preset",favoriteProviders:ce,onToggleFavorite:_t,favoriteModels:ve,onToggleModelFavorite:vt})]}),p&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),e.jsx(Jt,{id:"planning-model",label:"Planning Model",value:f||"",onChange:U=>{y("custom"),j(""),p(U)},models:q,disabled:F||v==="preset",favoriteProviders:ce,onToggleFavorite:_t,favoriteModels:ve,onToggleModelFavorite:vt})]}),x&&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=>x(U.target.value),disabled:F||v==="preset",children:[e.jsxs("option",{value:"",children:["Default (",Fe?.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:F,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:Pe.length>0&&Pe.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:P.includes(U.id),onChange:Ne=>{w(Ne.target.checked?[...P,U.id]:P.filter(pt=>pt!==U.id))},disabled:F}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[U.name,oM(U.phase||"pre-merge",U.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:U.description})]})]},U.id))})]}),P.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:"}),P.map((U,Ne)=>{const pt=Le.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:Ne+1}),e.jsx("span",{className:"workflow-step-order-name",children:pt?.name||U}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Dt(Ne),disabled:F||Ne===0,"data-testid":`workflow-step-move-up-${U}`,title:"Move up",children:e.jsx(Ds,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ke(Ne),disabled:F||Ne===P.length-1,"data-testid":`workflow-step-move-down-${U}`,title:"Move down",children:e.jsx(zt,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>bt(U),disabled:F,"data-testid":`workflow-step-remove-${U}`,title:"Remove",children:e.jsx(Lt,{size:14})})]})]},U)})]})]})]})]})}const Hu={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 cM(t){switch(t){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return t}}function dM(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 uM(t){return t?new Date(t).toLocaleString():null}function mM(t){const n=t.split(`
|
|
624
|
-
`);return n.length<=1?t:`${n.length} lines`}function gr(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 hM({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 pM({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,f]=a.useState(null),[p,b]=a.useState([]),[x,v]=a.useState(!1),y=n.some(S=>S.status==="pending"),{entries:A}=zp(t,!!o&&y,l);a.useEffect(()=>{let S=!1;return Gr(l).then(V=>{S||b(V.filter(de=>de.enabled))}).catch(()=>{S||b([])}),()=>{S=!0}},[l]);const j=i??[],P=a.useMemo(()=>[...p.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"}],[p]),w=a.useMemo(()=>new Map(P.map(S=>[S.id,S])),[P]),E=S=>{c(V=>({...V,[S]:!V[S]}))},k=S=>{h(V=>{const de=V[S]??"markdown";return{...V,[S]:de==="markdown"?"plain":"markdown"}})},T=S=>{f(S)},C=()=>{f(null)};a.useEffect(()=>{if(!g)return;const S=V=>{V.key==="Escape"&&C()};return document.addEventListener("keydown",S),()=>{document.removeEventListener("keydown",S)}},[g]);const $=a.useCallback((S,V)=>{if(d){if(V){if(j.includes(S)){d(j);return}d([...j,S]);return}d(j.filter(de=>de!==S))}},[d,j]),F=a.useCallback(S=>{if(!d||S<=0)return;const V=[...j];[V[S-1],V[S]]=[V[S],V[S-1]],d(V)},[d,j]),ee=a.useCallback(S=>{if(!d||S>=j.length-1)return;const V=[...j];[V[S],V[S+1]]=[V[S+1],V[S]],d(V)},[d,j]),I=a.useCallback(S=>{d&&d(j.filter(V=>V!==S))},[d,j]),_=n.length>0,N=j.length>0;a.useEffect(()=>{r||v(!1)},[r]);const J=a.useMemo(()=>j.map(S=>{const V=w.get(S);return{id:S,name:V?.name||S,description:V?.description||"Step definition not found.",phase:V?.phase||"pre-merge"}}),[j,w]),K=()=>!r||!x||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:P.map(S=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":S.id==="browser-verification"?"browser-verification-checkbox":`workflow-step-checkbox-${S.id}`,children:[e.jsx("input",{type:"checkbox",checked:j.includes(S.id),onChange:V=>$(S.id,V.target.checked)}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[S.name,gr(S.phase,S.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:S.description})]})]},S.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((S,V)=>{const de=w.get(S);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${S}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:V+1}),e.jsx("span",{className:"workflow-step-order-name",children:de?.name||S}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(V),disabled:V===0,"data-testid":`workflow-step-move-up-${S}`,title:"Move up",children:e.jsx(Ds,{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-${S}`,title:"Move down",children:e.jsx(zt,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>I(S),"data-testid":`workflow-step-remove-${S}`,title:"Remove",children:e.jsx(Lt,{size:14})})]})]},S)})]})]}),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(!_)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 S=n.filter(D=>D.status==="passed").length,V=n.filter(D=>D.status==="failed").length,de=n.filter(D=>D.status==="skipped").length,L=n.filter(D=>D.status==="pending").length,Z=[`${n.length} step${n.length!==1?"s":""}`];return S>0&&Z.push(`${S} passed`),V>0&&Z.push(`${V} failed`),de>0&&Z.push(`${de} skipped`),L>0&&Z.push(`${L} 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:Z.join(" · ")}),n.map((D,me)=>{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,gr(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:cM(D.status)})]}),e.jsxs("div",{className:"workflow-result-meta",children:[D.startedAt&&e.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",uM(D.startedAt)]}),D.completedAt&&e.jsx("span",{className:"workflow-result-duration",children:dM(D.startedAt,D.completedAt)})]}),D.status==="pending"&&D.startedAt?e.jsx(hM,{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:()=>E(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:mM(D.output)}),W&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>k(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:()=>T(D.workflowStepId),"data-testid":`workflow-result-expand-${D.workflowStepId}`,title:"Expand output",children:e.jsx(Xs,{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(ni,{remarkPlugins:[si],components:Hu,children:D.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:D.output})})]}):null]},`${D.workflowStepId}-${me}`)})]})},M=r?e.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>v(S=>!S),"data-testid":"workflow-steps-edit-toggle","aria-label":x?"Done editing workflow steps":"Edit workflow steps",title:x?"Done":"Edit",children:x?e.jsxs(e.Fragment,{children:[e.jsx(Mn,{size:14}),"Done"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ln,{size:14}),"Edit"]})}):null,O=!s&&!_&&N,X=r&&_;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:[J.length," step",J.length===1?"":"s"]})]}),M]}),e.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:J.map(S=>e.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${S.id}`,children:[e.jsxs("div",{className:"workflow-configured-name",children:[S.name,gr(S.phase,S.id,"workflow-configured-phase")]}),e.jsx("p",{className:"workflow-configured-description",children:S.description})]},S.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"}),M]}),G(),K()]}),g&&(()=>{const S=n.find(L=>L.workflowStepId===g);if(!S)return null;const V=u[S.workflowStepId]??"markdown",de=S.phase||"pre-merge";return e.jsx("div",{className:"workflow-output-modal-overlay",onClick:L=>{L.target===L.currentTarget&&C()},"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:S.workflowStepName}),gr(de,S.workflowStepId,"workflow-output-modal-phase")]}),e.jsxs("div",{className:"workflow-output-modal-controls",children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>k(S.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:C,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:e.jsx(Lt,{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(ni,{remarkPlugins:[si],components:Hu,children:S.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:S.output})})})]})})})()]})}const fM=/^[a-zA-Z0-9_-]{1,64}$/,gM=200;function qu(t){return t?new Date(t).toLocaleString():""}function bM(t,n=gM){return t.length<=n?t:t.substring(0,n)+"…"}function xM({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(""),[f,p]=a.useState(null),[b,x]=a.useState(""),[v,y]=a.useState(null),[A,j]=a.useState([]),[P,w]=a.useState(!1),[E,k]=a.useState(!1),[T,C]=a.useState(""),[$,F]=a.useState(""),[ee,I]=a.useState(!1),[_,N]=a.useState(null),[J,K]=a.useState(null),[G,M]=a.useState(!1),O=a.useCallback(async()=>{try{const q=await Hx(t,i);o(q)}catch(q){n(ge(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(""),p(null),x(""),y(null),j([]),M(!1)):(u(q.key),g(q.content),p(null),x(""),y(null),j([]),M(!1))}async function S(q){if(v===q)y(null),j([]);else{y(q),w(!0);try{const W=await qx(t,q,i);j(W)}catch(W){n(ge(W)||"Failed to load revisions","error")}finally{w(!1)}}}function V(){c&&(p(c),x(h))}function de(){p(null),x("")}async function L(){if(!(!f||!b.trim())){I(!0);try{await Vc(t,f,b,{},i),p(null),x(""),await O();const q=l.find(W=>W.key===f);q&&g(q.content),n("Document saved","success")}catch(q){n(ge(q)||"Failed to save document","error")}finally{I(!1)}}}async function Z(){const q=T.trim(),W=$.trim();if(!q){n("Document key is required","error");return}if(!fM.test(q)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!W){n("Content is required","error");return}I(!0);try{await Vc(t,q,W,{},i),k(!1),C(""),F(""),await O(),n("Document created","success")}catch(ce){n(ge(ce)||"Failed to create document","error")}finally{I(!1)}}async function D(q){N(q);try{await Vx(t,q,i),K(null),N(null),c===q&&(u(null),g("")),v===q&&(y(null),j([])),await O(),n("Document deleted","success")}catch(W){n(ge(W)||"Failed to delete document","error")}finally{N(null)}}function me(q){g(q.content),p(null),x("")}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"}),E&&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:T,onChange:q=>C(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:$,onChange:q=>F(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:()=>{k(!1),C(""),F("")},disabled:ee,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Z(),disabled:ee||!T.trim()||!$.trim(),children:ee?"Creating…":"Create"})]})]}),l.length===0&&!E?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(xi,{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:qu(q.updatedAt||q.createdAt)})]})]}),c===q.key&&f!==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:()=>M(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(ni,{remarkPlugins:[si],children:h})})}):e.jsx("pre",{className:"task-document-content-text",children:h})}),v===q.key&&e.jsxs("div",{className:"task-document-revisions",children:[e.jsx("h5",{children:"Revision History"}),P?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,ce)=>ce.revision-W.revision).map(W=>e.jsxs("div",{className:"task-document-revision-item",onClick:()=>me(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:qu(W.createdAt)})]}),e.jsx("div",{className:"revision-preview",children:bM(W.content,100)})]},W.id))})]})]}),f===q.key&&e.jsxs("div",{className:"task-document-edit-form",children:[e.jsx("textarea",{value:b,onChange:W=>x(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 L(),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(Ds,{size:14})," Collapse"]}):e.jsxs(e.Fragment,{children:[e.jsx(zt,{size:14})," Expand"]})}),c===q.key&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void S(q.key),children:[e.jsx(Ta,{size:14})," History"]}),r&&f!==q.key&&e.jsx("button",{className:"btn btn-sm",onClick:V,children:"Edit"}),r&&(J===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:_===q.key,children:_===q.key?"…":"Yes"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>K(null),disabled:_===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&&!E&&e.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>k(!0),children:[e.jsx(Ht,{size:14})," New Document"]})]})}function vM(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function yM(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 kM(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 jM(t,n,s){if(t.planningModelProvider&&t.planningModelId)return{provider:t.planningModelProvider,modelId:t.planningModelId};const i=kM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function wM(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 NM(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 SM(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function CM(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 Vu(t,n){return t.length>n?t.slice(0,n)+"…":t}function Wu(t=[],n=[]){return t.length===n.length&&t.every((s,i)=>s===n[i])}function Wl(t){const n=t.indexOf("/");return!t||n===-1?null:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function ga(t){return typeof t=="string"&&Ko.includes(t)?t:ds}const Kl=200,EM=new Set(["triage","todo"]);function MM({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:f="definition"}){const[p,b]=a.useState(f),[x,v]=a.useState(()=>"prompt"in t?t:null),[y,A]=a.useState(()=>!("prompt"in t));a.useEffect(()=>{if("prompt"in t){v(t),A(!1);return}let se=!1;return A(!0),v(null),Ar(t.id,n).then(tt=>{se||(v(tt),A(!1))}).catch(()=>{se||A(!1)}),()=>{se=!0}},[t.id,n]);const j=x??{...t,prompt:""},P=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(f)},[f]),a.useEffect(()=>{T(!1)},[t.id]);const[w,E]=a.useState("activity"),[k,T]=a.useState(!1),[C,$]=a.useState(t.attachments||[]),[F,ee]=a.useState(!1),[I,_]=a.useState(t.dependencies||[]),[N,J]=a.useState(!1),[K,G]=a.useState(""),[M,O]=a.useState(null),[X,S]=a.useState([]),[V,de]=a.useState(!1),[L,Z]=a.useState(!1),[D,me]=a.useState(!1),[q,W]=a.useState(!1),[ce,Se]=a.useState(!1),[ve,Ee]=a.useState(j.prompt||""),[Ae,Oe]=a.useState(""),[Fe,rt]=a.useState(!1),[Pe,Ie]=a.useState(""),[Be,nt]=a.useState(!1),[De,Qe]=a.useState(!1),[ie,te]=a.useState(t.title||""),[fe,ae]=a.useState(t.description||""),[_e,ke]=a.useState(t.dependencies||[]),[He,dt]=a.useState(""),[ht,he]=a.useState(""),[ne,ye]=a.useState(""),[we,st]=a.useState(""),[be,it]=a.useState("default"),[Me,qe]=a.useState(void 0),[oe,Ve]=a.useState(ds),[We,Re]=a.useState(""),[et,xt]=a.useState(t.enabledWorkflowSteps||[]),[wt,Et]=a.useState([]),[Rt,$t]=a.useState(!1),_t=a.useRef(!1),[vt,Dt]=a.useState(!1),[Ke,bt]=a.useState(!1),Le=a.useRef(null),lt=a.useRef(null),{getSlotsForId:xe}=bh(n),U=xe("task-detail-tab");a.useEffect(()=>(_t.current=!0,()=>{_t.current=!1}),[]);const[Ne,pt]=a.useState(void 0),[kt,je]=a.useState([]),[Ge,gt]=a.useState(!1),[qt,gn]=a.useState(t.enabledWorkflowSteps||[]);a.useEffect(()=>{te(t.title||""),ae(t.description||""),Qe(!1)},[t.id,t.title,t.description]),a.useEffect(()=>{gn(t.enabledWorkflowSteps||[])},[t.id,t.enabledWorkflowSteps]),a.useEffect(()=>{let se=!1;return Wi(n).then(tt=>{se||pt(tt)}).catch(()=>{}),()=>{se=!0}},[n]),a.useEffect(()=>{if(p!=="workflow")return;let se=!1;return gt(!0),oy(t.id,n).then(tt=>{se||je(tt)}).catch(tt=>{se||h(`Failed to load workflow results: ${ge(tt)}`,"error")}).finally(()=>{se||gt(!1)}),()=>{se=!0}},[p,t.id,n,h]),a.useEffect(()=>{if(p!=="workflow")return;const se=n?`?projectId=${encodeURIComponent(n)}`:"",tt=ft=>{try{const It=JSON.parse(ft.data);It.id===t.id&&Array.isArray(It.workflowStepResults)&&je(It.workflowStepResults)}catch{}};return Os(`/api/events${se}`,{events:{"task:updated":tt}})},[p,t.id,n]),a.useEffect(()=>{N||G("")},[N]),a.useEffect(()=>{if(!t.assignedAgentId){O(null);return}const se=X.find(ft=>ft.id===t.assignedAgentId);if(se){O(se);return}let tt=!1;return dh(t.assignedAgentId,n).then(ft=>{tt||O(ft)}).catch(()=>{tt||O(null)}),()=>{tt=!0}},[t.assignedAgentId,n,X]),a.useEffect(()=>{de(!1)},[t.id]),a.useEffect(()=>{if(!(vt||Ke))return;const tt=ft=>{const It=ft.target,Cs=Le.current?.contains(It),bs=lt.current?.contains(It);!Cs&&vt&&Dt(!1),!bs&&Ke&&bt(!1)};return document.addEventListener("mousedown",tt),()=>document.removeEventListener("mousedown",tt)},[vt,Ke]),a.useEffect(()=>{if(!(vt||Ke))return;const tt=ft=>{ft.key==="Escape"&&(ft.stopPropagation(),vt&&Dt(!1),Ke&&bt(!1))};return document.addEventListener("keydown",tt),()=>document.removeEventListener("keydown",tt)},[vt,Ke]),a.useEffect(()=>{Se(!1),Ee(j.prompt||""),Oe("")},[t.id,j.prompt]);const Wt=EM.has(t.column)&&!Rt,Rn=a.useCallback(()=>{if(!Wt)return;Qe(!0),te(t.title||""),ae(t.description||""),ke(t.dependencies||[]);const se=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"",tt=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"",ft=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";dt(se),he(tt),ye(ft),st(t.thinkingLevel??""),it(se||tt||ft?"custom":"default"),Re(""),xt(t.enabledWorkflowSteps||[]),Et([]),qe(t.reviewLevel),Ve(ga(t.priority))},[Wt,t]),Kt=a.useCallback(()=>{Qe(!1),te(t.title||""),ae(t.description||""),ke(t.dependencies||[]),Ve(ga(t.priority)),wt.forEach(se=>URL.revokeObjectURL(se.previewUrl)),Et([])},[t.title,t.description,t.dependencies,t.priority,wt]),$n=a.useCallback(async()=>{$t(!0);try{const se={},tt=ie.trim(),ft=fe.trim();tt&&tt!==(t.title??"")&&(se.title=tt),ft&&ft!==(t.description??"")&&(se.description=ft),Wu(_e,t.dependencies??[])||(se.dependencies=_e),Wu(et,t.enabledWorkflowSteps??[])||(se.enabledWorkflowSteps=et);const It=Wl(He),Cs=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"";He!==Cs&&(se.modelProvider=It?.provider??null,se.modelId=It?.modelId??null);const bs=Wl(ht),il=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"";ht!==il&&(se.validatorModelProvider=bs?.provider??null,se.validatorModelId=bs?.modelId??null);const Xa=Wl(ne),al=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";ne!==al&&(se.planningModelProvider=Xa?.provider??null,se.planningModelId=Xa?.modelId??null);const rl=t.thinkingLevel??"";we!==rl&&(se.thinkingLevel=we!==""?we:null);const ri=t.reviewLevel;Me!==ri&&(se.reviewLevel=Me);const Js=ga(t.priority);if(oe!==Js&&(se.priority=oe),Object.keys(se).length>0){const Us=await Ws(t.id,se,n);u?.(Us)}if(wt.length>0){const Us=[];for(const li of wt)try{const ll=await $a(t.id,li.file,n);$(Rs=>[...Rs,ll])}catch{Us.push(li.file.name)}Us.length>0&&h(`Failed to upload: ${Us.join(", ")}`,"error")}wt.forEach(Us=>URL.revokeObjectURL(Us.previewUrl)),Et([]),h(`Updated ${t.id}`,"success"),Qe(!1)}catch(se){h(`Failed to update ${t.id}: ${ge(se)}`,"error")}finally{_t.current&&$t(!1)}},[t,ie,fe,_e,He,ht,ne,we,Me,oe,et,wt,h,n,u]),bn=a.useCallback(async se=>{try{await Ws(t.id,{description:se},n),h("Description saved","success")}catch(tt){h(`Failed to save: ${ge(tt)}`,"error")}},[t.id,h,n]),on=a.useCallback(se=>{De&&(se.key==="Escape"?(se.preventDefault(),Kt()):se.key==="Enter"&&(se.ctrlKey||se.metaKey)&&(se.preventDefault(),$n()))},[De,Kt,$n]);a.useEffect(()=>{if(De)return document.addEventListener("keydown",on),()=>document.removeEventListener("keydown",on)},[De,on]);const en=a.useRef(null),{entries:xn,loading:wn,loadMore:Dn,hasMore:cn,total:sn,loadingMore:Vt}=zp(t.id,p==="logs"&&w==="agent-log",n);a.useEffect(()=>{const se=tt=>{tt.key==="Escape"&&!De&&i()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[i,De]);const Nn=a.useCallback(se=>{se.target===se.currentTarget&&i()},[i]),Un=a.useCallback(async se=>{try{await l(t.id,se),i(),h(`Moved to ${us[se]}`,"success")}catch(tt){h(ge(tt),"error")}},[t.id,l,i,h]),Sn=a.useCallback(async()=>{if(confirm(`Delete ${t.id}?`))try{await o(t.id),i(),h(`Deleted ${t.id}`,"info")}catch(se){const tt=CM(se);if(!tt||tt.dependentIds.length===0){h(ge(se),"error");return}const ft=tt.dependentIds.join(", ");if(!confirm(`${t.id} is a dependency of ${ft}.
|
|
625
|
-
|
|
626
|
-
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(ge(Cs),"error")}}},[t.id,o,i,h]),Hn=a.useCallback(()=>{confirm(`Merge ${t.id} into the current branch?`)&&(i(),h(`Merging ${t.id}...`,"info"),d(t.id).then(se=>{const tt=se.merged?`Merged ${t.id} (branch: ${se.branch})`:`Closed ${t.id} (${se.error||"no branch to merge"})`;h(tt,"success")}).catch(se=>{h(ge(se),"error")}))},[t.id,d,i,h]),Qn=a.useCallback(()=>{m&&(i(),m(t.id).then(()=>{h(`Retried ${t.id}`,"success")}).catch(se=>{h(ge(se),"error")}))},[t.id,m,i,h]),Q=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(ge(se),"error")}},[t.id,c,i,h]),Ue=a.useCallback(async()=>{try{t.paused?(await Sx(t.id,n),h(`Unpaused ${t.id}`,"success")):(await Nx(t.id,n),h(`Paused ${t.id}`,"success")),i()}catch(se){h(ge(se),"error")}},[t.id,t.paused,i,h]),R=a.useCallback(async()=>{try{await Ax(t.id,n),h(`Plan approved — ${t.id} moved to Todo`,"success"),i()}catch(se){h(ge(se),"error")}},[t.id,i,h]),B=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await Px(t.id,n),h(`Plan rejected — ${t.id} returned to Triage for re-specification`,"info"),i()}catch(se){h(ge(se),"error")}},[t.id,i,h]),re=a.useCallback(async()=>{if(confirm("Rebuild the specification for this task? The task will move to triage for re-specification."))try{await Gx(t.id,n),i(),h(`Respecifying ${t.id}...`,"info")}catch(se){h(ge(se),"error")}},[t.id,n,i,h]),pe=a.useCallback(()=>{rt(!0),Ie("")},[]),ue=a.useCallback(()=>{Dt(!1),bt(!1)},[]),Te=a.useCallback(se=>{ue(),Un(se)},[ue]),ut=a.useCallback(se=>{ue(),se()},[ue]),Mt=a.useCallback(()=>{ue(),Hn()},[ue]),dn=a.useCallback(()=>{rt(!1),Ie(""),nt(!1)},[]),Je=a.useCallback(async()=>{if(!Pe.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Pe.length>2e3){h("Feedback must be 2000 characters or less","error");return}nt(!0);try{const se=await Jx(t.id,Pe.trim(),n);h(`Refinement task created: ${se.id}`,"success"),i()}catch(se){h(ge(se),"error")}finally{nt(!1)}},[t.id,Pe,h,i]),ot=a.useCallback(async se=>{ee(!0);try{const tt=await $a(t.id,se,n);$(ft=>[...ft,tt]),h("Screenshot attached","success")}catch(tt){h(ge(tt),"error")}finally{ee(!1)}},[t.id,h]),qn=a.useCallback(async se=>{const tt=se.target.files?.[0];tt&&(await ot(tt),en.current&&(en.current.value=""))},[ot]);a.useEffect(()=>{const se=tt=>{const ft=tt.clipboardData?.items;if(ft)for(let It=0;It<ft.length;It++){const Cs=ft[It];if(Cs.type.startsWith("image/")){const bs=Cs.getAsFile();if(bs){tt.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 tt=se.dataTransfer.files;for(let ft=0;ft<tt.length;ft++){const It=tt[ft];if(It.type.startsWith("image/")){ot(It);return}}},[ot]),mt=a.useCallback(async se=>{try{await Ox(t.id,se,n),$(tt=>tt.filter(ft=>ft.filename!==se)),h("Attachment deleted","info")}catch(tt){h(ge(tt),"error")}},[t.id,h]),Nt=a.useCallback(async se=>{const tt=qt;gn(se);try{const ft=await Ws(t.id,{enabledWorkflowSteps:se},n);h("Workflow steps updated","success"),u?.(ft)}catch(ft){gn(tt),h(`Failed to update workflow steps: ${ge(ft)}`,"error")}},[t.id,n,qt,u,h]),Ct=a.useCallback(async()=>{Z(!0);try{const se=await ia(void 0,n);S(se),de(!0)}catch(se){h(`Failed to load agents: ${ge(se)}`,"error"),de(!1)}finally{Z(!1)}},[n,h]),un=a.useCallback(async se=>{try{const tt=await nd(t.id,se,n),ft=X.find(It=>It.id===se)??null;O(ft||(It=>It?.id===se?It:null)),de(!1),u?.(tt),h("Assigned agent updated","success")}catch(tt){h(`Failed to assign agent: ${ge(tt)}`,"error")}},[t.id,n,X,u,h]),mn=a.useCallback(async()=>{try{const se=await nd(t.id,null,n);O(null),de(!1),u?.(se),h("Agent unassigned","success")}catch(se){h(`Failed to unassign agent: ${ge(se)}`,"error")}},[t.id,n,u,h]),pn=a.useCallback(async se=>{const tt=[...I,se];_(tt);try{await Ws(t.id,{dependencies:tt},n)}catch(ft){_(I),h(ge(ft),"error")}},[t.id,I,h]),fn=a.useCallback(async(se,tt)=>{se.stopPropagation();const ft=I.filter(It=>It!==tt);_(ft);try{await Ws(t.id,{dependencies:ft},n)}catch(It){_(I),h(ge(It),"error")}},[t.id,I,h]),vn=a.useCallback(async se=>{try{const tt=await Ar(se,n);r(tt)}catch{h(`Failed to load dependency ${se}`,"error")}},[r,h]),Cn=a.useCallback(async se=>{me(!0);try{await Ws(j.id,{prompt:se},n),h("Spec updated","success"),x&&(x.prompt=se)}catch(tt){throw h(ge(tt),"error"),tt}finally{me(!1)}},[j,x,h]),ls=a.useCallback(async se=>{W(!0);try{await Kx(t.id,se,n),h("AI revision requested. Task moved to triage.","success"),i()}catch(tt){const ft=ge(tt);ft.includes("in-review")||ft.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(ft,"error")}finally{W(!1)}},[t.id,h,i]),Vn=a.useCallback(()=>{Se(!0),Ee(j.prompt||""),Oe("")},[j.prompt]),En=a.useCallback(()=>{Se(!1),Ee(j.prompt||""),Oe("")},[j.prompt]),Tn=a.useCallback(async()=>{if(ve===(j.prompt||"")){En();return}await Cn(ve),Se(!1)},[ve,j.prompt,Cn,En]),Xn=a.useCallback(async()=>{Ae.trim()&&await ls(Ae.trim())},[Ae,ls]),yn=a.useCallback(se=>{se.key==="Escape"?(se.preventDefault(),En()):se.key==="Enter"&&(se.ctrlKey||se.metaKey)&&(se.preventDefault(),Tn())},[En,Tn]),Wn=s.filter(se=>se.id!==t.id&&!I.includes(se.id)).sort((se,tt)=>{const ft=tt.createdAt.localeCompare(se.createdAt);if(ft!==0)return ft;const It=parseInt(se.id.slice(se.id.lastIndexOf("-")+1),10)||0;return(parseInt(tt.id.slice(tt.id.lastIndexOf("-")+1),10)||0)-It}),fs=M?.name??t.assignedAgentId??null,Zn=xo[t.column]||[],gs={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},Fn=t.status?gs[t.status]:void 0;return e.jsx("div",{className:"modal-overlay open",onClick:Nn,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:[!De&&Wt&&e.jsx("button",{className:"modal-edit-btn",onClick:Rn,title:"Edit task","aria-label":"Edit task",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),e.jsxs("div",{className:`detail-body${p==="logs"&&w==="agent-log"&&!De?" detail-body--agent-log":""}`,children:[De?e.jsx("div",{className:"modal-edit-form",children:e.jsx(Up,{mode:"edit",title:ie,onTitleChange:te,description:fe,onDescriptionChange:ae,dependencies:_e,onDependenciesChange:ke,executorModel:He,onExecutorModelChange:dt,validatorModel:ht,onValidatorModelChange:he,planningModel:ne,onPlanningModelChange:ye,thinkingLevel:we,onThinkingLevelChange:st,presetMode:be,onPresetModeChange:it,selectedPresetId:We,onSelectedPresetIdChange:Re,selectedWorkflowSteps:et,onWorkflowStepsChange:xt,pendingImages:wt,onImagesChange:Et,tasks:s.filter(se=>se.id!==t.id),projectId:n,disabled:Rt,addToast:h,isActive:De,onAutoSaveDescription:bn,reviewLevel:Me,onReviewLevelChange:qe,priority:oe,onPriorityChange:Ve})}):e.jsxs(e.Fragment,{children:[(()=>{const se=t.title||t.description||t.id,tt=!k&&se.length>Kl;return e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"detail-title",children:tt?se.slice(0,Kl)+"…":se}),se.length>Kl&&e.jsx("button",{className:"detail-description-toggle",onClick:()=>T(!k),children:k?"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--${ga(t.priority)}`,children:["Priority: ",ga(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})]})]}),!De&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"detail-tabs",children:[e.jsx("button",{className:`detail-tab${p==="definition"?" detail-tab-active":""}`,onClick:()=>b("definition"),children:"Definition"}),e.jsx("button",{className:`detail-tab${p==="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${p==="changes"?" detail-tab-active":""}`,onClick:()=>b("changes"),children:"Changes"}),e.jsx("button",{className:`detail-tab${p==="comments"?" detail-tab-active":""}`,onClick:()=>b("comments"),children:"Comments"}),e.jsx("button",{className:`detail-tab${p==="documents"?" detail-tab-active":""}`,onClick:()=>b("documents"),children:"Documents"}),e.jsx("button",{className:`detail-tab${p==="model"?" detail-tab-active":""}`,onClick:()=>b("model"),children:"Model"}),e.jsx("button",{className:`detail-tab${p==="workflow"?" detail-tab-active":""}`,onClick:()=>b("workflow"),children:"Workflow"}),U.map((se,tt)=>{const ft=`plugin-${tt}`;return e.jsx("button",{className:`detail-tab${p===ft?" detail-tab-active":""}`,onClick:()=>b(ft),children:se.slot.label},`plugin-tab-${se.pluginId}`)})]}),p==="workflow"?e.jsx("div",{className:"detail-section",children:e.jsx(pM,{taskId:t.id,results:kt,loading:Ge,enabledWorkflowSteps:qt,canEdit:Wt,projectId:n,isTaskInProgress:t.column==="in-progress"&&t.status!=="paused",onWorkflowStepsChange:Nt})}):p==="model"?e.jsx("div",{className:"detail-section",children:e.jsx(J2,{task:t,addToast:h,onTaskUpdated:u,settings:Ne})}):p==="logs"?e.jsxs("div",{className:`detail-section${w==="agent-log"?" detail-section--agent-log":""}`,children:[e.jsxs("div",{className:"log-subview-toggle",children:[e.jsx("button",{className:`log-subview-btn${w==="activity"?" log-subview-btn-active":""}`,onClick:()=>E("activity"),children:"Activity"}),e.jsx("button",{className:`log-subview-btn${w==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>E("agent-log"),children:"Agent Log"})]}),w==="agent-log"?e.jsx(q2,{entries:xn,loading:wn,executorModel:vM(t,Ne),validatorModel:yM(t,Ne),planningModel:jM(t,xn,Ne),hasMore:cn,onLoadMore:Dn,loadingMore:Vt,totalCount:sn}):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,tt)=>e.jsxs("div",{className:"detail-log-entry",children:[e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-timestamp",children:NM(se.timestamp)}),e.jsx("span",{className:"detail-log-action",children:se.action})]}),se.outcome&&e.jsx("div",{className:"detail-log-outcome",children:se.outcome})]},tt))}):e.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):p==="changes"?e.jsx(aM,{taskId:t.id,worktree:t.worktree,projectId:n,column:t.column,mergeDetails:t.mergeDetails,modifiedFiles:t.modifiedFiles}):p==="comments"?e.jsx(eM,{task:t,addToast:h,projectId:n,onTaskUpdated:u}):p==="documents"?e.jsx(xM,{taskId:t.id,addToast:h,projectId:n,onTaskUpdated:u,canEdit:Wt}):typeof p=="string"&&p.startsWith("plugin-")?e.jsx("div",{className:"detail-section",children:e.jsx(Ga,{slotId:"task-detail-tab",projectId:n})}):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(ni,{remarkPlugins:[si],children:t.summary})})]}),e.jsx(nM,{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(an,{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(an,{size:14}),fs,e.jsx("button",{className:"detail-agent-clear",onClick:()=>void mn(),title:"Unassign agent",children:e.jsx(Lt,{size:12})})]}):e.jsx("button",{className:"btn btn-sm",onClick:()=>{V?de(!1):Ct()},children:"Assign Agent"}),V&&e.jsxs("div",{className:"agent-picker-dropdown",children:[L&&e.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!L&&X.filter(se=>se.state!=="terminated").map(se=>e.jsxs("button",{className:`agent-picker-item${t.assignedAgentId===se.id?" selected":""}`,onClick:()=>void un(se.id),children:[e.jsx(an,{size:14}),e.jsx("span",{className:"agent-picker-name",children:se.name}),e.jsx("span",{className:"agent-picker-role",children:se.role})]},se.id)),!L&&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,tt)=>e.jsx("div",{className:`step-progress-segment step-progress-segment--${se.status}`,"data-tooltip":`${se.name} (${se.status})`,style:{backgroundColor:wM(se.status)}},tt))}),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:[!ce&&e.jsx("div",{className:"detail-spec-edit-trigger",children:e.jsx("button",{className:"btn btn-sm",onClick:Vn,children:"Edit"})}),ce?e.jsxs("div",{className:"spec-editor-edit-mode",children:[e.jsx("textarea",{className:"spec-editor-textarea",value:ve,onChange:se=>Ee(se.target.value),onKeyDown:yn,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:En,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:Ae,onChange:se=>Oe(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:[Ae.length,"/2000"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Xn(),disabled:!Ae.trim()||q,children:q?"Requesting…":"Request AI Revision"})]})]})]}):y?e.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?e.jsx("div",{className:"markdown-body",children:e.jsx(ni,{remarkPlugins:[si],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"}),C.length>0?e.jsx("div",{className:"detail-attachments-grid",children:C.map(se=>{const tt=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:tt,target:"_blank",rel:"noopener noreferrer",children:e.jsx("img",{src:tt,alt:se.originalName,className:"detail-attachment-image"})}),e.jsxs("div",{className:"detail-attachment-meta",children:[se.originalName," (",SM(se.size),")"]}),e.jsx("button",{className:"detail-attachment-delete",onClick:()=>mt(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:en,type:"file",accept:"image/*",onChange:qn}),e.jsx("button",{className:"btn btn-sm",onClick:()=>en.current?.click(),disabled:F,children:F?"Uploading…":"Attach Screenshot"})]}),e.jsxs("div",{className:"detail-deps",children:[e.jsx("h4",{children:"Dependencies"}),I.length>0?e.jsx("ul",{className:"detail-dep-list",children:I.map(se=>{const tt=s.find(It=>It.id===se),ft=tt?.title||tt?.description||se;return e.jsxs("li",{className:"detail-dep-item",children:[e.jsxs("span",{className:"detail-dep-link",onClick:()=>vn(se),onKeyDown:It=>{(It.key==="Enter"||It.key===" ")&&(It.preventDefault(),vn(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:Vu(ft,40)})]}),e.jsx("button",{className:"dep-remove-btn",onClick:It=>fn(It,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:()=>{N&&G(""),J(se=>!se)},children:"Add Dependency"}),N&&(()=>{const se=K.toLowerCase(),tt=se?Wn.filter(ft=>ft.id.toLowerCase().includes(se)||ft.title&&ft.title.toLowerCase().includes(se)||ft.description&&ft.description.toLowerCase().includes(se)):Wn;return e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:K,onChange:ft=>G(ft.target.value),onClick:ft=>ft.stopPropagation()}),tt.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):tt.map(ft=>e.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{pn(ft.id),J(!1)},children:[e.jsx("span",{className:"dep-dropdown-id",children:ft.id}),e.jsx("span",{className:"dep-dropdown-title",children:Vu(ft.title||ft.description||ft.id,30)})]},ft.id))]})})()]})]}),t.column==="in-review"&&e.jsx(Q2,{taskId:t.id,projectId:n,prInfo:t.prInfo,automationStatus:t.status??null,autoMerge:Ne?.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:De?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:Kt,disabled:Rt,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:$n,disabled:Rt,children:Rt?"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:R,children:"Approve Plan"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:B,children:"Reject Plan"})]}),t.column==="triage"&&t.status!=="awaiting-approval"&&!P&&e.jsx("button",{className:"btn btn-sm btn-danger",onClick:Sn,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(t.column!=="triage"||t.status==="awaiting-approval"||P)&&e.jsxs("div",{className:"detail-actions-dropdown",ref:lt,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>{bt(se=>!se),Dt(!1)},"aria-haspopup":"menu","aria-expanded":Ke,children:["Actions",e.jsx(zt,{size:12})]}),Ke&&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:()=>ut(Sn),children:"Delete"}),c&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ut(Q),children:"Duplicate"}),(t.column==="done"||t.column==="in-review")&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ut(pe),children:"Refine"}),e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ut(re),children:"Respecify"}),P&&m&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ut(Qn),children:"Retry"}),t.column!=="done"&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ut(Ue),children:t.paused?"Unpause":"Pause"})]})]}),e.jsx("div",{className:"modal-actions-spacer"}),e.jsx("div",{className:"detail-move-dropdown",ref:Le,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:()=>{Dt(se=>!se),bt(!1)},"aria-haspopup":"menu","aria-expanded":vt,children:["Move",e.jsx(zt,{size:12})]}),Fn?e.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Fn}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Mt,children:"Merge & Close"})]}),vt&&e.jsxs("div",{className:"detail-move-menu",role:"menu",children:[e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Te("todo"),children:"Move to Todo"}),e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Te("in-progress"),children:"Back to In Progress"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Te(Zn[0]),disabled:Zn.length===0,children:["Move to ",Zn.length>0?us[Zn[0]]:""]}),Zn.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{Dt(se=>!se),bt(!1)},"aria-haspopup":"menu","aria-expanded":vt,children:e.jsx(zt,{size:12})}),vt&&e.jsx("div",{className:"detail-move-menu",role:"menu",children:Zn.map(se=>e.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Te(se),children:["Move to ",us[se]]},se))})]})]})})]})}),Fe&&e.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:dn,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:dn,"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:Pe,onChange:se=>Ie(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:[Pe.length,"/2000 characters"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Je,disabled:!Pe.trim()||Be,children:Be?"Creating...":"Create Refinement Task"})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:dn,disabled:Be,children:"Cancel"})})]})})]})})}function AM(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),f=a.useRef(null),p=a.useRef(!0),b=a.useCallback(async(E=!1)=>{g.current&&g.current.abort(),g.current=new AbortController,E&&(d(!0),c(null));try{const k=await $x(n);if(!p.current)return;l(k),c(null),h(new Date),d(!1)}catch(k){if(k instanceof Error&&k.name==="AbortError"||!p.current)return;const T=k instanceof Error?k.message:"Failed to fetch memory backend status";c(T),d(!1)}},[n]);a.useEffect(()=>(p.current=!0,b(!1),()=>{p.current=!1}),[b]),a.useEffect(()=>{if(i)return f.current=setInterval(()=>{b(!1)},s),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[i,s,b]),a.useEffect(()=>()=>{p.current=!1,g.current&&g.current.abort(),f.current&&(clearInterval(f.current),f.current=null)},[]);const x=a.useCallback(()=>b(!0),[b]),v=r?.currentBackend??null,y=r?.capabilities??null,A=r?.availableBackends??[],j=y?.readable??!1,P=y?.writable??!1,w=y?.supportsAtomicWrite??!1;return{status:r,currentBackend:v,capabilities:y,availableBackends:A,isReadable:j,isWritable:P,supportsAtomicWrite:w,loading:o,error:m,lastUpdated:u,refresh:x}}const PM=[{value:"light",label:"Light",icon:Ym},{value:"dark",label:"Dark",icon:Km},{value:"system",label:"System",icon:Wr}],Ku=[{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 RM({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:PM.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(Ym,{size:20}):t==="dark"?e.jsx(Km,{size:20}):e.jsx(Wr,{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)}`," / ",Ku.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:Ku.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 TM(t){if(!t)return!1;const n=t.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function Hp({content:t,onChange:n,readOnly:s,filePath:i}){const[r,l]=a.useState(!1),[o,d]=a.useState(!0),m=TM(i),c=m&&(s?!0:r),u=a.useCallback(()=>{l(!1)},[]),h=a.useCallback(()=>{l(!0)},[]),g=a.useCallback(()=>{d(f=>!f)},[]);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(Um,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:h,disabled:c,"aria-label":"Preview mode",children:[e.jsx(Uo,{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(Er,{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(Er,{size:14})})]}),c?e.jsx("div",{className:"file-editor-preview markdown-body",children:e.jsx(ni,{remarkPlugins:[si],children:t})}):e.jsx("textarea",{className:`file-editor-textarea ${o?"file-editor-textarea--wrap":""}`,value:t,onChange:f=>n(f.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function qp({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 v=await Qx();return c.current&&r(v),v}catch(v){return c.current&&m({kind:"error",message:v instanceof Error?v.message:String(v)}),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 v=>{o(v?"enabling":"disabling"),m(null);try{const y=await Xx(v);c.current&&m({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await u()}catch(y){c.current&&m({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{c.current&&o(null)}},[n,u]),f=i?.binary.available??!1,p=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."]}),x=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"}),p?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||!f,title:f?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(is,{provider:"claude-cli",size:"sm"}),e.jsx("strong",{children:"Anthropic — via Claude CLI"}),e.jsx(_M,{status:i,authenticated:t})]}),e.jsx("div",{className:"auth-provider-cli-actions",children:x})]}),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(Gu,{status:i,authenticated:t}),d&&e.jsx(Ju,{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(is,{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(Gu,{status:i,authenticated:t})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:x}),d&&e.jsx(Ju,{action:d})]})}function _M({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 Gu({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 Ju({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 Li=[{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.
|
|
627
|
-
|
|
628
|
-
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.
|
|
629
|
-
|
|
630
|
-
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.
|
|
631
|
-
|
|
632
|
-
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.
|
|
633
|
-
|
|
634
|
-
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.
|
|
635
|
-
|
|
636
|
-
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.
|
|
637
|
-
|
|
638
|
-
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.
|
|
639
|
-
|
|
640
|
-
Be brief and precise — avoid verbosity.`,builtIn:!0}],IM={"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..."}},Yu=["executor","triage","reviewer","merger"],ba={executor:"Executor Agent",triage:"Triage Agent",reviewer:"Reviewer Agent",merger:"Merger Agent",scheduler:"Scheduler Agent",engineer:"Engineer Agent",custom:"Custom Agent"},qs={executor:"#3b82f6",triage:"#f59e0b",reviewer:"#8b5cf6",merger:"#10b981",scheduler:"#06b6d4",engineer:"#ec4899",custom:"#6b7280"},Gl={name:"",description:"",role:"executor",prompt:""};function $M(t,n){const s=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),i=new Set(Li.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 DM({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(Gl),[g,f]=a.useState(null),[p,b]=a.useState(null),[x,v]=a.useState(new Set),[y,A]=a.useState(null),[j,P]=a.useState(!1),[w,E]=a.useState(null),k=a.useRef(null),T=t?.templates??[],C=t?.roleAssignments??{},$=w===null?null:w.source==="builtin"?Li.find(L=>L.id===w.id):T.find(L=>L.id===w.id),F=a.useCallback(L=>{const Z=Li.filter(me=>me.role===L),D=T.filter(me=>me.role===L);return[...Z,...D]},[T]);a.useEffect(()=>{w!==null&&k.current?.focus()},[w]);const ee=a.useCallback(()=>{c(!0),d(null),h(Gl),f(null),E(null)},[]),I=a.useCallback(L=>{d(L.id),c(!1),h({name:L.name,description:L.description,role:L.role,prompt:L.prompt}),f(null),E(null)},[]),_=a.useCallback(()=>{d(null),c(!1),h(Gl),f(null),E(null),P(!1)},[]),N=a.useCallback(()=>{const L=u.name.trim();if(!L){f("Template name is required");return}let Z;if(m){if(Z=$M(L,T),new Set(Li.map(ce=>ce.id)).has(Z)){f(`Template ID "${Z}" conflicts with a built-in template. Please use a different name.`);return}}else Z=o;const D={id:Z,name:L,description:u.description.trim(),role:u.role,prompt:u.prompt,builtIn:!1};let me;m?me=[...T,D]:me=T.map(W=>W.id===Z?D:W);const q={...C};for(const[W,ce]of Object.entries(q))ce===Z&&u.role!==W&&delete q[W];n({...t,templates:me,roleAssignments:Object.keys(q).length>0?q:void 0}),_()},[u,m,o,T,C,t,n,_]),J=a.useCallback(L=>{const Z=T.filter(q=>q.id!==L),D={...C};let me=!1;for(const[q,W]of Object.entries(D))W===L&&(delete D[q],me=!0);n({...t,templates:Z.length>0?Z:void 0,roleAssignments:Object.keys(D).length>0||me?Object.keys(D).length>0?D:void 0:C}),b(null),o===L&&_()},[T,C,t,n,o,_]),K=a.useCallback((L,Z)=>{const D={...C};Z===""?delete D[L]:D[L]=Z,n({...t,roleAssignments:Object.keys(D).length>0?D:void 0})},[C,t,n]),G=a.useCallback((L,Z)=>{const D={...s};D[L]=Z||null,i(D)},[s,i]),M=a.useCallback(L=>{const Z={...s};Z[L]=null,i(Z)},[s,i]),O=a.useCallback(L=>{v(Z=>{const D=new Set(Z);return D.has(L)?D.delete(L):D.add(L),D})},[]),X=a.useCallback(L=>{A(Z=>Z===L?null:L)},[]),S=a.useCallback((L,Z)=>{P(!1),E({source:L,id:Z})},[]),V=a.useCallback(()=>{E(null),P(L=>!L)},[]),de=L=>Li.some(Z=>Z.id===L);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(Lm,{size:14}),"Templates"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="assignments"?"active":""}`,onClick:()=>l("assignments"),"data-testid":"tab-assignments",children:[e.jsx(Kb,{size:14}),"Assignments"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="overrides"?"active":""}`,onClick:()=>l("overrides"),"data-testid":"tab-overrides",children:[e.jsx(Pb,{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:L=>h(Z=>({...Z,name:L.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:L=>h(Z=>({...Z,description:L.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:L=>h(Z=>({...Z,role:L.target.value})),"data-testid":"template-role-select",children:Yu.map(L=>e.jsx("option",{value:L,children:ba[L]},L))})]}),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(Xs,{size:14})})]}),j?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:L=>{L.key==="Escape"&&(L.preventDefault(),P(!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:()=>P(!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:L=>h(Z=>({...Z,prompt:L.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:L=>h(Z=>({...Z,prompt:L.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:_,"data-testid":"cancel-template-btn",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:N,"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:Li.map(L=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${L.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:L.name}),e.jsx("span",{className:"prompt-template-badge-built-in",style:{borderColor:qs[L.role]},children:"Built-in"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:qs[L.role]+"20",color:qs[L.role]},children:ba[L.role]})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>S("builtin",L.id),title:"View full prompt","aria-label":`View full prompt for ${L.name}`,"data-testid":`expand-view-${L.id}`,children:e.jsx(Xs,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:L.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:L.prompt})})]},L.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."}),T.length===0&&!m&&e.jsx("div",{className:"prompt-template-empty",children:"No custom templates yet. Create one to get started."}),T.length>0&&e.jsx("div",{className:"prompt-template-list",children:T.map(L=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${L.id}`,children:p===L.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsxs("p",{children:['Delete "',L.name,'"?']}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>J(L.id),"data-testid":`confirm-delete-${L.id}`,children:"Delete"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>b(null),"data-testid":`cancel-delete-${L.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:L.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:"Custom"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:qs[L.role]+"20",color:qs[L.role]},children:ba[L.role]}),de(L.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:()=>S("custom",L.id),title:"View full prompt","aria-label":`View full prompt for ${L.name}`,"data-testid":`expand-view-${L.id}`,children:e.jsx(Xs,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>I(L),title:"Edit","aria-label":`Edit ${L.name}`,"data-testid":`edit-${L.id}`,children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>b(L.id),title:"Delete","aria-label":`Delete ${L.name}`,"data-testid":`delete-${L.id}`,children:e.jsx(Ut,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:L.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:L.prompt})})]})},L.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(Ht,{size:14}),"Add Custom Template"]})]}),$&&e.jsxs("div",{ref:k,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:L=>{L.key==="Escape"&&(L.preventDefault(),E(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[$.name,e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:qs[$.role]+"20",color:qs[$.role]},children:ba[$.role]})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>E(null),"data-testid":`collapse-view-${$.id}`,children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:$.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:Yu.map(L=>{const Z=F(L),D=C[L]??"",me=Z.find(W=>W.id===D),q=!!D;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${L}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:"prompt-role-badge",style:{backgroundColor:qs[L]+"20",color:qs[L]},children:ba[L]}),q&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[me?.name??"Custom"," (overrides default)"]})]}),e.jsxs("select",{className:"prompt-role-select",value:D,onChange:W=>K(L,W.target.value),"data-testid":`select-${L}`,children:[e.jsx("option",{value:"",children:"Use default"}),Z.map(W=>e.jsxs("option",{value:W.id,children:[W.name,de(W.id)?" (built-in)":" (custom)"]},W.id))]})]},L)})}),Object.keys(C).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(IM).map(L=>{const Z=L.key,D=s?.[Z]??"",me=D!=="",q=x.has(Z);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${Z}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("div",{className:"prompt-override-info",onClick:()=>O(Z),role:"button",tabIndex:0,onKeyDown:W=>{(W.key==="Enter"||W.key===" ")&&O(Z)},children:[e.jsx("span",{className:"prompt-override-name",children:L.name}),e.jsx("code",{className:"prompt-override-key",children:Z}),me&&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(Z)},"aria-label":"Expand to fullscreen","data-testid":`fullscreen-${Z}`,children:e.jsx(Xs,{size:14})}),e.jsx("button",{className:"prompt-override-expand-btn","aria-label":q?"Collapse":"Expand","data-testid":`expand-${Z}`,onClick:W=>{W.stopPropagation(),O(Z)},children:q?e.jsx(Ds,{size:16}):e.jsx(zt,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:L.description}),q&&(y===Z?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:[L.name,e.jsx("code",{className:"prompt-override-key",children:Z})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>A(null),"data-testid":`collapse-fullscreen-${Z}`,children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("textarea",{id:`prompt-${Z}-fullscreen`,"aria-label":`${L.name} prompt override (${Z}) - fullscreen`,className:"prompt-override-textarea",value:D,onChange:W=>{G(Z,W.target.value)},placeholder:`Default: ${L.defaultContent.slice(0,100)}${L.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${Z}`}),e.jsxs("div",{className:"prompt-override-footer",children:[me&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>M(Z),"data-testid":`reset-fullscreen-${Z}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:me?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${L.defaultContent.length} chars).`})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${Z}`,"aria-label":`${L.name} prompt override (${Z})`,className:"prompt-override-textarea",value:D,onChange:W=>{G(Z,W.target.value)},placeholder:`Default: ${L.defaultContent.slice(0,100)}${L.defaultContent.length>100?"...":""}`,rows:4,"data-testid":`override-input-${Z}`}),e.jsxs("div",{className:"prompt-override-footer",children:[me&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:W=>{W.stopPropagation(),M(Z)},"data-testid":`reset-${Z}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:me?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${L.defaultContent.length} chars).`})]})]}))]},Z)})})]})]})]})}const FM=a.lazy(()=>tn(()=>import("./PluginManager-BywTPbLB.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.PluginManager}))),LM=a.lazy(()=>tn(()=>import("./PiExtensionsManager-CriZBkQe.js"),__vite__mapDeps([7,1,4,5,8])).then(t=>({default:t.PiExtensionsManager}))),Qu="(max-width: 768px)",Jl=".fusion/memory/DREAMS.md",br=[{id:"__account_header",label:"Account",scope:void 0,isGroupHeader:!0},{id:"authentication",label:"Authentication",scope:void 0,icon:vi},{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"}],Xu=1440*60*1e3,zM=2,Di=["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],Zu={insights:"Insights",roadmap:"Roadmaps",memoryView:"Memory Editor",skillsView:"Skills View",nodesView:"Nodes View",devServer:"Dev Server",devServerView:"Dev Server View"};function OM({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),[f,p]=a.useState(null),[b,x]=a.useState(null),[v,y]=a.useState(null),A=br.find(R=>!R.isGroupHeader),[j,P]=a.useState(i??A?.id??"authentication"),[w,E]=a.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(Qu)?.matches===!0:!1),[k,T]=a.useState(null),C=br.find(R=>R.id===j)?.scope,[$,F]=a.useState([]),[ee,I]=a.useState(!1),[_,N]=a.useState(null),[J,K]=a.useState({}),[G,M]=a.useState({}),[O,X]=a.useState({}),S=a.useRef(null),[V,de]=a.useState([]),[L,Z]=a.useState(!1),[D,me]=a.useState([]),[q,W]=a.useState([]),[ce,Se]=a.useState(!1),[ve,Ee]=a.useState(null),[Ae,Oe]=a.useState(null),[Fe,rt]=a.useState(null),[Pe,Ie]=a.useState(!1),[Be,nt]=a.useState(""),[De,Qe]=a.useState(!1),[ie,te]=a.useState(!1),[fe,ae]=a.useState([]),[_e,ke]=a.useState([]),[He,dt]=a.useState(Jl),[ht,he]=a.useState(""),[ne,ye]=a.useState(!1),[we,st]=a.useState(null),[be,it]=a.useState(!1),[Me,qe]=a.useState(!1),oe=a.useRef(!1),[Ve,We]=a.useState(4),Re=a.useRef(4),[et,xt]=a.useState(!1),[,wt]=a.useState(null),[Et,Rt]=a.useState(null),[$t,_t]=a.useState(!1),[vt,Dt]=a.useState("both"),[Ke,bt]=a.useState(!0),Le=a.useRef(null),{status:lt,capabilities:xe,loading:U,error:Ne,refresh:pt}=AM({projectId:s});a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const R=window.matchMedia(Qu);if(!R)return;const B=re=>{E(re?re.matches:R.matches)};return B(),typeof R.addEventListener=="function"?(R.addEventListener("change",B),()=>R.removeEventListener("change",B)):(R.addListener(B),()=>R.removeListener(B))},[]),a.useEffect(()=>{Promise.all([Wi(s),Lx(s)]).then(([R,B])=>{u(R),p(R),x(B),y(B),g(!1)}).catch(R=>{n(ge(R),"error"),g(!1)})},[n,s]),a.useEffect(()=>{$y().then(R=>{We(R.globalMaxConcurrent),Re.current=R.globalMaxConcurrent}).catch(()=>{})},[]);const kt=a.useCallback(async()=>{try{const{providers:R}=await ji();F(R),K(B=>{const re={};for(const[pe,ue]of Object.entries(B)){const Te=R.find(ut=>ut.id===pe);Te&&!Te.authenticated&&(re[pe]=ue)}return Object.keys(re).length===Object.keys(B).length?B:re})}catch{}},[]);a.useEffect(()=>{(j==="global-models"||j==="project-models")&&(Z(!0),Jn().then(R=>{de(R.models),me(R.favoriteProviders),W(R.favoriteModels)}).catch(()=>de([])).finally(()=>Z(!1)))},[j]),a.useEffect(()=>{j==="backups"&&(Ie(!0),sd(s).then(R=>rt(R)).catch(()=>rt(null)).finally(()=>Ie(!1)))},[j,s]),a.useEffect(()=>{j==="worktrees"&&ih(s).then(R=>ae(R)).catch(()=>ae([]))},[j,s]),a.useEffect(()=>{if(j!=="memory"||ie)return;if(oe.current){oe.current=!1;return}let R=!1;return Qe(!0),Hc(s).then(async({files:B})=>{if(R)return;ke(B);const re=B.some(ue=>ue.path===He)?He:B.find(ue=>ue.path===Jl)?.path??B.find(ue=>ue.layer==="dreams")?.path??B[0]?.path??Jl;dt(re);const{content:pe}=await Tx(re,s);R||(nt(pe),te(!1))}).catch(B=>{R||(n(ge(B)||"Failed to load project memory","error"),nt(""))}).finally(()=>{R||Qe(!1)}),()=>{R=!0}},[j,ie,He,s,n]),a.useEffect(()=>(j==="authentication"&&(I(!0),kt().finally(()=>I(!1))),()=>{S.current&&(clearInterval(S.current),S.current=null)}),[j,kt]);const je=a.useCallback(async R=>{N(R),K(B=>{if(!(R in B))return B;const re={...B};return delete re[R],re});try{const{url:B,instructions:re}=await eh(R);re?.trim()&&K(pe=>({...pe,[R]:re})),window.open(Ps(B),"_blank"),S.current=setInterval(async()=>{try{const{providers:pe}=await ji();F(pe),pe.find(Te=>Te.id===R)?.authenticated&&(S.current&&(clearInterval(S.current),S.current=null),N(null),K(Te=>{if(!(R in Te))return Te;const ut={...Te};return delete ut[R],ut}),n("Login successful","success"))}catch{}},2e3)}catch(B){n(ge(B)||"Login failed","error"),N(null),K(re=>{if(!(R in re))return re;const pe={...re};return delete pe[R],pe})}},[n]),Ge=a.useCallback(async R=>{N(R);try{await th(R),await kt(),n("Logged out","success")}catch(B){n(ge(B)||"Logout failed","error")}finally{N(null)}},[n,kt]),gt=a.useCallback(async R=>{const B=G[R]?.trim();if(!B){X(re=>({...re,[R]:"API key is required"}));return}N(R),X(re=>{const pe={...re};return delete pe[R],pe});try{await nh(R,B),M(re=>{const pe={...re};return delete pe[R],pe}),await kt(),n("API key saved","success")}catch(re){X(pe=>({...pe,[R]:ge(re)||"Failed to save API key"}))}finally{N(null)}},[G,n,kt]),qt=a.useCallback(async R=>{N(R);try{await sh(R),M(B=>{const re={...B};return delete re[R],re}),X(B=>{const re={...B};return delete re[R],re}),await kt(),n("API key cleared","success")}catch(B){n(ge(B)||"Failed to clear API key","error")}finally{N(null)}},[n,kt]),gn=a.useCallback(async()=>{if(!(!c.ntfyEnabled||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic))){Se(!0);try{const R=c.ntfyBaseUrl?.trim();(await zx({ntfyEnabled:c.ntfyEnabled,ntfyTopic:c.ntfyTopic,...R?{ntfyBaseUrl:R}:{}},s)).success?n("Test notification sent — check your ntfy app!","success"):n("Failed to send test notification","error")}catch(R){n(ge(R)||"Failed to send test notification","error")}finally{Se(!1)}}},[n,c.ntfyBaseUrl,c.ntfyEnabled,c.ntfyTopic,s]),Wt=a.useCallback(async()=>{Ie(!0);try{const R=await Ny(s);if(R.success){n("Backup created successfully","success");const B=await sd(s);rt(B)}else n(R.error||"Failed to create backup","error")}catch(R){n(ge(R)||"Failed to create backup","error")}finally{Ie(!1)}},[n,s]),Rn=a.useCallback(async()=>{try{const R=C==="global"?"global":C==="project"?"project":"both",B=await Sy(R,s),re=new Blob([JSON.stringify(B,null,2)],{type:"application/json"}),pe=URL.createObjectURL(re),ue=document.createElement("a"),Te=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;ue.href=pe,ue.download=Te,document.body.appendChild(ue),ue.click(),document.body.removeChild(ue),URL.revokeObjectURL(pe),n(`Settings exported (${R==="global"?"global":R==="project"?"project":"all"} scope)`,"success")}catch(R){n(ge(R)||"Failed to export settings","error")}},[n,C,s]),Kt=a.useCallback(async R=>{const B=R.target.files?.[0];if(B){wt(B),_t(!0);try{const re=await B.text(),pe=JSON.parse(re);Rt(pe),xt(!0)}catch(re){n(`Invalid JSON file: ${ge(re)}`,"error"),wt(null)}finally{_t(!1)}}},[n]),$n=a.useCallback(async()=>{if(Et){_t(!0);try{const R=await Cy(Et,{scope:vt,merge:Ke},s);if(R.success){const B=[];R.globalCount>0&&B.push(`${R.globalCount} global`),R.projectCount>0&&B.push(`${R.projectCount} project`),n(`Imported ${B.join(", ")} setting(s)`,"success"),xt(!1),Rt(null),wt(null);const re=await Wi(s);u(re)}else n(R.error||"Import failed","error")}catch(R){n(ge(R)||"Failed to import settings","error")}finally{_t(!1)}}},[n,Et,vt,Ke,s]),bn=a.useCallback(async R=>{const B=D,pe=B.includes(R)?B.filter(ue=>ue!==R):[R,...B];me(pe);try{await Gt({favoriteProviders:pe,favoriteModels:q})}catch{me(B)}},[D,q]),on=a.useCallback(async R=>{const B=q,pe=B.includes(R)?B.filter(ue=>ue!==R):[R,...B];W(pe);try{await Gt({favoriteProviders:D,favoriteModels:pe})}catch{W(B)}},[q,D]);a.useEffect(()=>{const R=B=>{B.key==="Escape"&&t()};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[t]);const en=a.useCallback(R=>{R.target===R.currentTarget&&t()},[t]),xn=[{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 wn(R){if(!b?.project)return"inherited";const B=b.project[R.projectProviderKey],re=b.project[R.projectModelKey];return B!==void 0||re!==void 0?"overridden":"inherited"}function Dn(R){const B=c[R.projectProviderKey],re=c[R.projectModelKey];return B&&re?`${B}/${re}`:""}function cn(R,B){if(B){const re=B.indexOf("/");u(pe=>({...pe,[R.projectProviderKey]:B.slice(0,re),[R.projectModelKey]:B.slice(re+1)}))}else{if(wn(R)==="inherited")return;u(pe=>({...pe,[R.projectProviderKey]:void 0,[R.projectModelKey]:void 0}))}}function sn(R){wn(R)!=="inherited"&&u(re=>({...re,[R.projectProviderKey]:void 0,[R.projectModelKey]:void 0}))}const Vt=a.useCallback(async()=>{if(!(k||Ae))try{const R={...c,worktreeInitCommand:c.worktreeInitCommand?.trim()||void 0,taskPrefix:c.taskPrefix?.trim()||void 0},B={};for(const[pe,ue]of Object.entries(R))if(lj(pe)){const Te=f?.[pe];ue===void 0&&Te!==void 0?B[pe]=null:B[pe]=ue}const re={};for(const[pe,ue]of Object.entries(R)){if(pe==="githubTokenConfigured"||pe==="prAuthAvailable"||!oj(pe))continue;const Te=v?.project?.[pe];["planningProvider","planningModelId","validatorProvider","validatorModelId","executionProvider","executionModelId","titleSummarizerProvider","titleSummarizerModelId","defaultProviderOverride","defaultModelIdOverride","planningFallbackProvider","planningFallbackModelId","validatorFallbackProvider","validatorFallbackModelId","titleSummarizerFallbackProvider","titleSummarizerFallbackModelId"].includes(pe)?ue!==Te&&(ue==null&&Te!==void 0&&Te!==null?re[pe]=null:ue!==void 0&&(re[pe]=ue)):re[pe]=ue}await Promise.all([Object.keys(B).length>0?Gt(B):Promise.resolve(),Object.keys(re).length>0?Sa(re,s):Promise.resolve(),Ve!==Re.current?Dy({globalMaxConcurrent:Ve??4}):Promise.resolve()]),n("Settings saved","success"),t()}catch(R){n(ge(R),"error")}},[c,Ve,k,Ae,f,v,t,n,s]),Nn=a.useCallback(async()=>{try{await _x(He,Be,s),te(!1),n("Memory saved","success")}catch(R){n(ge(R)||"Failed to save memory","error")}},[He,Be,s,n]),Un=a.useCallback(async()=>{it(!0);try{const{path:R,content:B}=await Ix(He,s),re=R??He;He!==re&&(oe.current=!0),dt(re),nt(B),te(!1);const{files:pe}=await Hc(s);ke(pe),n("Memory file compacted","success")}catch(R){n(ge(R)||"Failed to compact memory","error")}finally{it(!1)}},[He,s,n]),Sn=a.useCallback(async()=>{ye(!0),st(null);try{const R=await Fx(ht,s);st(R),n(R.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",R.qmdAvailable?"success":"warning")}catch(R){n(ge(R)||"Failed to test memory retrieval","error")}finally{ye(!1)}},[ht,s,n]),Hn=a.useCallback(async()=>{qe(!0);try{const R=await Dx(s);await pt(),n(R.qmdAvailable?"qmd installed successfully":"qmd install finished, but qmd is still unavailable",R.qmdAvailable?"success":"warning")}catch(R){n(ge(R)||"Failed to install qmd","error")}finally{qe(!1)}},[s,pt,n]),Qn=()=>{if(!Ae)return;const R=Ae.name.trim();if(!R){n("Preset name is required","error");return}const B=c.modelPresets||[];let re;ve?re=ve:re=lM(R,B);const pe={id:re,name:R,executorProvider:Ae.executorProvider,executorModelId:Ae.executorModelId,validatorProvider:Ae.validatorProvider,validatorModelId:Ae.validatorModelId};u(ue=>{const Te=ue.modelPresets||[],ut=ve?Te.map(Mt=>Mt.id===ve?pe:Mt):[...Te,pe];return{...ue,modelPresets:ut}}),Ee(null),Oe(null)},Q=()=>C==="global"?e.jsxs("div",{className:"settings-scope-banner settings-scope-global",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(vi,{size:14})}),e.jsx("span",{children:"These settings are shared across all your Fusion projects."})]}):C==="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,Ue=()=>{switch(j){case"general":return e.jsxs(e.Fragment,{children:[Q(),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:R=>{const B=R.target.value;u(re=>({...re,taskPrefix:B||void 0})),B&&!/^[A-Z]{1,10}$/.test(B)?T("Prefix must be 1–10 uppercase letters"):T(null)}}),k&&e.jsx("small",{className:"field-error",children:k}),!k&&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:R=>u(B=>({...B,requirePlanApproval:R.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:R=>u(B=>({...B,showQuickChatFAB:R.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 R=c.defaultProvider&&c.defaultModelId?`${c.defaultProvider}/${c.defaultModelId}`:"",B=xn.filter(re=>re.laneId!=="default");return e.jsxs(e.Fragment,{children:[Q(),e.jsx("h4",{className:"settings-section-heading",children:"Default Model"}),L?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(Jt,{id:"defaultModel",label:"Default Model",models:V,value:R,onChange:re=>{if(!re)u(pe=>({...pe,defaultProvider:void 0,defaultModelId:void 0}));else{const pe=re.indexOf("/");u(ue=>({...ue,defaultProvider:re.slice(0,pe),defaultModelId:re.slice(pe+1)}))}},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on}),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(Jt,{id:"fallbackModel",label:"Fallback Model",models:V,value:c.fallbackProvider&&c.fallbackModelId?`${c.fallbackProvider}/${c.fallbackModelId}`:"",onChange:re=>{if(!re)u(pe=>({...pe,fallbackProvider:void 0,fallbackModelId:void 0}));else{const pe=re.indexOf("/");u(ue=>({...ue,fallbackProvider:re.slice(0,pe),fallbackModelId:re.slice(pe+1)}))}},placeholder:"No fallback",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on}),e.jsx("small",{children:"Used automatically if the primary default model hits a retryable provider error like rate limiting or overload."})]})]}),(()=>{const re=V.find(pe=>pe.provider===c.defaultProvider&&pe.id===c.defaultModelId);return re&&!re.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:pe=>{const ue=pe.target.value;u(Te=>({...Te,defaultThinkingLevel:ue||void 0}))},children:[e.jsx("option",{value:"",children:"Default"}),cj.map(pe=>e.jsx("option",{value:pe,children:pe.charAt(0).toUpperCase()+pe.slice(1)},pe))]}),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."}),B.map(re=>{const pe=c[re.globalProviderKey],ue=c[re.globalModelKey],Te=pe&&ue?`${pe}/${ue}`:"";return e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`global-${re.laneId}-model`,children:re.label}),e.jsx(Jt,{id:`global-${re.laneId}-model`,label:re.label,models:V,value:Te,onChange:ut=>{if(!ut){u(dn=>({...dn,[re.globalProviderKey]:void 0,[re.globalModelKey]:void 0}));return}const Mt=ut.indexOf("/");u(dn=>({...dn,[re.globalProviderKey]:ut.slice(0,Mt),[re.globalModelKey]:ut.slice(Mt+1)}))},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on}),e.jsx("small",{children:re.helperText})]},`global-${re.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:re=>u(pe=>({...pe,openrouterModelSync:re.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 R=c.modelPresets||[],B=R.map(ue=>({id:ue.id,name:ue.name})),re=new Set(Object.values(c.defaultPresetBySize||{}).filter(Boolean)),pe=xn.filter(ue=>ue.laneId==="execution"||ue.laneId==="planning"||ue.laneId==="validator"||ue.laneId==="summarization");return e.jsxs(e.Fragment,{children:[Q(),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:ue=>{const Te=ue.target.value;u(ut=>({...ut,tokenCap:Te?parseInt(Te,10):null}))}}),c.tokenCap!=null&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to default (no cap)",onClick:()=>u(ue=>({...ue,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."}),L?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:pe.map(ue=>{const Te=wn(ue),ut=Dn(ue),Mt=Te==="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:`${ue.laneId}Model`,children:ue.label}),e.jsx("span",{className:`settings-lane-badge ${Mt?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:Mt?"Explicitly set for this project":"Inherited from global settings",children:Mt?"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(Jt,{id:`${ue.laneId}Model`,label:ue.label,models:V,value:ut,onChange:dn=>cn(ue,dn),placeholder:"Use global",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on})}),Mt&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to inherit from global",onClick:()=>sn(ue),style:{whiteSpace:"nowrap"},children:"Reset"})]}),e.jsxs("small",{children:[ue.helperText," Falls back to: ",ue.fallbackOrder,"."]})]},ue.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Fallback Models"}),L?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(Jt,{id:"planningFallbackModel",label:"Planning Fallback Model",models:V,value:c.planningFallbackProvider&&c.planningFallbackModelId?`${c.planningFallbackProvider}/${c.planningFallbackModelId}`:"",onChange:ue=>{if(!ue)u(Te=>({...Te,planningFallbackProvider:void 0,planningFallbackModelId:void 0}));else{const Te=ue.indexOf("/");u(ut=>({...ut,planningFallbackProvider:ue.slice(0,Te),planningFallbackModelId:ue.slice(Te+1)}))}},placeholder:"Use global fallback",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on}),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(Jt,{id:"validatorFallbackModel",label:"Validator Fallback Model",models:V,value:c.validatorFallbackProvider&&c.validatorFallbackModelId?`${c.validatorFallbackProvider}/${c.validatorFallbackModelId}`:"",onChange:ue=>{if(!ue)u(Te=>({...Te,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0}));else{const Te=ue.indexOf("/");u(ut=>({...ut,validatorFallbackProvider:ue.slice(0,Te),validatorFallbackModelId:ue.slice(Te+1)}))}},placeholder:"Use global fallback",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on}),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"}),R.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No presets configured yet."}):e.jsx("div",{className:"settings-preset-list",children:R.map(ue=>{const Te=Io(ue),ut=`${Te.executorValue||"default"} / ${Te.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:ue.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:ut})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Ee(ue.id),Oe({...ue})},children:"Edit"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{re.has(ue.id)&&!confirm(`Preset "${ue.name}" is used in auto-selection. Delete it anyway?`)||(u(Mt=>({...Mt,modelPresets:(Mt.modelPresets||[]).filter(dn=>dn.id!==ue.id),defaultPresetBySize:Object.fromEntries(Object.entries(Mt.defaultPresetBySize||{}).filter(([,dn])=>dn!==ue.id))})),ve===ue.id&&(Ee(null),Oe(null)))},children:"Delete"})]})]},ue.id)})}),Ae?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Ee(null),Oe({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:"Add Preset"})})]}),Ae?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:Ae.name,onChange:ue=>{const Te=ue.target.value;Oe(ut=>ut&&{...ut,name:Te})}})]}),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(Jt,{id:"preset-executor-model",label:"Preset executor model",models:V,value:Ae.executorProvider&&Ae.executorModelId?`${Ae.executorProvider}/${Ae.executorModelId}`:"",onChange:ue=>{if(!ue){Oe(ut=>ut&&{...ut,executorProvider:void 0,executorModelId:void 0});return}const Te=ue.indexOf("/");Oe(ut=>ut&&{...ut,executorProvider:ue.slice(0,Te),executorModelId:ue.slice(Te+1)})},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:"Validator model"}),e.jsx(Jt,{id:"preset-validator-model",label:"Preset validator model",models:V,value:Ae.validatorProvider&&Ae.validatorModelId?`${Ae.validatorProvider}/${Ae.validatorModelId}`:"",onChange:ue=>{if(!ue){Oe(ut=>ut&&{...ut,validatorProvider:void 0,validatorModelId:void 0});return}const Te=ue.indexOf("/");Oe(ut=>ut&&{...ut,validatorProvider:ue.slice(0,Te),validatorModelId:ue.slice(Te+1)})},placeholder:"Use default",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Qn,children:"Save preset"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Ee(null),Oe(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:ue=>u(Te=>({...Te,autoSelectModelPreset:ue.target.checked}))}),"Auto-select preset based on task size"]})}),c.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(ue=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${ue}`,children:ue==="S"?"Small tasks (S):":ue==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${ue}`,value:c.defaultPresetBySize?.[ue]||"",onChange:Te=>{const ut=Te.target.value||void 0;u(Mt=>({...Mt,defaultPresetBySize:{...Mt.defaultPresetBySize||{},[ue]:ut}}))},children:[e.jsx("option",{value:"",children:"No preset"}),B.map(Te=>e.jsx("option",{value:Te.id,children:Te.name},Te.id))]})]},ue))}):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:ue=>u(Te=>({...Te,autoSummarizeTitles:ue.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"}),L?e.jsx("small",{children:"Loading available models..."}):V.length===0?e.jsx("small",{children:"No models available. Configure authentication first."}):e.jsx(Jt,{id:"titleSummarizerModel",label:"Title summarization model",models:V,value:c.titleSummarizerProvider&&c.titleSummarizerModelId?`${c.titleSummarizerProvider}/${c.titleSummarizerModelId}`:"",onChange:ue=>{if(!ue){u(ut=>({...ut,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0}));return}const Te=ue.indexOf("/");u(ut=>({...ut,titleSummarizerProvider:ue.slice(0,Te),titleSummarizerModelId:ue.slice(Te+1)}))},placeholder:"Use fallback model",favoriteProviders:D,onToggleFavorite:bn,favoriteModels:q,onToggleModelFavorite:on}),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(ue=>({...ue,titleSummarizerProvider:ue.planningProvider,titleSummarizerModelId:ue.planningModelId})),disabled:!c.planningProvider||!c.planningModelId,children:"Use planning model"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>u(ue=>({...ue,titleSummarizerProvider:ue.defaultProvider,titleSummarizerModelId:ue.defaultModelId})),disabled:!c.defaultProvider||!c.defaultModelId,children:"Use default model"})]})})]})]})}case"appearance":return e.jsxs(e.Fragment,{children:[Q(),e.jsx("h4",{className:"settings-section-heading",children:"Appearance"}),e.jsx(RM,{themeMode:r,colorTheme:l,onThemeModeChange:R=>{u(B=>({...B,themeMode:R})),o?.(R)},onColorThemeChange:R=>{u(B=>({...B,colorTheme:R})),d?.(R)}})]});case"scheduling":return e.jsxs(e.Fragment,{children:[Q(),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:Ve??"",onChange:R=>{const B=R.target.value;We(B===""?void 0:Number(B))}}),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:R=>{const B=R.target.value;u(re=>({...re,maxConcurrent:B===""?void 0:Number(B)}))}})]}),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:R=>{const B=R.target.value;u(re=>({...re,maxTriageConcurrent:B===""?void 0:Number(B)}))}}),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:R=>{const B=R.target.value;u(re=>({...re,pollIntervalMs:B===""?void 0:Number(B)}))}})]}),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:R=>{const B=R.target.value,re=Number(B);u(pe=>({...pe,taskStuckTimeoutMs:B&&re>0?re*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:R=>u(B=>({...B,specStalenessEnabled:R.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:R=>{const B=R.target.value,re=Number(B);u(pe=>({...pe,specStalenessMaxAgeMs:B!==""?re*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:R=>u(B=>({...B,autoArchiveDoneTasksEnabled:R.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/Xu):zM,onChange:R=>{const B=R.target.value,re=Number(B);u(pe=>({...pe,autoArchiveDoneAfterMs:B===""?void 0:re*Xu}))},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:R=>u(B=>({...B,archiveAgentLogMode:R.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:R=>{const B=R.target.value,re=Number(B);u(pe=>({...pe,maxStuckKills:B&&re>0?re: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:R=>u(B=>({...B,groupOverlappingFiles:R.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:R=>u(B=>({...B,runStepsInNewSessions:R.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:R=>{const B=R.target.value;u(re=>({...re,maxParallelSteps:B===""?void 0:Number(B)}))},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:[Q(),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:R=>{const B=R.target.value;u(re=>({...re,maxWorktrees:B===""?void 0:Number(B)}))}}),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:R=>u(B=>({...B,worktreeInitCommand:R.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:R=>u(B=>({...B,recycleWorktrees:R.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:R=>u(B=>({...B,worktreeNaming:R.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:R=>u(B=>({...B,worktreeRebaseBeforeMerge:R.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:R=>u(B=>({...B,worktreeRebaseRemote:R.target.value||void 0})),children:[e.jsx("option",{value:"",children:"Use git default"}),fe.map(R=>e.jsxs("option",{value:R.name,children:[R.name," (",R.fetchUrl,")"]},R.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:[Q(),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:R=>u(B=>({...B,testCommand:R.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:R=>u(B=>({...B,buildCommand:R.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:[Q(),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:R=>u(B=>({...B,autoMerge:R.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:R=>u(B=>({...B,mergeStrategy:R.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:R=>u(B=>({...B,includeTaskIdInCommit:R.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:R=>u(B=>({...B,commitAuthorEnabled:R.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:R=>u(B=>({...B,commitAuthorName:R.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:R=>u(B=>({...B,commitAuthorEmail:R.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:R=>u(B=>({...B,autoResolveConflicts:R.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:R=>u(B=>({...B,smartConflictResolution:R.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:R=>u(B=>({...B,pushAfterMerge:R.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:R=>u(B=>({...B,pushRemote:R.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:R,status:B,loading:re,error:pe}={capabilities:xe,status:lt,loading:U,error:Ne},ue=c.memoryEnabled!==!1,Te=R?.writable??!0,ut=ue&&Te,Mt=_e.find(Je=>Je.path===He),dn={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[Q(),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."})]}),re?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:"Checking memory write access..."})}):pe?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Failed to load backend status: ",pe]})}):null,B?.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:B.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Hn,disabled:Me,children:Me?"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:!ue}),"Process dreams from daily memory"]}),e.jsx("small",{children:"Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md."})]}),ue&&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=>he(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:Sn,disabled:ne,children:ne?"Testing…":"Test Retrieval"})}),we&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[we.results.length," result",we.results.length===1?"":"s"," ",'for "',we.query,'"']}),e.jsxs("small",{children:["qmd ",we.qmdAvailable?"available":"missing"," · ",we.usedFallback?"local fallback used":"qmd path used"]}),we.results.length>0?e.jsx("ul",{children:we.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."})]})]}),!ue&&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."}),ue&&!Te&&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."}),De?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:He,onChange:Je=>{dt(Je.target.value),te(!1)},disabled:ie,children:_e.map(Je=>e.jsxs("option",{value:Je.path,children:[Je.label," - ",Je.path]},Je.path))}),e.jsx("small",{children:ie?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),Mt&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:dn[Mt.layer]}),e.jsx("strong",{children:Mt.path}),e.jsxs("small",{children:[Mt.size.toLocaleString()," bytes · updated ",new Date(Mt.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:Mt?.label||"Memory Editor"}),e.jsxs("small",{children:[Mt?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",Mt?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",Mt?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!Mt&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(Hp,{content:Be,onChange:Je=>{nt(Je),te(!0)},readOnly:!ut,filePath:He})})]})]}),!De&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Un,disabled:!ut||ie||be,children:be?"Compacting…":"Compact Selected File"}),e.jsx("small",{children:ie?"Save or discard edits before compacting this file.":`Compacts ${He} and writes the result back to the same file.`})]}),ie&&ut&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Nn,children:"Save Memory"})}),ie&&!ut&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Cannot save: ",ue?"Backend is read-only":"Memory is disabled"]})})]})}case"experimental":{const R=c.experimentalFeatures??{},re=Array.from(new Set([...Object.keys(Zu),...Object.keys(R)])).sort((pe,ue)=>pe.localeCompare(ue)).map(pe=>[pe,R[pe]===!0]);return e.jsxs(e.Fragment,{children:[Q(),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:re.map(([pe,ue])=>e.jsxs("label",{htmlFor:`experimental-${pe}`,className:"checkbox-label",children:[e.jsx("input",{id:`experimental-${pe}`,type:"checkbox",checked:ue,onChange:Te=>{u(ut=>({...ut,experimentalFeatures:{...ut.experimentalFeatures??{},[pe]:Te.target.checked}}))}}),e.jsx("span",{children:Zu[pe]??pe})]},pe))})]})]})}case"backups":return e.jsxs(e.Fragment,{children:[Q(),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:R=>u(B=>({...B,autoBackupEnabled:R.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:R=>u(B=>({...B,autoBackupSchedule:R.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:R=>{const B=R.target.value;u(re=>({...re,autoBackupRetention:B===""?void 0:Number(B)}))},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:R=>u(B=>({...B,autoBackupDir:R.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 (..)"})]}),Pe?e.jsx("div",{className:"settings-empty-state",children:"Loading backup info…"}):Fe?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:Fe.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:Fe.totalSize>1024*1024?`${(Fe.totalSize/(1024*1024)).toFixed(1)} MB`:`${(Fe.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:"total size"})]})]}),Fe.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:["View ",Fe.backups.length," backup(s)"]}),e.jsxs("ul",{children:[Fe.backups.slice(0,10).map(R=>e.jsxs("li",{children:[e.jsx("code",{children:R.filename}),e.jsx("span",{className:"backup-size",children:R.size>1024*1024?`${(R.size/(1024*1024)).toFixed(1)} MB`:`${(R.size/1024).toFixed(1)} KB`})]},R.filename)),Fe.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:["...and ",Fe.backups.length-10," more"]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Wt,disabled:Pe,children:Pe?"Creating…":"Backup Now"})})]});case"notifications":return e.jsxs(e.Fragment,{children:[Q(),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:R=>u(B=>({...B,ntfyEnabled:R.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:R=>{const B=R.target.value;u(re=>({...re,ntfyTopic:B||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:R=>{const B=R.target.value;u(re=>({...re,ntfyBaseUrl:B||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:gn,disabled:ce||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic),children:ce?"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:R=>{const B=c.ntfyEvents??[...Di],re=R.target.checked?B.includes("in-review")?B:[...B,"in-review"]:B.filter(pe=>pe!=="in-review");u(pe=>({...pe,ntfyEvents:re.length>0?re: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:R=>{const B=c.ntfyEvents??[...Di],re=R.target.checked?B.includes("merged")?B:[...B,"merged"]:B.filter(pe=>pe!=="merged");u(pe=>({...pe,ntfyEvents:re.length>0?re: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:R=>{const B=c.ntfyEvents??[...Di],re=R.target.checked?B.includes("failed")?B:[...B,"failed"]:B.filter(pe=>pe!=="failed");u(pe=>({...pe,ntfyEvents:re.length>0?re: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:R=>{const B=c.ntfyEvents??[...Di],re=R.target.checked?B.includes("awaiting-approval")?B:[...B,"awaiting-approval"]:B.filter(pe=>pe!=="awaiting-approval");u(pe=>({...pe,ntfyEvents:re.length>0?re: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:R=>{const B=c.ntfyEvents??[...Di],re=R.target.checked?B.includes("awaiting-user-review")?B:[...B,"awaiting-user-review"]:B.filter(pe=>pe!=="awaiting-user-review");u(pe=>({...pe,ntfyEvents:re.length>0?re: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:R=>{const B=c.ntfyEvents??[...Di],re=R.target.checked?B.includes("planning-awaiting-input")?B:[...B,"planning-awaiting-input"]:B.filter(pe=>pe!=="planning-awaiting-input");u(pe=>({...pe,ntfyEvents:re.length>0?re: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:R=>{const B=R.target.value;u(re=>({...re,ntfyDashboardHost:B||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:[Q(),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:R=>u(B=>({...B,settingsSyncEnabled:R.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:R=>u(B=>({...B,settingsSyncAuth:R.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:R=>u(B=>({...B,settingsSyncInterval:parseInt(R.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:R=>u(B=>({...B,settingsSyncConflictResolution:R.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:[Q(),e.jsx("h4",{className:"settings-section-heading",children:"Prompts"}),e.jsx(DM,{value:c.agentPrompts,onChange:R=>{u(B=>({...B,agentPrompts:R}))},promptOverrides:c.promptOverrides,onPromptOverridesChange:R=>{u(B=>({...B,promptOverrides:R}))}})]});case"plugins":return e.jsxs(e.Fragment,{children:[Q(),e.jsx("h4",{className:"settings-section-heading",children:"Plugins"}),e.jsx(a.Suspense,{fallback:null,children:e.jsx(FM,{addToast:n,projectId:s})}),e.jsx(Ga,{slotId:"settings-section",projectId:s})]});case"pi-extensions":return e.jsx(a.Suspense,{fallback:null,children:e.jsx(LM,{addToast:n,projectId:s})});case"authentication":{const R=$.filter(Te=>Te.type==="cli"),re=[...$.filter(Te=>Te.type!=="cli")].sort((Te,ut)=>Te.authenticated!==ut.authenticated?Te.authenticated?-1:1:Te.name.localeCompare(ut.name)),pe=re.filter(Te=>Te.authenticated),ue=re.filter(Te=>!Te.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…"}):$.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No providers available"}):e.jsxs(e.Fragment,{children:[R.some(Te=>Te.id==="claude-cli")&&e.jsx(qp,{compact:!0,authenticated:R.find(Te=>Te.id==="claude-cli")?.authenticated??!1,onToggled:()=>{kt()}}),pe.length===0&&e.jsx("div",{className:"auth-section-hint",children:"Sign in to at least one provider to get started with AI models."}),pe.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Authenticated"}),pe.map(Te=>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:Te.name}),e.jsx("span",{"data-testid":`auth-status-${Te.id}`,className:`auth-status-badge ${Te.authenticated?"authenticated":"not-authenticated"}`,children:"✓ Active"}),Te.authenticated&&Te.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",Te.keyHint]})]}),Te.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[Te.id]??"",onChange:ut=>M(Mt=>({...Mt,[Te.id]:ut.target.value})),disabled:_===Te.id}),Te.authenticated&&!G[Te.id]?e.jsx("button",{className:"btn btn-sm",onClick:()=>qt(Te.id),disabled:_===Te.id,children:"Clear"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>gt(Te.id),disabled:_===Te.id,children:"Save"})]}),_===Te.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),O[Te.id]&&e.jsx("small",{className:"auth-apikey-error",children:O[Te.id]})]}):e.jsx("div",{children:_===Te.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>Ge(Te.id),children:"Logout"})})]})},Te.id))]}),ue.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Available"}),ue.map(Te=>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:Te.name}),e.jsx("span",{"data-testid":`auth-status-${Te.id}`,className:`auth-status-badge ${Te.authenticated?"authenticated":"not-authenticated"}`,children:"✗ Not connected"})]}),Te.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[Te.id]??"",onChange:ut=>M(Mt=>({...Mt,[Te.id]:ut.target.value})),disabled:_===Te.id}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>gt(Te.id),disabled:_===Te.id,children:"Save"})]}),_===Te.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),O[Te.id]&&e.jsx("small",{className:"auth-apikey-error",children:O[Te.id]})]}):e.jsxs("div",{children:[_===Te.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(Te.id),children:"Login"}),J[Te.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`auth-login-instructions-${Te.id}`,children:J[Te.id]})]})]})},Te.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:en,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:[w&&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:R=>P(R.target.value),children:br.filter(R=>!R.isGroupHeader).map(R=>e.jsx("option",{value:R.id,children:R.label},R.id))})]}),e.jsx("nav",{className:"settings-sidebar",children:br.map(R=>R.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:R.label},R.id):e.jsxs("button",{className:`settings-nav-item${j===R.id?" active":""}`,onClick:()=>P(R.id),title:R.scope==="global"?"Shared across all projects":R.scope==="project"?"Specific to this project":void 0,children:[R.scope==="global"&&e.jsx(vi,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),R.scope==="project"&&e.jsx(Pn,{className:"settings-scope-icon","aria-label":"Project setting",size:16}),R.icon&&!R.scope&&e.jsx(R.icon,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),R.label]},R.id))}),e.jsx("div",{className:"settings-content",children:Ue()})]}),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:Rn,title:"Export settings to JSON file",children:"Export"}),e.jsx("input",{type:"file",ref:Le,accept:".json,application/json",style:{display:"none"},onChange:Kt}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Le.current?.click(),disabled:$t,title:"Import settings from JSON file",children:$t?"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:Vt,disabled:h,children:"Save"})]})]})]}),et&&Et&&e.jsx("div",{className:"modal-overlay open",onClick:R=>R.target===R.currentTarget&&xt(!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:()=>xt(!1),"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:"Review the settings to be imported:"}),Et.global&&Object.keys(Et.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(Et.global).filter(([,R])=>R!==void 0).map(([R])=>e.jsx("li",{children:R},R))})]}),Et.project&&Object.keys(Et.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(Et.project).filter(([,R])=>R!==void 0).map(([R])=>e.jsx("li",{children:R},R))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:"Import Scope:"}),e.jsxs("select",{id:"import-scope",value:vt,onChange:R=>Dt(R.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:Ke,onChange:R=>bt(R.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:()=>xt(!1),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:$n,disabled:$t,children:$t?"Importing…":"Confirm Import"})]})]})})]})}const BM=640;function UM({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),[f,p]=a.useState("issues"),[b,x]=a.useState([]),[v,y]=a.useState(null),[A,j]=a.useState([]),[P,w]=a.useState(null),[E,k]=a.useState(null),[T,C]=a.useState(!1),[$,F]=a.useState([]),[ee,I]=a.useState(!1),[_,N]=a.useState(""),J=a.useRef(!1),[K,G]=a.useState(!1),[M,O]=a.useState("list"),X=a.useRef(null),S=new Set;for(const ae of i){const _e=ae.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);_e&&S.add(_e[1]);const ke=ae.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);ke&&S.add(ke[1])}a.useEffect(()=>{if(t)return o(""),m(""),u(""),x([]),y(null),j([]),w(null),p("issues"),k(null),C(!1),F([]),I(!0),N(""),X.current=null,J.current=!0,sv().then(ae=>{if(J.current)if(F(ae),I(!1),ae.length===1){const _e=ae[0];o(_e.owner),m(_e.repo),N(_e.name)}else ae.length>1&&(o(""),m(""),N(""))}).catch(()=>{J.current&&I(!1)}),()=>{J.current=!1}},[t]);const V=a.useCallback(ae=>{if(N(ae),ae==="")o(""),m("");else{const _e=$.find(ke=>ke.name===ae);_e&&(o(_e.owner),m(_e.repo))}},[$]),de=a.useCallback(async()=>{if(!l.trim()||!d.trim()){k("Repository must be selected");return}g(!0),k(null),x([]),y(null);try{const ae=c.split(",").map(ke=>ke.trim()).filter(Boolean),_e=await Zx(l.trim(),d.trim(),30,ae.length>0?ae:void 0);x(_e),_e.length===0&&k("No open issues found")}catch(ae){k(ge(ae)||"Failed to fetch issues")}finally{g(!1)}},[l,d,c]),L=a.useCallback(async()=>{if(!l.trim()||!d.trim()){k("Repository must be selected");return}g(!0),k(null),j([]),w(null);try{const ae=await tv(l.trim(),d.trim(),30);j(ae),ae.length===0&&k("No open pull requests found")}catch(ae){k(ge(ae)||"Failed to fetch pull requests")}finally{g(!1)}},[l,d]);a.useEffect(()=>{if(!t||!l.trim()||!d.trim()||h||T)return;const ae={owner:l.trim(),repo:d.trim(),labels:c.trim(),tab:f};X.current?.owner===ae.owner&&X.current?.repo===ae.repo&&X.current?.labels===ae.labels&&X.current?.tab===ae.tab||(X.current=ae,f==="issues"?de():L())},[l,d,c,f,t,h,T,de,L]),a.useEffect(()=>{if(!t)return;const ae=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[t,n]),a.useEffect(()=>{if(!t)return;const ae=()=>{G(window.innerWidth<=BM)};return ae(),window.addEventListener("resize",ae),()=>window.removeEventListener("resize",ae)},[t]);const Z=a.useCallback(ae=>{y(ae),K&&O("preview")},[K]),D=a.useCallback(ae=>{w(ae),K&&O("preview")},[K]),me=a.useCallback(()=>{O("list")},[]),q=a.useCallback(async()=>{if(f==="issues"){if(v===null)return;C(!0),k(null);try{const ae=await ev(l.trim(),d.trim(),v,r);s(ae),n()}catch(ae){const _e=ge(ae);_e?.includes("already imported")?k(_e):k(_e||"Failed to import issue")}finally{C(!1)}}else{if(P===null)return;C(!0),k(null);try{const ae=await nv(l.trim(),d.trim(),P,r);s(ae),n()}catch(ae){const _e=ge(ae);_e?.includes("already imported")?k(_e):k(_e||"Failed to import pull request")}finally{C(!1)}}},[f,v,P,l,d,s,n]),W=b.find(ae=>ae.number===v),ce=A.find(ae=>ae.number===P);if(!t)return null;const Se=$.length>0,ve=$.length===1,Ee=b.filter(ae=>S.has(ae.html_url)).length,Ae=A.filter(ae=>S.has(ae.html_url)).length,Oe=E==="No open issues found",Fe=E==="No open pull requests found",rt=f==="issues"?Oe:Fe,Pe=!!E&&!Oe&&b.length===0&&!h,Ie=!!E&&!Fe&&A.length===0&&!h,Be=f==="issues"?Pe:Ie,nt=h||b.length>0||Oe||Pe,De=h||A.length>0||Fe||Ie,Qe=f==="issues"?nt:De,ie=!!E&&b.length>0&&!Oe,te=!!E&&A.length>0&&!Fe,fe=f==="issues"?ie:te;return e.jsx("div",{className:"modal-overlay open",onClick:ae=>ae.target===ae.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":f==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${f==="issues"?"active":""}`,onClick:()=>{p("issues"),w(null)},disabled:h||T,children:[e.jsx(Hr,{size:16}),e.jsx("span",{children:"Issues"})]}),e.jsxs("button",{role:"tab","aria-selected":f==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${f==="pulls"?"active":""}`,onClick:()=>{p("pulls"),y(null)},disabled:h||T,children:[e.jsx(ns,{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…"})]}):Se?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:$[0].name}),e.jsxs("span",{className:"github-import-remote-pill__repo",children:[$[0].owner,"/",$[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:_,onChange:ae=>V(ae.target.value),disabled:h||T,"aria-label":"Select Git remote",children:[e.jsx("option",{value:"",children:"Select remote…"}),$.map(ae=>e.jsxs("option",{value:ae.name,children:[ae.name," (",ae.owner,"/",ae.repo,")"]},ae.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:f==="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:ae=>u(ae.target.value),onKeyDown:ae=>ae.key==="Enter"&&de(),disabled:h||T||!Se,"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:f==="issues"?de:L,disabled:h||T||!l.trim()||!d.trim(),"aria-label":h?`Loading ${f}`:`Load ${f} from repository`,title:h?"Loading…":`Load ${f}`,children:[h?e.jsx(ct,{size:14,className:"spin"}):e.jsx(An,{size:14}),e.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!ee&&!Se&&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"})]}),fe&&e.jsx("div",{className:"form-error github-import-banner",role:"alert",children:E}),e.jsxs("div",{className:"github-import-workspace",children:[e.jsxs("section",{className:`github-import-list-pane ${K?"mobile":""} ${M==="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:f==="issues"?"Issues":"Pull Requests"}),f==="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:[Ee," imported"]})]}),f==="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:[Ae," imported"]})]})]}),e.jsxs("div",{className:"github-import-pane-content",children:[!Qe&&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 ",f==="issues"?"issues":"pull requests","…"]}),e.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),Be&&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 ",f==="issues"?"issues":"pull requests"]}),e.jsx("span",{children:E})]})}),rt&&e.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:e.jsxs("div",{children:[e.jsxs("strong",{children:["No open ",f==="issues"?"issues":"pull requests"," found"]}),e.jsx("span",{children:f==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),f==="issues"&&b.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(ae=>{const _e=S.has(ae.html_url);return e.jsxs("div",{className:`issue-item ${v===ae.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&Z(ae.number),children:[e.jsx("input",{type:"radio",name:"issue",checked:v===ae.number,onChange:()=>Z(ae.number),disabled:_e,"aria-label":`Select issue #${ae.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",ae.number]}),e.jsx("span",{className:"issue-title",children:ae.title})]}),ae.labels.length>0&&e.jsx("span",{className:"issue-labels",children:ae.labels.map(ke=>e.jsx("span",{className:"label-chip",children:ke.name},ke.name))})]}),_e&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},ae.number)})}),f==="pulls"&&A.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:A.map(ae=>{const _e=S.has(ae.html_url);return e.jsxs("div",{className:`issue-item ${P===ae.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&D(ae.number),children:[e.jsx("input",{type:"radio",name:"pull",checked:P===ae.number,onChange:()=>D(ae.number),disabled:_e,"aria-label":`Select pull request #${ae.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",ae.number]}),e.jsx("span",{className:"issue-title",children:ae.title})]}),e.jsxs("span",{className:"pull-branch-info",children:[ae.headBranch," → ",ae.baseBranch]})]}),_e&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},ae.number)})})]})]}),e.jsxs("section",{className:`github-import-preview-pane ${K?"mobile":""} ${M==="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:me,"data-testid":"github-import-back-button","aria-label":`Back to ${f==="issues"?"issues":"pull requests"} list`,children:[e.jsx(na,{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:[f==="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)"})]}):f==="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,f==="pulls"&&ce?e.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[e.jsxs("div",{className:"preview-meta",children:["Pull Request #",ce.number]}),e.jsx("div",{className:"preview-title",children:ce.title}),e.jsxs("div",{className:"preview-branch",children:[e.jsx("strong",{children:"Branch:"})," ",ce.headBranch," → ",ce.baseBranch]}),e.jsx("div",{className:"preview-body",children:ce.body?ce.body.slice(0,200)+(ce.body.length>200?"…":""):"(no description)"})]}):f==="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:T,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:q,disabled:(f==="issues"?v===null:P===null)||T,children:T?e.jsx(ct,{size:14,className:"spin"}):"Import"})]})]})})}const HM=["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 qM(t,n){return t&&n?`${t}/${n}`:""}function VM(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 WM({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,f]=a.useState(null),[p,b]=a.useState([]),[x,v]=a.useState([]),[y,A]=a.useState(null),j=a.useRef(!1),[P,w]=a.useState(""),[E,k]=a.useState(!0),[T,C]=a.useState(!1),[$,F]=a.useState(!1),ee=a.useRef(null),I=a.useRef(null),_=a.useRef(null),[N,J]=a.useState(d??null),K=a.useMemo(()=>Si(),[]),{isLockedByOther:G,takeControl:M,isLoading:O}=Xr(t?N:null),{activeTabMap:X,broadcastUpdate:S,broadcastCompleted:V,broadcastLock:de,broadcastUnlock:L,broadcastHeartbeat:Z}=aa(),[D,me]=a.useState(void 0),[q,W]=a.useState(void 0),[ce,Se]=a.useState([]),[ve,Ee]=a.useState(!1),[Ae,Oe]=a.useState(null),[Fe,rt]=a.useState([]),[Pe,Ie]=a.useState([]),Be=a.useRef(null),nt=qM(D,q),De=a.useCallback((oe,Ve)=>{if(!oe||!Ve)return"Using default";const We=ce.find(Re=>Re.provider===oe&&Re.id===Ve);return We?`${We.provider}/${We.id}`:`${oe}/${Ve}`},[ce]),Qe=a.useCallback(async()=>{Ee(!0),Oe(null);try{const oe=await Jn();Se(oe.models),rt(oe.favoriteProviders),Ie(oe.favoriteModels)}catch(oe){Oe(ge(oe)||"Failed to load models")}finally{Ee(!1)}},[]),ie=a.useCallback(oe=>{rt(Ve=>{const We=Ve,et=We.includes(oe)?We.filter(xt=>xt!==oe):[oe,...We];return Gt({favoriteProviders:et,favoriteModels:Pe}).catch(()=>{rt(We)}),et})},[Pe]),te=a.useCallback(oe=>{Ie(Ve=>{const We=Ve,et=We.includes(oe)?We.filter(xt=>xt!==oe):[oe,...We];return Gt({favoriteProviders:Fe,favoriteModels:et}).catch(()=>{Ie(We)}),et})},[Fe]),fe=a.useCallback(oe=>{I.current?.close();const Ve=ey(oe,o,{onThinking:We=>{w(Re=>Re+We),S({sessionId:oe,status:"generating",needsInput:!1,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onQuestion:We=>{C(!1),F(!1),Ti(o),h({type:"question",session:{sessionId:oe,currentQuestion:We,summary:null}}),w(""),S({sessionId:oe,status:"awaiting_input",needsInput:!0,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onSummary:We=>{C(!1),F(!1),Ti(o),h({type:"summary",session:{sessionId:oe,currentQuestion:null,summary:We},summary:We}),A(We),w(""),S({sessionId:oe,status:"complete",needsInput:!1,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onError:We=>{const Re=We||"Session failed while contacting the AI.";C(!1),F(!1),f(null),h(et=>et.type==="question"||et.type==="summary"||et.type==="error"?{type:"error",session:et.session,errorMessage:Re}:{type:"error",session:{sessionId:oe,currentQuestion:null,summary:null},errorMessage:Re}),w(""),_.current=oe,S({sessionId:oe,status:"error",needsInput:!1,owningTabId:K,type:"planning",title:m.trim()||"Planning session",projectId:o??null}),V({sessionId:oe,status:"error"})},onComplete:()=>{C(!1),F(!1),_.current=null,V({sessionId:oe,status:"complete"})},onConnectionStateChange:We=>{C(We==="reconnecting")}});I.current=Ve},[V,S,m,o,K]),ae=a.useCallback(async oe=>{const Ve=oe??m;if(Ve.trim()){f(null),w(""),v([]),b([]),C(!1),h({type:"loading"});try{const We=D&&q?{planningModelProvider:D,planningModelId:q}:void 0,{sessionId:Re}=await Lv(Ve.trim(),o,We);_.current=Re,J(Re),fe(Re),b([])}catch(We){C(!1),f(ge(We)||"Failed to start planning session"),h({type:"initial"}),_.current=null,J(null)}}},[fe,m,q,D,o]);a.useEffect(()=>{t&&u.type==="initial"&&ee.current?.focus()},[t,u.type]),a.useEffect(()=>{t&&Qe()},[t,Qe]),a.useEffect(()=>{if(t&&l&&!j.current&&u.type==="initial"){c(l);const oe=setTimeout(()=>{j.current=!0,ae(l)},0);return()=>clearTimeout(oe)}else if(t&&!l&&!j.current&&u.type==="initial"){const oe=$w(o);oe&&c(oe)}},[t,l,u.type,ae]),a.useEffect(()=>{if(!t||!d||u.type!=="initial")return;let oe=!1;return(async()=>{try{const Ve=await ti(d);if(oe||!Ve)return;_.current=d,J(d);const We=Gi(Ve.conversationHistory);if(v(We),b(We.map(Re=>Re.response).filter(Re=>!!(Re&&typeof Re=="object"&&!Array.isArray(Re)))),Ve.status==="awaiting_input"&&Ve.currentQuestion){Ti(o);const Re=JSON.parse(Ve.currentQuestion);h({type:"question",session:{sessionId:d,currentQuestion:Re,summary:null}}),Ve.thinkingOutput&&w(Ve.thinkingOutput),fe(d)}else if(Ve.status==="complete"&&Ve.result){Ti(o);const Re=JSON.parse(Ve.result);h({type:"summary",session:{sessionId:d,currentQuestion:null,summary:Re},summary:Re}),A(Re)}else Ve.status==="generating"?(h({type:"loading"}),Ve.thinkingOutput&&w(Ve.thinkingOutput),fe(d)):Ve.status==="error"&&(f(null),h({type:"error",session:{sessionId:d,currentQuestion:null,summary:null},errorMessage:Ve.error||"Session failed"}))}catch{f("Failed to resume session")}})(),()=>{oe=!0}},[fe,t,d,u.type,o]),a.useEffect(()=>{t||(j.current=!1,C(!1),F(!1),J(null))},[t]),a.useEffect(()=>{if(!t){Be.current&&(L(Be.current,K),Be.current=null);return}if(N&&Be.current!==N){Be.current&&L(Be.current,K),de(N,K),Be.current=N;return}!N&&Be.current&&(L(Be.current,K),Be.current=null)},[de,L,t,N,K]),a.useEffect(()=>{if(!t||!N||Be.current!==N)return;Z(K);const oe=setInterval(()=>{Z(K)},3e4);return()=>{clearInterval(oe)}},[Z,t,N,K]),a.useEffect(()=>()=>{I.current?.close(),I.current=null,Be.current&&(L(Be.current,K),Be.current=null)},[L,K]),a.useEffect(()=>{if(!t)return;const oe=()=>{I.current?.close(),I.current=null};return window.addEventListener("beforeunload",oe),()=>window.removeEventListener("beforeunload",oe)},[t]);const _e=a.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),ke=a.useCallback(()=>{let oe=null;u.type==="question"||u.type==="summary"||u.type==="error"?oe=u.session.sessionId:u.type==="breakdown"?oe=u.sessionId:u.type==="loading"&&(oe=_.current),m&&Iw(m,o),I.current?.close(),I.current=null,oe&&rh(oe,o,K).catch(()=>{}),c(""),h({type:"initial"}),f(null),b([]),v([]),A(null),w(""),C(!1),F(!1),me(void 0),W(void 0),_.current=null,J(null),n()},[m,n,o,K,u]);a.useEffect(()=>{if(!t)return;const oe=Ve=>{Ve.key==="Escape"&&ke()};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[t,ke]);const He=a.useCallback(async oe=>{if(u.type!=="question")return;const{session:Ve}=u,We=Ve.sessionId,Re=Ve.currentQuestion;if(!Re){f("No active question in session");return}f(null),b(et=>[...et,oe]),v(et=>[...et,{question:Re,response:oe}]),h({type:"loading"}),w("");try{await zv(We,oe,o,K)}catch(et){f(ge(et)||"Failed to submit response"),h({type:"question",session:Ve})}},[o,K,u]),dt=a.useCallback(async()=>{if(u.type!=="error")return;const oe=u.session;f(null),F(!0),w(""),h({type:"loading"}),fe(oe.sessionId);try{_.current=oe.sessionId,J(oe.sessionId),await Ov(oe.sessionId,o,K)}catch(Ve){let We=Ve;if((ge(Ve)||"").includes("not in an error state"))try{const et=await ti(oe.sessionId);if(!et)throw new Error("Failed to refresh planning session.");if(_.current=et.id,J(et.id),et.status==="generating")w(et.thinkingOutput??""),h({type:"loading"});else if(et.status==="awaiting_input"){if(!et.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const xt=JSON.parse(et.currentQuestion);Ti(o),h({type:"question",session:{sessionId:et.id,currentQuestion:xt,summary:null}}),I.current?.isConnected()||fe(et.id)}else if(et.status==="complete"){if(!et.result)throw new Error("Planning session is complete but has no result.");const xt=JSON.parse(et.result);Ti(o),h({type:"summary",session:{sessionId:et.id,currentQuestion:null,summary:xt},summary:xt}),A(xt)}else et.status==="error"&&h({type:"error",session:{sessionId:et.id,currentQuestion:null,summary:null},errorMessage:et.error||"Retry failed. Please try again."});C(!1);return}catch(et){We=et}I.current?.close(),I.current=null,h({type:"error",session:oe,errorMessage:ge(We)||"Retry failed. Please try again."}),C(!1)}finally{F(!1)}},[fe,o,K,u]),ht=a.useCallback(async()=>{if(u.type==="summary"){f(null),h({type:"loading"});try{const oe=await Bv(u.session.sessionId,y??void 0,o);s(oe),ke()}catch(oe){f(ge(oe)||"Failed to create task"),h({type:"summary",session:u.session,summary:u.summary})}}},[y,u,o,s,ke]),he=a.useCallback(async()=>{if(u.type==="summary"){f(null),h({type:"loading"});try{const oe=await Uv(u.session.sessionId,y??void 0,o);J(oe.sessionId),h({type:"breakdown",sessionId:oe.sessionId,subtasks:oe.subtasks,dirty:!1})}catch(oe){f(ge(oe)||"Failed to start breakdown"),h({type:"summary",session:u.session,summary:u.summary})}}},[y,u,o]),ne=a.useCallback(async()=>{if(u.type==="breakdown"){f(null),h({type:"creating"});try{const oe=await Hv(u.sessionId,u.subtasks,o);i(oe.tasks),c(""),h({type:"initial"}),f(null),b([]),v([]),A(null),w(""),me(void 0),W(void 0),_.current=null,J(null),n()}catch(oe){f(ge(oe)||"Failed to create tasks"),h({type:"breakdown",sessionId:u.sessionId,subtasks:u.subtasks,dirty:u.dirty})}}},[u,i,n,o]),ye=a.useCallback(()=>{if(u.type==="question"&&p.length>0){const oe=p.slice(0,-1);b(oe),h({type:"question",session:u.session})}},[u,p]),we=()=>u.type==="question"?Math.min(p.length+1,3):3,st=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",be=N?X.get(N):null,it=be&&be.tabId!==K,Me=!!(it&&!be.stale),qe=G&&(!it||be.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:oe=>oe.target===oe.currentTarget&&ke(),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(Ls,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Planning Mode"})]}),e.jsxs("div",{className:"modal-header-actions",children:[st&&e.jsx("button",{className:"modal-send-to-background",onClick:_e,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:ke,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[g&&e.jsx("div",{className:"form-error planning-error",children:g}),T&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Me&&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(On,{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:oe=>c(oe.target.value),onKeyDown:oe=>{oe.key==="Enter"&&!oe.shiftKey&&m.trim()&&(oe.preventDefault(),ae())}})]}),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:HM.map((oe,Ve)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>c(oe),children:oe.length>40?oe.slice(0,40)+"...":oe},Ve))})]}),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(Jt,{id:"planning-modal-model",label:"Planning Model",value:nt,onChange:oe=>{const{provider:Ve,modelId:We}=VM(oe);me(Ve),W(We)},models:ce,disabled:ve,favoriteProviders:Fe,onToggleFavorite:ie,favoriteModels:Pe,onToggleModelFavorite:te}),Ae&&e.jsxs("div",{className:"form-hint form-hint-error",children:[Ae," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{Qe()},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:De(D,q)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ae(),disabled:!m.trim(),children:[e.jsx(Ls,{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:P?"AI is thinking...":"Generating next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>k(!E),type:"button",children:E?"Hide thinking":"Show thinking"}),E&&P&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:P})})]})]}),u.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[x.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ss,{entries:x}),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:$,children:[$?e.jsx(ct,{size:14,className:"spin"}):e.jsx(An,{size:14}),e.jsx("span",{className:"icon-ml-6",children:$?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:ke,disabled:$,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(KM,{question:u.session.currentQuestion,progress:we(),historyEntries:x,onSubmit:He,onBack:p.length>0?ye:void 0})}),u.type==="summary"&&y&&e.jsx(GM,{summary:y,historyEntries:x,onSummaryChange:A,tasks:r,onCreateTask:ht,onBreakIntoTasks:he,onRefine:()=>{h({type:"question",session:u.session})},isLoading:!1}),u.type==="breakdown"&&e.jsx(YM,{subtasks:u.subtasks,dirty:u.dirty,isLoading:!1,onUpdateSubtasks:oe=>h({...u,subtasks:oe,dirty:!0}),onCreateTasks:ne,onBack:()=>{const Ve={sessionId:u.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:Ve,summary:y})}}),G&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(Vr,{size:16}),e.jsx("span",{children:qe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),qe&&e.jsx("button",{type:"button",onClick:()=>{M()},disabled:O,className:"btn btn-primary session-lock-take-control",children:O?"Taking control...":"Take Control"})]})})]})]})}):null}function KM({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:f=>{const p=f.target.checked?[...g,h.id]:g.filter(b=>b!==h.id);o({[t.id]:p})}}),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(nn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${l[t.id]===!1?"selected":""}`,onClick:()=>o({[t.id]:!1}),children:[e.jsx(Lt,{size:18}),"No"]})]})]})]})]})]}),e.jsxs("div",{className:"planning-actions",children:[r&&e.jsxs("button",{className:"btn",onClick:r,children:[e.jsx(na,{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(Oa,{size:16,className:"icon-ml-4"})]})]})]})}function GM({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=f=>{const p=u.includes(f)?u.filter(b=>b!==f):[...u,f];h(p),s({...t,suggestedDependencies: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-header",children:[e.jsx(nn,{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:f=>s({...t,description:f.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:f=>s({...t,suggestedSize:f.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(f=>e.jsxs("label",{className:`planning-dep-chip ${u.includes(f.id)?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:u.includes(f.id),onChange:()=>g(f.id)}),e.jsx("span",{className:"planning-dep-id",children:f.id}),e.jsx("span",{className:"planning-dep-title",children:f.title||f.description.slice(0,30)})]},f.id))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Key Deliverables"}),e.jsx("ul",{className:"planning-deliverables",children:t.keyDeliverables.map((f,p)=>e.jsx("li",{children:f},p))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:o,disabled:d,children:[e.jsx(na,{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(qr,{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(nn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function em(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 JM(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function YM({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([]),f=a.useMemo(()=>t.length===0||t.some(E=>!E.title.trim())?!0:em(t),[t]),p=a.useCallback((E,k)=>{i(t.map(T=>T.id===E?{...T,...k}:T))},[t,i]),b=a.useCallback(()=>{i([...t,JM(t.length+1)])},[t,i]),x=a.useCallback(E=>{i(t.filter(k=>k.id!==E).map(k=>({...k,dependsOn:k.dependsOn.filter(T=>T!==E)})))},[t,i]),v=a.useCallback((E,k)=>{if(k<0||k>=t.length)return;const T=[...t],[C]=T.splice(E,1);T.splice(k,0,C),i(T)},[t,i]),y=a.useCallback(E=>k=>{d(E),k.dataTransfer.setData("text/plain",E),k.dataTransfer.effectAllowed="move"},[]),A=a.useCallback(()=>{d(null),c(null),h(null)},[]),j=a.useCallback(E=>k=>{if(k.preventDefault(),E===o)return;const T=k.currentTarget.getBoundingClientRect(),C=T.top+T.height/2,$=k.clientY<C?"before":"after";c(E),h($)},[o]),P=a.useCallback(E=>k=>{k.preventDefault();const T=k.dataTransfer.getData("text/plain");if(!T||T===E){A();return}const C=t.findIndex(_=>_.id===T),$=t.findIndex(_=>_.id===E);if(C===-1||$===-1){A();return}const F=[...t],[ee]=F.splice(C,1);let I=$;u==="after"&&C<$&&I--,u==="after"&&I++,F.splice(I,0,ee),i(F),A()},[t,u,i,A]),w=a.useCallback(E=>{const k=E.currentTarget.getBoundingClientRect(),T=E.clientX,C=E.clientY;(T<k.left||T>k.right||C<k.top||C>k.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(qr,{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((E,k)=>{const T=o===E.id,C=m===E.id,$=["task-detail-section","subtask-item",T?"subtask-item-dragging":"",C?"subtask-item-drop-target":"",C&&u==="before"?"subtask-item-drop-before":"",C&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:$,"data-testid":`subtask-item-${k}`,draggable:!s,onDragStart:y(E.id),onDragEnd:A,onDragOver:j(E.id),onDrop:P(E.id),onDragLeave:w,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(Ho,{size:16}),e.jsx("strong",{children:E.id})]}),e.jsxs("div",{className:"subtask-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(k,k-1),disabled:s||k===0,title:"Move up","aria-label":"Move subtask up",children:e.jsx(gi,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(k,k+1),disabled:s||k===t.length-1,title:"Move down","aria-label":"Move subtask down",children:e.jsx(za,{size:14})}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>x(E.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:F=>{g.current[k]=F},value:E.title,onChange:F=>p(E.id,{title:F.target.value}),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),k<t.length-1&&g.current[k+1]?.focus())},disabled:s})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{rows:3,value:E.description,onChange:F=>p(E.id,{description:F.target.value}),disabled:s})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Size"}),e.jsxs("select",{className:"planning-size-select",value:E.suggestedSize,onChange:F=>p(E.id,{suggestedSize:F.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,k).filter(F=>F.id!==E.id).map(F=>{const ee=E.dependsOn.includes(F.id);return e.jsxs("label",{className:`planning-dep-chip ${ee?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:ee,onChange:()=>{const I=ee?E.dependsOn.filter(_=>_!==F.id):[...E.dependsOn,F.id];p(E.id,{dependsOn:I})},disabled:s}),e.jsx("span",{className:"planning-dep-id",children:F.id}),e.jsx("span",{className:"planning-dep-title",children:F.title||"Untitled"})]},F.id)}),k===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),k>0&&t.slice(0,k).filter(F=>F.id!==E.id).length===0&&e.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},E.id)}),e.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[e.jsx(Ht,{size:16,className:"icon-mr-6"})," Add subtask"]}),em(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(na,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),e.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||f,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 QM(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function tm(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 XM({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([]),[f,p]=a.useState(""),[b,x]=a.useState(!0),[v,y]=a.useState(!1),[A,j]=a.useState(!1),[P,w]=a.useState(s),[E,k]=a.useState(null),[T,C]=a.useState(!1),[$,F]=a.useState(null),[ee,I]=a.useState(null),[_,N]=a.useState(null),J=a.useRef(null),K=a.useRef([]),G=a.useRef(!1),M=a.useRef(null),O=d.type==="generating"||d.type==="editing"||d.type==="creating"||d.type==="error"?d.sessionId:null,X=a.useMemo(()=>Si(),[]),{isLockedByOther:S,takeControl:V,isLoading:de}=Xr(t?O:null),{activeTabMap:L,broadcastUpdate:Z,broadcastCompleted:D,broadcastLock:me,broadcastUnlock:q,broadcastHeartbeat:W}=aa(),ce=a.useMemo(()=>c.length===0||c.some(he=>!he.title.trim())?!0:tm(c),[c]),Se=d.type==="generating"||d.type==="editing"||d.type==="error",ve=O?L.get(O):null,Ee=ve&&ve.tabId!==X,Ae=!!(Ee&&!ve.stale),Oe=S&&(!Ee||ve.stale),Fe=a.useCallback(()=>{P&&Dw(P,l),J.current?.close(),J.current=null,m({type:"initial"}),u([]),g([]),p(""),x(!0),y(!1),j(!1),k(null),C(!1),G.current=!1},[P,l]),rt=a.useCallback(()=>{J.current?.close(),J.current=null,n()},[n]),Pe=a.useCallback(async()=>{if(!((T||d.type==="editing"||d.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(O)try{await ch(O,l,X)}catch{}Fe(),n()}},[T,n,Fe,O,X,d.type,l]),Ie=a.useCallback(he=>{J.current?.close(),J.current=gy(he,l,{onThinking:ne=>{p(ye=>ye+ne),Z({sessionId:he,status:"generating",needsInput:!1,owningTabId:X,type:"subtask",title:P.trim()||"Subtask breakdown",projectId:l??null})},onSubtasks:ne=>{y(!1),j(!1),xl(l),u(ne),m({type:"editing",sessionId:he}),C(!1),Z({sessionId:he,status:"awaiting_input",needsInput:!0,owningTabId:X,type:"subtask",title:P.trim()||"Subtask breakdown",projectId:l??null})},onError:ne=>{const ye=ne||"Session failed while contacting the AI.";y(!1),j(!1),k(null),m({type:"error",sessionId:he,errorMessage:ye}),Z({sessionId:he,status:"error",needsInput:!1,owningTabId:X,type:"subtask",title:P.trim()||"Subtask breakdown",projectId:l??null}),D({sessionId:he,status:"error"})},onComplete:()=>{D({sessionId:he,status:"complete"})},onConnectionStateChange:ne=>{y(ne==="reconnecting")}})},[D,Z,P,l,X]),Be=a.useCallback(async()=>{if(P.trim()){k(null),g([]),p(""),y(!1);try{const{sessionId:he}=await hy(P.trim(),l);m({type:"generating",sessionId:he}),Ie(he)}catch(he){k(ge(he)||"Failed to start subtask breakdown"),m({type:"initial"})}}},[Ie,P,l]);a.useEffect(()=>{if(!t){Fe();return}if(t&&s&&!G.current)w(s),G.current=!0,Be();else if(t&&!s&&!G.current){const he=Fw(l);he&&w(he)}},[t,s,Be,Fe]),a.useEffect(()=>{!t||!o||d.type!=="initial"||(async()=>{try{const he=await ti(o);if(!he)return;const ne=Gi(he.conversationHistory);if(g(ne),he.status==="generating"||he.status==="awaiting_input")p(he.thinkingOutput??""),m({type:"generating",sessionId:o}),Ie(o);else if(he.status==="complete"&&he.result){xl(l);const ye=JSON.parse(he.result);u(ye),m({type:"editing",sessionId:o})}else he.status==="error"&&(k(null),m({type:"error",sessionId:o,errorMessage:he.error??"Session encountered an error"}))}catch(he){k(ge(he)||"Failed to resume session")}})()},[Ie,t,o,d.type,l]),a.useEffect(()=>{if(!t){M.current&&(q(M.current,X),M.current=null);return}if(O&&M.current!==O){M.current&&q(M.current,X),me(O,X),M.current=O;return}!O&&M.current&&(q(M.current,X),M.current=null)},[me,q,t,O,X]),a.useEffect(()=>{if(!t||!O||M.current!==O)return;W(X);const he=setInterval(()=>{W(X)},3e4);return()=>{clearInterval(he)}},[W,t,O,X]),a.useEffect(()=>()=>{J.current?.close(),M.current&&(q(M.current,X),M.current=null)},[q,X]),a.useEffect(()=>{if(!t)return;const he=ne=>{ne.key==="Escape"&&(ne.preventDefault(),Pe())};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[t,Pe]);const nt=a.useCallback((he,ne)=>{u(ye=>ye.map(we=>we.id===he?{...we,...ne}:we)),C(!0)},[]),De=a.useCallback(()=>{u(he=>[...he,QM(he.length+1)]),C(!0)},[]),Qe=a.useCallback(he=>{u(ne=>ne.filter(ye=>ye.id!==he).map(ye=>({...ye,dependsOn:ye.dependsOn.filter(we=>we!==he)}))),C(!0)},[]),ie=a.useCallback(he=>ne=>{F(he),ne.dataTransfer.setData("text/plain",he),ne.dataTransfer.effectAllowed="move"},[]),te=a.useCallback(()=>{F(null),I(null),N(null)},[]),fe=a.useCallback(he=>ne=>{if(ne.preventDefault(),he===$)return;const ye=ne.currentTarget.getBoundingClientRect(),we=ye.top+ye.height/2,st=ne.clientY<we?"before":"after";I(he),N(st)},[$]),ae=a.useCallback(he=>ne=>{ne.preventDefault();const ye=ne.dataTransfer.getData("text/plain");if(!ye||ye===he){F(null),I(null),N(null);return}u(we=>{const st=we.findIndex(oe=>oe.id===ye),be=we.findIndex(oe=>oe.id===he);if(st===-1||be===-1)return we;const it=[...we],[Me]=it.splice(st,1);let qe=be;return _==="after"&&st<be&&qe--,_==="after"&&qe++,it.splice(qe,0,Me),it}),C(!0),F(null),I(null),N(null)},[_]),_e=a.useCallback(he=>{const ne=he.currentTarget.getBoundingClientRect(),ye=he.clientX,we=he.clientY;(ye<ne.left||ye>ne.right||we<ne.top||we>ne.bottom)&&(I(null),N(null))},[]),ke=a.useCallback((he,ne)=>{ne<0||ne>=c.length||(u(ye=>{const we=[...ye],[st]=we.splice(he,1);return we.splice(ne,0,st),we}),C(!0))},[c.length]),He=a.useCallback(he=>{K.current[he+1]?.focus()},[]),dt=a.useCallback(async()=>{if(!(!O||ce)){k(null),m({type:"creating",sessionId:O});try{const he=await by(O,c,r,l);i(he.tasks),Fe(),n()}catch(he){k(ge(he)||"Failed to create tasks"),m({type:"editing",sessionId:O})}}},[ce,n,i,r,l,Fe,O,c]),ht=a.useCallback(async()=>{if(d.type!=="error")return;const he=d.sessionId;k(null),j(!0),p(""),m({type:"generating",sessionId:he}),Ie(he);try{await py(he,l,X)}catch(ne){let ye=ne;if((ge(ne)||"").includes("not in an error state"))try{const st=await ti(he);if(!st)throw new Error("Failed to refresh subtask session.");if(g(Gi(st.conversationHistory)),st.status==="generating"||st.status==="awaiting_input")p(st.thinkingOutput??""),m({type:"generating",sessionId:st.id}),J.current?.isConnected()||Ie(st.id);else if(st.status==="complete"){if(!st.result)throw new Error("Subtask session is complete but has no result.");xl(l);const be=JSON.parse(st.result);u(be),m({type:"editing",sessionId:st.id}),C(!1)}else st.status==="error"&&m({type:"error",sessionId:st.id,errorMessage:st.error??"Retry failed. Please try again."});y(!1);return}catch(st){ye=st}J.current?.close(),J.current=null,m({type:"error",sessionId:he,errorMessage:ge(ye)||"Retry failed. Please try again."}),y(!1)}finally{j(!1)}},[Ie,l,X,d]);return t?e.jsx("div",{className:"modal-overlay open",onClick:he=>he.target===he.currentTarget&&void 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(qr,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Subtask Breakdown"})]}),e.jsxs("div",{className:"modal-header-actions",children:[Se&&e.jsx("button",{className:"modal-send-to-background",onClick:rt,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:()=>void Pe(),"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[E&&e.jsx("div",{className:"form-error planning-error",children:E}),v&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ae&&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:P})]})}),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:()=>x(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&f&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:f})})]})]}),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(An,{size:14}),e.jsx("span",{className:"icon-ml-6",children:A?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:()=>void Pe(),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(nn,{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((he,ne)=>{const ye=$===he.id,we=ee===he.id,st=["task-detail-section","subtask-item",ye?"subtask-item-dragging":"",we?"subtask-item-drop-target":"",we&&_==="before"?"subtask-item-drop-before":"",we&&_==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:st,"data-testid":`subtask-item-${ne}`,draggable:d.type!=="creating",onDragStart:ie(he.id),onDragEnd:te,onDragOver:fe(he.id),onDrop:ae(he.id),onDragLeave:_e,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(Ho,{size:16}),e.jsx("strong",{children:he.id})]}),e.jsxs("div",{className:"subtask-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ke(ne,ne-1),disabled:d.type==="creating"||ne===0,title:"Move up","aria-label":"Move subtask up",children:e.jsx(gi,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ke(ne,ne+1),disabled:d.type==="creating"||ne===c.length-1,title:"Move down","aria-label":"Move subtask down",children:e.jsx(za,{size:14})}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Qe(he.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:be=>{K.current[ne]=be},value:he.title,onChange:be=>nt(he.id,{title:be.target.value}),onKeyDown:be=>{be.key==="Enter"&&(be.preventDefault(),He(ne))},disabled:d.type==="creating"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{rows:8,value:he.description,onChange:be=>nt(he.id,{description:be.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:he.suggestedSize,onChange:be=>nt(he.id,{suggestedSize:be.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,ne).filter(be=>be.id!==he.id).map(be=>{const it=he.dependsOn.includes(be.id);return e.jsxs("label",{className:`planning-dep-chip ${it?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:it,onChange:()=>{const Me=it?he.dependsOn.filter(qe=>qe!==be.id):[...he.dependsOn,be.id];nt(he.id,{dependsOn:Me})},disabled:d.type==="creating"}),e.jsx("span",{className:"planning-dep-id",children:be.id}),e.jsx("span",{className:"planning-dep-title",children:be.title||"Untitled"})]},be.id)}),ne===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),ne>0&&c.slice(0,ne).filter(be=>be.id!==he.id).length===0&&e.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},he.id)}),e.jsxs("button",{type:"button",className:"btn",onClick:De,disabled:d.type==="creating",children:[e.jsx(Ht,{size:16,className:"icon-mr-6"})," Add subtask"]}),tm(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 Pe(),disabled:d.type==="creating",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void dt(),disabled:d.type==="creating"||ce,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"})})]})]}),S&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(Vr,{size:16}),e.jsx("span",{children:Oe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Oe&&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 ZM=5,eA=1e3,tA=45e3;function xr(){return{scrollback:null,connected:null,data:[]}}function nA(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),f=a.useRef(new Set),p=a.useRef(new Set),b=a.useRef(new Set),x=a.useRef(new Set),v=a.useRef(new Set),y=a.useRef(xr()),A=a.useCallback(I=>{f.current.add(I);const _=y.current;return _.data.length>0&&(_.data.forEach(N=>I(N)),_.data=[]),()=>f.current.delete(I)},[]),j=a.useCallback(I=>(p.current.add(I),()=>p.current.delete(I)),[]),P=a.useCallback(I=>{b.current.add(I);const _=y.current;return _.connected&&(I(_.connected),_.connected=null),()=>b.current.delete(I)},[]),w=a.useCallback(I=>{x.current.add(I);const _=y.current;return _.scrollback&&(I(_.scrollback),_.scrollback=null),()=>x.current.delete(I)},[]),E=a.useCallback(I=>(v.current.add(I),()=>v.current.delete(I)),[]),k=a.useCallback(I=>{const _=m.current;_?.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"input",data:I}))},[]),T=a.useCallback((I,_)=>{const N=m.current;N?.readyState===WebSocket.OPEN&&N.send(JSON.stringify({type:"resize",cols:I,rows:_}))},[]),C=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),y.current=xr()},[]),$=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),y.current=xr()},[]),F=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 I=r.current;let N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(t)}`;n&&(N+=`&projectId=${encodeURIComponent(n)}`);const J=new WebSocket(Ps(N));m.current=J,J.onopen=()=>{if(r.current!==I){J.close();return}y.current=xr(),i("connected"),c.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===I&&J.readyState===WebSocket.OPEN&&J.send(JSON.stringify({type:"ping"}))},tA)},J.onmessage=K=>{if(r.current===I)try{const G=JSON.parse(K.data),M=y.current;switch(G.type){case"data":G.data&&(f.current.size===0&&M.data.push(G.data),f.current.forEach(O=>O(G.data)));break;case"scrollback":G.data&&(M.scrollback=G.data,x.current.forEach(O=>O(G.data)));break;case"connected":G.shell&&G.cwd&&(M.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&&p.current.forEach(O=>O(G.exitCode));break;case"ping":J.readyState===WebSocket.OPEN&&J.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},J.onclose=K=>{if(r.current!==I)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&&v.current.forEach(O=>O());return}if(c.current++,c.current>ZM){i("disconnected");return}const G=eA*Math.pow(2,c.current-1);i("reconnecting");const M=r.current;u.current=setTimeout(()=>{r.current===M&&(g.current||F())},Math.min(G,16e3))},J.onerror=()=>{}},[t,n]),ee=a.useCallback(()=>{c.current=0,$(),F()},[$,F]);return a.useEffect(()=>(d&&(C(),c.current=0,i("disconnected")),t?F():i("disconnected"),$),[t,n,d,F,$,C]),{connectionStatus:s,sendInput:k,resize:T,onData:A,onExit:j,onConnect:P,onScrollback:w,reconnect:ee,onSessionInvalid:E}}const Vp="kb-terminal-tabs",sA=15e3,iA=15e3;function nm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function sm(t){if(typeof window>"u")return[];try{const n=In(Vp,t);if(n)return JSON.parse(n)}catch{}return[]}function Yl(t){const n=t instanceof Error?t.message:typeof t=="string"?t:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function im(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 aA(t){const[n,s]=a.useState(()=>sm(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(sm(t)),r(!1),o(!0),m(null)},[t]),a.useEffect(()=>{try{ms(Vp,JSON.stringify(n),t)}catch{}},[t,n]),a.useEffect(()=>{let P=!1;const w=h.current;return(async()=>{if(!P)try{const k=await im(uv(t),sA,"listTerminalSessions");if(P||w!==h.current)return;const T=new Set(k.map(C=>C.id));o(!0),s(C=>{if(P||w!==h.current)return C;const F=C.map(_=>({..._,_verified:T.has(_.sessionId)})).filter(_=>_._verified);if(F.length===0)return[];const ee=F.map(({_verified:_,...N})=>N);return ee.find(_=>_.isActive)?ee:ee.map((_,N)=>({..._,isActive:N===0}))}),r(!0)}catch(k){if(P||w!==h.current)return;const T=Yl(k);T||console.warn("Failed to validate terminal sessions with server:",k),o(!T),r(!0)}})(),()=>{P=!0}},[t]),a.useEffect(()=>{if(n.length===0&&i&&l){const P=h.current,w=setTimeout(()=>{im(tr(void 0,void 0,void 0,t),iA,"createTerminalSession").then(E=>{if(P!==h.current)return;const k={id:nm(),sessionId:E.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(T=>T.length>0?T:[...T.map($=>({...$,isActive:!1})),k]),m(null)}).catch(E=>{if(P!==h.current)return;Yl(E)||console.error(E);const k=E instanceof Error?E.message:typeof E=="string"?E:"Failed to create terminal session";m(k)})},0);return()=>clearTimeout(w)}},[i,l,n.length,c]);const g=a.useCallback(async()=>{const P=await tr(void 0,void 0,void 0,t),w={id:nm(),sessionId:P.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(E=>[...E.map(T=>({...T,isActive:!1})),w]),w},[n.length]),f=a.useCallback(async()=>g(),[g]),p=a.useCallback(P=>{s(w=>{const E=w.find($=>$.id===P);if(!E)return w;Wc(E.sessionId,t).catch($=>{console.warn(`Failed to kill terminal session ${E.sessionId}:`,$)});const k=w.findIndex($=>$.id===P),T=E.isActive,C=w.filter($=>$.id!==P);if(C.length===0)return[];if(T){const $=Math.min(k,C.length-1);return C.map((F,ee)=>({...F,isActive:ee===$}))}return C})},[]),b=a.useCallback(P=>{s(w=>{let E=!1;const k=w.map(T=>T.id===P?(E=!0,{...T,isActive:!0}):{...T,isActive:!1});return E?k:w})},[]),x=a.useCallback((P,w)=>{s(E=>E.map(k=>k.id===P?{...k,title:w}:k))},[]),v=a.useCallback(async()=>{s(E=>{const k=E.find(T=>T.isActive);return k&&Wc(k.sessionId,t).catch(T=>{console.warn(`Failed to kill old session ${k.sessionId}:`,T)}),E});const P=n.find(E=>E.isActive);if(!P)return;const w=await tr(void 0,void 0,void 0,t);s(E=>E.map(k=>k.id===P.id?{...k,sessionId:w.sessionId}:k))},[n]),y=a.useCallback(async()=>{const P=n.find(w=>w.isActive);if(P)try{const w=await tr(void 0,void 0,void 0,t);s(E=>E.map(k=>k.id===P.id?{...k,sessionId:w.sessionId}:k)),m(null)}catch(w){Yl(w)||console.error(w);const E=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";m(E)}},[n]),A=n.find(P=>P.isActive)??null,j=a.useCallback(()=>{m(null),h.current+=1,u(P=>P+1)},[]);return{tabs:n,activeTab:A,isReady:i,bootstrapError:d,createTab:f,closeTab:p,setActiveTab:b,updateTabTitle:x,restartActiveTab:v,retryBootstrap:j,replaceActiveTabSession:y}}const rA=1e4,lA=[500,1500,3e3];function oA(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 cA(t){return new Promise(n=>setTimeout(n,t))}async function dA(t,n=lA){let s;for(let i=0;i<=n.length;i+=1)try{return await t()}catch(r){if(!oA(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 cA(l)}throw s??new Error("Dynamic import failed")}function am(){if(typeof window>"u")return!1;const t="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return t&&n}function uA(){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=mA()-t.offsetTop-t.height;return i>=30&&i>80?i:0}let Ql=null;function mA(){return Ql===null&&(Ql=window.innerHeight),Ql}function hA({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,f]=a.useState(0),[p,b]=a.useState(0),[x,v]=a.useState(null),y=a.useRef(null),A=a.useRef(null),j=a.useRef(null),P=a.useRef(null),w=a.useRef(!1),E=a.useRef(!1),k=a.useRef(null),T=a.useRef(0),C=a.useRef(null),$=a.useRef(i);T.current=p;const F=a.useCallback(Pe=>{if(Pe&&E.current!==Pe)return;const Ie=P.current,Be=j.current,nt=k.current;if(!(!Ie||!Be)&&!(Pe&&E.current!==Pe))try{Ie.fit(),nt&&nt(Be.cols,Be.rows)}catch{}},[]);a.useEffect(()=>{t&&f(Pe=>Pe+1)},[t]),a.useEffect(()=>{if(!t||!am())return;const Pe=window.visualViewport;if(!Pe)return;const Ie=()=>{const Be=uA();b(Be),v(Pe.height),Be>0&&A.current?.scrollIntoView&&A.current.scrollIntoView({block:"end",behavior:"smooth"}),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const nt=typeof E.current=="string"?E.current:void 0;C.current=requestAnimationFrame(()=>{C.current=null,F(nt)})};return Ie(),Pe.addEventListener("resize",Ie),Pe.addEventListener("scroll",Ie),()=>{Pe.removeEventListener("resize",Ie),Pe.removeEventListener("scroll",Ie),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),b(0),v(null)}},[F,t]);const{tabs:ee,activeTab:I,isReady:_,bootstrapError:N,createTab:J,closeTab:K,setActiveTab:G,updateTabTitle:M,restartActiveTab:O,retryBootstrap:X,replaceActiveTabSession:S}=aA(i),{connectionStatus:V,sendInput:de,resize:L,onData:Z,onConnect:D,onExit:me,onScrollback:q,reconnect:W,onSessionInvalid:ce}=nA(I?.sessionId??null,i);k.current=L,a.useEffect(()=>{if(!t||!_||!I)return;const Pe=I.sessionId,Ie=$.current!==i;if(Ie&&($.current=i),E.current===Pe&&j.current&&!Ie)return;j.current&&(E.current!==Pe||Ie)&&(j.current.dispose(),j.current=null,P.current=null,E.current=!1,c(!1),h(null));let Be=!0,nt;const Qe=(async()=>{const ie=dA(()=>Promise.all([tn(()=>import("./vendor-xterm-DzcZoU0P.js").then(_e=>_e.x),__vite__mapDeps([4,1,5])),tn(()=>import("./addon-fit-C7jRorKK.js").then(_e=>_e.a),__vite__mapDeps([9,1])),tn(()=>import("./addon-web-links-CkJwd4cQ.js").then(_e=>_e.a),__vite__mapDeps([10,1]))])),te=new Promise((_e,ke)=>{nt=setTimeout(()=>{ke(new Error("xterm initialization timed out"))},rA)});let fe,ae;try{const[{Terminal:_e},{FitAddon:ke},{WebLinksAddon:He}]=await Promise.race([ie,te]);if(!Be||!y.current||j.current)return;fe=new _e({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}),ae=new ke,fe.loadAddon(ae);const dt=new He;if(fe.loadAddon(dt),!am())try{const{WebglAddon:ye}=await tn(async()=>{const{WebglAddon:st}=await import("./addon-webgl-BjvOw43o.js").then(be=>be.a);return{WebglAddon:st}},__vite__mapDeps([11,1])),we=new ye;we.onContextLoss(()=>{we.dispose()}),fe.loadAddon(we)}catch{}fe.open(y.current),clearTimeout(nt);const ht=y.current?.querySelector(".xterm-helper-textarea");if(ht&&ht.focus(),y.current)try{y.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ae.fit();const ye=y.current?.querySelector(".xterm-helper-textarea");ye&&ye.focus()},50),j.current=fe,P.current=ae,E.current=Pe,T.current>0&&(C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),C.current=requestAnimationFrame(()=>{C.current=null,F(Pe)})),c(!0),h(null);const he=fe.onData(ye=>{de(ye)}),ne=()=>{if(P.current&&j.current)try{P.current.fit();const{cols:ye,rows:we}=j.current;L(ye,we)}catch{}};return window.addEventListener("resize",ne),()=>{he.dispose(),window.removeEventListener("resize",ne)}}catch(_e){if(clearTimeout(nt),!Be)return;const ke=_e instanceof Error?_e.message:"xterm initialization failed";h(ke)}})();return()=>{Be=!1,clearTimeout(nt),Qe.then(ie=>ie?.())}},[F,t,_,I,I?.sessionId,de,L]),a.useEffect(()=>{t||(j.current&&(j.current.dispose(),j.current=null),P.current=null,E.current=!1,c(!1),h(null),w.current=!1,l(null),d(null))},[t]),a.useEffect(()=>{if(!m||!j.current||!I)return;const Pe=I.sessionId,Ie=ie=>{E.current===Pe&&j.current?.write(ie)},Be=Z(ie=>{Ie(ie)}),nt=q(ie=>{Ie(ie)}),De=D(ie=>{M(I.id,ie.shell.split("/").pop()||ie.shell)}),Qe=me(ie=>{E.current===Pe&&(d(ie),j.current?.write(`\r
|
|
641
|
-
\x1B[33m[Process exited with code ${ie}]\x1B[0m\r
|
|
642
|
-
`))});return()=>{Be(),nt(),De(),Qe()}},[m,I?.sessionId,I?.id,I,V,Z,q,D,me,M]),a.useEffect(()=>{V==="connected"&&s&&w.current!==s&&I&&(w.current=s,setTimeout(()=>{de(s+`
|
|
643
|
-
`)},500))},[V,s,de,I,g]),a.useEffect(()=>{if(!t)return;const Pe=Ie=>{if(!(!Ie.ctrlKey&&!Ie.metaKey)){if(Ie.code==="Equal"||Ie.code==="NumpadAdd"){if(Ie.preventDefault(),j.current){const Be=j.current.options.fontSize||14;j.current.options.fontSize=Math.min(Be+1,32),P.current?.fit()}return}if(Ie.code==="Minus"||Ie.code==="NumpadSubtract"){if(Ie.preventDefault(),j.current){const Be=j.current.options.fontSize||14;j.current.options.fontSize=Math.max(Be-1,8),P.current?.fit()}return}if(Ie.code==="Digit0"||Ie.code==="Numpad0"){Ie.preventDefault(),j.current&&(j.current.options.fontSize=14,P.current?.fit());return}}};return window.addEventListener("keydown",Pe),()=>window.removeEventListener("keydown",Pe)},[t]),a.useEffect(()=>{if(!t)return;const Pe=Ie=>{Ie.key==="Escape"&&n()};return document.addEventListener("keydown",Pe),()=>document.removeEventListener("keydown",Pe)},[t,n]),a.useEffect(()=>{V==="connected"&&j.current&&setTimeout(()=>{if(!j.current||!y.current)return;const Pe=y.current.querySelector(".xterm-helper-textarea");Pe&&Pe.focus();try{y.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[V]);const Se=a.useCallback(()=>{if(!y.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;j.current?.focus();const Ie=y.current.querySelector(".xterm-helper-textarea");if(!Ie)return;Ie.autocapitalize="off",Ie.autocomplete="off",Ie.autocorrect="off",Ie.spellcheck=!1,Ie.setAttribute("inputmode","text");try{Ie.focus({preventScroll:!0})}catch{Ie.focus()}const Be=Ie.value.length;Ie.setSelectionRange(Be,Be)},[]);a.useEffect(()=>ce(()=>{j.current?.clear(),d(null),w.current=!1,j.current&&(j.current.dispose(),j.current=null),P.current=null,E.current=!1,c(!1),h(null),S().catch(Ie=>{console.error("Failed to replace invalid terminal session:",Ie)})}),[ce,S]);const ve=a.useCallback(Pe=>{Pe.target===Pe.currentTarget&&n()},[n]),Ee=a.useCallback(()=>{j.current?.clear()},[]),Ae=a.useCallback(async()=>{j.current?.clear(),d(null),w.current=!1;try{await O()}catch(Pe){l(ge(Pe)||"Failed to restart terminal session")}},[O]),Oe=a.useCallback(()=>{j.current&&(j.current.dispose(),j.current=null),P.current=null,E.current=!1,h(null),c(!1)},[]);if(!t)return null;const Fe=()=>{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}},rt=!_||!I&&!N||!m&&!u;return e.jsx("div",{className:"modal-overlay open",onClick:ve,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:p>0?{"--overlay-padding-top":"0px"}:void 0,children:e.jsxs("div",{ref:A,className:"modal terminal-modal","data-testid":"terminal-modal",style:p>0?{"--keyboard-overlap":`${p}px`,"--vv-height":x?`${x}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(Pe=>e.jsxs("div",{className:`terminal-tab ${Pe.isActive?"terminal-tab--active":""}`,onClick:()=>G(Pe.id),title:Pe.title,role:"tab","aria-selected":Pe.isActive,children:[e.jsx("span",{className:"terminal-tab-label",children:Pe.title}),ee.length>1&&e.jsx("button",{className:"terminal-tab-close",onClick:Ie=>{Ie.stopPropagation(),K(Pe.id)},title:"Close tab",children:"×"})]},Pe.id)),e.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:J,title:"New terminal",children:"+"})]}),e.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[e.jsx(zs,{size:16}),Fe()]}),e.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[V==="disconnected"&&I&&e.jsxs("button",{className:"terminal-reconnect-btn",onClick:W,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[e.jsx(An,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),o!==null&&e.jsxs("button",{className:"terminal-restart-btn",onClick:Ae,title:"New Session","data-testid":"terminal-restart-btn",children:[e.jsx(An,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),e.jsxs("button",{className:"terminal-clear-btn",onClick:Ee,"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(Lt,{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:[rt&&!N&&e.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[e.jsx("div",{className:"terminal-spinner"}),e.jsx("span",{children:"Starting terminal..."})]}),N&&!I&&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: ",N]}),e.jsxs("button",{className:"terminal-retry-btn",onClick:X,"data-testid":"terminal-retry-btn",children:[e.jsx(An,{size:14}),"Retry"]})]})}),u&&I&&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("button",{className:"terminal-retry-btn",onClick:Oe,"data-testid":"terminal-reinit-btn",children:[e.jsx(An,{size:14}),"Reinitialize"]})]})}),e.jsx("div",{ref:y,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Se,onTouchStart:Se},I?.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 xa={name:"",command:""};function rm(t){return/^[a-zA-Z0-9_-]+$/.test(t)}function pA(t,n=60){return t.length<=n?t:t.slice(0,n-3)+"..."}function fA({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),[f,p]=a.useState(xa),[b,x]=a.useState(!1),[v,y]=a.useState(null),[A,j]=a.useState(null),P=a.useCallback(async()=>{try{m(!0);const _=await Va(i);o(_)}catch(_){s(ge(_)||"Failed to load scripts","error")}finally{m(!1)}},[s,i]);a.useEffect(()=>{t&&P()},[t,P]);const w=a.useCallback(()=>{u(!0),g(null),p(xa),j(null)},[]),E=a.useCallback((_,N)=>{g(_),u(!1),p({name:_,command:N}),j(null)},[]),k=a.useCallback(()=>{g(null),u(!1),p(xa),j(null)},[]),T=a.useCallback(_=>{p(N=>({...N,name:_})),_&&!rm(_)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),C=a.useCallback(async()=>{const _=f.name.trim(),N=f.command.trim();if(!_){s("Script name is required","error");return}if(!rm(_)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!N){s("Script command is required","error");return}x(!0);try{await uy(_,N,i),s(h?"Script updated":"Script created","success"),g(null),u(!1),p(xa),j(null),await P()}catch(J){const K=ge(J);K?.includes("already exists")?s("A script with this name already exists","error"):s(K||"Failed to save script","error")}finally{x(!1)}},[f,h,s,P,i]),$=a.useCallback(async _=>{try{await my(_,i),s("Script deleted","success"),y(null),h===_&&(g(null),p(xa)),await P()}catch(N){s(ge(N)||"Failed to delete script","error")}},[h,s,P,i]),F=a.useCallback((_,N)=>{r&&r(_,N)},[r]);if(!t)return null;const ee=c||h!==null,I=Object.entries(l).map(([_,N])=>({name:_,command:N}));return e.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:e.jsxs("div",{className:"modal scripts-modal",onClick:_=>_.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx(zs,{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:f.name,onChange:_=>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:f.command,onChange:_=>p(N=>({...N,command:_.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:k,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:C,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:I.length===0?"No scripts defined":`${I.length} script${I.length===1?"":"s"}`}),e.jsxs("button",{className:"btn btn-primary",onClick:w,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(Ht,{size:14}),"Add Script"]})]}),I.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(zs,{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:I.map(_=>e.jsx("div",{className:"script-card","data-testid":`script-${_.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:_.name})}),e.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:_.command,children:pA(_.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:()=>F(_.name,_.command),title:"Run script","aria-label":`Run ${_.name}`,"data-testid":`run-script-${_.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[e.jsx(rn,{size:12}),"Run"]}),e.jsx("button",{className:"btn-icon",onClick:()=>E(_.name,_.command),title:"Edit","aria-label":`Edit ${_.name}`,"data-testid":`edit-script-${_.name}`,children:e.jsx(Ht,{size:14,style:{transform:"rotate(45deg)"}})}),v===_.name?e.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[e.jsx("button",{className:"btn-icon",onClick:()=>$(_.name),title:"Confirm delete","aria-label":`Confirm delete ${_.name}`,"data-testid":`confirm-delete-script-${_.name}`,style:{color:"var(--color-error)"},children:e.jsx(Ut,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${_.name}`,children:e.jsx(Lt,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>y(_.name),title:"Delete","aria-label":`Delete ${_.name}`,"data-testid":`delete-script-${_.name}`,children:e.jsx(Ut,{size:14})})]})]})},_.name))})]})})]})})}function gA(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),f=a.useCallback(()=>{g(b=>b+1)},[]),p=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 x(){m(!0),u(null);try{const v=await Av(t,l==="."?void 0:l,s);b||r(v.entries)}catch(v){b||(u(ge(v)||"Failed to load files"),r([]))}finally{b||m(!1)}}return x(),()=>{b=!0}},[t,l,n,h,s]),{entries:i,currentPath:l,setPath:p,loading:d,error:c,refresh:f}}function bA(t,n,s,i){const[r,l]=a.useState(""),[o,d]=a.useState(""),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,f]=a.useState(!1),[p,b]=a.useState(null),x=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 P=await Pv(t,n,i);A||(l(P.content),d(P.content),c(P.mtime))}catch(P){A||(b(ge(P)||"Failed to load file"),l(""),d(""),c(null))}finally{A||h(!1)}}return j(),()=>{A=!0}},[t,n,s,i]);const v=r!==o,y=a.useCallback(async()=>{if(!(!t||!n||!v)){f(!0),b(null);try{const A=await Rv(t,n,r,i);d(r),c(A.mtime)}catch(A){throw b(ge(A)||"Failed to save file"),A}finally{f(!1)}}},[t,n,r,v,i]);return{content:r,setContent:x,originalContent:o,loading:u,saving:g,error:p,save:y,hasChanges:v,mtime:m}}const xA=1e4;function vA(t){const s=t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||t||"Project Root"}function yA(t){return{id:t.id,label:t.id,title:t.title,worktree:t.worktree,kind:"task"}}function kA(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 Mv(t);if(c)return;s(vA(g.project)),r(g.tasks.map(yA)),m(null)}catch(g){c||m(ge(g)||"Failed to load workspaces")}finally{c||o(!1)}}u();const h=window.setInterval(()=>{u()},xA);return()=>{c=!0,window.clearInterval(h)}},[t]),{projectName:n,workspaces:i,loading:l,error:d}}function jA(t){return t===void 0?"":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function wA(t){return t?new Date(t).toLocaleDateString():""}function lm(t,n){return t==="."?n:`${t}/${n}`}const va={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Xl={type:null,entry:null,entryFullPath:""},NA=200,SA=500,om=10;function CA({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,f=g?.width&&g.width>0?g.width:window.innerWidth,p=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,x=g?.offsetTop??0,v=8;let y=t-b,A=n-x;y+h.width>f-v&&(y=f-v-h.width),A+h.height>p-v&&(A=p-v-h.height),y<v&&(y=v),A<v&&(A=v),d({x:y+b,y:A+x})},[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:Hi,disabled:!1},{id:"move",label:"Move",icon:ub,disabled:!1},{id:"rename",label:"Rename",icon:Ln,disabled:!1},...m?[{id:"download-zip",label:"Download as ZIP",icon:Ur,disabled:!1}]:[{id:"download",label:"Download",icon:cg,disabled:!1}],{id:"divider",label:"",icon:Hi,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 EA({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 p=n.name.lastIndexOf(".");p>0?d.current.setSelectionRange(0,p):d.current.select()}},[t,n.name]);const h=p=>{p.key==="Enter"&&c.trim()&&i(c.trim()),p.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:p=>p.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 f={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:p=>p.stopPropagation(),children:[e.jsx("div",{className:"file-browser-dialog-title",children:f.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:p=>u(p.target.value),placeholder:f.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?`${f.confirm}ing...`:f.confirm})]})]})})}function MA({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(va),[g,f]=a.useState(Xl),[p,b]=a.useState(!1),[x,v]=a.useState(null),[y,A]=a.useState(!1),[j,P]=a.useState(null),w=a.useRef(null),E=a.useRef(null),k=a.useRef(null),T=a.useRef(!1),C=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),$=a.useCallback(()=>{C(),k.current=null,A(!1),P(null)},[C]);a.useEffect(()=>()=>{C()},[C]);const F=a.useCallback((O,X,S,V)=>{h({visible:!0,x:O,y:X,entry:S,entryFullPath:V})},[]),ee=a.useCallback((O,X,S)=>{if(O.touches.length!==1)return;const V=O.touches[0];V&&($(),k.current={x:V.clientX,y:V.clientY},E.current=window.setTimeout(()=>{A(!0),P(S)},NA),w.current=window.setTimeout(()=>{const de=k.current;de&&(T.current=!0,A(!1),P(null),C(),F(de.x,de.y,X,S))},SA))},[$,C,F]),I=a.useCallback(O=>{const X=k.current,S=O.touches[0];!X||!S||(Math.abs(S.clientX-X.x)>om||Math.abs(S.clientY-X.y)>om)&&$()},[$]),_=a.useCallback(()=>{$()},[$]);a.useEffect(()=>{if(!u.visible)return;const O=document.querySelector(".file-browser-list"),X=()=>{T.current=!1,$(),h(va)};return O?.addEventListener("scroll",X),()=>O?.removeEventListener("scroll",X)},[$,u.visible]),a.useEffect(()=>{if(!u.visible)return;const O=X=>{X.key==="Escape"&&(T.current=!1,h(va))};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[u.visible]);const N=a.useCallback((O,X)=>{O.preventDefault(),O.stopPropagation(),$(),T.current=!1,F(O.clientX,O.clientY,X,lm(n,X.name))},[$,n,F]),J=a.useCallback(O=>{if(!u.entry)return;T.current=!1;const X=u.entry,S=u.entryFullPath;if(h(va),O==="download"){if(!d)return;const V=ah(d,S,c);window.open(Ps(V),"_blank");return}if(O==="download-zip"){if(!d)return;const V=Fv(d,S,c);window.open(Ps(V),"_blank");return}f({type:O,entry:X,entryFullPath:S}),v(null)},[u,d,c]),K=a.useCallback(async O=>{if(!(!g.type||!g.entry||!d)){b(!0),v(null);try{switch(g.type){case"copy":await _v(d,g.entryFullPath,O,c);break;case"move":await Iv(d,g.entryFullPath,O,c);break;case"rename":await Dv(d,g.entryFullPath,O,c);break;case"delete":await $v(d,g.entryFullPath,c);break}f(Xl),m?.()}catch(X){v(ge(X)||"Operation failed")}finally{b(!1)}}},[g,d,m,c]),G=a.useCallback(()=>{f(Xl),v(null)},[]),M=a.useCallback((O,X)=>{if(T.current){T.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(ln,{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=lm(n,O.name),S=y&&j===X;return e.jsxs("div",{className:`file-node file-node--${O.type} ${S?"file-node--long-pressing":""}`,onClick:()=>M(O,X),onContextMenu:V=>N(V,O),onTouchStart:V=>ee(V,O,X),onTouchMove:I,onTouchEnd:_,onTouchCancel:_,children:[e.jsx("div",{className:"file-node-icon",children:O.type==="directory"?e.jsx(Pn,{size:16}):e.jsx(Hm,{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:jA(O.size)}),O.mtime&&e.jsx("div",{className:"file-node-time",children:wA(O.mtime)})]},O.name)})}),u.visible&&u.entry&&e.jsx(CA,{x:u.x,y:u.y,entry:u.entry,onAction:J,onClose:()=>{T.current=!1,h(va)}}),g.type&&g.entry&&e.jsx(EA,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:K,onCancel:G,loading:p,error:x})]})}function AA(t,n=44){if(t)return t.length<=n?t:`${t.slice(0,n-1)}…`}function PA({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(Fc,{size:14}):e.jsx(uo,{size:14}),e.jsx("span",{className:"workspace-selector-trigger-label",children:o}),e.jsx(zt,{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(Fc,{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(uo,{size:14}),e.jsx("span",{children:d.id})]}),d.title&&e.jsx("span",{className:"workspace-selector-option-meta",title:d.title,children:AA(d.title)})]},d.id))]})]})]})}const RA=768,Wp=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),TA=new Set([...Wp,".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 cm(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return TA.has(n)}function _A(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return Wp.has(n)}function IA({initialWorkspace:t="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:l}=kA(i),[o,d]=a.useState(t),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,f]=a.useState("list"),{entries:p,currentPath:b,setPath:x,loading:v,error:y,refresh:A}=gA(o,!0,i),{content:j,setContent:P,originalContent:w,loading:E,saving:k,error:T,save:C,hasChanges:$,mtime:F}=bA(o,m,!0,i);a.useEffect(()=>{d(t)},[t]),a.useEffect(()=>{const O=()=>{h(window.innerWidth<=RA)};return O(),window.addEventListener("resize",O),()=>window.removeEventListener("resize",O)},[]),a.useEffect(()=>{m||f("list")},[m]),a.useEffect(()=>{const O=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),$&&!k&&C())};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[n,$,k,C]);const ee=a.useCallback(O=>{c(O),u&&f("editor")},[u]),I=a.useCallback(()=>{f("list")},[]),_=a.useCallback(()=>{P(w)},[w,P]),N=a.useCallback(O=>{d(O),c(null),f("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||!_A(m)?null:ah(o,m,i),[m,o,i]),M=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(PA,{currentWorkspace:o,projectName:r,workspaces:l,onSelect:N}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Lt,{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(MA,{entries:p,currentPath:b,onSelectFile:ee,onNavigate:x,loading:v,error:y,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:I,"aria-label":"Back to file list",children:[e.jsx(na,{size:16}),e.jsx("span",{children:"Back"})]}),m,cm(m)&&e.jsxs("span",{className:"file-browser-binary-indicator",children:[e.jsx(Eg,{size:12}),"Binary file — read only"]}),F&&e.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(F).toLocaleString()]}),E&&e.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),e.jsx("div",{className:"file-browser-actions",children:!G&&$&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:_,disabled:k,children:[e.jsx(Nb,{size:14}),"Discard"]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void C(),disabled:k,children:[e.jsx(Jm,{size:14}),k?"Saving...":"Save"]})]})})]}),T&&!G&&e.jsx("div",{className:"file-browser-error-banner",children:T}),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(Hp,{content:j,onChange:P,filePath:m,readOnly:cm(m)})}),!G&&e.jsxs("div",{className:"file-browser-footer",children:[e.jsx("span",{children:M(j)}),$&&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 $A(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 Yx();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:ge(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 DA(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 FA(t){return t>90?"usage-progress-fill--high":t>70?"usage-progress-fill--medium":"usage-progress-fill--low"}function LA({window:t,viewMode:n,providerName:s}){const i=FA(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 x=Math.floor(b/36e5),v=Math.floor(x/24),y=x%24;v>0&&y>0?m=`resets in ${v}d ${y}h`:v>0?m=`resets in ${v}d`:x>0?m=`resets in ${x}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",f=c?.status==="behind",p=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:DA(t.resetAt)})]})]}),u&&e.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(qo,{size:14,className:"pace-icon pace-ahead"}),e.jsx("span",{className:"pace-text pace-ahead",children:c.message})]}),f&&e.jsxs(e.Fragment,{children:[e.jsx(Ub,{size:14,className:"pace-icon pace-behind"}),e.jsx("span",{className:"pace-text pace-behind",children:c.message})]}),p&&e.jsxs(e.Fragment,{children:[e.jsx(nn,{size:14,className:"pace-icon pace-ontrack"}),e.jsx("span",{className:"pace-text pace-ontrack",children:c.message})]})]})]})}function zA(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 OA({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(is,{provider:zA(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(LA,{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 BA(){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 UA({isOpen:t,onClose:n,projectId:s}){const{providers:i,loading:r,error:l,lastUpdated:o,refresh:d}=$A({autoRefresh:t}),[m,c]=a.useState(!1),[u,h]=a.useState("used"),g=a.useRef(null),f=a.useRef(t),p=a.useRef(!1);a.useEffect(()=>{t||(p.current=!1)},[t]),a.useEffect(()=>{i.length>0&&(p.current=!0)},[i.length]),a.useEffect(()=>{!f.current&&t&&(!o||Date.now()-o.getTime()>5e3)&&d(),f.current=t},[t,o,d]),a.useEffect(()=>{const y=In("kb-usage-view-mode",s);if(y==="used"||y==="remaining"){h(y);return}h("used")},[s]);const b=a.useCallback(y=>{h(y),ms("kb-usage-view-mode",y,s)},[s]),x=a.useCallback(async()=>{c(!0),await d(),c(!1)},[d]);a.useEffect(()=>{if(!t)return;const y=A=>{A.key==="Escape"&&n()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,n]);const v=a.useCallback(y=>{y.target===y.currentTarget&&n()},[n]);return t?e.jsx("div",{className:"modal-overlay open",onClick:v,"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(Lt,{size:20})})]})]}),e.jsx("div",{className:"usage-content",ref:g,children:(r||!p.current&&!l)&&i.length===0?e.jsx(BA,{}):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:x,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(y=>e.jsx(OA,{provider:y,viewMode:u},y.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:x,disabled:r||m,"data-testid":"usage-refresh-btn",children:[e.jsx(An,{size:14,className:m?"spin":"",style:{marginRight:6}}),"Refresh"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function Kp(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 zr(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 HA={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Gp={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},qA={cron:zm,webhook:Qm,api:Om,manual:jn},VA={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},WA={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function KA({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(nn,{size:12}):e.jsx(Ba,{size:12}),e.jsx("span",{children:t.success?"Success":"Failed"}),n>0&&e.jsx("span",{className:"schedule-run-duration",children:Kp(n)})]})}function GA({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"} ${zr(t.startedAt)}`,children:[e.jsx("span",{className:`schedule-history-status ${t.success?"success":"failure"}`,children:t.success?e.jsx(nn,{size:12}):e.jsx(Ba,{size:12})}),e.jsx("span",{className:"schedule-history-time",children:zr(t.startedAt)}),t.triggerType&&e.jsx("span",{className:"routine-history-trigger-type",children:Gp[t.triggerType]}),e.jsx("span",{className:"schedule-history-duration",children:Kp(r)}),s?e.jsx(Ds,{size:12}):e.jsx(zt,{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 JA({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=HA[t.trigger.type],u=qA[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}),Gp[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(vi,{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(rn,{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($s,{size:14}):e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>n(t),title:"Edit","aria-label":`Edit ${t.name}`,children:e.jsx(Ln,{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(yi,{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(Ui,{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:VA[t.executionPolicy]})}),e.jsx("div",{className:"routine-meta-item",children:e.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${t.catchUpPolicy}`,children:WA[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:zr(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:zr(t.lastRunAt)})]}),t.lastRunResult&&e.jsx(KA,{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(Ds,{size:12}):e.jsx(zt,{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,f)=>e.jsx(GA,{result:g,index:f},`${g.startedAt}-${f}`)),t.runHistory.length>10&&e.jsxs("div",{className:"schedule-history-more",children:["…and ",t.runHistory.length-10," more"]})]})]})]})}function YA({type:t,size:n=12}){return t==="command"?e.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[e.jsx(zs,{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(Xg,{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(On,{size:n}),e.jsx("span",{children:"AI Prompt"})]})}function Zl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function QA(t){return t==="command"?{id:Zl(),type:t,name:"New Command Step",command:"",continueOnFailure:!1}:t==="ai-prompt"?{id:Zl(),type:t,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Zl(),type:t,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function XA({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??""),[f,p]=a.useState(t.modelId??""),[b,x]=a.useState(t.taskTitle??""),[v,y]=a.useState(t.taskDescription??""),[A,j]=a.useState(t.taskColumn??"triage"),[P,w]=a.useState(t.timeoutMs),[E,k]=a.useState(t.continueOnFailure??!1),[T,C]=a.useState({}),[$,F]=a.useState([]),[ee,I]=a.useState(!1),[_,N]=a.useState(null);a.useEffect(()=>{let O=!1;return I(!0),N(null),Jn().then(X=>{O||F(X.models)}).catch(X=>{O||N(X instanceof Error?X.message:"Failed to load models")}).finally(()=>{O||I(!1)}),()=>{O=!0}},[]);const J=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"&&!v.trim()&&(O.taskDescription="Task description is required"),(l==="ai-prompt"||l==="create-task")&&(h||f)&&(!h||!f)&&(O.modelProvider="Both model provider and model ID must be set together"),P!==void 0&&P<1e3&&(O.timeoutMs="Timeout must be at least 1 second (1000ms)"),C(O),Object.keys(O).length===0},[i,l,d,c,v,h,f,P]),K=h&&f?`${h}/${f}`:"",G=a.useCallback(O=>{if(!O)g(""),p("");else{const X=O.indexOf("/");X!==-1&&(g(O.slice(0,X)),p(O.slice(X+1)))}},[]),M=a.useCallback(()=>{if(!J())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"&&v.trim()?v.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")&&f.trim()?f.trim():void 0,timeoutMs:P||void 0,continueOnFailure:E};l!=="ai-prompt"&&delete O.prompt,l!=="create-task"&&(delete O.taskTitle,delete O.taskDescription,delete O.taskColumn),n(O)},[J,n,t,i,l,d,c,b,v,A,h,f,P,E]);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":!!T.name}),T.name&&e.jsx("small",{className:"field-error",children:T.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":!!T.command}),T.command&&e.jsx("small",{className:"field-error",children:T.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":!!T.prompt}),T.prompt&&e.jsx("small",{className:"field-error",children:T.prompt})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-model-${t.id}`,children:"Model (optional)"}),e.jsx(Jt,{id:`step-model-${t.id}`,label:"Model",models:$,value:K,onChange:G,placeholder:"Use default",disabled:ee}),_&&e.jsx("small",{className:"field-error",children:_}),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=>x(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:v,onChange:O=>y(O.target.value),rows:4,"aria-invalid":!!T.taskDescription}),T.taskDescription&&e.jsx("small",{className:"field-error",children:T.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(Jt,{id:`step-task-model-${t.id}`,label:"Model",models:$,value:K,onChange:G,placeholder:"Use default",disabled:ee}),_&&e.jsx("small",{className:"field-error",children:_}),T.modelProvider&&e.jsx("small",{className:"field-error",children:T.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:P??"",onChange:O=>w(O.target.value?Number(O.target.value):void 0),"aria-invalid":!!T.timeoutMs}),T.timeoutMs&&e.jsx("small",{className:"field-error",children:T.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:E,onChange:O=>k(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:M,children:"Save Step"})]})]})}function ZA({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=QA(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(p=>p.id===c);if(h<0)return;const g=u==="up"?h-1:h+1;if(g<0||g>=t.length)return;const f=[...t];[f[h],f[g]]=[f[g],f[h]],n(f)},[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(XA,{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(Ho,{size:14})}),e.jsx("span",{className:"step-card-index",children:u+1}),e.jsx(YA,{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(Ds,{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(zt,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(c.id),title:"Edit","aria-label":`Edit ${c.name}`,children:e.jsx(Ln,{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(Ht,{size:14}),"Add Command Step"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("ai-prompt"),children:[e.jsx(Ht,{size:14}),"Add AI Prompt Step"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("create-task"),children:[e.jsx(Ht,{size:14}),"Add Create Task Step"]})]})]})}const Jp={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},eP={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function tP(t){const n=t.trim();for(const[s,i]of Object.entries(Jp))if(i===n)return s;return"custom"}function nP(t){const n=t.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function sP(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 iP(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 aP=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],rP=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function dm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function um({routine:t,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:l}){const o=!!t,d=t?iP(t):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[m,c]=a.useState(t?.name??""),[u,h]=a.useState(t?.description??""),[g,f]=a.useState(d.triggerType),[p,b]=a.useState(d.cronExpression),[x,v]=a.useState(()=>d.triggerType!=="cron"?"custom":tP(d.cronExpression)),[y,A]=a.useState(d.webhookPath),[j,P]=a.useState(d.webhookSecret),[w,E]=a.useState(d.endpoint),[k,T]=a.useState(t?.executionPolicy??"queue"),[C,$]=a.useState(t?.catchUpPolicy??"run_one"),[F,ee]=a.useState(t?.enabled??!0),I=t?.steps&&t.steps.length===1&&t.steps[0].type==="ai-prompt"&&!t.command,_=t?.steps&&t.steps.length===1&&t.steps[0].type==="create-task"&&!t.command,[N,J]=a.useState(t?.steps&&t.steps.length>0&&!I&&!_?"advanced":"simple"),[K,G]=a.useState(()=>I?"ai-prompt":_?"create-task":"command"),[M,O]=a.useState(t?.command??""),[X,S]=a.useState(t?.steps??[]),[V,de]=a.useState(!1),[L,Z]=a.useState(t?.timeoutMs??3e5),[D,me]=a.useState(I?t.steps?.[0]?.prompt??"":""),[q,W]=a.useState(_?t.steps?.[0]?.taskTitle??"":""),[ce,Se]=a.useState(_?t.steps?.[0]?.taskDescription??"":""),[ve,Ee]=a.useState(_?t.steps?.[0]?.taskColumn??"triage":"triage"),[Ae,Oe]=a.useState(I||_?t.steps?.[0]?.modelProvider??"":""),[Fe,rt]=a.useState(I||_?t.steps?.[0]?.modelId??"":""),[Pe,Ie]=a.useState([]),[Be,nt]=a.useState(!1),[De,Qe]=a.useState(null),[ie,te]=a.useState(i??"global"),[fe,ae]=a.useState({}),[_e,ke]=a.useState(!1),He=a.useRef(!0);a.useEffect(()=>()=>{He.current=!1},[]),a.useEffect(()=>{i&&te(i)},[i]),a.useEffect(()=>{let Re=!1;return nt(!0),Qe(null),Jn().then(et=>{Re||Ie(et.models)}).catch(et=>{Re||Qe(et instanceof Error?et.message:"Failed to load models")}).finally(()=>{Re||nt(!1)}),()=>{Re=!0}},[]);const dt=Ae&&Fe?`${Ae}/${Fe}`:"",ht=a.useCallback(Re=>{if(!Re){Oe(""),rt("");return}const et=Re.indexOf("/");et!==-1&&(Oe(Re.slice(0,et)),rt(Re.slice(et+1)))},[]),he=a.useCallback(()=>{const Re={};if(m.trim()||(Re.name="Name is required"),ie==="project"&&!r&&(Re.scope="Project-specific entries require an active project."),g==="cron"&&x==="custom"&&(p.trim()?nP(p)||(Re.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Re.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(Re.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(Re.endpoint="API endpoint is required"),N==="simple")K==="command"&&!M.trim()&&(Re.command="Command is required"),K==="ai-prompt"&&!D.trim()&&(Re.prompt="Prompt is required"),K==="create-task"&&!ce.trim()&&(Re.taskDescription="Task description is required"),(Ae.trim()&&!Fe.trim()||!Ae.trim()&&Fe.trim())&&(Re.model="Both model provider and model ID must be set, or both must be empty");else{X.length===0&&(Re.steps="At least one step is required"),V&&(Re.stepsEditing="Please save or cancel all step edits before saving the routine");const et=[];X.forEach((xt,wt)=>{xt.name?.trim()||et.push(`Step ${wt+1}: Name is required`),xt.type==="command"&&!xt.command?.trim()&&et.push(`Step ${wt+1}: Command is required`),xt.type==="ai-prompt"&&!xt.prompt?.trim()&&et.push(`Step ${wt+1}: Prompt is required`),xt.type==="create-task"&&!xt.taskDescription?.trim()&&et.push(`Step ${wt+1}: Task description is required`)}),et.length>0&&(Re.steps=et.join("; "))}return L<1e3&&(Re.timeoutMs="Timeout must be at least 1 second (1000ms)"),ae(Re),Object.keys(Re).length===0},[m,g,p,x,y,w,ie,r,N,K,M,D,ce,Ae,Fe,X,V,L]),ne=a.useCallback(async Re=>{if(Re.preventDefault(),!!he()){ke(!0);try{let et=t?.scope??ie??(r?"project":"global");et==="project"&&!r&&(et="global");const xt=sP(g,p,y,j,w);let wt,Et;N==="simple"?K==="command"?wt=M.trim()||void 0:K==="ai-prompt"?Et=[{id:dm(),type:"ai-prompt",name:m.trim(),prompt:D.trim(),modelProvider:Ae.trim()||void 0,modelId:Fe.trim()||void 0}]:Et=[{id:dm(),type:"create-task",name:m.trim(),taskTitle:q.trim()||void 0,taskDescription:ce.trim(),taskColumn:ve,modelProvider:Ae.trim()||void 0,modelId:Fe.trim()||void 0}]:Et=X;const Rt={name:m.trim(),agentId:t?.agentId??"",description:u.trim()||void 0,trigger:xt,command:wt,steps:Et,timeoutMs:L,executionPolicy:k,catchUpPolicy:C,enabled:F,scope:et};await n(Rt)}finally{He.current&&ke(!1)}}},[he,n,m,u,g,p,y,j,w,N,K,M,D,Ae,Fe,q,ce,ve,X,L,k,C,F,ie,r,t?.scope,t?.agentId]),ye="routine-name-error",we="routine-cron-error",st="routine-webhook-error",be="routine-endpoint-error",it="routine-command-error",Me="routine-prompt-error",qe="routine-task-description-error",oe="routine-model-error",Ve="routine-timeout-error",We=a.useCallback(Re=>{v(Re),Re!=="custom"&&b(Jp[Re])},[]);return e.jsxs("form",{className:"routine-form",onSubmit:ne,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:Re=>c(Re.target.value),"aria-invalid":!!fe.name,"aria-describedby":fe.name?ye:void 0}),fe.name&&e.jsx("small",{id:ye,className:"field-error",children:fe.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:Re=>h(Re.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${ie==="global"?" active":""}`,onClick:()=>{te("global"),l?.("global")},role:"radio","aria-checked":ie==="global"?"true":"false",disabled:!!t?.scope,title:t?.scope?`Scope is locked to ${t.scope} for existing routines`:"Global scope",children:[e.jsx(vi,{size:12}),"Global"]}),e.jsxs("button",{type:"button",className:`routine-scope-btn${ie==="project"?" active":""}`,onClick:()=>{te("project"),l?.("project")},role:"radio","aria-checked":ie==="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.":ie==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),fe.scope&&e.jsx("small",{className:"field-error",children:fe.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:()=>f("cron"),role:"radio","aria-checked":g==="cron",children:[e.jsx(zm,{size:14}),"Cron"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>f("webhook"),role:"radio","aria-checked":g==="webhook",children:[e.jsx(Qm,{size:14}),"Webhook"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>f("api"),role:"radio","aria-checked":g==="api",children:[e.jsx(Om,{size:14}),"API"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>f("manual"),role:"radio","aria-checked":g==="manual",children:[e.jsx(jn,{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:x,onChange:Re=>We(Re.target.value),children:Object.entries(eP).map(([Re,et])=>e.jsx("option",{value:Re,children:et},Re))}),e.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),e.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:p,onChange:Re=>b(Re.target.value),disabled:x!=="custom","aria-invalid":!!fe.cronExpression,"aria-describedby":fe.cronExpression?we:void 0}),fe.cronExpression?e.jsx("small",{id:we,className:"field-error",children:fe.cronExpression}):e.jsx("small",{children:x==="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: ${p}`})]}),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:y,onChange:Re=>A(Re.target.value),"aria-invalid":!!fe.webhookPath,"aria-describedby":fe.webhookPath?st:void 0}),fe.webhookPath?e.jsx("small",{id:st,className:"field-error",children:fe.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:Re=>P(Re.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:w,onChange:Re=>E(Re.target.value),"aria-invalid":!!fe.endpoint,"aria-describedby":fe.endpoint?be:void 0}),fe.endpoint?e.jsx("small",{id:be,className:"field-error",children:fe.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${N==="simple"?" active":""}`,onClick:()=>J("simple"),role:"radio","aria-checked":N==="simple",children:"Simple"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${N==="advanced"?" active":""}`,onClick:()=>J("advanced"),role:"radio","aria-checked":N==="advanced",children:"Multi-Step"})]}),e.jsx("small",{children:N==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),N==="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:M,onChange:Re=>O(Re.target.value),"aria-invalid":!!fe.command,"aria-describedby":fe.command?it:void 0}),fe.command?e.jsx("small",{id:it,className:"field-error",children:fe.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:Re=>me(Re.target.value),rows:3,"aria-invalid":!!fe.prompt,"aria-describedby":fe.prompt?Me:void 0}),fe.prompt?e.jsx("small",{id:Me,className:"field-error",children:fe.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(Jt,{id:"routine-model",label:"Model",models:Pe,value:dt,onChange:ht,placeholder:"Use default",disabled:Be}),De&&e.jsx("small",{className:"field-error",children:De}),fe.model&&e.jsx("small",{id:oe,className:"field-error",children:fe.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:Re=>W(Re.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:ce,onChange:Re=>Se(Re.target.value),rows:4,"aria-invalid":!!fe.taskDescription,"aria-describedby":fe.taskDescription?qe:void 0}),fe.taskDescription?e.jsx("small",{id:qe,className:"field-error",children:fe.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:Re=>Ee(Re.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(Jt,{id:"routine-task-model",label:"Executor Model",models:Pe,value:dt,onChange:ht,placeholder:"Use default",disabled:Be}),De&&e.jsx("small",{className:"field-error",children:De}),fe.model&&e.jsx("small",{id:oe,className:"field-error",children:fe.model})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(ZA,{steps:X,onChange:S,onEditingChange:de}),fe.steps&&e.jsx("small",{className:"field-error",children:fe.steps}),fe.stepsEditing&&e.jsx("small",{className:"field-error",children:fe.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:L,onChange:Re=>Z(Number(Re.target.value)),"aria-invalid":!!fe.timeoutMs,"aria-describedby":fe.timeoutMs?Ve:void 0}),fe.timeoutMs?e.jsx("small",{id:Ve,className:"field-error",children:fe.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:k,onChange:Re=>T(Re.target.value),children:aP.map(Re=>e.jsx("option",{value:Re.value,children:Re.label},Re.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:C,onChange:Re=>$(Re.target.value),children:rP.map(Re=>e.jsx("option",{value:Re.value,children:Re.label},Re.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:F,onChange:Re=>ee(Re.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:_e,children:"Cancel"}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:_e,children:_e?"Saving…":o?"Save Changes":"Create Routine"})]})]})}const lP=3e4;function oP({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),f=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),p=a.useCallback(async()=>{try{const $=await ty(f);o($)}catch($){n(ge($)||"Failed to load routines","error")}},[n,f]);a.useEffect(()=>{p()},[p]),a.useEffect(()=>{const $=setInterval(()=>{p()},lP);return()=>clearInterval($)},[p]),a.useEffect(()=>{const $=F=>{F.key==="Escape"&&(d!=="list"?(m("list"),u(void 0)):t())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[t,d]);const b=a.useCallback($=>{$.target===$.currentTarget&&t()},[t]),x=a.useCallback(async $=>{try{await ny($,f),n("Routine created","success"),m("list"),await p()}catch(F){n(ge(F)||"Failed to create routine","error")}},[n,p,f]),v=a.useCallback($=>{u($),m("edit")},[]),y=a.useCallback(async $=>{if(c)try{await Xc(c.id,$,f),n("Routine updated","success"),m("list"),u(void 0),await p()}catch(F){n(ge(F)||"Failed to update routine","error")}},[c,n,p,f]),A=a.useCallback(async $=>{try{await sy($.id,f),n(`Deleted "${$.name}"`,"success"),await p()}catch(F){n(ge(F)||"Failed to delete routine","error")}},[n,p,f]),j=a.useCallback(async $=>{g($.id);try{const{result:F}=await iy($.id,f);F.success?n(`"${$.name}" completed successfully`,"success"):n(`"${$.name}" failed: ${F.error||"Unknown error"}`,"error"),await p()}catch(F){n(ge(F)||"Failed to run routine","error")}finally{g(null)}},[n,p,f]),P=a.useCallback(async $=>{try{await Xc($.id,{enabled:!$.enabled},f),n(`"${$.name}" ${$.enabled?"disabled":"enabled"}`,"success"),await p()}catch(F){n(ge(F)||"Failed to toggle routine","error")}},[n,p,f]),w=a.useCallback(()=>{m("list"),u(void 0)},[]),E=a.useCallback($=>{r($),m("list"),u(void 0)},[]),k=()=>d==="create"?e.jsx(um,{onSubmit:x,onCancel:w,scope:i,projectId:s}):d==="edit"&&c?e.jsx(um,{routine:c,onSubmit:y,onCancel:w,scope:i,projectId:s}):l.length===0?e.jsxs("div",{className:"routine-empty-state",children:[e.jsx(jn,{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(Ht,{size:14}),"Create your first automation"]})]}):e.jsx("div",{className:"routine-list",children:l.map($=>e.jsx(JA,{routine:$,onEdit:v,onDelete:A,onRun:j,onToggle:P,running:h===$.id},$.id))}),T=()=>k(),C=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(jn,{size:20,className:"icon-triage"}),e.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),e.jsxs("div",{className:"modal-header-actions",children:[C&&e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),"aria-label":"Create new automation",children:[e.jsx(Ht,{size:14}),"New Automation"]}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:e.jsx(Lt,{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:()=>E("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[e.jsx(vi,{size:14}),"Global"]}),e.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>E("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(jn,{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(jn,{size:14})," Routines"]})}),e.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:T()})]})})}const cP=3e4,$o=new Map,eo=new Map;function mm(t){return t??"default"}function hm(t){const n=$o.get(t);return n?Date.now()>=n.expiresAt?($o.delete(t),null):n:null}function dP(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 uP(t){const n=eo.get(t);if(n)return n;const s=ji().then(({providers:i,ghCli:r})=>{const o={...dP(i,r),ghCli:r,expiresAt:Date.now()+cP};return $o.set(t,o),o}).finally(()=>{eo.delete(t)});return eo.set(t,s),s}function Yp(t){const n=mm(t),s=hm(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=mm(t),f=hm(g);if(f)return r(f.hasAiProvider),o(f.hasGithub),d(f.ghCli),c(!1),u.current=!0,()=>{h=!0};u.current=!1;async function p(){!u.current&&c(!0);try{const x=await uP(g);if(h)return;r(x.hasAiProvider),o(x.hasGithub),d(x.ghCli)}catch{}finally{h||(u.current=!0,c(!1))}}return p(),()=>{h=!0}},[t]),a.useMemo(()=>({hasAiProvider:i,hasGithub:l,loading:m,hasWarnings:!i||!l}),[i,l,m])}function Qp({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(Lt,{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 mP({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,f]=a.useState([]),[p,b]=a.useState(!1),[x,v]=a.useState(""),[y,A]=a.useState(""),[j,P]=a.useState(""),[w,E]=a.useState(""),[k,T]=a.useState(""),[C,$]=a.useState("default"),[F,ee]=a.useState(!1),[I,_]=a.useState([]),[N,J]=a.useState(!1),[K,G]=a.useState(void 0),[M,O]=a.useState(ds),[X,S]=a.useState(null),[V,de]=a.useState([]),[L,Z]=a.useState(!1),[D,me]=a.useState(!1),q=a.useRef(null),[W,ce]=a.useState(!1),[Se,ve]=a.useState(""),Ee=a.useRef(null),{hasAiProvider:Ae,hasGithub:Oe,loading:Fe}=Yp(s),rt=a.useCallback(ke=>{J(!0),_(ke)},[]),Pe=a.useCallback(()=>{J(!1)},[]),Ie=a.useCallback(async()=>{if(V.length>0){Z(!0);return}me(!0);try{const ke=await ia(void 0,s);de(ke),Z(!0)}catch(ke){const He=ge(ke);l(He?`Failed to load agents: ${He}`:"Failed to load agents","error"),Z(!1)}finally{me(!1)}},[V.length,s,l]);a.useEffect(()=>{if(!L)return;const ke=He=>{q.current&&!q.current.contains(He.target)&&Z(!1)};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[L]),a.useEffect(()=>{if(!W)return;const ke=He=>{Ee.current&&!Ee.current.contains(He.target)&&(ce(!1),ve(""))};return document.addEventListener("mousedown",ke),()=>document.removeEventListener("mousedown",ke)},[W]);const Be=i.filter(ke=>!u.includes(ke.id)).sort((ke,He)=>{const dt=He.createdAt.localeCompare(ke.createdAt);if(dt!==0)return dt;const ht=parseInt(ke.id.slice(ke.id.lastIndexOf("-")+1),10)||0;return(parseInt(He.id.slice(He.id.lastIndexOf("-")+1),10)||0)-ht}),nt=Se?Be.filter(ke=>ke.id.toLowerCase().includes(Se.toLowerCase())||ke.title&&ke.title.toLowerCase().includes(Se.toLowerCase())||ke.description&&ke.description.toLowerCase().includes(Se.toLowerCase())):Be,De=(ke,He)=>ke.length>He?ke.slice(0,He)+"…":ke;a.useEffect(()=>{const ke=m.trim()!==""||u.length>0||g.length>0||x!==""||y!==""||j!==""||w!==""||I.length>0||X!==null||K!==void 0||M!==ds;ee(ke)},[m,u,g,x,y,j,w,I,X,K,M]);const Qe=a.useCallback(()=>{F&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(ke=>URL.revokeObjectURL(ke.previewUrl)),f([]),c(""),h([]),v(""),A(""),P(""),E(""),T(""),$("default"),_([]),J(!1),S(null),Z(!1),G(void 0),O(ds),ee(!1),n())},[F,n,g]),ie=a.useCallback(async()=>{const ke=m.trim();if(!(!ke||p)){b(!0);try{const He=x.indexOf("/"),dt=y.indexOf("/"),ht=j.indexOf("/"),he=await r({title:void 0,description:ke,column:"triage",dependencies:u.length?u:void 0,enabledWorkflowSteps:N?I.length>0?I:[]:void 0,...X?{assignedAgentId:X}:{},modelPresetId:C==="preset"&&k||void 0,modelProvider:x&&He!==-1?x.slice(0,He):void 0,modelId:x&&He!==-1?x.slice(He+1):void 0,validatorModelProvider:y&&dt!==-1?y.slice(0,dt):void 0,validatorModelId:y&&dt!==-1?y.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:w!==""?w:void 0,reviewLevel:K,priority:M});if(g.length>0){const ne=[];for(const ye of g)try{await $a(he.id,ye.file,s)}catch{ne.push(ye.file.name)}ne.length>0&&l(`Failed to upload: ${ne.join(", ")}`,"error")}g.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),f([]),c(""),h([]),v(""),A(""),P(""),E(""),T(""),$("default"),_([]),J(!1),S(null),Z(!1),G(void 0),O(ds),l(`Created ${he.id}`,"success"),n()}catch(He){l(ge(He)||"Failed to create task","error")}finally{b(!1)}}},[m,u,g,x,y,j,w,p,r,l,n,s,C,k,I,N,X,K,M]),te=a.useCallback(ke=>{ke.key==="Escape"&&(ke.preventDefault(),Qe())},[Qe]),ae=(X?V.find(ke=>ke.id===X):void 0)?.name??X,_e=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:Ee,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ce(ke=>!ke),disabled:p,"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:Se,onChange:ke=>ve(ke.target.value),onClick:ke=>ke.stopPropagation()}),nt.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):nt.map(ke=>e.jsxs("div",{className:`dep-dropdown-item${u.includes(ke.id)?" selected":""}`,onClick:()=>{h(u.includes(ke.id)?u.filter(He=>He!==ke.id):[...u,ke.id]),ce(!1),ve("")},onMouseDown:He=>He.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:ke.id}),e.jsx("span",{className:"dep-dropdown-title",children:De(ke.title||ke.description||ke.id,30)})]},ke.id))]})]}),u.length>0&&e.jsx("div",{className:"selected-deps",children:u.map(ke=>e.jsxs("span",{className:"dep-chip",children:[ke,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(u.filter(He=>He!==ke)),disabled:p,children:"×"})]},ke))})]}),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:()=>{L?Z(!1):Ie()},disabled:p,"data-testid":"new-task-agent-button",children:[e.jsx(an,{size:12,style:{verticalAlign:"middle"}}),ae?` ${ae}`:" Assign agent"]}),L&&e.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ke=>ke.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(ke=>ke.state!=="terminated").map(ke=>e.jsxs("div",{className:`dep-dropdown-item${X===ke.id?" selected":""}`,onMouseDown:He=>He.preventDefault(),onClick:()=>{S(ke.id===X?null:ke.id),Z(!1)},"data-testid":`agent-option-${ke.id}`,children:[e.jsx(an,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:ke.role}),e.jsx("span",{className:"dep-dropdown-title",children:ke.name})]},ke.id)),!D&&V.filter(ke=>ke.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),X&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:ke=>ke.preventDefault(),onClick:()=>{S(null),Z(!1)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return t?e.jsx("div",{className:"modal-overlay open",onClick:Qe,onKeyDown:te,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ke=>ke.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"New Task"}),e.jsx("button",{className:"modal-close",onClick:Qe,disabled:p,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[!Fe&&e.jsx(Qp,{hasAiProvider:Ae,hasGithub:Oe}),e.jsx(Up,{mode:"create",description:m,onDescriptionChange:c,dependencies:u,onDependenciesChange:h,executorModel:x,onExecutorModelChange:v,validatorModel:y,onValidatorModelChange:A,presetMode:C,onPresetModeChange:$,selectedPresetId:k,onSelectedPresetIdChange:T,selectedWorkflowSteps:I,onWorkflowStepsChange:rt,onDefaultOnApplied:Pe,pendingImages:g,onImagesChange:f,tasks:i,projectId:s,disabled:p,addToast:l,isActive:t,onPlanningMode:o,onSubtaskBreakdown:d,onClose:Qe,planningModel:j,onPlanningModelChange:P,thinkingLevel:w,onThinkingLevelChange:E,reviewLevel:K,onReviewLevelChange:G,priority:M,onPriorityChange:O,renderBelowPrimary:_e,hideDependencies:!0})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:Qe,disabled:p,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:ie,disabled:!m.trim()||p,children:p?"Creating...":"Create Task"})]})]})}):null}const hP=5e3;function pP(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,f]=a.useState(!1),p=a.useRef(null),b=a.useRef(void 0),x=a.useCallback(async()=>{try{c(!0),h(null);let A;l?A=await ld({limit:i,projectId:n,type:s}):A=(await Zc({limit:i,type:s,projectId:n})).map(P=>({...P,projectId:n??"",projectName:""})),d(A),f(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]),v=a.useCallback(async()=>{if(b.current)try{c(!0);let A;l?A=await ld({limit:i,projectId:n,type:s,since:b.current}):A=(await Zc({limit:i,type:s,since:b.current,projectId:n})).map(P=>({...P,projectId:n??"",projectName:""})),d(j=>[...j,...A]),f(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]),y=a.useCallback(()=>{d([]),f(!1),b.current=void 0},[]);return a.useEffect(()=>{x()},[x]),a.useEffect(()=>{if(r)return p.current=setInterval(()=>{x()},hP),()=>{p.current&&(clearInterval(p.current),p.current=null)}},[r,x]),{entries:o,loading:m,error:u,refresh:x,clear:y,hasMore:g,loadMore:v}}const to={"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"},fP={"task:created":e.jsx(Ht,{size:14,className:"activity-icon created"}),"task:moved":e.jsx(Oa,{size:14,className:"activity-icon moved"}),"task:updated":e.jsx(An,{size:14,className:"activity-icon updated"}),"task:deleted":e.jsx(Lt,{size:14,className:"activity-icon deleted"}),"task:merged":e.jsx(nn,{size:14,className:"activity-icon merged"}),"task:failed":e.jsx(Ba,{size:14,className:"activity-icon failed"}),"settings:updated":e.jsx(Ia,{size:14,className:"activity-icon settings"})};function gP(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 bP({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,f]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const p=m==="all"?void 0:m,b=u==="all"?void 0:u,x=!d&&l.length>0,{entries:v,loading:y,error:A,refresh:j,hasMore:P}=pP({projectId:b,type:p,limit:100,autoRefresh:t,useCentralFeed:x}),w=v.map($=>({id:$.id,timestamp:$.timestamp,type:$.type,taskId:$.taskId,taskTitle:$.taskTitle,details:$.details,metadata:$.metadata,projectId:$.projectId,projectName:$.projectName})),E=async()=>{try{await ay(),j(),f(!1)}catch{f(!1)}},k=$=>{i&&i($)},T=$=>{h($),o?.($==="all"?void 0:$)};a.useEffect(()=>{if(!t)return;const $=F=>{F.key==="Escape"&&(g?f(!1):n())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[t,n,g]);const C=m!=="all"||u!=="all";return t?e.jsx("div",{className:"modal-overlay open",onClick:$=>{$.target===$.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(Ta,{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:$=>T($.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[e.jsx("option",{value:"all",children:"All Projects"}),l.map($=>e.jsx("option",{value:$.id,children:$.name},$.id))]})]}),e.jsxs("div",{className:"activity-log-filter",children:[e.jsx(Sr,{size:14}),e.jsxs("select",{value:m,onChange:$=>c($.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[e.jsx("option",{value:"all",children:"All Events"}),Object.entries(to).map(([$,F])=>e.jsx("option",{value:$,children:F},$))]})]}),e.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?e.jsx(ct,{size:14,className:"spin"}):e.jsx(An,{size:14})}),w.length>0&&e.jsx("button",{className:"activity-log-clear",onClick:()=>f(!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:"×"})]}),C&&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($=>$.id===u)?.name||u]}),m!=="all"&&e.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",to[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(as,{size:16}),e.jsx("span",{children:A})]}),w.length===0&&!y&&!A&&e.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[e.jsx(Ta,{size:48,className:"activity-log-empty-icon"}),e.jsx("p",{children:C?"No activity matches the current filters":"No activity recorded yet"}),C&&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:w.map($=>e.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[e.jsx("div",{className:"activity-log-entry-icon",children:fP[$.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:to[$.type]}),e.jsx("span",{className:"activity-log-entry-time",children:gP($.timestamp)})]}),e.jsxs("div",{className:"activity-log-entry-details",children:[$.taskId&&e.jsx("button",{className:"activity-log-task-link",onClick:()=>k($.taskId),"data-testid":"activity-task-link",children:$.taskId}),$.taskTitle&&e.jsx("span",{className:"activity-log-task-title",children:$.taskTitle}),e.jsx("span",{className:"activity-log-entry-text",children:$.details})]}),$.metadata&&Object.keys($.metadata).length>0&&e.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof $.metadata.from=="string"&&typeof $.metadata.to=="string"&&e.jsxs("span",{className:"activity-log-metadata-item",children:[$.metadata.from," → ",$.metadata.to]}),typeof $.metadata.merged=="boolean"&&e.jsx("span",{className:`activity-log-metadata-item ${$.metadata.merged?"success":"error"}`,children:$.metadata.merged?"Merged":"Not merged"})]})]})]},$.id))}),P&&!y&&e.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&w.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:()=>f(!1),children:"Cancel"}),e.jsx("button",{className:"activity-log-confirm-clear",onClick:E,children:"Clear Log"})]})]})})]})}):null}const ya=[{id:"status",label:"Status",icon:Gm},{id:"changes",label:"Changes",icon:Bm},{id:"commits",label:"Commits",icon:Ra},{id:"branches",label:"Branches",icon:Fs},{id:"worktrees",label:"Worktrees",icon:Bg},{id:"stashes",label:"Stashes",icon:Ur},{id:"remotes",label:"Remotes",icon:qm}];function pm({status:t}){switch(t){case"added":case"untracked":return e.jsx(jg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return e.jsx(Um,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return e.jsx(vg,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return e.jsx(xi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return e.jsx(Ng,{size:14,className:"gm-file-icon"})}}function fm({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 xP(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 Qi(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 vP({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=xP(i),[f,p]=a.useState(null),[b,x]=a.useState([]),[v,y]=a.useState(new Set),[A,j]=a.useState(""),[P,w]=a.useState(!1),[E,k]=a.useState(null),[T,C]=a.useState(!1),[$,F]=a.useState(null),[ee,I]=a.useState(null),_=a.useRef(0),[N,J]=a.useState([]),[K,G]=a.useState(null),[M,O]=a.useState(null),[X,S]=a.useState(!1),[V,de]=a.useState(20),[L,Z]=a.useState(""),[D,me]=a.useState([]),[q,W]=a.useState(""),[ce,Se]=a.useState(""),[ve,Ee]=a.useState(""),[Ae,Oe]=a.useState(null),[Fe,rt]=a.useState([]),[Pe,Ie]=a.useState(!1),[Be,nt]=a.useState(null),[De,Qe]=a.useState(null),[ie,te]=a.useState(!1),[fe,ae]=a.useState([]),[_e,ke]=a.useState([]),[He,dt]=a.useState(""),[ht,he]=a.useState(null),[ne,ye]=a.useState(null),[we,st]=a.useState(null),be=a.useCallback(async()=>{if(t){m(!0),u(null);try{switch(l){case"status":{const je=await Es(r);p(je);break}case"changes":{const[je,Ge]=await Promise.all([Es(r),Pi(r)]);p(je),x(Ge),y(new Set),I(null),k(null),F(null);break}case"commits":{const je=await mv(V,r);J(je);break}case"branches":{const[je,Ge]=await Promise.all([oa(r),Es(r)]);me(je),p(Ge);break}case"worktrees":{const je=await gv(r);ae(je);break}case"stashes":{const je=await nr(r);ke(je);break}case"remotes":{const je=await Es(r);p(je);break}}}catch(je){u(ge(je)||"Failed to fetch git data"),i(ge(je)||"Failed to fetch git data","error")}finally{m(!1)}}},[l,t,V,i,r]);a.useEffect(()=>{t&&be()},[be,t]),a.useEffect(()=>{if(!t)return;const je=Ge=>{if(Ge.key==="Escape"){n();return}if((Ge.key==="ArrowUp"||Ge.key==="ArrowDown")&&Ge.altKey){Ge.preventDefault();const gt=ya.findIndex(qt=>qt.id===l);Ge.key==="ArrowUp"&>>0?o(ya[gt-1].id):Ge.key==="ArrowDown"&><ya.length-1&&o(ya[gt+1].id)}};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[t,n,l]);const it=a.useCallback(async je=>{try{await Gc(je,r),i(`Staged ${je.length} file(s)`,"success");const Ge=await Pi(r);x(Ge),y(new Set),I(null),k(null),F(null)}catch(Ge){i(ge(Ge)||"Failed to stage files","error")}},[i,r]),Me=a.useCallback(async je=>{try{await Cv(je,r),i(`Unstaged ${je.length} file(s)`,"success");const Ge=await Pi(r);x(Ge),y(new Set),I(null),k(null),F(null)}catch(Ge){i(ge(Ge)||"Failed to unstage files","error")}},[i,r]),qe=a.useCallback(async je=>{if(confirm(`Discard changes to ${je.length} file(s)? This cannot be undone.`))try{await Ev(je,r),i(`Discarded changes to ${je.length} file(s)`,"success");const[Ge,gt]=await Promise.all([Pi(r),Es(r)]);x(Ge),p(gt),y(new Set),I(null),k(null),F(null)}catch(Ge){i(ge(Ge)||"Failed to discard changes","error")}},[i,r]),oe=a.useCallback(async je=>{if(je.preventDefault(),!!A.trim()){w(!0);try{const Ge=await Jc(A.trim(),r);i(`Committed: ${Ge.hash}`,"success"),j("");const[gt,qt]=await Promise.all([Pi(r),Es(r)]);x(gt),p(qt),I(null),k(null),F(null)}catch(Ge){i(ge(Ge)||"Failed to commit","error")}finally{w(!1)}}},[A,i,r]),Ve=a.useCallback(async()=>{if(A.trim()){w(!0);try{const je=b.filter(gn=>!gn.staged).map(gn=>gn.file);je.length>0&&await Gc(je,r);const Ge=await Jc(A.trim(),r);i(`Committed: ${Ge.hash}`,"success"),j("");const[gt,qt]=await Promise.all([Pi(r),Es(r)]);x(gt),p(qt),I(null),k(null),F(null)}catch(je){i(ge(je)||"Failed to commit","error")}finally{w(!1)}}},[A,b,i,r]),We=a.useCallback(async(je,Ge)=>{I({file:je,staged:Ge}),C(!0),F(null);const gt=_.current+1;_.current=gt;try{const qt=await Sv(je,Ge,r);if(_.current!==gt)return;k(qt)}catch(qt){if(_.current!==gt)return;const gn=ge(qt)||"Failed to load file diff";k(null),F(gn),i(gn,"error")}finally{_.current===gt&&C(!1)}},[i,r]),Re=a.useCallback(je=>{y(Ge=>{const gt=new Set(Ge);return gt.has(je)?gt.delete(je):gt.add(je),gt})},[]),et=a.useCallback(async je=>{if(K===je){G(null),O(null);return}G(je),S(!0);try{const Ge=await Pr(je,r);O(Ge)}catch(Ge){i(ge(Ge)||"Failed to load diff","error"),O(null)}finally{S(!1)}},[K,i,r]),xt=a.useCallback(()=>{de(je=>Math.min(je+20,100))},[]),wt=a.useMemo(()=>{if(!L.trim())return N;const je=L.toLowerCase();return N.filter(Ge=>Ge.message.toLowerCase().includes(je)||Ge.author.toLowerCase().includes(je)||Ge.shortHash.toLowerCase().includes(je))},[N,L]),Et=a.useCallback(async je=>{if(je.preventDefault(),!!q.trim()){m(!0);try{await bv(q.trim(),ce.trim()||void 0,r),i(`Created branch ${q}`,"success"),W(""),Se("");const Ge=await oa(r);me(Ge)}catch(Ge){i(ge(Ge)||"Failed to create branch","error")}finally{m(!1)}}},[q,ce,i,r]),Rt=a.useCallback(async je=>{m(!0);try{await xv(je,r),i(`Switched to ${je}`,"success");const[Ge,gt]=await Promise.all([Es(r),oa(r)]);p(Ge),me(gt)}catch(Ge){i(ge(Ge)||"Failed to checkout branch","error")}finally{m(!1)}},[i,r]),$t=a.useCallback(async je=>{if(confirm(`Delete branch "${je}"?`)){m(!0);try{await Kc(je,void 0,r),i(`Deleted branch ${je}`,"success");const Ge=await oa(r);me(Ge)}catch(Ge){if(ge(Ge).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await Kc(je,!0,r),i(`Force deleted branch ${je}`,"success");const gt=await oa(r);me(gt)}catch(gt){i(ge(gt)||"Failed to delete branch","error")}}else i(ge(Ge)||"Failed to delete branch","error")}finally{m(!1)}}},[i,r]),_t=a.useMemo(()=>{if(!ve.trim())return D;const je=ve.toLowerCase();return D.filter(Ge=>Ge.name.toLowerCase().includes(je))},[D,ve]),vt=a.useCallback(async je=>{if(Ae===je){Oe(null),rt([]),nt(null),Qe(null);return}Oe(je),rt([]),nt(null),Qe(null),Ie(!0);try{const Ge=await fv(je,10,r);rt(Ge)}catch{rt([])}finally{Ie(!1)}},[Ae,r]),Dt=a.useCallback(async je=>{if(Be===je){nt(null),Qe(null);return}nt(je),Qe(null),te(!0);try{const Ge=await Pr(je,r);Qe(Ge)}catch{Qe(null)}finally{te(!1)}},[Be,r]),Ke=a.useCallback(()=>{Oe(null),rt([]),nt(null),Qe(null)},[]),bt=a.useCallback(async je=>{je.preventDefault(),he("create");try{await jv(He.trim()||void 0,r),i("Changes stashed","success"),dt("");const Ge=await nr(r);ke(Ge)}catch(Ge){i(ge(Ge)||"Failed to stash changes","error")}finally{he(null)}},[He,i,r]),Le=a.useCallback(async(je,Ge=!1)=>{he(`apply-${je}`);try{await wv(je,Ge,r),i(Ge?"Stash popped":"Stash applied","success");const gt=await nr(r);ke(gt)}catch(gt){i(ge(gt)||"Failed to apply stash","error")}finally{he(null)}},[i,r]),lt=a.useCallback(async je=>{if(confirm(`Drop stash@{${je}}? This cannot be undone.`)){he(`drop-${je}`);try{await Nv(je,r),i("Stash dropped","success");const Ge=await nr(r);ke(Ge)}catch(Ge){i(ge(Ge)||"Failed to drop stash","error")}finally{he(null)}}},[i,r]),xe=a.useCallback(async()=>{ye("fetch");try{const je=await vv(void 0,r);st(je),i(je.message||"Fetch completed",je.fetched?"success":"info");const Ge=await Es(r);p(Ge)}catch(je){i(ge(je)||"Fetch failed","error")}finally{ye(null)}},[i,r]),U=a.useCallback(async()=>{ye("pull");try{const je=await yv(r);st(je),je.conflict?i("Merge conflict detected. Resolve manually.","error"):i(je.message||"Pull completed","success");const Ge=await Es(r);p(Ge)}catch(je){i(ge(je)||"Pull failed","error")}finally{ye(null)}},[i,r]),Ne=a.useCallback(async()=>{ye("push");try{const je=await kv(r);st(je),i(je.message||"Push completed","success");const Ge=await Es(r);p(Ge)}catch(je){i(ge(je)||"Push failed","error")}finally{ye(null)}},[i,r]),pt=a.useMemo(()=>b.filter(je=>je.staged),[b]),kt=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(uo,{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:be,disabled:d,title:"Refresh",children:e.jsx(An,{size:14,className:d?"spin":""})}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Lt,{size:18})})]})]}),e.jsxs("div",{className:"gm-layout",children:[e.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ya.map(je=>{const Ge=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(Ge,{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(as,{size:18}),e.jsx("span",{children:c}),e.jsx("button",{className:"btn btn-sm",onClick:be,children:"Retry"})]}),l==="status"&&!d&&f&&e.jsx(yP,{status:f,copyToClipboard:g}),l==="changes"&&!d&&e.jsx(kP,{status:f,stagedFiles:pt,unstagedFiles:kt,selectedFiles:v,toggleFileSelection:Re,onStageFiles:it,onUnstageFiles:Me,onDiscardChanges:qe,onSelectDiffFile:We,selectedDiffTarget:ee,changeDiff:E,loadingChangeDiff:T,changeDiffError:$,commitMessage:A,setCommitMessage:j,onCommit:oe,onStageAllAndCommit:Ve,committing:P}),l==="commits"&&!d&&e.jsx(jP,{commits:wt,commitSearch:L,setCommitSearch:Z,selectedCommit:K,commitDiff:M,loadingDiff:X,onCommitClick:et,onLoadMore:xt,canLoadMore:N.length>=V&&V<100,copyToClipboard:g}),l==="branches"&&!d&&e.jsx(wP,{branches:_t,branchSearch:ve,setBranchSearch:Ee,newBranchName:q,setNewBranchName:W,branchBase:ce,setBranchBase:Se,onCreateBranch:Et,onCheckoutBranch:Rt,onDeleteBranch:$t,loading:d,allBranches:D,selectedBranch:Ae,branchCommits:Fe,loadingBranchCommits:Pe,expandedBranchCommit:Be,branchCommitDiff:De,loadingBranchCommitDiff:ie,onSelectBranch:vt,onBranchCommitClick:Dt,onCloseBranchDetails:Ke}),l==="worktrees"&&!d&&e.jsx(NP,{worktrees:fe}),l==="stashes"&&!d&&e.jsx(SP,{stashes:_e,stashMessage:He,setStashMessage:dt,onCreateStash:bt,onApplyStash:Le,onDropStash:lt,stashLoading:ht}),l==="remotes"&&!d&&e.jsx(CP,{status:f,remoteLoading:ne,lastRemoteResult:we,onFetch:xe,onPull:U,onPush:Ne,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function yP({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(Fs,{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(Hi,{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(as,{size:12}),"Modified"]}):e.jsxs(e.Fragment,{children:[e.jsx(nn,{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(gi,{size:12}),t.ahead]}),t.behind>0&&e.jsxs("span",{className:"gm-behind",title:`${t.behind} commit(s) behind`,children:[e.jsx(za,{size:12}),t.behind]}),t.ahead===0&&t.behind===0&&e.jsxs("span",{className:"gm-in-sync",children:[e.jsx(nn,{size:12}),"Up to date"]})]})]})]})]})}function kP({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:f,setCommitMessage:p,onCommit:b,onStageAllAndCommit:x,committing:v}){const y=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(Fs,{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:[y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>l(y.map(j=>j.file)),title:"Stage selected",children:[e.jsx(Ht,{size:12})," Stage (",y.length,")"]}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>d(y.map(j=>j.file)),title:"Discard selected",children:e.jsx(Ba,{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 P=c?.file===j.file&&c.staged===!1;return e.jsxs("div",{className:`gm-file-item${P?" active":""}`,onClick:()=>m(j.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),m(j.file,!1))},children:[e.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),e.jsx(pm,{status:j.status}),e.jsx("span",{className:"gm-file-name",title:j.file,children:j.file}),e.jsx(fm,{status:j.status}),e.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([j.file])},title:"Stage file",children:e.jsx(Ht,{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 P=c?.file===j.file&&c.staged===!0;return e.jsxs("div",{className:`gm-file-item staged${P?" active":""}`,onClick:()=>m(j.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),m(j.file,!0))},children:[e.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),e.jsx(pm,{status:j.status}),e.jsx("span",{className:"gm-file-name",title:j.file,children:j.file}),e.jsx(fm,{status:j.status}),e.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([j.file])},title:"Unstage file",children:e.jsx(Lt,{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(Bm,{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:f,onChange:j=>p(j.target.value),rows:3,disabled:v}),e.jsxs("div",{className:"gm-commit-actions",children:[e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:v||!f.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[v?e.jsx(ct,{size:14,className:"spin"}):e.jsx(fi,{size:14}),"Commit"]}),s.length>0&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:x,disabled:v||!f.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function jP({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(zi,{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:Qi(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(Hi,{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 wP({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:f,loadingBranchCommits:p,expandedBranchCommit:b,branchCommitDiff:x,loadingBranchCommitDiff:v,onSelectBranch:y,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(zi,{size:14}),e.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:P=>s(P.target.value)})]})]}),e.jsxs("form",{className:"gm-create-form",onSubmit:d,children:[e.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:P=>r(P.target.value),disabled:u}),e.jsxs("select",{value:l,onChange:P=>o(P.target.value),disabled:u,className:"gm-branch-select",children:[e.jsx("option",{value:"",children:"Base: HEAD"}),h.map(P=>e.jsx("option",{value:P.name,children:P.name},P.name))]}),e.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:u||!i.trim(),children:[e.jsx(Ht,{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(P=>e.jsxs("div",{children:[e.jsxs("div",{className:`gm-branch-item${P.isCurrent?" current":""}${g===P.name?" selected":""}`,onClick:()=>y(P.name),children:[e.jsxs("div",{className:"gm-branch-info",children:[e.jsxs("span",{className:"gm-branch-name",children:[P.isCurrent&&e.jsx(Mn,{size:14,className:"gm-current-icon"}),P.name]}),P.remote&&e.jsxs("span",{className:"gm-branch-remote",children:["→ ",P.remote]}),P.lastCommitDate&&e.jsx("span",{className:"gm-branch-date",children:Qi(P.lastCommitDate)})]}),e.jsx("div",{className:"gm-branch-actions",children:!P.isCurrent&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),m(P.name)},disabled:u,title:"Checkout",children:e.jsx(Fs,{size:14})}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),c(P.name)},disabled:u,title:"Delete",children:e.jsx(Ut,{size:14})})]})})]}),g===P.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(Ra,{size:14}),"Commits on ",P.name]}),e.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:e.jsx(Lt,{size:14})})]}),p?e.jsxs("div",{className:"gm-branch-details-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading commits..."]}):f.length===0?e.jsx("div",{className:"gm-empty",children:"No commits found"}):e.jsx("div",{className:"gm-branch-commits-list",children:f.map(w=>e.jsxs("div",{className:"gm-branch-commit",children:[e.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>A(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[e.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),e.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),e.jsxs("div",{className:"gm-commit-meta",children:[e.jsx("span",{children:w.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Qi(w.date)}),w.parents.length>1&&e.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===w.hash&&e.jsx("div",{className:"gm-commit-diff",children:v?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}):x?e.jsxs(e.Fragment,{children:[x.stat&&e.jsx("pre",{className:"gm-diff-stat",children:x.stat}),e.jsx("pre",{className:"gm-diff-patch",children:x.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},P.name))})]})}function NP({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(Fs,{size:12}),n.branch]}),n.taskId&&e.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function SP({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(Ur,{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(Fs,{size:12}),d.branch]}),e.jsx("span",{children:Qi(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 CP({status:t,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:l,addToast:o,projectId:d,copyToClipboard:m}){const c=te=>{try{return new URL(te).hostname}catch{return te.replace(/^git@/,"").split(":")[0]||te}},[u,h]=a.useState([]),[g,f]=a.useState(!1),[p,b]=a.useState(null),[x,v]=a.useState(""),[y,A]=a.useState(""),[j,P]=a.useState(null),[w,E]=a.useState(""),[k,T]=a.useState(""),[C,$]=a.useState(!1),[F,ee]=a.useState([]),[I,_]=a.useState(!1),[N,J]=a.useState(null),[K,G]=a.useState([]),[M,O]=a.useState(!1),[X,S]=a.useState(null),V=u.find(te=>te.name===N),[de,L]=a.useState(null),[Z,D]=a.useState(null),[me,q]=a.useState(!1),[W,ce]=a.useState(null),[Se,ve]=a.useState(null),[Ee,Ae]=a.useState(!1);a.useEffect(()=>{Oe()},[]),a.useEffect(()=>{t&&t.ahead>0?Fe():t&&t.ahead===0&&ee([])},[t?.ahead]),a.useEffect(()=>{u.length>0&&!N&&J(u[0].name)},[u]),a.useEffect(()=>{N?rt(N):(G([]),S(null))},[N]),a.useEffect(()=>{N&&!u.find(te=>te.name===N)&&J(u.length>0?u[0].name:null)},[u,N]);const Oe=async()=>{f(!0);try{const te=await ih(d);h(te)}catch(te){o(ge(te)||"Failed to load remotes","error")}finally{f(!1)}},Fe=async()=>{_(!0);try{const te=await hv(d);ee(te)}catch{ee([])}finally{_(!1)}},rt=async te=>{O(!0),S(null);try{const fe=await pv(te,void 0,10,d);G(fe)}catch(fe){S(ge(fe)||"Failed to load remote commits"),G([])}finally{O(!1)}},Pe=async te=>{if(te.preventDefault(),!(!x.trim()||!y.trim())){b("add");try{await iv(x.trim(),y.trim(),d),o(`Remote '${x}' added successfully`,"success"),v(""),A(""),$(!1),await Oe()}catch(fe){o(ge(fe)||"Failed to add remote","error")}finally{b(null)}}},Ie=async te=>{if(confirm(`Are you sure you want to remove remote '${te}'?`)){b(`remove-${te}`);try{await av(te,d),o(`Remote '${te}' removed`,"success"),await Oe()}catch(fe){o(ge(fe)||"Failed to remove remote","error")}finally{b(null)}}},Be=async te=>{if(k.trim()){b(`rename-${te}`);try{await rv(te,k.trim(),d),o(`Remote renamed to '${k.trim()}'`,"success"),P(null),T(""),await Oe()}catch(fe){o(ge(fe)||"Failed to rename remote","error")}finally{b(null)}}},nt=async te=>{if(w.trim()){b(`url-${te}`);try{await lv(te,w.trim(),d),o("Remote URL updated","success"),P(null),E(""),await Oe()}catch(fe){o(ge(fe)||"Failed to update remote URL","error")}finally{b(null)}}},De=a.useCallback(async(te,fe)=>{if(fe==="ahead"){if(de===te){L(null),D(null);return}L(te),D(null),q(!0);try{const ae=await Pr(te);D(ae)}catch{D(null)}finally{q(!1)}}else{if(W===te){ce(null),ve(null);return}ce(te),ve(null),Ae(!0);try{const ae=await Pr(te);ve(ae)}catch{ve(null)}finally{Ae(!1)}}},[de,W]),Qe=te=>{P(`url-${te.name}`),E(te.pushUrl||te.fetchUrl)},ie=te=>{P(`name-${te.name}`),T(te.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:()=>$(!C),disabled:p!==null,title:C?"Cancel":"Add Remote",children:C?e.jsx(Lt,{size:14}):e.jsx(Ht,{size:14})})]}),C&&e.jsxs("form",{className:"gm-remote-form",onSubmit:Pe,children:[e.jsx("input",{type:"text",placeholder:"Remote name",value:x,onChange:te=>v(te.target.value),disabled:p==="add",className:"gm-input"}),e.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:te=>A(te.target.value),disabled:p==="add",className:"gm-input gm-input-url"}),e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!x.trim()||!y.trim()||p==="add",children:[p==="add"?e.jsx(ct,{size:12,className:"spin"}):e.jsx(Ht,{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(te=>e.jsxs("div",{className:`gm-remote-selector-item${N===te.name?" selected":""}`,onClick:()=>J(te.name),role:"button",tabIndex:0,children:[e.jsxs("div",{className:"gm-remote-selector-info",children:[e.jsxs("span",{className:"gm-remote-selector-name",children:[te.name,te.name==="origin"&&e.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),e.jsx("span",{className:"gm-remote-selector-host",children:c(te.fetchUrl)})]}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:fe=>{fe.stopPropagation(),Ie(te.name)},disabled:p!==null,title:"Remove remote",children:e.jsx(Ut,{size:14})})]},te.name))]}),e.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[N&&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:N}),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(gi,{size:14}),t.ahead," to push"]}),t.behind>0&&e.jsxs("div",{className:"gm-remote-indicator behind",children:[e.jsx(za,{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(An,{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(ns,{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(gi,{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-${N}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:w,onChange:te=>E(te.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>nt(N),disabled:p===`url-${N}`,children:p===`url-${N}`?e.jsx(ct,{size:12,className:"spin"}):e.jsx(Mn,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{P(null),E("")},title:"Cancel",children:e.jsx(Lt,{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(Hi,{size:14})}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Qe(V),disabled:p!==null,title:"Edit remote URL",children:e.jsx(Ln,{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(Hi,{size:14})})]})]}),e.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${N}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:k,onChange:te=>T(te.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Be(N),disabled:p===`rename-${N}`,children:p===`rename-${N}`?e.jsx(ct,{size:12,className:"spin"}):e.jsx(Mn,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{P(null),T("")},title:"Cancel",children:e.jsx(Lt,{size:12})})]}):e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ie(V),disabled:p!==null,title:"Edit remote name",children:e.jsx(Ln,{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(gi,{size:14}),"Commits to Push (",t.ahead,")"]})}),I?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ct,{size:14,className:"spin"}),"Loading..."]}):F.length>0?e.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:F.map(te=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>De(te.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:te.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:te.message,children:te.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:te.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Qi(te.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:de===te.hash?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})})]}),de===te.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..."]}):Z?e.jsxs(e.Fragment,{children:[te.message&&e.jsx("div",{className:"gm-commit-message-full",children:te.message}),Z.stat&&e.jsx("pre",{className:"gm-diff-stat",children:Z.stat}),e.jsx("pre",{className:"gm-diff-patch",children:Z.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},te.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(Gm,{size:14}),"Recent commits on ",N]})}),M?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(as,{size:14}),X]}):K.length===0?e.jsxs("div",{className:"gm-empty",children:["No commits found on ",N,". Try fetching first."]}):e.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:K.map(te=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>De(te.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:te.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:te.message,children:te.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:te.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Qi(te.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:W===te.hash?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})})]}),W===te.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Ee?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ct,{size:16,className:"spin"}),"Loading diff..."]}):Se?e.jsxs(e.Fragment,{children:[te.message&&e.jsx("div",{className:"gm-commit-message-full",children:te.message}),Se.stat&&e.jsx("pre",{className:"gm-diff-stat",children:Se.stat}),e.jsx("pre",{className:"gm-diff-patch",children:Se.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},te.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 ka={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function EP(t,n){return t&&n?`${t}/${n}`:""}function MP(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 AP(t){switch(t){case"file-text":return xi;case"check-circle":return nn;case"shield":return _b;case"zap":return jn;case"eye":return Uo;case"globe":return vi;case"layout-grid":return ki;default:return nn}}function PP(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 RP({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,f]=a.useState("my-steps"),[p,b]=a.useState(null),[x,v]=a.useState(!1),[y,A]=a.useState(ka),[j,P]=a.useState(!1),[w,E]=a.useState(!1),[k,T]=a.useState(null),[C,$]=a.useState(null),[F,ee]=a.useState({}),[I,_]=a.useState([]),N=a.useCallback(async()=>{try{c(!0);const D=await Gr(i);l(D)}catch(D){s(ge(D)||"Failed to load workflow steps","error")}finally{c(!1)}},[s,i]),J=a.useCallback(async()=>{try{const D=await Va(i);ee(D||{})}catch{}},[i]),K=a.useCallback(async()=>{try{const D=await Jn();_(D.models||[])}catch{}},[]),G=a.useCallback(async()=>{try{h(!0);const D=await cy();d(D.templates)}catch(D){s(ge(D)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{t&&(N(),G(),J(),K())},[t,N,G,J,K]);const M=a.useCallback(()=>{v(!0),b(null),A(ka)},[]),O=a.useCallback(D=>{b(D.id),v(!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),v(!1),A(ka)},[]),S=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}P(!0);try{const D=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(x){const me={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...D};await ed(me,i),s("Workflow step created","success")}else p&&(await ry(p,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...D},i),s("Workflow step updated","success"));v(!1),b(null),A(ka),await N()}catch(D){s(ge(D)||"Failed to save workflow step","error")}finally{P(!1)}},[y,x,p,s,N]),V=a.useCallback(async D=>{try{await ly(D,i),s("Workflow step deleted","success"),T(null),p===D&&(b(null),A(ka)),await N()}catch(me){s(ge(me)||"Failed to delete workflow step","error")}},[p,s,N]),de=a.useCallback(async()=>{if(!(!p&&!x)&&y.mode==="prompt"){if(x){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}P(!0);try{const D=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},me={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...D},q=await ed(me,i);v(!1),b(q.id),E(!0);const W=await td(q.id,i);A(ce=>({...ce,prompt:W.prompt})),s("Prompt refined with AI","success"),await N()}catch(D){s(ge(D)||"Failed to refine prompt","error")}finally{P(!1),E(!1)}return}if(p){E(!0);try{const D=await td(p,i);A(me=>({...me,prompt:D.prompt})),s("Prompt refined with AI","success"),await N()}catch(D){s(ge(D)||"Failed to refine prompt","error")}finally{E(!1)}}}},[p,x,y,s,N]),L=a.useCallback(async D=>{$(D.id);try{await dy(D.id,i),s(`Added ${D.name} workflow step`,"success"),await N(),f("my-steps")}catch(me){const q=ge(me);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{$(null)}},[s,N]);if(!t)return null;const Z=x||p!==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:[!Z&&e.jsxs("div",{className:"wfm-tab-row",children:[e.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>f("my-steps"),"data-testid":"tab-my-steps",children:[e.jsx(Lm,{size:14}),"My Workflow Steps (",r.length,")"]}),e.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>f("templates"),"data-testid":"tab-templates",children:[e.jsx(ki,{size:14}),"Templates (",o.length,")"]})]}),g==="my-steps"&&!Z&&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(Ln,{size:14})}),k===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(Mn,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>T(null),title:"Cancel delete","aria-label":"Cancel delete",children:e.jsx(Lt,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>T(D.id),title:"Delete","aria-label":`Delete ${D.name}`,children:e.jsx(Ut,{size:14})})]})]})},D.id))})]}),g==="templates"&&!Z&&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 me=AP(D.icon),q=PP(D.category),W=C===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(me,{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:()=>L(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(Ht,{size:12}),"Add"]})})]})]})},D.id)})})}),Z&&e.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[e.jsx("h3",{className:"wfm-form-title",children:x?"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:y.name,onChange:D=>A(me=>({...me,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:y.description,onChange:D=>A(me=>({...me,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 ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>A(D=>({...D,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[e.jsx(Zs,{size:14}),"AI Prompt"]}),e.jsxs("button",{className:`btn ${y.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(zs,{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 ${y.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 ${y.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:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&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:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?e.jsx(ct,{size:12,className:"spin"}):e.jsx(On,{size:12}),e.jsx("span",{children:"Refine with AI"})]})]}),e.jsx("textarea",{value:y.prompt,onChange:D=>A(me=>({...me,prompt:D.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.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"}),y.modelProvider&&y.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(Lt,{size:12}),e.jsx("span",{children:"Use default"})]})]}),e.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),e.jsx("div",{"data-testid":"workflow-step-model-select",children:e.jsx(Jt,{models:I,value:EP(y.modelProvider,y.modelId),onChange:D=>{const me=MP(D);A(q=>({...q,modelProvider:me.provider,modelId:me.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Script"}),Object.keys(F).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:y.scriptName,onChange:D=>A(me=>({...me,scriptName:D.target.value})),"data-testid":"workflow-step-script-select",children:[e.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([D,me])=>e.jsxs("option",{value:D,children:[D," (",me,")"]},D))]})]}),e.jsxs("label",{className:"wfm-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:y.enabled,onChange:D=>A(me=>({...me,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:y.defaultOn,onChange:D=>A(me=>({...me,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:S,disabled:j||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:j?"Saving...":x?"Create":"Save"})]})]})]})]})}),!Z&&e.jsx("div",{className:"wfm-footer",children:e.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:M,"data-testid":"add-workflow-step",children:[e.jsx(Ht,{size:14}),"Add Workflow Step"]})})]})})}const TP=36e5,_P=3e5,no=[{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 IP(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 $P(t){return typeof t!="number"||!Number.isFinite(t)?TP:Math.max(_P,Math.round(t))}function LI(t){if(no.some(s=>s.value===t))return[...no];const n={value:t,label:`${IP(t)} (custom)`};return[...no,n].sort((s,i)=>s.value-i.value)}const DP=4,FP=5*6e4;function LP(t){const n=$P(t?.heartbeatIntervalMs);return Math.max(n*DP,FP)}function zP(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 OP(t){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:l}=t,o=zP(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($s,{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(an,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),m=Date.now()-d,c=LP(l);return m>c?{label:"Unresponsive",icon:e.jsx(Ns,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:e.jsx(Hg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const ja=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}];function BP({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,f]=a.useState("custom"),[p,b]=a.useState("all"),[x,v]=a.useState(()=>{if(typeof window>"u")return"list";const N=In("fn-agent-view",i);return N==="board"||N==="list"?N:"list"});a.useEffect(()=>{const N=In("fn-agent-view",i);if(N==="board"||N==="list"){v(N);return}v("list")},[i]),a.useEffect(()=>{ms("fn-agent-view",x,i)},[i,x]);const[y,A]=a.useState(null),j=a.useRef(null),P=a.useMemo(()=>p==="all"?r.filter(N=>N.state!=="terminated"):r,[r,p]),w=a.useCallback(async()=>{d(!0);try{const J=await ia(p!=="all"?{state:p}:void 0,i);l(J)}catch(N){s(`Failed to load agents: ${ge(N)}`,"error")}finally{d(!1)}},[p,s,i]);a.useEffect(()=>{t&&w()},[t,w]),a.useEffect(()=>{if(!t)return;const N=setInterval(()=>{w()},3e4);return()=>{clearInterval(N)}},[t,w]);const E=async()=>{if(u.trim())try{await vy({name:u.trim(),role:g},i),s(`Agent "${u}" created`,"success"),h(""),c(!1),w()}catch(N){s(`Failed to create agent: ${ge(N)}`,"error")}},k=async(N,J)=>{try{await ky(N,J,i),s(`Agent state updated to ${J}`,"success"),w()}catch(K){s(`Failed to update state: ${ge(K)}`,"error")}},T=async(N,J)=>{if(confirm(`Delete agent "${J}"? This cannot be undone.`))try{await jy(N,i),s(`Agent "${J}" deleted`,"success"),w()}catch(K){s(`Failed to delete agent: ${ge(K)}`,"error")}},C=async(N,J)=>{const K=r.find(G=>G.id===N);if(K){if(K.role===J){A(null);return}try{await yy(N,{role:J},i),s(`Agent role updated to ${ja.find(G=>G.value===J)?.label??J}`,"success"),A(null),w()}catch(G){s(`Failed to update role: ${ge(G)}`,"error")}}},$=(N,J)=>{N.key==="Escape"&&A(null)},F=N=>ja.find(J=>J.value===N)?.label??N,ee=N=>ja.find(J=>J.value===N)?.icon??"◆",I=N=>OP(N),_=N=>N.color==="var(--state-active-text)"?"active":N.color==="var(--state-paused-text)"?"paused":N.color==="var(--state-error-text)"?"error":"muted";return t?e.jsx("div",{className:"modal-overlay open",onClick:N=>N.target===N.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(an,{size:20}),"Agents"]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${x==="board"?" active":""}`,onClick:()=>v("board"),title:"Board view","aria-label":"Board view","aria-pressed":x==="board",children:e.jsx(ki,{size:16})}),e.jsx("button",{className:`view-toggle-btn${x==="list"?" active":""}`,onClick:()=>v("list"),title:"List view","aria-label":"List view","aria-pressed":x==="list",children:e.jsx(mo,{size:16})})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void w(),title:"Refresh",disabled:o,children:e.jsx(An,{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(Sr,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:p,onChange:N=>b(N.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(Ht,{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:N=>h(N.target.value),onKeyDown:N=>N.key==="Enter"&&E(),className:"input",autoFocus:!0}),e.jsx("select",{className:"select",value:g,onChange:N=>f(N.target.value),children:ja.map(N=>e.jsxs("option",{value:N.value,children:[N.icon," ",N.label]},N.value))}),e.jsx("button",{className:"btn btn--primary",onClick:()=>void E(),children:"Create"})]}),e.jsx("div",{className:x==="board"?"agent-board":"agent-list",children:P.length===0?e.jsxs("div",{className:"agent-empty",children:[e.jsx(an,{size:48,opacity:.3}),e.jsx("p",{children:"No agents found"}),e.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):x==="board"?P.map(N=>{const J=I(N),K=_(J);return e.jsxs("div",{className:"agent-board-card","data-state":N.state,children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:ee(N.role)}),e.jsx("span",{className:"agent-board-badge","data-state":N.state,children:N.state}),e.jsx("span",{className:"agent-board-health","data-health":K,title:J.label,children:J.icon})]}),e.jsx("div",{className:"agent-board-name",title:N.name,children:N.name}),e.jsx("div",{className:"agent-board-id",children:N.id}),e.jsxs("div",{className:"agent-board-actions",children:[N.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Activate",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(N.id,N.name),title:"Delete",children:e.jsx(Ut,{size:14})})]}),N.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:e.jsx($s,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),N.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Resume",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),N.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:e.jsx($s,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),N.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Retry",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(cs,{size:14})})]}),N.state==="terminated"&&e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(N.id,N.name),title:"Delete",children:e.jsx(Ut,{size:14})})]})]},N.id)}):P.map(N=>{const J=I(N),K=_(J);return e.jsxs("div",{className:"agent-card","data-state":N.state,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[y===N.id?e.jsx("select",{ref:j,className:"select agent-role-select",value:N.role,onChange:G=>void C(N.id,G.target.value),onKeyDown:G=>$(G,N.id),onBlur:()=>A(null),autoFocus:!0,children:ja.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(N.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&A(N.id)},children:ee(N.role)}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:N.name}),e.jsx("span",{className:"agent-id text-secondary",children:N.id})]})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:"badge agent-list-state-badge","data-state":N.state,children:N.state}),e.jsxs("span",{className:"badge agent-list-health-badge","data-health":K,title:J.label,children:[J.icon,!J.stateDerived&&` ${J.label}`]}),e.jsx("span",{className:"badge text-secondary",children:F(N.role)})]})]}),e.jsxs("div",{className:"agent-card-body",children:[N.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:N.taskId})]}),N.lastHeartbeatAt&&e.jsxs("div",{className:"agent-heartbeat",children:[e.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),e.jsx("span",{children:new Date(N.lastHeartbeatAt).toLocaleString()})]})]}),e.jsxs("div",{className:"agent-card-actions",children:[N.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Activate",children:[e.jsx(rn,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(N.id,N.name),title:"Delete",children:[e.jsx(Ut,{size:14})," Delete"]})]}),N.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:[e.jsx($s,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),N.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Resume",children:[e.jsx(rn,{size:14})," Resume"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),N.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:[e.jsx($s,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),N.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Retry",children:[e.jsx(rn,{size:14})," Retry"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(cs,{size:14})," Stop"]})]}),N.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void k(N.id,"active"),title:"Start",children:[e.jsx(rn,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T(N.id,N.name),title:"Delete",children:[e.jsx(Ut,{size:14})," Delete"]})]})]})]},N.id)})})]})]})}):null}const Ni="fusion_model_onboarding_state",Xi=[],Zi=[],Or=!1,Br=!1,ea={},UP=void 0,HP={"ai-setup":"AI Setup",github:"GitHub","first-task":"First Task",complete:"Complete"};function ps(){if(typeof window>"u")return null;try{const t=localStorage.getItem(Ni);if(!t)return null;const n=JSON.parse(t);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?qP(n):null}catch{return null}}function qP(t){const n=t.postOnboardingDismissedAt??UP;return{...t,completedSteps:t.completedSteps??Xi,skippedSteps:t.skippedSteps??Zi,dismissed:t.dismissed??Or,completed:t.completed??Br,stepData:t.stepData??ea,...n?{postOnboardingDismissedAt:n}:{}}}function vr(t,n){if(!(typeof window>"u")){if(!n){const s={currentStep:t,updatedAt:new Date().toISOString(),completedSteps:Xi,skippedSteps:Zi,dismissed:Or,completed:Br,stepData:ea};try{localStorage.setItem(Ni,JSON.stringify(s))}catch{}return}try{const s=ps(),i=new Date().toISOString(),r=n.completed??Br;let l=n.dismissed??Or;r&&(l=!1);const o=n.completedSteps??s?.completedSteps??Xi,d=n.skippedSteps??s?.skippedSteps??Zi,m={...s?.stepData??ea};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(Ni,JSON.stringify(c))}catch{}}}function VP(t){if(!(typeof window>"u"))try{const n=ps(),s=new Date().toISOString();if(!n){const l={currentStep:t,updatedAt:s,completedSteps:Xi,skippedSteps:[t],dismissed:Or,completed:Br,stepData:ea};localStorage.setItem(Ni,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(Ni,JSON.stringify(r))}catch{}}function gm(){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:Xi,skippedSteps:Zi,dismissed:!1,completed:!0,stepData:ea};localStorage.setItem(Ni,JSON.stringify(s))}catch{}}function ta(){const t=ps();return t?t.completed===!0?!0:typeof t.completedAt=="string"&&t.completedAt.length>0:!1}function WP(){if(!(typeof window>"u"))try{const t=ps(),n=new Date().toISOString(),s=t?{...t,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Xi,skippedSteps:Zi,dismissed:!1,completed:!1,stepData:ea,postOnboardingDismissedAt:n};localStorage.setItem(Ni,JSON.stringify(s))}catch{}}function Xp(){const t=ps();return t?typeof t.postOnboardingDismissedAt=="string"&&t.postOnboardingDismissedAt.length>0:!1}function KP(){const t=ps();return!t||ta()?!1:t.currentStep!=="complete"}function GP(){const t=ps();if(!t||ta()||t.currentStep==="complete")return null;const n=t.currentStep,s=HP[n]??QP(t.currentStep);return{currentStep:t.currentStep,label:s,completedSteps:t.completedSteps}}function JP(){const t=ps();return t?t.skippedSteps:Zi}function YP(t){const n=ps();return!n||!n.stepData?null:n.stepData[t]??null}function QP(t){return t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Zp="fusion_onboarding_events",bm="fusion_onboarding_session_id",XP=200,ZP=50;function ks(t,n={}){if(!(typeof window>"u"))try{const s=tR(),i=iR(n.step),r={type:t,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:eR()},l=sR([...s,r]);nR(l)}catch{}}function eR(){if(typeof window>"u")return"server-session";try{const t=sessionStorage.getItem(bm);if(t)return t;const n=xm();return sessionStorage.setItem(bm,n),n}catch{return xm()}}function xm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function tR(){try{const t=localStorage.getItem(Zp);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(aR):[]}catch{return[]}}function nR(t){try{localStorage.setItem(Zp,JSON.stringify(t))}catch{}}function sR(t){const n=[...t];for(;n.length>XP;)n.splice(0,ZP);return n}function iR(t){if(t==="ai-setup"||t==="github"||t==="first-task"||t==="complete")return t}function aR(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 rR=1e4,lR=1e3;function oR(){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 f=await ad();n(f)}catch(f){l(f instanceof Error?f.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let f=!1;async function p(){i(!0);try{const x=await ad();f||(n(x),l(null))}catch(x){f||l(x instanceof Error?x.message:"Failed to fetch nodes")}finally{f||i(!1)}}p();const b=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-d.current<lR||(d.current=x,m())};return document.addEventListener("visibilitychange",b),()=>{f=!0,document.removeEventListener("visibilitychange",b)}},[m]),a.useEffect(()=>{if(!s)return o.current=setInterval(()=>{m()},rR),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async f=>{const p=await Ey(f);return n(b=>[...b,p]),p},[]),u=a.useCallback(async(f,p)=>{const b=await My(f,p);return n(x=>x.map(v=>v.id===f?b:v)),b},[]),h=a.useCallback(async f=>{await Ay(f),n(p=>p.filter(b=>b.id!==f))},[]),g=a.useCallback(async f=>{const p=await Py(f);n(b=>b.map(x=>x.id===f?{...x,status:p.status,updatedAt:p.checkedAt}:x))},[]);return{nodes:t,loading:s,error:r,refresh:m,register:c,update:u,unregister:h,healthCheck:g}}function ef({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 cR={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"}}},tf={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:"..."}},dR={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},vm={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 Do(t){if(vm[t])return vm[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 so=["anthropic","openai","google","gemini","ollama"],uR=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],mR={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"},hR={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Fo(t){return mR[t]??t}function ym(t){const n=Fo(t),s=uR.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function km(t,n){if(t.authenticated!==n.authenticated)return t.authenticated?-1:1;const s=ym(t.id),i=ym(n.id);if(s!==i)return s-i;const r=Fo(t.id),l=Fo(n.id);if(r!==l)return r.localeCompare(l);const o=hR[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 pR(t,n){const s=n.trim();if(!s)return"API key is required";const i=tf[t]??dR;return i.pattern.test(s)?null:`${Do(t)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const nf={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"},fR={description:"AI provider — connect to start using AI models",apiKeyInfo:nf};function Lo(t){return cR[t]??fR}function gR(t){return Lo(t.id).apiKeyInfo??nf}function Vs({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(ln,{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 bR({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 xR({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=tf[t.id],f=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${l?" onboarding-apikey-input--success":""}`,p=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(Vs,{summary:"Advanced setup details",children:p}),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:f,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(Vs,{summary:"Advanced setup details",children:p})]})}const vR=150;function yR({onComplete:t,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:l,firstCreatedTask:o,onViewTask:d}){const m=ps(),c=m&&m.currentStep!=="complete"?m.currentStep:"ai-setup",u=m?.completedSteps??[],h=m?.skippedSteps??JP(),[g,f]=a.useState(!0),[p,b]=a.useState(c),[x,v]=a.useState(u),[y,A]=a.useState(h),[j,P]=a.useState(!1),[w,E]=a.useState(""),[k,T]=a.useState(!1),[C,$]=a.useState(null),[F,ee]=a.useState(null),[I,_]=a.useState([]),[N,J]=a.useState(void 0),[K,G]=a.useState(!0),[M,O]=a.useState(null),[X,S]=a.useState({}),[V,de]=a.useState([]),[L,Z]=a.useState(""),[D,me]=a.useState(!1),[q,W]=a.useState({}),[ce,Se]=a.useState({}),[ve,Ee]=a.useState({}),Ae=a.useRef({}),Oe=a.useRef(null),Fe=a.useRef(null),[rt,Pe]=a.useState({}),[Ie,Be]=a.useState(()=>ps()?.stepData?.github?.skipped===!0),nt=a.useRef(0),De=a.useRef(o),Qe=a.useRef(!1),ie=m?.currentStep,te=!!m&&m.currentStep!=="complete",[fe,ae]=a.useState(()=>ps()?.stepData?.["ai-setup"]?.skippedProviders??{}),_e=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"first-task",label:"First Task"}],ke=_e.findIndex(Q=>Q.key===p),He=p==="complete"?_e.length:ke;a.useEffect(()=>{p!=="complete"&&vr(p,{completedSteps:x,skippedSteps:y})},[p,x,y]),a.useEffect(()=>{Qe.current||(Qe.current=!0,ks("onboarding:wizard-opened",{source:te?"resume":"initial",resumedFromStep:ie}))},[te,ie]),a.useEffect(()=>{const Q=De.current!=null,Ue=o!=null;!Q&&Ue&&P(!0),Ue||P(!1),De.current=o},[o]);const dt=a.useRef(c);a.useEffect(()=>{if(dt.current==="ai-setup"&&p!=="ai-setup"&&!I.some(Ue=>Ue.id!=="github"&&Ue.authenticated)){const Ue={};for(const R of I)R.id!=="github"&&!R.authenticated&&!fe[R.id]&&(Ue[R.id]=!0);if(Object.keys(Ue).length>0){const R={...fe,...Ue};ae(R),vr(p,{stepData:{"ai-setup":{skippedProviders:R}}})}}dt.current=p},[p,I,fe]);const ht=a.useCallback(async()=>{try{const{providers:Q,ghCli:Ue}=await ji();_(Q),J(Ue),S(R=>{const B={};for(const[re,pe]of Object.entries(R)){const ue=Q.find(Te=>Te.id===re);ue&&!ue.authenticated&&(B[re]=pe)}return Object.keys(B).length===Object.keys(R).length?R:B}),ae(R=>{const B={...R};for(const re of Q)re.authenticated&&B[re.id]&&delete B[re.id];return Object.keys(B).length===Object.keys(R).length?R:B})}catch{}},[]),he=a.useRef(!1);a.useEffect(()=>{he.current&&ht(),he.current=p!=="ai-setup"},[p,ht]);const ne=I.find(Q=>Q.id==="github"),ye=!!ne,we=ne?.authenticated??!1,st=N?.authenticated??!1,be=we||st,it=!we&&st,Me=a.useCallback(Q=>{if(Q.authenticated)return"connected";const Ue=rt?.[Q.id];return Ue==="timeout"||Ue==="failed"?"retry":fe[Q.id]?"skipped":"not-connected"},[rt,fe]);function qe({status:Q}){const Ue={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:R,className:B}=Ue[Q];return e.jsx("span",{"data-testid":"provider-status-badge",className:B,"data-status":Q,children:R})}const oe=a.useCallback(()=>{if(be)return"connected";const Q=rt.github;return Q==="pending"?"pending":Q==="failed"||Q==="timeout"?"failed":Ie?"skipped":"not-connected"},[be,rt,Ie]);function Ve({status:Q}){const Ue={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:R,className:B}=Ue[Q];return e.jsx("span",{"data-testid":"github-status-badge",className:B,"data-status":Q,children:R})}const We=a.useCallback(async()=>{try{const Q=await Jn();de(Q.models)}catch{}},[]),Re=a.useCallback(async()=>{try{const Q=await sa();if(Q.defaultProvider&&Q.defaultModelId){const Ue=`${Q.defaultProvider}/${Q.defaultModelId}`;Z(Ue)}}catch{}},[]);a.useEffect(()=>{Promise.all([ht(),We(),Re()]).finally(()=>G(!1))},[ht,We,Re]),a.useEffect(()=>{const Q=YP("ai-setup");if(Q?.loginOutcomes){const Ue=Q.loginOutcomes,R={};for(const[B,re]of Object.entries(Ue))re!=="pending"&&(R[B]=re);Object.keys(R).length>0&&Pe(R)}},[]);const et=a.useCallback((Q,Ue)=>{vr(p,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[Q]:Ue}}}})},[p,x]);a.useEffect(()=>{const Q=Object.entries(rt).filter(([Ue,R])=>R!=="pending");for(const[Ue,R]of Q)et(Ue,R)},[rt,et]),a.useEffect(()=>()=>{Fe.current&&clearInterval(Fe.current),Object.values(Ae.current).forEach(clearTimeout),Ae.current={}},[]);const xt=a.useCallback(Q=>{Be(Q),vr(p,{completedSteps:x,stepData:{github:{skipped:Q}}})},[p,x]),wt=a.useCallback(()=>{v(Q=>[...new Set([...Q,p])]),A(Q=>Q.filter(Ue=>Ue!==p)),ks("onboarding:step-completed",{step:p}),p==="github"&&!we&&xt(!1),p==="ai-setup"?b("github"):p==="github"&&b("first-task")},[p,we,xt]),Et=a.useCallback(()=>{A(Q=>[...new Set([...Q,p])]),VP(p),ks("onboarding:step-skipped",{step:p}),p==="github"&&!we&&xt(!0),p==="ai-setup"?b("github"):p==="github"&&b("first-task")},[p,we,xt]),Rt=a.useCallback(()=>{const Q=p;v(Ue=>Ue.filter(R=>R!==Q)),A(Ue=>Ue.filter(R=>R!==Q)),Q==="github"&&!we&&xt(!1),p==="github"?b("ai-setup"):p==="first-task"&&b("github")},[p,we,xt]),$t=a.useCallback(()=>{Et()},[Et]),_t=a.useCallback(async Q=>{Pe(Ue=>{const R=Ue[Q];if(R&&R!=="pending"){const{[Q]:B,...re}=Ue;return re}return Ue}),S(Ue=>{if(!(Q in Ue))return Ue;const R={...Ue};return delete R[Q],R}),Pe(Ue=>({...Ue,[Q]:"pending"})),O(Q),nt.current=0;try{const{url:Ue,instructions:R}=await eh(Q);R?.trim()&&S(B=>({...B,[Q]:R})),window.open(Ps(Ue),"_blank"),Fe.current=setInterval(async()=>{if(nt.current++,nt.current>=vR){Fe.current&&(clearInterval(Fe.current),Fe.current=null),O(null),Pe(B=>({...B,[Q]:"timeout"})),S(B=>{if(!(Q in B))return B;const re={...B};return delete re[Q],re}),n("Login timed out. Please try again.","warning");return}try{const{providers:B,ghCli:re}=await ji();_(B),J(re),B.find(ue=>ue.id===Q)?.authenticated&&(Fe.current&&(clearInterval(Fe.current),Fe.current=null),O(null),Pe(ue=>({...ue,[Q]:"success"})),S(ue=>{if(!(Q in ue))return ue;const Te={...ue};return delete Te[Q],Te}),Q==="github"&&xt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Ue){Ue instanceof Error&&Ue.message.includes("already in progress")||Ue&&typeof Ue=="object"&&"status"in Ue&&Ue.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Pe(B=>({...B,[Q]:"failed"}))):(n(Ue instanceof Error?Ue.message:"Login failed","error"),Pe(B=>({...B,[Q]:"failed"}))),O(null),S(B=>{if(!(Q in B))return B;const re={...B};return delete re[Q],re})}},[n,xt]),vt=a.useCallback(Q=>{Fe.current&&(clearInterval(Fe.current),Fe.current=null),O(null),nt.current=0,Pe(Ue=>({...Ue,[Q]:"cancelled"})),S(Ue=>{if(!(Q in Ue))return Ue;const R={...Ue};return delete R[Q],R})},[]),Dt=a.useCallback((Q,Ue)=>{W(B=>({...B,[Q]:Ue}));const R=Ae.current[Q];R&&(clearTimeout(R),delete Ae.current[Q]),Se(B=>{if(!B[Q])return B;const re={...B};return delete re[Q],re}),Ee(B=>{if(!B[Q])return B;const re={...B};return delete re[Q],re})},[]),Ke=a.useCallback(()=>{const Q=Oe.current;if(!Q)return;const Ue=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof Q.scrollTo=="function"){Q.scrollTo({top:0,behavior:Ue?"auto":"smooth"});return}}catch{}Q.scrollTop=0},[]),bt=a.useCallback(async(Q,Ue)=>{const R=(Ue??q[Q]??"").trim(),B=pR(Q,R);if(B){Se(pe=>({...pe,[Q]:B}));return}const re=Ae.current[Q];re&&(clearTimeout(re),delete Ae.current[Q]),O(Q),Se(pe=>{const ue={...pe};return delete ue[Q],ue}),Ee(pe=>{if(!pe[Q])return pe;const ue={...pe};return delete ue[Q],ue});try{await nh(Q,R),await ht(),Ke(),W(pe=>{const ue={...pe};return delete ue[Q],ue}),Se(pe=>{if(!pe[Q])return pe;const ue={...pe};return delete ue[Q],ue}),Ee(pe=>({...pe,[Q]:"✓ Key saved"})),Ae.current[Q]=setTimeout(()=>{Ee(pe=>{if(!pe[Q])return pe;const ue={...pe};return delete ue[Q],ue}),delete Ae.current[Q]},3e3),n("API key saved","success")}catch(pe){const ue=pe instanceof TypeError&&pe.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":pe instanceof Error?pe.message:"Failed to save API key";Se(Te=>({...Te,[Q]:ue})),Ee(Te=>{if(!Te[Q])return Te;const ut={...Te};return delete ut[Q],ut}),n(ue,"error")}finally{O(null)}},[q,n,ht,Ke]),Le=a.useCallback(async Q=>{O(Q);try{await sh(Q),await ht(),n("API key removed","success")}catch(Ue){n(Ue instanceof Error?Ue.message:"Failed to clear API key","error")}finally{O(null)}},[n,ht]),lt=a.useCallback(async Q=>{O(Q);try{await th(Q),await ht(),n("Logged out","success")}catch(Ue){n(Ue instanceof Error?Ue.message:"Logout failed","error")}finally{O(null)}},[n,ht]),xe=a.useCallback(Q=>{Z(Q)},[]),U=a.useCallback(async()=>{try{const Q={modelOnboardingComplete:!0};if(L){const Ue=L.indexOf("/"),R=Ue!==-1?L.slice(0,Ue):void 0,B=Ue!==-1?L.slice(Ue+1):L,re=V.find(pe=>pe.id===B);re?(Q.defaultProvider=re.provider,Q.defaultModelId=re.id):R&&B&&(Q.defaultProvider=R,Q.defaultModelId=B)}await Gt(Q),gm()}catch{}},[L,V,Gt,gm]),Ne=a.useCallback(async()=>{const Q=[...new Set([...x,"first-task"])];me(!0);try{await U(),ks("onboarding:completed",{completedSteps:Q,skippedSteps:y}),v(Q),A(Ue=>Ue.filter(R=>R!=="first-task")),b("complete")}finally{me(!1)}},[U,x,y]),pt=a.useCallback(async()=>{if(!s)return;const Q=w.trim();if(!Q){$("Please enter a task description.");return}$(null),T(!0);let Ue=!1;try{const R=await Zm({description:Q},s);ee(R),P(!0),ks("onboarding:first-task-created",{taskId:R?.id}),n("Task created","success"),Ue=!0}catch(R){const B=R instanceof Error?R.message:"Something went wrong creating your task. Please try again.";$(B),n(B,"error")}finally{T(!1)}Ue&&U()},[s,w,n,U]),kt=a.useCallback(async()=>{me(!0);try{await U()}finally{me(!1)}ks("onboarding:open-new-task",{}),r?.()},[U,r]),je=a.useCallback(async()=>{if(be){me(!0);try{await U()}finally{me(!1)}f(!1),t(),ks("onboarding:open-github-import",{}),l?.()}},[U,be,t,l]),Ge=a.useCallback(async()=>{ks("onboarding:dismissed",{currentStep:p,completedSteps:x,skippedSteps:y}),me(!0);try{await Gt({modelOnboardingComplete:!0})}catch{}f(!1),t()},[p,x,y,t]),gt=a.useCallback(()=>{ks("onboarding:finished",{}),f(!1),t()},[t]),qt=a.useCallback(()=>{const Q=o??F;Q&&(U(),d?.(Q),t())},[o,F,U,d,t]),gn=a.useCallback(()=>{U(),t()},[U,t]);if(!g)return null;const Wt=oe(),Rn=I.filter(Q=>Q.id!=="github"),Kt=[...Rn].sort(km),$n=Kt.some(Q=>!Q.type||Q.type==="oauth"),bn=Kt.some(Q=>Q.type==="api_key"),on=Rn.filter(Q=>Q.authenticated),en=on.length>0,xn=!!s,wn=p==="github"&&!en,Dn=(()=>{if(!L)return"";const Q=L.indexOf("/"),Ue=Q===-1?void 0:L.slice(0,Q),R=Q===-1?L:L.slice(Q+1),B=V.find(re=>re.id===R&&(!Ue||re.provider===Ue));return B?.name?B.name:Ue?`${Do(Ue)} ${R}`:L})(),cn=[];if(xn?cn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):cn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),en){const Q=Do(on[0]?.id??"");cn.push({label:"AI Provider",status:"connected",detail:`${Q} connected — AI agents can work on tasks`})}else Rn.length>0&&Rn.some(Q=>fe[Q.id])?cn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):cn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});be?cn.push({label:"GitHub",status:"connected",detail:it?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ye||Ie?cn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):cn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Dn&&cn.push({label:"Default Model",status:"connected",detail:Dn});const sn=o??F,Vt=sn?.description?.split(`
|
|
644
|
-
`)[0]?.trim()||sn?.title||"",Nn=new Set(so),Un=Kt.filter(Q=>Nn.has(Q.id)).sort((Q,Ue)=>{const R=so.indexOf(Q.id),B=so.indexOf(Ue.id);return R!==B?R-B:km(Q,Ue)}),Sn=Kt.filter(Q=>Q.authenticated&&!Nn.has(Q.id)),Hn=Kt.filter(Q=>!Q.authenticated&&!Nn.has(Q.id)),Qn=Q=>{if(Q.id==="claude-cli"&&Q.type==="cli")return e.jsx(qp,{authenticated:Q.authenticated,onToggled:()=>{ht()}},Q.id);if(Q.type==="api_key"){const Ue=Lo(Q.id),R=gR(Q);return e.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(is,{provider:Q.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsxs("strong",{className:"onboarding-provider-card__name",children:[e.jsx(Wm,{size:14,className:"onboarding-provider-key-icon"}),Q.name]}),e.jsx("span",{className:"onboarding-provider-card__description",children:Ue.description}),e.jsx(qe,{status:Me(Q)}),Q.authenticated&&Q.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",Q.keyHint]})]}),e.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:e.jsx(xR,{provider:Q,apiKeyInfo:R,inputValue:q[Q.id]??"",isSaving:M===Q.id,error:ce[Q.id],success:ve[Q.id],isConnected:Q.authenticated,onInputChange:Dt,onSave:bt,onClear:Le})})]},Q.id)}return e.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(is,{provider:Q.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:Q.name}),e.jsx("span",{className:"onboarding-provider-card__description",children:Lo(Q.id).description}),e.jsx(qe,{status:Me(Q)})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:M===Q.id?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:Q.authenticated?"Logging out…":"Waiting for login…"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>vt(Q.id),children:"Cancel"})]}):Q.authenticated?e.jsx("button",{className:"btn btn-sm",onClick:()=>lt(Q.id),children:"Logout"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_t(Q.id),children:"Login"})}),M===Q.id&&X[Q.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`onboarding-login-instructions-${Q.id}`,children:X[Q.id]}),rt[Q.id]==="timeout"&&M!==Q.id&&e.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),rt[Q.id]==="failed"&&M!==Q.id&&e.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},Q.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:[p==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx(jn,{size:24})," Set Up AI ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),p==="github"&&e.jsxs(e.Fragment,{children:[e.jsx(ns,{size:24})," Connect GitHub ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),p==="first-task"&&e.jsxs(e.Fragment,{children:[e.jsx(jb,{size:24})," Create Your First Task"]}),p==="complete"&&e.jsxs(e.Fragment,{children:[e.jsx(nn,{size:24})," All Set!"]})]}),p!=="complete"&&e.jsx("button",{className:"modal-close",onClick:Ge,"aria-label":"Skip onboarding",title:"Skip for now",children:e.jsx(Lt,{size:20})})]}),e.jsx("div",{className:"model-onboarding-steps",children:_e.map((Q,Ue)=>{const R=He>Ue,B=x.includes(Q.key)&&R,re=y.includes(Q.key)&&!x.includes(Q.key)&&R,pe=B||re;return e.jsxs("div",{className:"onboarding-step-wrapper",children:[Ue>0&&e.jsx("div",{className:`model-onboarding-step-connector ${Ue<=He?"done":""}`}),pe?e.jsxs("button",{className:`model-onboarding-step-indicator ${p===Q.key?"active":""} ${B?"done":""} ${re?"skipped":""}`,onClick:()=>b(Q.key),"aria-label":`Go back to ${Q.label}`,title:`Review ${Q.label}`,children:[e.jsx("span",{className:"step-number",children:B?e.jsx(nn,{size:14}):re?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ue+1}),e.jsx("span",{className:"step-label",children:Q.label})]}):e.jsxs("div",{className:`model-onboarding-step-indicator ${p===Q.key?"active":""} ${B?"done":""} ${re?"skipped":""}`,children:[e.jsx("span",{className:"step-number",children:B?e.jsx(nn,{size:14}):re?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ue+1}),e.jsx("span",{className:"step-label",children:Q.label})]})]},Q.key)})}),e.jsxs("div",{className:"model-onboarding-content",ref:Oe,children:[p==="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."}),!K&&I.length>0&&(()=>{const Q=I.filter(pe=>pe.id!=="github"&&pe.authenticated).length,Ue=I.filter(pe=>pe.id!=="github").length,R=Object.keys(fe).filter(pe=>!I.find(ue=>ue.id===pe)?.authenticated).length;if(Ue===0)return null;let B="onboarding-provider-summary",re="";return Q>0?(B+=" onboarding-provider-summary--connected",re=`✓ ${Q} of ${Ue} provider${Ue!==1?"s":""} connected`):R>0?(B+=" onboarding-provider-summary--skipped",re=`${R} provider${R!==1?"s":""} skipped`):(B+=" onboarding-provider-summary--none",re="No providers connected yet"),e.jsx("div",{className:B,"data-testid":"provider-summary",children:re})})(),e.jsx(Vs,{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."})}),I.length>0&&!I.some(Q=>Q.authenticated)&&e.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),K?e.jsxs("div",{className:"model-onboarding-loading",children:[e.jsx(ct,{size:24,className:"animate-spin"}),e.jsx("span",{children:"Loading providers…"})]}):I.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"}),Un.length>0?e.jsx("div",{className:"model-onboarding-providers",children:Un.map(Q=>Qn(Q))}):e.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Sn.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:Sn.map(Q=>Qn(Q))})]}),e.jsx(Vs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:e.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Hn.length>0?e.jsx("div",{className:"model-onboarding-providers",children:Hn.map(Q=>Qn(Q))}):e.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),$n&&e.jsx(Vs,{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."})}),bn&&e.jsx(Vs,{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(Vs,{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."})}),V.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(Jt,{models:V,value:L,onChange:xe,placeholder:"Select a default model…",label:"Default model"})}),L&&e.jsx("div",{className:"onboarding-model-preview",children:e.jsxs("small",{className:"settings-muted",children:["Selected:"," ",V.find(Q=>Q.id===L)?.name??L]})})]})]}),p==="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"})]})}),wn&&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(Vs,{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."})}),ye?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(ns,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),e.jsx("span",{"data-testid":"onboarding-auth-status-github",children:e.jsx(Ve,{status:Wt})})]}),we&&(M==="github"?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>lt("github"),children:"Disconnect"}))]}),(Wt==="not-connected"||Wt==="pending")&&e.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[M==="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:()=>vt("github"),children:"Cancel"})]}):e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>_t("github"),children:[e.jsx(ns,{size:16}),"Connect"]}),M==="github"&&X.github&&e.jsx("p",{className:"auth-login-instructions","data-testid":"onboarding-login-instructions-github",children:X.github})]}),Wt==="connected"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:it?"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."}),Wt==="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:$t,children:"Skip for now"})]})]}),Wt==="pending"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Wt==="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"})})]}),Wt==="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(ns,{size:48,className:"optional-icon"}),it?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:()=>b("first-task"),children:"Continue without GitHub →"})]})]}),p==="first-task"&&e.jsxs("div",{className:"model-onboarding-first-task",children:[e.jsx("p",{className:"model-onboarding-description",children:xn?"Your workspace is ready. Here's how to get started:":"Before creating your first task, register a project directory."}),j&&sn?e.jsxs("div",{className:"onboarding-task-created",children:[e.jsx(nn,{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:sn.id}),Vt&&e.jsx("p",{className:"onboarding-task-created__description",children:Vt}),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:qt,children:"View Task"}),e.jsx("button",{type:"button",className:"btn",onClick:gn,children:"Go to Dashboard"})]})]}):e.jsxs(e.Fragment,{children:[xn?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:w,onChange:Q=>{E(Q.target.value),$(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:pt,disabled:k,"data-testid":"onboarding-first-task-submit",children:k?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),C&&e.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[e.jsx("p",{className:"field-error",children:C}),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(bR,{items:cn}),xn&&e.jsxs(e.Fragment,{children:[e.jsx(Vs,{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:kt,disabled:D,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(Ht,{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${be?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:je,disabled:D||!be,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(ns,{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"}),!be&&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."]})]})]})]}),p==="complete"&&e.jsxs("div",{className:"model-onboarding-complete",children:[e.jsx(nn,{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:[p==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Ge,disabled:D,children:"Skip for now"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip setup →"}),e.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),p==="github"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Rt,children:"← Back"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip GitHub →"}),e.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),p==="first-task"&&!j&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Rt,children:"← Back"}),e.jsx("button",{className:"btn btn-primary",onClick:Ne,disabled:D,children:D?e.jsxs(e.Fragment,{children:[e.jsx(ct,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),p==="complete"&&e.jsxs("button",{className:"btn btn-primary",onClick:gt,children:[e.jsx(nn,{size:16}),e.jsx("span",{children:"Get Started"})]})]})]})})}const kR=a.lazy(()=>tn(()=>import("./SetupWizardModal-CVtmwoJC.js"),__vite__mapDeps([12,1,2,3,4,5])).then(t=>({default:t.SetupWizardModal})));function jR({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:f,onReopenOnboarding:p}){const[b,x]=a.useState(null),v=f??d.closeSettings,y=a.useCallback(()=>{d.openNewTask()},[d]),A=a.useCallback(()=>{d.openGitHubImport()},[d]),j=a.useCallback(w=>{x(null),d.closeModelOnboarding(),d.openDetailTask(w)},[d]),P=a.useCallback(async w=>{const E=await c.handleModalCreate(w);return d.modelOnboardingOpen&&x(E),E},[c.handleModalCreate,d.modelOnboardingOpen]);return a.useEffect(()=>{!d.modelOnboardingOpen&&b&&x(null)},[d.modelOnboardingOpen,b]),e.jsxs(e.Fragment,{children:[d.detailTask&&e.jsx(ui,{children:e.jsx(MM,{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(ui,{children:e.jsx(OM,{onClose:v,addToast:r,initialSection:d.settingsInitialSection,projectId:t,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:p})}),e.jsx(UM,{isOpen:d.githubImportOpen,onClose:d.closeGitHubImport,onImport:c.handleGitHubImport,tasks:n,projectId:t}),e.jsx(ui,{children:e.jsx(WM,{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(ui,{children:e.jsx(XM,{isOpen:d.isSubtaskOpen,onClose:d.closeSubtask,initialDescription:d.subtaskInitialDescription??"",onTasksCreated:c.handleSubtaskTasksCreated,projectId:t,resumeSessionId:d.subtaskResumeSessionId})}),e.jsx(hA,{isOpen:d.terminalOpen,onClose:d.closeTerminal,initialCommand:d.terminalInitialCommand,projectId:t}),e.jsx(fA,{isOpen:d.scriptsOpen,onClose:d.closeScripts,addToast:r,onRunScript:d.runScript,projectId:t}),d.filesOpen&&e.jsx(IA,{initialWorkspace:d.fileBrowserWorkspace,isOpen:!0,onClose:d.closeFiles,onWorkspaceChange:d.setFileWorkspace,projectId:t}),e.jsx(UA,{isOpen:d.usageOpen,onClose:d.closeUsage,projectId:t}),d.schedulesOpen&&e.jsx(oP,{onClose:d.closeSchedules,addToast:r,projectId:t}),e.jsx(ui,{children:e.jsx(mP,{isOpen:d.newTaskModalOpen,onClose:d.closeNewTask,tasks:n,onCreateTask:P,addToast:r,projectId:t,onPlanningMode:d.openPlanningWithInitialPlan,onSubtaskBreakdown:d.openSubtaskBreakdown})}),e.jsx(bP,{isOpen:d.activityLogOpen,onClose:d.closeActivityLog,tasks:n,projectId:t,projects:s,currentProject:i,onOpenTaskDetail:w=>{const E=n.find(k=>k.id===w);E&&d.openDetailTask(E)}}),e.jsx(ui,{children:e.jsx(vP,{isOpen:d.gitManagerOpen,onClose:d.closeGitManager,tasks:n,addToast:r,projectId:t})}),e.jsx(ui,{children:e.jsx(RP,{isOpen:d.workflowStepsOpen,onClose:d.closeWorkflowSteps,addToast:r,projectId:t})}),e.jsx(BP,{isOpen:d.agentsOpen,onClose:d.closeAgents,addToast:r,projectId:t}),d.setupWizardOpen&&e.jsx(a.Suspense,{fallback:null,children:e.jsx(kR,{onProjectRegistered:m.handleSetupComplete,onClose:d.closeSetupWizard})}),d.modelOnboardingOpen&&e.jsx(yR,{onComplete:m.handleModelOnboardingComplete,addToast:r,projectId:t??"",onOpenSetupWizard:m.handleAddProject,onOpenNewTask:y,onOpenGitHubImport:A,firstCreatedTask:b,onViewTask:j}),e.jsx(ef,{toasts:l,onRemove:o})]})}function wR({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 zo=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function NR(t,n){if(n==="ready")return"done";const s=zo.findIndex(r=>r.id===n),i=zo.findIndex(r=>r.id===t);return i<s?"done":i===s?"active":"pending"}function SR({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:zo.map(n=>{const s=NR(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 CR=5e3;function ER(t,n,s){return t||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function MR(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++,Tr(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 AR(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 x=await Ty(n);l(x)}catch(x){if(x instanceof Error&&x.name==="AbortError")return;c(x instanceof Error?x.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()},CR),()=>{u.current&&(clearInterval(u.current),u.current=null)}),[g]);const f=MR(t,s,i),p=ER(r.globalPause,r.enginePaused,f.runningTaskCount);return{stats:{...f,executorState:p,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:o,error:m,refresh:g}}const PR={planning:Ls,subtask:yi,mission_interview:ss,milestone_interview:ss,slice_interview:ss},RR={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function TR({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}=aa(),f=a.useMemo(()=>Si(),[]);if(a.useEffect(()=>{if(!l)return;const x=v=>{c.current&&!c.current.contains(v.target)&&o(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,v=new Map;for(const y of t){const A=g.get(y.id),j=[y.status,y.updatedAt,A?.tabId??y.lockedByTab??"",A?.stale?"stale":"fresh"].join("|"),P=u.current.get(y.id);P&&P!==j&&x.add(y.id),v.set(y.id,j)}if(u.current=v,x.size!==0)return m(x),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 p=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(x=>!x),title:`${p} background AI task${p!==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(Dc,{size:12}),e.jsxs("span",{children:["AI ",p]})]}),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(x=>{const v=PR[x.type],y=x.status==="generating",A=x.status==="awaiting_input",j=x.status==="error",P=g.get(x.id),w=P?.tabId??x.lockedByTab??null,E=!!(w&&w!==f&&!P?.stale),k=d.has(x.id);return e.jsxs("div",{className:`background-tasks-indicator__item${k?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:k?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:k?"translateY(-1px)":void 0},onClick:()=>{E&&!window.confirm("This session is active in another tab. Open anyway?")||(i(x),o(!1))},children:[j?e.jsx(as,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):e.jsx(v,{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:x.title}),e.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[j?"Failed":RR[x.type],y&&" — generating...",A&&!E&&" — needs input",A&&E&&" — active in another tab"]})]}),y&&e.jsx(ct,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),A&&!E&&e.jsx(Dc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),A&&E&&e.jsx(Vr,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),e.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:T=>{T.stopPropagation(),r(x.id)},title:"Dismiss",children:e.jsx(Lt,{size:12})})]},x.id)})})]})]})}function _R(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 IR(t){switch(t){case"running":return{label:"Running",color:"var(--color-success)",icon:rn};case"paused":return{label:"Paused",color:"var(--triage)",icon:$s};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:jn}}}function $R({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}=AR(t,n,s,m),g=a.useMemo(()=>IR(c.executorState),[c.executorState]),f=a.useMemo(()=>_R(c.lastActivityAt),[c.lastActivityAt]),p=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(qo,{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(TR,{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(Ui,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__time",children:f})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx(p,{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 DR={planning:Ls,subtask:yi,mission_interview:ss,milestone_interview:ss,slice_interview:ss},FR={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},pi=new Set;function LR({sessions:t,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,l]=a.useState(0),o=()=>l(p=>p+1);a.useEffect(()=>{if(pi.size===0)return;const p=new Map(t.map(x=>[x.id,x]));let b=!1;for(const x of pi){const v=p.get(x);v&&v.status!=="awaiting_input"&&v.status!=="error"&&(pi.delete(x),b=!0)}b&&o()},[t]);const d=a.useMemo(()=>t.filter(p=>(p.status==="awaiting_input"||p.status==="error")&&!pi.has(p.id)),[t,r]);if(d.length===0)return null;const m=d.filter(p=>p.status==="awaiting_input").length,c=d.filter(p=>p.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=p=>{pi.add(p),o()},g=p=>{pi.delete(p.id),o(),n(p)},f=()=>{for(const p of d)pi.add(p.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(as,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:u})]}),e.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:f,children:[e.jsx(Lt,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Dismiss all"})]})]}),e.jsx("div",{className:"session-notification-banner__list",children:d.map(p=>{const b=DR[p.type],x=p.status==="error";return e.jsxs("article",{className:`session-notification-banner__item${x?" session-notification-banner__item--error":""}`,"data-session-type":p.type,"data-session-status":p.status,children:[e.jsxs("div",{className:"session-notification-banner__item-main",children:[x?e.jsx(as,{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:p.title,children:p.title}),e.jsx("p",{className:"session-notification-banner__meta",children:x?"Failed":FR[p.type]})]})]}),e.jsxs("div",{className:"session-notification-banner__actions",children:[e.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(p),children:x?"Retry":"Resume"}),e.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(p.id),s(p.id)},"aria-label":`Dismiss ${p.title}`,children:e.jsx(Lt,{size:14,"aria-hidden":"true"})})]})]},p.id)})})]})}function zR({onResume:t}){const n=GP();if(!n)return null;const s=n.completedSteps.length,r=s>0?`${s} of 3 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(On,{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(rn,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Continue onboarding"})]})})]})}function OR({onOpenSettings:t,onOpenModelOnboarding:n}){const s=ta(),i=Xp(),[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 v=!1;return(async()=>{try{l(!0),d(!1);const[A,j]=await Promise.all([ji(),sa()]);if(v)return;const P=A.providers??[],w=P.find($=>$.id==="github"),k=!P.some($=>$.id!=="github"&&$.authenticated),T=!j.defaultProvider&&!j.defaultModelId,C=w?!w.authenticated:!1;h({needsAiProvider:k,needsDefaultModel:T,needsGitHub:C})}catch{v||d(!0)}finally{v||l(!1)}})(),()=>{v=!0}},[s,i]);const g=a.useCallback(()=>{WP(),c(!0)},[]),f=a.useCallback(()=>{n()},[n]),p=a.useCallback(()=>{t("global-models")},[t]),b=a.useCallback(()=>{t("authentication")},[t]),x=a.useMemo(()=>{const v=[];return u.needsAiProvider&&v.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:f,icon:jn}),u.needsDefaultModel&&v.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:p,icon:Wm}),u.needsGitHub&&v.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:ns}),v},[u.needsAiProvider,u.needsDefaultModel,u.needsGitHub,b,p,f]);return!s||i||m||r||o||x.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(Ls,{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:x.map(v=>{const y=v.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(as,{size:14,"aria-hidden":!0}),e.jsx(y,{size:14,"aria-hidden":!0})]}),e.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[e.jsx("strong",{children:v.title}),e.jsx("span",{children:v.description})]}),e.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:v.onAction,children:v.actionLabel})]},v.id)})})]})]}),e.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:e.jsx(Lt,{size:16,"aria-hidden":!0})})]})}function BR({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 io(t){return t>99?"99+":String(t)}function UR({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:f,onOpenGitHubImport:p,onOpenPlanning:b,onResumePlanning:x,activePlanningSessionCount:v=0,onOpenUsage:y,onRunScript:A,projectId:j,onViewAllProjects:P,showSkillsTab:w,experimentalFeatures:E}){const k=Yr(),[T,C]=a.useState(!1),[$,F]=a.useState(!1),[ee,I]=a.useState({}),[_,N]=a.useState(!1),J=a.useMemo(()=>Object.entries(ee).sort(([Z],[D])=>Z.localeCompare(D)),[ee]);a.useEffect(()=>{if(!$)return;let Z=!1;return N(!0),Va(j).then(D=>{Z||I(D)}).catch(()=>{Z||I({})}).finally(()=>{Z||N(!1)}),()=>{Z=!0}},[$,j]);const K=a.useCallback(()=>C(!1),[]),G=a.useCallback(Z=>{K(),Z?.()},[K]);if(a.useEffect(()=>{if(!T)return;const Z=D=>{D.key==="Escape"&&C(!1)};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[T]),k!=="mobile"||i)return null;const M=v>0&&x?x:b,O=!!E?.roadmap,X=!!w,S=O&&(!X||t==="roadmaps"),V=X&&(!O||t!=="roadmaps"),de=X&&!V,L=t==="documents"||t==="insights"||t==="memory"||t==="devserver"||t==="dev-server"||t==="roadmaps"&&!S||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(ki,{}),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(an,{}),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(ss,{}),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(Zs,{}),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(_a,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-nav-tab-badge",children:io(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(jn,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),S&&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(ho,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${L?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>C(Z=>!Z),children:[e.jsx(co,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),T&&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(_a,{}),e.jsx("span",{children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:io(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(Fs,{}),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(zs,{}),e.jsx("span",{children:"Terminal"})]}),e.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>F(Z=>!Z),"aria-expanded":$,"aria-haspopup":"menu","aria-label":"Show scripts",children:e.jsx(ln,{size:14,className:`mobile-more-chevron${$?" mobile-more-chevron--open":""}`})})]}),$&&e.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:_?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…"})]}):J.length>0?e.jsxs(e.Fragment,{children:[J.map(([Z,D])=>e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${Z}`,onClick:()=>{A&&A(Z,D),K(),F(!1)},children:[e.jsx(rn,{size:14}),e.jsx("span",{children:Z})]},Z)),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(),F(!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(),F(!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(f),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(M),children:[e.jsx(Ls,{}),e.jsx("span",{children:"Planning"}),v>0&&e.jsx("span",{className:"mobile-more-item-badge",children:io(v)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>G(c),children:[e.jsx(fo,{}),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(Ui,{}),e.jsx("span",{children:"Automation"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>G(p),children:[e.jsx(BR,{}),e.jsx("span",{children:"Import from GitHub"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>G(y),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(P),children:[e.jsx(Vm,{}),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(xi,{}),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(jn,{}),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(ho,{}),e.jsx("span",{children:"Roadmaps"})]}),E?.insights&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>G(()=>n("insights")),children:[e.jsx(On,{}),e.jsx("span",{children:"Insights"})]}),E?.memoryView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>G(()=>n("memory")),children:[e.jsx(Nr,{}),e.jsx("span",{children:"Memory"})]}),E?.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(Wr,{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(Ia,{}),e.jsx("span",{children:"Settings"})]})]})]})]})}function HR({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(an,{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 xc="__fn_agent__";function sf(t,n){const s=typeof t=="string"?t.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function jm(t,n,s){const i=typeof t=="string"?t.trim():"",r=sf(n,s),l=i||(r.modelProvider&&r.modelId?xc:"");return l?{agentId:l,...r}:null}function ao(t,n,s){const i=sf(n,s),r=i.modelProvider??"",l=i.modelId??"";return`${t}::${r}/${l}`}function qR(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 wm(t){return{id:t.id,sessionId:t.sessionId,role:t.role,content:t.content,thinkingOutput:t.thinkingOutput,toolCalls:qR(t.metadata),createdAt:t.createdAt}}function VR(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,f]=a.useState(""),[p,b]=a.useState(""),[x,v]=a.useState([]),[y,A]=a.useState(""),j=a.useRef(null),P=a.useRef(!1),w=a.useRef(""),E=a.useRef(""),k=a.useRef(null);a.useEffect(()=>{w.current=y},[y]);const T=a.useCallback(async G=>{const M={agentId:G.agentId};return G.modelProvider&&G.modelId&&(M.modelProvider=G.modelProvider,M.modelId=G.modelId),(await Kk(M,t)).session},[t]),C=a.useCallback(async(G,M,O)=>{const X=jm(G,M,O);if(!X)return;const S=ao(X.agentId,X.modelProvider,X.modelId);l(!0);try{const{session:V}=await Wk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},t);if(V)i(V),E.current=S;else{const de=await T(X);i(de),E.current=S}}catch(V){console.error("[useQuickChat] Failed to initialize session:",V),n?.("Failed to initialize chat","error")}finally{l(!1)}},[t,n,T]),$=a.useCallback(async()=>{if(s){c(!0);try{const G=await dd(s.id,{limit:50},t);d(G.messages.map(wm))}catch(G){console.error("[useQuickChat] Failed to load messages:",G)}finally{c(!1)}}},[s,t]);a.useEffect(()=>{s?$():d([])},[s,$]);const F=a.useCallback(async()=>{if(s){c(!0);try{const G=await dd(s.id,{limit:50},t);d(G.messages.map(wm))}catch(G){console.error("[useQuickChat] Failed to reload messages:",G)}finally{c(!1)}}},[s,t]),ee=a.useCallback(async(G,M,O)=>{const X=jm(G,M,O);if(!X)return;const S=ao(X.agentId,X.modelProvider,X.modelId);if(k.current=X,j.current&&(j.current.close(),j.current=null),f(""),b(""),v([]),h(!1),S===E.current&&s){await F();return}d([]),E.current=S,await C(X.agentId,X.modelProvider,X.modelId)},[C,F,s]),I=a.useCallback(async(G,M)=>{await ee(xc,G,M)},[ee]),_=a.useCallback(async()=>{const G=k.current;if(!G)return;const M=ao(G.agentId,G.modelProvider,G.modelId);j.current&&(j.current.close(),j.current=null),f(""),b(""),v([]),h(!1),d([]),l(!0);try{const O=await T(G);i(O),E.current=M}catch(O){console.error("[useQuickChat] Failed to start a fresh session:",O),n?.("Failed to start a new chat","error")}finally{l(!1)}},[n,T]),N=a.useCallback(()=>{s&&(P.current=!0,j.current?.close(),j.current=null,Gk(s.id,t).catch(()=>{}),h(!1),f(""),b(""),v([]))},[s,t]),J=a.useCallback(()=>{w.current="",A("")},[]),K=a.useCallback(G=>{if(!s||!G.trim())return;if(u){w.current=G,A(G);return}P.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(L=>[...L,O]),f(""),b(""),v([]),h(!0);let X="",S="",V=[];const de={onThinking:L=>{S+=L,b(S)},onText:L=>{X+=L,f(X)},onToolStart:L=>{V=[...V,{toolName:L.toolName,args:L.args,isError:!1,status:"running"}],v(V)},onToolEnd:L=>{const Z=[...V];for(let D=Z.length-1;D>=0;D--){const me=Z[D];if(me?.toolName===L.toolName&&me.status==="running"){Z[D]={...me,status:"completed",isError:L.isError,result:L.result},V=Z,v(Z);return}}V=[...Z,{toolName:L.toolName,isError:L.isError,result:L.result,status:"completed"}],v(V)},onDone:L=>{const Z={id:L.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:S||void 0,toolCalls:V.length>0?V:void 0,createdAt:new Date().toISOString()};d(me=>[...me,Z]),f(""),b(""),v([]),h(!1),j.current=null;const D=w.current.trim();D&&(w.current="",A(""),K(D))},onError:L=>{if(f(""),b(""),v([]),h(!1),j.current=null,console.error("[useQuickChat] Stream error:",L),n?.("Failed to get response","error"),!P.current){const Z=w.current.trim();Z&&(w.current="",A(""),K(Z))}F()}};j.current=Jk(s.id,G,de,t)},[s,u,t,n,F]);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:p,streamingToolCalls:x,pendingMessage:y,sendMessage:K,stopStreaming:N,clearPendingMessage:J,switchSession:ee,startModelChat:I,startFreshSession:_,loadMessages:$,reloadMessages:F}),[s,r,o,m,u,g,p,x,y,K,N,J,ee,I,_,$,F])}function WR(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 f=n?.filterState,p=f&&f!=="all"?{state:f}:void 0,b=n?.showSystemAgents??!1,x=await ia({...p,...g,includeEphemeral:g?.includeEphemeral??b},t),v=Array.from(new Map(x.map(y=>[y.id,y])).values());i(v)}catch(f){console.error("Failed to load agents:",f)}finally{d(!1)}},[t,n?.filterState,n?.showSystemAgents]),c=a.useCallback(async()=>{try{const g=await wy(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)}`:"",f=()=>{m(),c()};return Os(`/api/events${g}`,{events:{"agent:created":f,"agent:updated":f,"agent:deleted":f,"agent:stateChanged":f}})},[t,m,c]);const u=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:u||!mj(g));return{agents:s,activeAgents:h,stats:r,isLoading:o,loadAgents:m,loadStats:c}}function KR({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(Hm,{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 GR=200;function JR(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),[f,p]=a.useState(0),b=a.useRef(null),x=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),x.current?.abort()},[]);const v=a.useCallback((w,E)=>{if(E<0||E>w.length){r(!1);return}const k=T=>/[a-zA-Z0-9/_.-]/.test(T);for(let T=E-1;T>=0;T--){if(w[T]==="#")if(T===0){const C=w.slice(T+1,E);m(T),o(C),p(0),r(!0);return}else{const C=w[T-1];if(/[\s,.;:!?'"()[\]{}]/.test(C)){const $=w.slice(T+1,E);m(T),o($),p(0),r(!0);return}r(!1);return}if(!k(w[T])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),o(""),m(-1),u([]),p(0),g(!1)},[]),A=a.useCallback(async w=>{if(!w.trim()){u([]),g(!1);return}x.current?.abort(),x.current=new AbortController;try{g(!0);const E=await Tv(w,s,n);u(E.files),p(0)}catch(E){E.name!=="AbortError"&&u([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{A(l)},GR),()=>{b.current&&clearTimeout(b.current)}},[l,i,A]);const j=a.useCallback((w,E)=>{if(!i||d<0)return E;const k=E.slice(0,d),T=E.slice(d+1),C=T.match(/[\s]|$/),$=C?C.index:T.length,F=T.slice($);return`${k}#${w.path}${F}`},[i,d]),P=a.useCallback((w,E)=>{if(!i||c.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),p(k=>Math.min(k+1,c.length-1)),!0;case"ArrowUp":return w.preventDefault(),p(k=>Math.max(k-1,0)),!0;case"Enter":case"Tab":return c[f]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[i,c,f,y]);return{mentionActive:i,files:c,loading:h,mentionQuery:l,selectedIndex:f,setSelectedIndex:p,detectMention:v,selectFile:j,dismissMention:y,handleKeyDown:P}}const YR={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"},QR={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function XR(t){return`${t.name?.trim()||t.id} (${t.role})`}function ZR(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 eT(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 wr(t,n){return t.length>n?`${t.slice(0,n)}…`:t}function tT(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}=${wr(r,50)}`}).join(", ")}function nT(t){if(t===void 0)return null;if(typeof t=="string")return wr(t,200);try{return wr(JSON.stringify(t),200)}catch{return wr(String(t),200)}}function Nm(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(Qb,{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=tT(s.args),d=nT(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 sT(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 iT(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 x=localStorage.getItem(b);if(x){const v=JSON.parse(x);if(typeof v.x=="number"&&typeof v.y=="number"&&!isNaN(v.x)&&!isNaN(v.y))return v}}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 x=48,v=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,A=window.innerWidth>768?s():0,j=window.innerWidth-x-v,P=window.innerHeight-x-v-y-A;return{x:Math.max(v,Math.min(j,b.x)),y:Math.max(v,Math.min(P,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const x=`fusion-quick-chat-position-${t||"default"}`;try{localStorage.setItem(x,JSON.stringify(b))}catch{}},[t]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const v=b.target.closest(".quick-chat-fab");v&&(b.preventDefault(),typeof v.setPointerCapture=="function"&&v.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]),f=a.useCallback(b=>{if(!m.current||!o)return;const x=b.clientX-m.current.pointerX,v=b.clientY-m.current.pointerY;if((Math.abs(x)>=5||Math.abs(v)>=5)&&(c.current=!0),c.current){const y=m.current.x-x,A=m.current.y-v,j=u({x:y,y:A});l(j)}},[o,u]),p=a.useCallback(b=>{if(!m.current)return;const x=b.target.closest(".quick-chat-fab");if(x&&typeof x.releasePointerCapture=="function"&&x.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:f,handlePointerUp:p}}function aT({projectId:t,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:l=[],favoriteModels:o=[],onToggleFavorite:d,onToggleModelFavorite:m}){const{agents:c}=WR(t),[u,h]=a.useState(!1),g=i!==void 0,f=g?i:u,p=g?Le=>{r?.(typeof Le=="function"?Le(f):Le)}:h,[b,x]=a.useState("agent"),[v,y]=a.useState(""),[A,j]=a.useState([]),[P,w]=a.useState(!1),[E,k]=a.useState(""),[T,C]=a.useState(""),[$,F]=a.useState(""),[ee,I]=a.useState(!1),[_,N]=a.useState(0),[J,K]=a.useState(-1),[,G]=a.useState(!1),[M,O]=a.useState({top:0,left:0}),X=JR({projectId:t}),S=a.useCallback(Le=>{if(!Le||!X.mentionActive)return;const lt=Le.getBoundingClientRect();O({top:lt.top-260,left:lt.left+8})},[X.mentionActive]),V=a.useRef(!1),de=a.useRef(!1),L=a.useRef(""),Z=a.useRef(0),D=a.useRef(null),{position:me,isDragging:q,handlePointerDown:W,handlePointerMove:ce,handlePointerUp:Se}=iT(t,V),{activeSession:ve,messages:Ee,isStreaming:Ae,streamingText:Oe,streamingThinking:Fe,streamingToolCalls:rt,sessionsLoading:Pe,messagesLoading:Ie,sendMessage:Be,stopStreaming:nt,pendingMessage:De,clearPendingMessage:Qe,switchSession:ie,startModelChat:te,startFreshSession:fe}=VR(t,n),ae=a.useRef(null),_e=a.useRef(null),ke=a.useRef(null),He=a.useRef(null),dt=a.useMemo(()=>ZR(E),[E]),ht=a.useMemo(()=>A.find(Le=>`${Le.provider}/${Le.id}`===E)??null,[A,E]),he=a.useMemo(()=>eT(ht,dt),[ht,dt]),ne=a.useMemo(()=>b==="model"?dt?`${xc}::${dt.modelProvider}/${dt.modelId}`:"":v?`${v}::`:"",[b,dt,v]),ye=b==="agent"?!!v:!!dt;a.useEffect(()=>{if(c.length===0){y(""),x("model");return}c.some(lt=>lt.id===v)||y(c[0]?.id??"")},[c,v]),a.useEffect(()=>{!f||de.current||(de.current=!0,w(!0),Jn().then(Le=>{const lt=Le.models??[];if(j(lt),c.length===0&<.length>0&&!E){const xe=lt[0];xe&&k(`${xe.provider}/${xe.id}`)}}).catch(Le=>{console.error("[QuickChatFAB] Failed to load models:",Le),j([])}).finally(()=>{w(!1)}))},[f,c.length,E]),a.useEffect(()=>{if(!f){L.current="";return}if(!ne){L.current="";return}if(ne!==L.current){if(L.current=ne,b==="model"&&dt){te(dt.modelProvider,dt.modelId);return}b==="agent"&&v&&ie(v)}},[f,b,dt,v,ne,te,ie]),a.useEffect(()=>{f||(I(!1),F(""),K(-1))},[f]);const we=a.useCallback(Le=>{y(Le)},[]),st=a.useCallback(Le=>{k(Le)},[]),be=a.useCallback(()=>{!ye||Pe||fe()},[ye,Pe,fe]),it=a.useMemo(()=>c.find(Le=>Le.id===v)??null,[c,v]),Me=a.useMemo(()=>{const Le=$.trim().toLowerCase();return Le?c.filter(lt=>lt.name.toLowerCase().includes(Le)):c},[c,$]),qe=a.useMemo(()=>{const Le=new Map;for(const lt of c)Le.set(lt.name.toLowerCase(),lt);return Le},[c]);a.useEffect(()=>{N(0)},[$,ee]),a.useEffect(()=>()=>{D.current!==null&&(window.clearTimeout(D.current),D.current=null)},[]),a.useEffect(()=>{if(!f)return;const Le=xe=>{const U=xe.target;ae.current?.contains(U)||_e.current?.contains(U)||U.closest(".model-combobox-dropdown--portal")||p(!1)},lt=xe=>{xe.key==="Escape"&&p(!1)};return document.addEventListener("mousedown",Le),document.addEventListener("keydown",lt),()=>{document.removeEventListener("mousedown",Le),document.removeEventListener("keydown",lt)}},[f,p]),a.useEffect(()=>{if(!f)return;const Le=ke.current;Le&&(Le.scrollTop=Le.scrollHeight)},[Ee,Oe,Fe,f]);const oe=a.useMemo(()=>b==="agent"?it?`Message ${it.name||it.id}`:"Select an agent to start chatting":he?`Message ${he}`:"Select a model to start chatting",[b,it,he]),Ve=!ye||!ve||Pe,We=De.length>50?`${De.slice(0,50)}…`:De,Re=a.useCallback(()=>{const Le=T.trim();!Le||Ve||(C(""),I(!1),F(""),K(-1),Be(Le))},[Be,Ve,T]),et=a.useCallback((Le,lt)=>{const xe=sT(Le,lt);if(xe){I(!0),F(xe.filter),K(xe.start);return}I(!1),F(""),K(-1)},[]),xt=a.useCallback(Le=>{const lt=He.current;if(!lt||J<0)return;const xe=lt.selectionStart??Z.current,U=lt.selectionEnd??xe,Ne=Math.max(xe,U),pt=Math.min(J,Ne),je=`${`@${Le.name.replace(/\s+/g,"_")}`} `,Ge=T.slice(0,pt)+je+T.slice(Ne),gt=pt+je.length;C(Ge),I(!1),F(""),N(0),K(-1),window.requestAnimationFrame(()=>{He.current&&(He.current.focus(),He.current.setSelectionRange(gt,gt))})},[J,T]),wt=a.useCallback(Le=>{const lt=Le.target.value,xe=Le.target.selectionStart??lt.length;Z.current=xe,C(lt),et(lt,xe),X.detectMention(lt,xe),G(X.mentionActive),X.mentionActive&&S(Le.target)},[et,X,S]),Et=a.useCallback(()=>{D.current!==null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{I(!1),F(""),K(-1),G(!1),X.dismissMention(),D.current=null},120)},[X]),Rt=a.useCallback(()=>{D.current!==null&&(window.clearTimeout(D.current),D.current=null)},[]),$t=a.useCallback(Le=>{const lt=Le.currentTarget,xe=lt.selectionStart??lt.value.length;Z.current=xe,et(lt.value,xe),X.detectMention(lt.value,xe),G(X.mentionActive),X.mentionActive&&S(lt)},[et,X,S]),_t=a.useCallback(Le=>{Le.key!=="Escape"&&$t(Le)},[$t]),vt=a.useCallback(Le=>{const lt=/@([\w-]+)/g,xe=[];let U=0,Ne=lt.exec(Le);for(;Ne;){const[pt,kt=""]=Ne,je=Ne.index;je>U&&xe.push(Le.slice(U,je));const Ge=kt.replace(/_/g," ").toLowerCase(),gt=qe.get(Ge);gt?xe.push(e.jsxs("span",{className:"chat-mention-chip",children:["@",gt.name.replace(/\s+/g,"_")]},`${gt.id}-${je}`)):xe.push(pt),U=je+pt.length,Ne=lt.exec(Le)}return U<Le.length&&xe.push(Le.slice(U)),xe.length===0?Le:xe},[qe]),Dt=a.useCallback(Le=>{if(Z.current=Le.currentTarget.selectionStart??Z.current,X.mentionActive&&X.files.length>0){if(X.handleKeyDown(Le,T),Le.key==="Enter"||Le.key==="Tab"){const lt=X.files[X.selectedIndex];if(lt){const xe=X.selectFile(lt,T);C(xe),X.dismissMention(),G(!1)}}return}if(ee&&Le.key==="ArrowDown"){Le.preventDefault(),Me.length>0&&N(lt=>(lt+1)%Me.length);return}if(ee&&Le.key==="ArrowUp"){Le.preventDefault(),Me.length>0&&N(lt=>lt===0?Me.length-1:lt-1);return}if(ee&&Le.key==="Enter"){Le.preventDefault();const lt=Me[_]??Me[0];lt&&xt(lt);return}if(ee&&Le.key==="Escape"){Le.preventDefault(),Le.stopPropagation(),I(!1),F(""),K(-1);return}Le.key!=="Enter"||Le.shiftKey||(Le.preventDefault(),Re())},[ee,Me,_,xt,Re,X,T]),Ke=a.useCallback(()=>{if(V.current){V.current=!1;return}p(Le=>!Le)},[p]),bt=me.y+60;return e.jsxs(e.Fragment,{children:[s&&e.jsx("button",{ref:_e,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":q?"true":"false",style:{right:me.x,bottom:me.y},onPointerDown:W,onPointerMove:ce,onPointerUp:Se,onClick:Ke,children:e.jsx(Zs,{size:24})}),f&&e.jsxs("div",{className:"quick-chat-panel",ref:ae,"data-testid":"quick-chat-panel",style:{right:me.x,bottom:bt},children:[e.jsxs("div",{className:"quick-chat-panel-header",children:[e.jsxs("div",{style:QR,children:[e.jsx("h3",{children:"Quick Chat"}),he&&e.jsx("span",{style:YR,"data-testid":"quick-chat-model-tag",title:he,children:he})]}),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:be,disabled:!ye||Pe,children:"New chat"}),e.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>p(!1),children:e.jsx(Lt,{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:()=>{x("agent"),k("")},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:()=>{x("model"),y("")},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:v,onChange:Le=>we(Le.target.value),"data-testid":"quick-chat-agent-select",children:c.map(Le=>e.jsx("option",{value:Le.id,children:XR(Le)},Le.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(Jt,{id:"quick-chat-model-override",models:A,value:E,onChange:st,label:"Select model override",placeholder:P?"Loading models…":"Select a model",disabled:P||A.length===0,favoriteProviders:l,favoriteModels:o,onToggleFavorite:d,onToggleModelFavorite:m})]}),e.jsx("div",{className:"quick-chat-panel-messages",ref:ke,"data-testid":"quick-chat-messages",children:Pe||Ie?e.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ee.length===0&&!Oe&&!Fe&&!Ae?e.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):e.jsxs(e.Fragment,{children:[Ee.map(Le=>{const lt=Le.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-${Le.id}`,children:[e.jsx("p",{children:vt(Le.content)}),Nm(Le.toolCalls,!0)]},Le.id)}),Ae&&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:[Oe?e.jsx("p",{"data-testid":"quick-chat-streaming-text",children:vt(Oe)}):e.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Fe?"Thinking…":"Connecting…"}),Nm(rt,!0),Fe&&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:Fe})]})]})]})}),e.jsxs("div",{className:"quick-chat-panel-input",children:[e.jsxs("div",{className:"quick-chat-input-wrapper",children:[e.jsx("input",{ref:He,type:"text",value:T,onChange:wt,onKeyDown:Dt,onKeyUp:_t,onClick:$t,onBlur:Et,onFocus:Rt,placeholder:oe,disabled:Ve,"data-testid":"quick-chat-input"}),e.jsx(HR,{agents:c,filter:$,highlightedIndex:_,visible:ee,onSelect:xt,position:"above"}),e.jsx(KR,{visible:X.mentionActive&&!ee,position:M,files:X.files,selectedIndex:X.selectedIndex,onSelect:Le=>{const lt=X.selectFile(Le,T);C(lt),X.dismissMention(),G(!1),He.current?.focus()},loading:X.loading}),De&&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:Qe,children:"×"})]})]}),Ae?e.jsx("button",{type:"button",className:"chat-input-stop",onClick:nt,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:e.jsx(cs,{size:14})}):e.jsx("button",{type:"button",onClick:()=>void Re(),disabled:Ve||T.trim().length===0,"data-testid":"quick-chat-send",children:e.jsx(fi,{size:16})})]})]})]})}function yr(t){if(!t)return 0;const n=Date.parse(t);return Number.isFinite(n)?n:0}function Sm(t){return t.status==="generating"||t.status==="awaiting_input"}function rT(t){const[n,s]=a.useState([]),i=a.useRef(new Map),{sessions:r,broadcastUpdate:l,broadcastCompleted:o,requestSync:d}=aa(),m=a.useCallback(()=>{fh(t).then(g=>{const f=new Map;for(const p of g)f.set(p.id,yr(p.updatedAt));i.current=f,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 f=!1;const p=new Map(g.map(b=>[b.id,b]));for(const b of r.values()){if(t&&b.projectId&&b.projectId!==t)continue;const x=b.lastEventTimestamp,v=i.current.get(b.sessionId)??0;if(x<v)continue;const y=p.get(b.sessionId),A=b.type??y?.type,j=b.title??y?.title;if(!y&&(!A||!j))continue;const P={id:b.sessionId,type:A??"planning",status:b.status,title:j??"AI Session",projectId:b.projectId??y?.projectId??t??null,lockedByTab:b.owningTabId??y?.lockedByTab??null,updatedAt:b.updatedAt??y?.updatedAt??new Date(x).toISOString()},w=p.get(b.sessionId);(!w||w.status!==P.status||w.title!==P.title||w.type!==P.type||w.projectId!==P.projectId||w.lockedByTab!==P.lockedByTab||w.updatedAt!==P.updatedAt)&&(p.set(b.sessionId,P),i.current.set(b.sessionId,x),f=!0)}return f?[...p.values()].sort((b,x)=>yr(x.updatedAt)-yr(b.updatedAt)):g})},[t,r]),a.useEffect(()=>{const g=t?`?projectId=${encodeURIComponent(t)}`:"",f=b=>{try{const x=JSON.parse(b.data),v=yr(x.updatedAt)||Date.now();s(y=>{const A=i.current.get(x.id)??0;if(v<A)return y;if(i.current.set(x.id,v),x.status==="complete"||x.status==="error")return y.filter(P=>P.id!==x.id);const j=y.findIndex(P=>P.id===x.id);if(j>=0){const P=[...y];return P[j]=x,P}return Sm(x)?[x,...y]:y}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:v}),(x.status==="complete"||x.status==="error")&&o({sessionId:x.id,status:x.status,timestamp:v})}catch{}},p=b=>{try{const x=JSON.parse(b.data);s(v=>v.filter(y=>y.id!==x)),i.current.delete(x)}catch{}};return Os(`/api/events${g}`,{events:{"ai_session:updated":f,"ai_session:deleted":p}})},[o,l,t]);const c=a.useCallback(async g=>{const p=n.find(y=>y.id===g)?.type,b=Si();let x=!1,v=!1;if(p==="planning")try{await rh(g,t,b)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(v=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${g}: locked by another tab`))}else if(p==="subtask")try{await ch(g,t,b)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(v=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${g}: locked by another tab`))}else if(p==="mission_interview")try{await ph(g,t,b)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(v=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${g}: locked by another tab`))}x&&!v&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${g}, attempting delete anyway`);try{await $k(g)}catch{}s(y=>y.filter(A=>A.id!==g)),i.current.delete(g)},[t,n]),u=a.useMemo(()=>n.filter(g=>Sm(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 Kn(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 Cm(t,n){return!t&&!n?0:t?n?t.localeCompare(n):1:-1}function lT(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),f=a.useRef(null),p=a.useRef(void 0),b=a.useRef(0),x=a.useRef(n);c.current=r,g.current=s,x.current!==n&&(x.current=n,b.current++);const v=1e3,y=a.useCallback(async I=>{const _=++u.current,N=n,J=I?.searchQueryOverride??s,K=I?.includeArchivedOverride??m.current;try{const G=await bx(void 0,void 0,N,J,K);if(u.current!==_||n!==N)return;l(G.map(Kn)),p.current=Date.now()}catch{if(u.current!==_||n!==N)return;if(I?.clearOnError){l([]);return}l(G=>G)}},[n,s]);f.current=y;const A=a.useCallback(async()=>{m.current||(d(!0),m.current=!0,await f.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const I=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{y({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const _=Date.now();_-h.current<v||(h.current=_,y())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[y]),a.useEffect(()=>{if(i===!1)return;const I=b.current,_=n?`?projectId=${encodeURIComponent(n)}`:"",N=()=>b.current!==I;let J=!0;const K=V=>{if(N())return;const de=Kn(JSON.parse(V.data));if(g.current){f.current({searchQueryOverride:g.current});return}l(L=>L.some(Z=>Z.id===de.id)?L:[...L,de])},G=V=>{if(N())return;if(g.current){f.current({searchQueryOverride:g.current});return}const{task:de,to:L}=JSON.parse(V.data),Z=Kn(de);l(D=>D.map(me=>me.id===Z.id?{...Z,column:L}:me)),p.current=Date.now()},M=V=>{if(N())return;if(g.current){f.current({searchQueryOverride:g.current});return}const de=Kn(JSON.parse(V.data));l(L=>L.map(Z=>{if(Z.id!==de.id||Cm(de.updatedAt,Z.updatedAt)<0)return Z;if(Z.column===de.column)return de;const me=Cm(Z.columnMovedAt,de.columnMovedAt);return Z.columnMovedAt&&!de.columnMovedAt?{...de,column:Z.column,columnMovedAt:Z.columnMovedAt}:me>0?{...de,column:Z.column,columnMovedAt:Z.columnMovedAt}:de})),p.current=Date.now()},O=V=>{if(N())return;if(g.current){f.current({searchQueryOverride:g.current});return}const de=Kn(JSON.parse(V.data));l(L=>L.filter(Z=>Z.id!==de.id))},X=V=>{if(N())return;if(g.current){f.current({searchQueryOverride:g.current});return}const{task:de}=JSON.parse(V.data),L=Kn(de);l(Z=>Z.map(D=>D.id===L.id?{...L,column:"done"}:D))},S=Os(`/api/events${_}`,{events:{"task:created":K,"task:moved":G,"task:updated":M,"task:deleted":O,"task:merged":X},onReconnect:()=>{J&&(N()||f.current())}});return()=>{J=!1,S()}},[n,i]);const j=a.useCallback(async I=>{const _=Kn(await Zm(I,n));return l(N=>N.some(J=>J.id===_.id)?N:[...N,_]),_},[n]),P=a.useCallback(async(I,_)=>Kn(await vx(I,_,n)),[n]),w=a.useCallback(async I=>Kn(await yx(I,n)),[n]),E=a.useCallback(async I=>kx(I,n),[n]),k=a.useCallback(async I=>Kn(await jx(I,n)),[n]),T=a.useCallback(async I=>{const _=Kn(await wx(I,n));return l(N=>N.some(J=>J.id===_.id)?N:[...N,_]),_},[n]),C=a.useCallback(async(I,_)=>{const N=c.current.find(K=>K.id===I),J=N?{...N,..._,updatedAt:new Date().toISOString()}:void 0;J&&l(K=>K.map(G=>G.id===I?J:G));try{const K=Kn(await Ws(I,_,n));return l(G=>G.map(M=>M.id===I?K:M)),K}catch(K){throw N&&l(G=>G.map(M=>M.id===I?N:M)),K}},[n]),$=a.useCallback(async I=>{const _=Kn(await Cx(I,n));return l(N=>N.map(J=>J.id===I?_:J)),_},[n]),F=a.useCallback(async I=>{const _=Kn(await Ex(I,n));return l(N=>N.map(J=>J.id===I?_:J)),_},[n]),ee=a.useCallback(async()=>{const _=(await Mx(n)).map(Kn);return l(N=>N.map(J=>_.find(G=>G.id===J.id)||J)),_},[n]);return{tasks:r,createTask:j,moveTask:P,deleteTask:w,mergeTask:E,retryTask:k,duplicateTask:T,updateTask:C,archiveTask:$,unarchiveTask:F,archiveAllDone:ee,loadArchivedTasks:A,includeArchived:o,lastFetchTimeMs:p.current}}const oT=5e3,cT=1e3;function dT(){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 id();n(g)}catch(g){l(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function f(){i(!0);const b=performance.now();try{const x=await id(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${x.length} projects)`;console.log(`[useProjects] ${y}`),Ea("[useProjects]",y),g||(n(x),l(null))}catch(x){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${x instanceof Error?x.message:String(x)}`;console.warn(`[useProjects] ${y}`),Ea("[useProjects]",y),g||l(x instanceof Error?x.message:"Failed to fetch projects")}finally{g||i(!1)}}f();const p=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-d.current<cT||(d.current=b,m())};return document.addEventListener("visibilitychange",p),()=>{g=!0,document.removeEventListener("visibilitychange",p)}},[m]),a.useEffect(()=>{if(!s)return o.current=setInterval(()=>{m()},oT),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async g=>{const f=await Ry(g);return n(p=>[...p,f]),f},[]),u=a.useCallback(async(g,f)=>{const p=await Fy(g,f);return n(b=>b.map(x=>x.id===g?p:x)),p},[]),h=a.useCallback(async g=>{await uh(g),n(f=>f.filter(p=>p.id!==g))},[]);return{projects:t,loading:s,error:r,refresh:m,register:c,update:u,unregister:h}}const uT="kb-dashboard-current-project";function mT(t){return t??"local"}function hT(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=mT(s);a.useEffect(()=>{let f=!1;async function p(){try{const b=await sa();if(f)return;c.current=b.dashboardCurrentProjectIdByNode??{};const x=c.current[u];if(x){const v=t.find(y=>y.id===x);v&&(r(v),d.current=!0)}if(!x)try{const v=localStorage.getItem(uT);if(v){const y=JSON.parse(v);y?.id&&t.some(j=>j.id===y.id)&&(r(y),d.current=!0,c.current={...c.current,[u]:y.id},await Gt({dashboardCurrentProjectIdByNode:c.current}).catch(()=>{}))}}catch{}}catch{}finally{f||o(!1)}}return p(),()=>{f=!0}},[u,t]),a.useEffect(()=>{if(!l){if(i){if(!t.some(b=>b.id===i.id)&&t.length>0){const b=t.find(x=>x.status==="active");r(b||t[0]||null);return}const p={...c.current,[u]:i.id};c.current=p,Gt({dashboardCurrentProjectIdByNode:p}).catch(()=>{})}else if(t.length>0&&!m.current){const f=t.find(p=>p.status==="active");f&&r(f)}}},[i,t,l,u]);const h=a.useCallback(f=>{if(m.current=!1,r(f),f){const p={...c.current,[u]:f.id};c.current=p,Gt({dashboardCurrentProjectIdByNode:p}).catch(()=>{})}},[u]),g=a.useCallback(()=>{m.current=!0,r(null);const f={...c.current};delete f[u],c.current=f,Gt({dashboardCurrentProjectIdByNode:f}).catch(()=>{})},[u]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:l}}const af=a.createContext(null);function pT({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()},[]),$m.createElement(af.Provider,{value:{toasts:n,addToast:o,removeToast:l}},t)}function fT(){const t=a.useContext(af);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const rf="kb-dashboard-theme-mode",lf="kb-dashboard-color-theme",of=[...dj],Oo="theme-data",ro="theme-data.css";function gT(){const t=document.baseURI||(typeof document.location<"u"?document.location.href:"");return t?t.endsWith("/")?t.slice(0,-1)+`/${ro}`:t.replace(/\/[^/]+$/,`/${ro}`):`/${ro}`}const ws=typeof window<"u",bT=ws?a.useLayoutEffect:a.useEffect;function cf(t){return t==="dark"||t==="light"||t==="system"}function Em(){if(!ws)return"dark";try{const t=localStorage.getItem(rf);if(cf(t))return t}catch{}return"dark"}function Mm(){if(!ws)return"default";try{const t=localStorage.getItem(lf);if(t&&of.includes(t))return t}catch{}return"default"}function Am(t){if(ws)try{localStorage.setItem(rf,t)}catch{}}function Pm(t){if(ws)try{localStorage.setItem(lf,t)}catch{}}function xT(t,n){return t==="system"?n?"dark":"light":t}function vT(t,n,s){if(!ws)return;const i=xT(t,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Rm(){if(!ws)return;const t=gT(),n=document.getElementById(Oo);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=Oo,document.head.appendChild(s)}function Tm(){if(!ws)return;const t=document.getElementById(Oo);t&&t.remove()}function yT(){const[t,n]=a.useState(()=>Em()),[s,i]=a.useState(()=>Mm()),[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 p=!1;return sa().then(b=>{p||(cf(b.themeMode)&&!u.current&&(m.current!==b.themeMode&&(m.current=b.themeMode,n(b.themeMode)),Em()!==b.themeMode&&Am(b.themeMode)),b.colorTheme&&of.includes(b.colorTheme)&&!h.current&&(c.current!==b.colorTheme&&(c.current=b.colorTheme,i(b.colorTheme)),Mm()!==b.colorTheme&&Pm(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{p||l(!1)}),()=>{p=!0}},[r]),a.useEffect(()=>{if(!ws)return;const p=window.matchMedia("(prefers-color-scheme: dark)"),b=x=>{d(x.matches)};return p.addEventListener("change",b),()=>p.removeEventListener("change",b)},[]),bT(()=>{vT(t,s,o)},[t,s,o]),a.useEffect(()=>{!ws||r||(s!=="default"?Rm():Tm())},[s,r]);const g=a.useCallback(p=>{u.current=!0,m.current=p,n(p),Am(p),Gt({themeMode:p}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),f=a.useCallback(p=>{h.current=!0,c.current=p,i(p),Pm(p),p!=="default"?Rm():Tm(),Gt({colorTheme:p}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:t,colorTheme:s,setThemeMode:g,setColorTheme:f,isSystemDark:o}}function kT(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,f]=a.useState(null),[p,b]=a.useState(void 0),[x,v]=a.useState(null),[y,A]=a.useState("definition"),[j,P]=a.useState(!1),[w,E]=a.useState(void 0),[k,T]=a.useState(!1),[C,$]=a.useState(!1),[F,ee]=a.useState(!1),[I,_]=a.useState(!1),[N,J]=a.useState(void 0),[K,G]=a.useState(!1),[M,O]=a.useState("project"),[X,S]=a.useState(!1),[V,de]=a.useState(!1),[L,Z]=a.useState(!1),[D,me]=a.useState(!1),[q,W]=a.useState(!1),[ce,Se]=a.useState(!1),[ve,Ee]=a.useState(!1),Ae=!!(x||j||s||r||u||I||K||X||V||L||q||D||F||k||C||ce||ve),Oe=a.useCallback(()=>i(!0),[]),Fe=a.useCallback(()=>i(!1),[]),rt=a.useCallback(()=>l(!0),[]),Pe=a.useCallback(U=>{d(U),l(!0)},[]),Ie=a.useCallback(()=>{const U=n[0];U&&(c(U.id),l(!0))},[n]),Be=a.useCallback(U=>{c(U),l(!0)},[]),nt=a.useCallback(()=>{l(!1),d(null),c(void 0)},[]),De=a.useCallback(U=>{f(U),h(!0)},[]),Qe=a.useCallback(U=>{b(U),h(!0)},[]),ie=a.useCallback(()=>{h(!1),f(null),b(void 0)},[]),te=a.useCallback((U,Ne="definition")=>{v(U),A(Ne)},[]),fe=a.useCallback(U=>{v(U),A("changes")},[]),ae=a.useCallback(U=>{v(Ne=>Ne&&{...Ne,...U})},[]),_e=a.useCallback(()=>{v(null)},[]),ke=a.useCallback(U=>{E(U),P(!0)},[]),He=a.useCallback(()=>{P(!1),E(void 0)},[]),dt=a.useCallback(()=>T(!0),[]),ht=a.useCallback(()=>T(!1),[]),he=a.useCallback(()=>$(!0),[]),ne=a.useCallback(()=>$(!1),[]),ye=a.useCallback(()=>ee(!0),[]),we=a.useCallback(()=>ee(!1),[]),st=a.useCallback(()=>{_(U=>!U)},[]),be=a.useCallback(()=>{_(!1),J(void 0)},[]),it=a.useCallback(()=>G(!0),[]),Me=a.useCallback(()=>G(!1),[]),qe=a.useCallback(U=>{O(U)},[]),oe=a.useCallback(()=>S(!0),[]),Ve=a.useCallback(()=>S(!1),[]),We=a.useCallback(()=>de(!0),[]),Re=a.useCallback(()=>de(!1),[]),et=a.useCallback(()=>Z(!0),[]),xt=a.useCallback(()=>Z(!1),[]),wt=a.useCallback(()=>me(!0),[]),Et=a.useCallback(()=>me(!1),[]),Rt=a.useCallback(()=>W(!0),[]),$t=a.useCallback(()=>W(!1),[]),_t=a.useCallback(async(U,Ne)=>{W(!1),J(Ne),_(!0)},[]),vt=a.useCallback(()=>Se(!0),[]),Dt=a.useCallback(()=>Se(!1),[]),Ke=a.useCallback(()=>Ee(!0),[]),bt=a.useCallback(()=>Ee(!1),[]),Le=a.useCallback((U,Ne)=>{Ne(`Created ${U.id} from planning mode`,"success"),l(!1),d(null)},[]),lt=a.useCallback((U,Ne)=>{const pt=U.map(kt=>kt.id).join(", ");Ne(`Created ${pt} from planning mode`,"success"),l(!1),d(null)},[]),xe=a.useCallback((U,Ne)=>{const pt=U.map(kt=>kt.id).join(", ");Ne(`Created ${pt} from subtask breakdown`,"success"),h(!1),f(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:o,planningResumeSessionId:m,isSubtaskOpen:u,subtaskInitialDescription:g,subtaskResumeSessionId:p,detailTask:x,detailTaskInitialTab:y,settingsOpen:j,settingsInitialSection:w,schedulesOpen:k,githubImportOpen:C,usageOpen:F,terminalOpen:I,terminalInitialCommand:N,filesOpen:K,fileBrowserWorkspace:M,activityLogOpen:X,gitManagerOpen:V,workflowStepsOpen:L,agentsOpen:D,scriptsOpen:q,setupWizardOpen:ce,modelOnboardingOpen:ve,anyModalOpen:Ae,openNewTask:Oe,closeNewTask:Fe,openPlanning:rt,openPlanningWithInitialPlan:Pe,resumePlanning:Ie,openPlanningWithSession:Be,closePlanning:nt,openSubtaskBreakdown:De,openSubtaskWithSession:Qe,closeSubtask:ie,openDetailTask:te,openDetailWithChangesTab:fe,updateDetailTask:ae,closeDetailTask:_e,openSettings:ke,closeSettings:He,openSchedules:dt,closeSchedules:ht,openGitHubImport:he,closeGitHubImport:ne,openUsage:ye,closeUsage:we,toggleTerminal:st,closeTerminal:be,openFiles:it,closeFiles:Me,setFileWorkspace:qe,openActivityLog:oe,closeActivityLog:Ve,openGitManager:We,closeGitManager:Re,openWorkflowSteps:et,closeWorkflowSteps:xt,openAgents:wt,closeAgents:Et,openScripts:Rt,closeScripts:$t,runScript:_t,openSetupWizard:vt,closeSetupWizard:Dt,openModelOnboarding:Ke,closeModelOnboarding:bt,onPlanningTaskCreated:Le,onPlanningTasksCreated:lt,onSubtaskTasksCreated:xe}}function jT(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),[f,p]=a.useState(!1),[b,x]=a.useState(!1),[v,y]=a.useState({}),[A,j]=a.useState(!1),[P,w]=a.useState(!1),[E,k]=a.useState(!1),[T,C]=a.useState(!1),$=a.useCallback(async()=>{const[N,J]=await Promise.allSettled([Rx(t),Wi(t)]);if(N.status==="fulfilled"&&(s(N.value.maxConcurrent),r(N.value.rootDir)),J.status==="fulfilled"){const K=J.value;o(!!K.autoMerge),m(!!K.globalPause),u(!!K.enginePaused),x(!!K.prAuthAvailable),g(K.taskStuckTimeoutMs),p(K.showQuickChatFAB===!0),y(K.experimentalFeatures??{});const G=K.experimentalFeatures??{};j(G.insights===!0),w(G.roadmap===!0),k(G.memoryView===!0),C(G.devServerView===!0)}},[t]);a.useEffect(()=>{$()},[$]);const F=a.useCallback(async()=>{const N=!l;o(N);try{await Sa({autoMerge:N},t)}catch{o(!N)}},[l,t]),ee=a.useCallback(async()=>{const N=!d;m(N);try{await Sa({globalPause:N,globalPauseReason:N?"manual":void 0},t)}catch{m(!N)}},[d,t]),I=a.useCallback(async()=>{const N=!c;u(N);try{await Sa({enginePaused:N},t)}catch{u(!N)}},[c,t]),_=a.useCallback(async()=>{const N=!f;p(N);try{await Sa({showQuickChatFAB:N},t)}catch{p(!N)}},[f,t]);return{maxConcurrent:n,rootDir:i,autoMerge:l,globalPaused:d,enginePaused:c,taskStuckTimeoutMs:h,showQuickChatFAB:f,prAuthAvailable:b,experimentalFeatures:v,insightsEnabled:A,roadmapEnabled:P,memoryEnabled:E,devServerEnabled:T,toggleAutoMerge:F,toggleGlobalPause:ee,toggleEnginePause:I,toggleShowQuickChatFAB:_,refresh:$}}function wT(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),f=g.get("project"),p=g.get("task");if(!p||i)return;if(f){const x=s.find(v=>v.id===f);if(!x){o(`Project '${f}' not found`,"error");return}r?.id!==x.id&&l(x)}if(c.current)return;c.current=!0,Ar(p,f??n).then(x=>{d(x),u.current=p}).catch(()=>{o(`Task ${p} 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 f=g.toString();window.history.replaceState(null,"",f?`${window.location.pathname}?${f}`:window.location.pathname),u.current=null}m()},[m])}}function NT(){const[t,n]=a.useState([]),[s,i]=a.useState([]),[r,l]=a.useState([]);a.useEffect(()=>{Jn().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 Gt({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 Gt({favoriteProviders:s,favoriteModels:h})}catch(g){throw l(c),g}},[r,s]);return{availableModels:t,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:o,toggleFavoriteModel:d}}function ST({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;ji().then(({providers:o})=>{const d=o.some(c=>c.authenticated);if(o.length>0&&!d||o.length>0&&d)return sa().then(c=>{const u=!!(c.defaultProvider&&c.defaultModelId);(c.modelOnboardingComplete===!1||c.modelOnboardingComplete===void 0)&&(!d||!u)&&!ta()?r=!0:!d&&!ta()&&(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 CT=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function _m(t){return t!==null&&CT.includes(t)}function ET(t){return t==="devserver"?"dev-server":t}function MT(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 v=window.localStorage.getItem("kb-dashboard-view-mode");if(v==="overview"||v==="project")return v}return"overview"}),[g,f]=a.useState(()=>{const v=In("kb-dashboard-task-view");return _m(v)?v:"board"}),p=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",u)},[u]),a.useEffect(()=>{const v=In("kb-dashboard-task-view",r?.id);if(_m(v)){const y=!p.current&&v==="devserver";f(y?"devserver":ET(v))}else f("board");r?.id&&(p.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 v=window.setTimeout(()=>{d()},500);return()=>window.clearTimeout(v)},[n,s,l,i,r,o,d]);const b=a.useCallback(v=>{f(v)},[]),x=a.useCallback(()=>{const v=["dark","light","system"],y=v.indexOf(m),A=v[(y+1)%v.length];c(A)},[m,c]);return{viewMode:u,setViewMode:h,taskView:g,setTaskView:f,handleChangeTaskView:b,handleToggleTheme:x}}function AT(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,f=a.useCallback(k=>{n(k),i("project")},[n,i]),p=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{c()},[c]),x=a.useCallback(()=>{u()},[u]),v=a.useCallback(k=>{h(),n(k),i("project"),m(`Project ${k.name} registered successfully`,"success"),l()},[h,n,i,m,l]),y=a.useCallback(()=>{g()},[g]),A=a.useCallback(async k=>{try{await _y(k.id),m(`Project ${k.name} paused`,"success"),await l()}catch{m(`Failed to pause project ${k.name}`,"error")}},[m,l]),j=a.useCallback(async k=>{try{await Iy(k.id),m(`Project ${k.name} resumed`,"success"),await l()}catch{m(`Failed to resume project ${k.name}`,"error")}},[m,l]),P=a.useCallback(async k=>{try{await uh(k.id),m(`Project ${k.name} removed`,"success"),r?.id===k.id&&(s(),i("overview")),await l()}catch{m(`Failed to remove project ${k.name}`,"error")}},[r,s,i,m,l]),w=a.useCallback(async k=>{try{await o(k)}catch{m("Failed to update favorites","error")}},[o,m]),E=a.useCallback(async k=>{try{await d(k)}catch{m("Failed to update model favorites","error")}},[d,m]);return{handleSelectProject:f,handleViewAllProjects:p,handleOpenSettings:b,handleAddProject:x,handleSetupComplete:v,handleModelOnboardingComplete:y,handlePauseProject:A,handleResumeProject:j,handleRemoveProject:P,handleToggleFavorite:w,handleToggleModelFavorite:E}}function PT(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 RT(t){return Jr("/health",{nodeId:t})}async function TT(t){return Jr("/projects",{nodeId:t})}async function _T(t,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Jr(`/tasks?${i.toString()}`,{nodeId:t})}async function IT(t,n){return Jr(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:t})}async function zI(t){return z(`/nodes/${encodeURIComponent(t)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function OI(t){return z(`/nodes/${encodeURIComponent(t)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function BI(t){return z(`/nodes/${encodeURIComponent(t)}/settings/sync-status`)}async function UI(t){return z(`/nodes/${encodeURIComponent(t)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function $T(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,f]=a.useState(null),p=a.useRef(null),b=a.useCallback(async()=>{if(!t){l([]),d([]),c(null),h(!1),f(null);return}p.current?.abort();const v=new AbortController;p.current=v,h(!0),f(null);try{const y=[RT(t),TT(t)];s&&(y.push(_T(t,s,i)),y.push(IT(t,s)));const A=await Promise.allSettled(y);if(v.signal.aborted)return;const j=A[0],P=A[1];if(j.status==="rejected"){f(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(c(j.value),P.status==="rejected"){f(`Failed to fetch projects: ${P.reason}`),h(!1);return}if(l(P.value),s&&A[2]){const w=A[2];if(w.status==="rejected"){f(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&d(w.value)}h(!1)}catch(y){v.signal.aborted||(f(y instanceof Error?y.message:"Unknown error"),h(!1))}},[t,s,i]);a.useEffect(()=>(b(),()=>{p.current?.abort()}),[b]);const x=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:o,health:m,loading:u,error:g,refresh:x}}function DT(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 Os(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 FT="fusion-dashboard-current-node",df=a.createContext(null);function LT({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 sa();if(u)return;o.current=g.dashboardCurrentNodeId;const f=g.dashboardCurrentNodeId;if(f&&(l.current=!0),!f)try{const p=localStorage.getItem(FT);if(p){const b=JSON.parse(p);b?.id&&b?.type==="remote"&&(o.current=b.id,await Gt({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,Gt({dashboardCurrentNodeId:u}).catch(()=>{}))}else n===null&&o.current!==void 0&&(o.current=void 0,Gt({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const d=a.useCallback(u=>{s(u)},[]),m=a.useCallback(()=>{s(null),o.current=void 0,Gt({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),c={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:d,clearCurrentNode:m};return e.jsx(df.Provider,{value:c,children:t})}function zT(){const t=a.useContext(df);if(t===null)throw new Error("useNodeContext must be used within a NodeProvider");return t}function OT({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&&(rx(o),window.location.reload())},[n]),l=a.useCallback(()=>{lx(),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 auth-token-recovery-modal",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("h2",{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 BT=a.lazy(()=>tn(()=>import("./AgentsView-CWFLMIDP.js").then(t=>t.A),__vite__mapDeps([13,1,14,3,15])).then(t=>({default:t.AgentsView}))),UT=a.lazy(()=>tn(()=>import("./DocumentsView-CjfVl8mZ.js"),__vite__mapDeps([16,1,4,5,17])).then(t=>({default:t.DocumentsView}))),HT=a.lazy(()=>tn(()=>import("./InsightsView-Rb735C9_.js"),__vite__mapDeps([18,1,4,5,19])).then(t=>({default:t.InsightsView}))),qT=a.lazy(()=>tn(()=>import("./NodesView-BviqBWRA.js"),__vite__mapDeps([20,1,14,4,5,21])).then(t=>({default:t.NodesView}))),VT=a.lazy(()=>tn(()=>import("./ChatView-C_T91ebd.js"),__vite__mapDeps([22,1,4,5])).then(t=>({default:t.ChatView}))),WT=a.lazy(()=>tn(()=>import("./RoadmapsView-Dhl--4vY.js"),__vite__mapDeps([23,1,4,5,24])).then(t=>({default:t.RoadmapsView}))),KT=a.lazy(()=>tn(()=>import("./SkillsView-CG9y4fsE.js"),__vite__mapDeps([25,1,4,5,26])).then(t=>({default:t.SkillsView}))),GT=a.lazy(()=>tn(()=>import("./MemoryView-LLc_uNtG.js"),__vite__mapDeps([27,1,4,5,28])).then(t=>({default:t.MemoryView}))),JT=a.lazy(()=>tn(()=>import("./DevServerView-ChWTzTvy.js"),__vite__mapDeps([29,1,4,5,30])).then(t=>({default:t.DevServerView})));function YT(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{tn(()=>import("./AgentsView-CWFLMIDP.js").then(n=>n.A),__vite__mapDeps([13,1,14,3,15])),tn(()=>import("./DocumentsView-CjfVl8mZ.js"),__vite__mapDeps([16,1,4,5,17])),tn(()=>import("./InsightsView-Rb735C9_.js"),__vite__mapDeps([18,1,4,5,19])),tn(()=>import("./NodesView-BviqBWRA.js"),__vite__mapDeps([20,1,14,4,5,21])),tn(()=>import("./ChatView-C_T91ebd.js"),__vite__mapDeps([22,1,4,5])),tn(()=>import("./RoadmapsView-Dhl--4vY.js"),__vite__mapDeps([23,1,4,5,24])),tn(()=>import("./SkillsView-CG9y4fsE.js"),__vite__mapDeps([25,1,4,5,26])),tn(()=>import("./MemoryView-LLc_uNtG.js"),__vite__mapDeps([27,1,4,5,28])),tn(()=>import("./DevServerView-ChWTzTvy.js"),__vite__mapDeps([29,1,4,5,30]))})}const lo="kb-setup-warning-dismissed";function QT(){const{toasts:t,addToast:n,removeToast:s}=fT(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{YT()},[]);const{projects:r,loading:l,error:o,refresh:d}=dT(),{nodes:m}=oR(),{currentNode:c,currentNodeId:u,isRemote:h,setCurrentNode:g,clearCurrentNode:f}=zT(),{currentProject:p,setCurrentProject:b,clearCurrentProject:x,loading:v}=hT(r,{nodeId:u}),{hasAiProvider:y,hasGithub:A,loading:j,hasWarnings:P}=Yp(p?.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)||f())},[u,c,m,g,f]);const[w,E]=a.useState(""),k=$T(u,{projectId:p?.id,searchQuery:w||void 0});DT(u);const T=h&&k.projects.length>0?k.projects:r,{themeMode:C,colorTheme:$,setThemeMode:F,setColorTheme:ee}=yT(),{sessions:I,generating:_,needsInput:N,planningSessions:J,dismissSession:K}=rT(p?.id),G=I.filter(Je=>Je.status==="awaiting_input"||Je.status==="error"),M=kT({projectId:p?.id,planningSessions:J}),{viewMode:O,setViewMode:X,taskView:S,handleChangeTaskView:V}=MT({projectsLoading:l,projectsError:o,currentProjectLoading:v,currentProject:p,projectsLength:r.length,setupWizardOpen:M.setupWizardOpen,openSetupWizard:M.openSetupWizard,themeMode:C,setThemeMode:F}),de=a.useCallback(Je=>{Je==="missions"&&(ne(void 0),we(void 0),be(void 0)),V(Je)},[V]),L=S==="board"||S==="list",{tasks:Z,createTask:D,moveTask:me,deleteTask:q,mergeTask:W,retryTask:ce,updateTask:Se,duplicateTask:ve,archiveTask:Ee,unarchiveTask:Ae,archiveAllDone:Oe,loadArchivedTasks:Fe,lastFetchTimeMs:rt}=lT({...p?{projectId:p.id}:{},searchQuery:w||void 0,sseEnabled:L}),[Pe,Ie]=a.useState(!1),Be=a.useRef(performance.now()),nt=a.useRef(!1),De=a.useRef(!1),Qe=a.useMemo(()=>l?"projects":v?"project":"tasks",[l,v]);a.useEffect(()=>{if(!l&&!nt.current){nt.current=!0;const Je=`projects loaded at ${Math.round(performance.now()-Be.current)}ms from mount`;console.log(`[App] ${Je}`),Ea("[App]",Je)}if(!v&&!De.current){De.current=!0;const Je=`current-project resolved at ${Math.round(performance.now()-Be.current)}ms from mount`;console.log(`[App] ${Je}`),Ea("[App]",Je)}},[l,v]),a.useEffect(()=>{if(Pe||l||v)return;const Je=performance.now(),ot=window.setTimeout(()=>{const qn=`dashboard ready at ${Math.round(performance.now()-Be.current)}ms from mount (settle delay=${Math.round(performance.now()-Je)}ms)`;console.log(`[App] ${qn}`),Ea("[App]",qn),Ie(!0)},200);return()=>{window.clearTimeout(ot)}},[Pe,l,v]);const te=Yr()==="mobile",[fe,ae]=a.useState(0),_e=a.useCallback(()=>{gh(p?.id).then(Je=>{ae(Je.unreadCount)}).catch(Je=>{console.warn("[App] Failed to fetch mailbox unread count:",Je)})},[p?.id]);a.useEffect(()=>{_e();const Je=new URLSearchParams;p?.id&&Je.set("projectId",p.id);const ot=Je.size>0?`?${Je.toString()}`:"";return Os(`/api/events${ot}`,{events:{"message:sent":_e,"message:received":_e,"message:read":_e,"message:deleted":_e}})},[p?.id,_e]);const[ke,He]=a.useState(!1),[dt,ht]=a.useState(!1),[he,ne]=a.useState(void 0),[ye,we]=a.useState(void 0),[st,be]=a.useState(void 0),[it,Me]=a.useState(!1),[qe,oe]=a.useState(!1),[Ve,We]=a.useState(()=>In(lo,p?.id)==="true");a.useEffect(()=>{We(In(lo,p?.id)==="true")},[p?.id]),a.useEffect(()=>{const Je=()=>{oe(!0)};return window.addEventListener(go,Je),()=>{window.removeEventListener(go,Je)}},[]);const Re=a.useCallback(()=>{ms(lo,"true",p?.id),We(!0)},[p?.id]),{maxConcurrent:et,autoMerge:xt,globalPaused:wt,enginePaused:Et,taskStuckTimeoutMs:Rt,showQuickChatFAB:$t,prAuthAvailable:_t,experimentalFeatures:vt,insightsEnabled:Dt,roadmapEnabled:Ke,memoryEnabled:bt,devServerEnabled:Le,toggleAutoMerge:lt,toggleGlobalPause:xe,toggleEnginePause:U,refresh:Ne}=jT(p?.id),pt=vt.skillsView===!0,kt=vt.nodesView===!0,je=!0;a.useEffect(()=>{Object.keys(vt).length!==0&&(S==="insights"&&!Dt&&V("board"),S==="roadmaps"&&!Ke&&V("board"),S==="memory"&&!bt&&V("board"),(S==="devserver"||S==="dev-server")&&!Le&&V("board"))},[S,Dt,Ke,vt,V,je,bt,Le]),a.useEffect(()=>{ke&&!kt&&He(!1)},[ke,kt]);const{availableModels:Ge,favoriteProviders:gt,favoriteModels:qt,toggleFavoriteProvider:gn,toggleFavoriteModel:Wt}=NT();ST({projectId:p?.id,openModelOnboarding:M.openModelOnboarding,openSettings:M.openSettings});const{handleSelectProject:Rn,handleViewAllProjects:Kt,handleOpenSettings:$n,handleAddProject:bn,handleSetupComplete:on,handleModelOnboardingComplete:en,handlePauseProject:xn,handleResumeProject:wn,handleRemoveProject:Dn,handleToggleFavorite:cn,handleToggleModelFavorite:sn}=AT({setCurrentProject:b,clearCurrentProject:x,setViewMode:X,currentProject:p,refreshProjects:d,toggleFavoriteProvider:gn,toggleFavoriteModel:Wt,addToast:n,openSettings:M.openSettings,openSetupWizard:M.openSetupWizard,closeSetupWizard:M.closeSetupWizard,closeModelOnboarding:M.closeModelOnboarding}),{handleDetailClose:Vt}=wT({projectId:p?.id,projects:r,projectsLoading:l,currentProject:p,setCurrentProject:b,addToast:n,openTaskDetail:M.openDetailTask,closeTaskDetail:M.closeDetailTask}),{handleBoardQuickCreate:Nn,handleModalCreate:Un,handlePlanningTaskCreated:Sn,handlePlanningTasksCreated:Hn,handleSubtaskTasksCreated:Qn,handleGitHubImport:Q}=PT({createTask:D,onPlanningTaskCreated:M.onPlanningTaskCreated,onPlanningTasksCreated:M.onPlanningTasksCreated,onSubtaskTasksCreated:M.onSubtaskTasksCreated,addToast:n}),Ue=a.useCallback((Je,ot)=>{if(ot==="changes"){M.openDetailWithChangesTab(Je);return}M.openDetailTask(Je,ot)},[M]),R=a.useCallback(()=>{kt&&He(Je=>!Je)},[kt]),B=a.useCallback(async()=>{ht(!0);try{await d()}finally{ht(!1)}},[d]),re=a.useCallback(Je=>{we(Je),ne(void 0),V("missions")},[V]),pe=a.useCallback(Je=>{Je.type==="planning"?M.openPlanningWithSession(Je.id):Je.type==="subtask"?M.openSubtaskWithSession(Je.id):Je.type==="mission_interview"?(we(void 0),ne(Je.id),be(void 0),V("missions")):(Je.type==="milestone_interview"||Je.type==="slice_interview")&&(ne(void 0),we(void 0),be(Je.id),V("missions"))},[V,M]),ue=a.useCallback(()=>{for(const Je of G)K(Je.id)},[K,G]),Te=!l&&!v&&r.length===0&&!p&&!!o,ut=()=>Te?e.jsx(wR,{errorMessage:o??"Failed to fetch projects",isRetrying:dt,onRetry:B}):ke?e.jsx("div",{className:"nodes-management-overlay",children:e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(qT,{addToast:n,onClose:()=>He(!1)})})})}):O==="overview"?e.jsx(es,{children:e.jsx(Sw,{projects:r,loading:l,onSelectProject:Rn,onAddProject:bn,onPauseProject:xn,onResumeProject:wn,onRemoveProject:Dn,nodes:m})}):S==="skills"?pt?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(KT,{addToast:n,projectId:p?.id,onClose:()=>V("board")})})}):(V("board"),null):S==="chat"?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(VT,{addToast:n,projectId:p?.id})})}):S==="mailbox"?e.jsx(es,{children:e.jsx(xN,{projectId:p?.id,addToast:n,onUnreadCountChange:ae})}):S==="roadmaps"?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(WT,{addToast:n,projectId:p?.id})})}):S==="missions"?e.jsx(es,{children:e.jsx(hN,{isInline:!0,isOpen:!0,onClose:()=>{we(void 0),ne(void 0),be(void 0),V("board")},addToast:n,projectId:p?.id,onSelectTask:Je=>{const ot=Z.find(qn=>qn.id===Je);ot&&M.openDetailTask(ot)},availableTasks:Z.map(Je=>({id:Je.id,title:Je.title})),resumeSessionId:he,targetMissionId:ye,milestoneSliceResumeSessionId:st,onMilestoneSliceResumeFetchError:()=>be(void 0)})}):S==="agents"&&je?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(BT,{addToast:n,projectId:p?.id})})}):S==="documents"?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(UT,{projectId:p?.id,addToast:n,onOpenDetail:M.openDetailTask})})}):S==="insights"?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(HT,{projectId:p?.id,addToast:n,onClose:()=>V("board")})})}):S==="memory"?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(GT,{addToast:n,projectId:p?.id})})}):S==="devserver"||S==="dev-server"?e.jsx(es,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(JT,{addToast:n,projectId:p?.id})})}):S==="board"?e.jsx(es,{children:e.jsx(hw,{tasks:h&&k.tasks.length>0?k.tasks:Z,projectId:p?.id,maxConcurrent:et,onMoveTask:me,onOpenDetail:M.openDetailTask,addToast:n,onQuickCreate:Nn,onNewTask:M.openNewTask,onPlanningMode:M.openPlanningWithInitialPlan,onSubtaskBreakdown:M.openSubtaskBreakdown,autoMerge:xt,onToggleAutoMerge:lt,globalPaused:wt,onUpdateTask:Se,onArchiveTask:Ee,onUnarchiveTask:Ae,onDeleteTask:q,onArchiveAllDone:Oe,onLoadArchivedTasks:Fe,searchQuery:w,availableModels:Ge,onOpenDetailWithTab:Ue,favoriteProviders:gt,favoriteModels:qt,onToggleFavorite:cn,onToggleModelFavorite:sn,taskStuckTimeoutMs:Rt,onOpenMission:re,lastFetchTimeMs:rt})}):e.jsx(es,{children:e.jsx(fw,{tasks:h&&k.tasks.length>0?k.tasks:Z,projectId:p?.id,onMoveTask:me,onOpenDetail:M.openDetailTask,addToast:n,globalPaused:wt,onNewTask:M.openNewTask,onQuickCreate:Nn,onPlanningMode:M.openPlanningWithInitialPlan,onSubtaskBreakdown:M.openSubtaskBreakdown,availableModels:Ge,favoriteProviders:gt,favoriteModels:qt,onToggleFavorite:cn,onToggleModelFavorite:sn,taskStuckTimeoutMs:Rt,searchQuery:w,lastFetchTimeMs:rt})});if(!Pe)return e.jsxs(e.Fragment,{children:[e.jsx(SR,{stage:Qe}),e.jsx(ef,{toasts:t,onRemove:s})]});const Mt=!M.modelOnboardingOpen&&KP(),dn=!M.modelOnboardingOpen&&!Mt&&ta()&&!Xp();return e.jsxs(e.Fragment,{children:[e.jsx(nj,{isElectron:i,onOpenSettings:$n,onOpenGitHubImport:M.openGitHubImport,onOpenPlanning:M.openPlanning,onResumePlanning:M.resumePlanning,activePlanningSessionCount:J.length,onOpenUsage:M.openUsage,onOpenActivityLog:M.openActivityLog,onOpenMailbox:()=>de("mailbox"),mailboxUnreadCount:fe,onOpenSchedules:M.openSchedules,onOpenGitManager:M.openGitManager,onOpenNodes:R,showNodesButton:kt,onOpenWorkflowSteps:M.openWorkflowSteps,onOpenScripts:M.openScripts,onRunScript:M.runScript,onToggleTerminal:M.toggleTerminal,onOpenFiles:M.openFiles,filesOpen:M.filesOpen,globalPaused:wt,enginePaused:Et,onToggleGlobalPause:xe,onToggleEnginePause:U,view:S,onChangeView:O==="project"&&p?de:void 0,showSkillsTab:pt,showAgentsTab:je,searchQuery:w,onSearchChange:E,projects:T,currentProject:p,onSelectProject:Rn,onViewAllProjects:Kt,projectId:p?.id,mobileNavEnabled:te,availableNodes:m,currentNode:c,onSelectNode:Je=>{Je===null?f():g(Je)},isRemote:h,experimentalFeatures:{insights:Dt,roadmap:Ke,memoryView:bt,devServer:Le,devServerView:Le}}),O==="project"&&p&&!ke&&S!=="missions"&&!M.isPlanningOpen&&e.jsx(LR,{sessions:G,onResumeSession:pe,onDismissSession:K,onDismissAll:ue}),O==="project"&&p&&Mt&&e.jsx(zR,{onResume:M.openModelOnboarding}),O==="project"&&p&&dn&&e.jsx(OR,{onOpenModelOnboarding:M.openModelOnboarding,onOpenSettings:Je=>M.openSettings(Je)}),O==="project"&&p&&!j&&P&&!Ve&&e.jsx(Qp,{hasAiProvider:y,hasGithub:A,onDismiss:Re}),e.jsx("div",{className:`project-content${O==="project"&&p?" project-content--with-footer":""}${te?" project-content--with-mobile-nav":""}`,children:ut()}),O==="project"&&p&&!ke&&e.jsx($R,{tasks:h&&k.tasks.length>0?k.tasks:Z,projectId:p.id,taskStuckTimeoutMs:Rt,backgroundSessions:I,backgroundGenerating:_,backgroundNeedsInput:N,onOpenBackgroundSession:pe,onDismissBackgroundSession:K,lastFetchTimeMs:rt}),e.jsx(UR,{view:S,onChangeView:O==="project"&&p?de:()=>{},footerVisible:O==="project"&&!!p,modalOpen:M.anyModalOpen,onOpenSettings:$n,onOpenActivityLog:M.openActivityLog,onOpenMailbox:()=>de("mailbox"),mailboxUnreadCount:fe,onOpenGitManager:M.openGitManager,onOpenWorkflowSteps:M.openWorkflowSteps,onOpenSchedules:M.openSchedules,onOpenScripts:M.openScripts,onToggleTerminal:M.toggleTerminal,onOpenFiles:M.openFiles,onOpenGitHubImport:M.openGitHubImport,onOpenPlanning:M.openPlanning,onResumePlanning:M.resumePlanning,activePlanningSessionCount:J.length,onOpenUsage:M.openUsage,onViewAllProjects:Kt,onRunScript:M.runScript,projectId:p?.id,showSkillsTab:pt,experimentalFeatures:{insights:Dt,roadmap:Ke,memoryView:bt,devServer:Le,devServerView:Le}}),O==="project"&&p&&S!=="chat"&&S!=="mailbox"&&S!=="insights"&&S!=="devserver"&&S!=="dev-server"&&e.jsx(aT,{projectId:p.id,addToast:n,showFAB:$t,open:it,onOpenChange:Me,favoriteProviders:gt,favoriteModels:qt,onToggleFavorite:cn,onToggleModelFavorite:sn}),e.jsx(jR,{projectId:p?.id,tasks:Z,projects:r,currentProject:p,addToast:n,toasts:t,removeToast:s,modalManager:M,projectActions:{handleAddProject:bn,handleSetupComplete:on,handleModelOnboardingComplete:en},taskHandlers:{handleModalCreate:Un,handlePlanningTaskCreated:Sn,handlePlanningTasksCreated:Hn,handleSubtaskTasksCreated:Qn,handleGitHubImport:Q},taskOperations:{moveTask:me,deleteTask:q,mergeTask:W,retryTask:ce,duplicateTask:ve},deepLink:{handleDetailClose:Vt},settings:{prAuthAvailable:_t,themeMode:C,colorTheme:$,setThemeMode:F,setColorTheme:ee},onSettingsClose:()=>{M.closeSettings(),Ne()},onReopenOnboarding:()=>{M.closeSettings(),M.openModelOnboarding()}}),e.jsx(OT,{open:qe})]})}function XT(){return e.jsx(pT,{children:e.jsx(LT,{children:e.jsx(QT,{})})})}px();jf.createRoot(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(ex,{children:e.jsx(XT,{})})}));"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{f_ as $,Ns as A,an as B,nn as C,ln as D,rn as E,xi as F,vi as G,no as H,Ut as I,$s as J,zt as K,ct as L,OP as M,yy as N,_P as O,is as P,IP as Q,An as R,zi as S,qo as T,ky as U,$_ as V,jy as W,Lt as X,p_ as Y,jn as Z,tn as _,ms as a,aI as a$,Ar as a0,Pv as a1,pg as a2,Uo as a3,na as a4,ni as a5,si as a6,Ds as a7,_I as a8,DI as a9,Kk as aA,RI as aB,TI as aC,Gk as aD,Jk as aE,JR as aF,Yr as aG,Bo as aH,HR as aI,KR as aJ,cs as aK,fi as aL,Zs as aM,Qb as aN,W_ as aO,G_ as aP,K_ as aQ,J_ as aR,Y_ as aS,Q_ as aT,X_ as aU,Z_ as aV,eI as aW,tI as aX,nI as aY,sI as aZ,iI as a_,$I as aa,II as ab,FI as ac,On as ad,as as ae,Ub as af,Kb as ag,Ls as ah,mg as ai,Ur as aj,Ui as ak,BI as al,zI as am,OI as an,UI as ao,Cr as ap,_b as aq,Ia as ar,cg as as,Ln as at,Jm as au,oR as av,dT as aw,PI as ax,dd as ay,Da as az,q_ as b,m_ as b$,lI as b0,oI as b1,rI as b2,Mn as b3,Ho as b4,Hi as b5,MI as b6,EI as b7,AI as b8,AM as b9,Yv as bA,Qv as bB,Gv as bC,g_ as bD,Ks as bE,Xs as bF,Wr as bG,Vi as bH,Ry as bI,rx as bJ,lx as bK,xI as bL,Nb as bM,po as bN,NI as bO,SI as bP,kI as bQ,yI as bR,jI as bS,vI as bT,wI as bU,V_ as bV,Pn as bW,d_ as bX,o_ as bY,c_ as bZ,Lm as b_,Tx as ba,Hc as bb,n_ as bc,_x as bd,Dx as be,Fx as bf,r_ as bg,s_ as bh,i_ as bi,a_ as bj,Ix as bk,t_ as bl,l_ as bm,Hp as bn,v_ as bo,x_ as bp,S_ as bq,b_ as br,y_ as bs,k_ as bt,j_ as bu,w_ as bv,Xv as bw,N_ as bx,Wo as by,Jv as bz,Xe as c,h_ as c0,u_ as c1,cI as c2,uI as c3,pI as c4,mI as c5,dI as c6,hI as c7,fI as c8,dh as c9,qc as ca,Hg as cb,gI as cc,F_ as cd,T_ as ce,I_ as cf,__ as cg,O_ as ch,z_ as ci,Um as cj,P_ as ck,A_ as cl,TP as cm,D_ as cn,Ba as co,q2 as cp,E_ as cq,C_ as cr,Rv as cs,M_ as ct,R_ as cu,bI as cv,U_ as d,H_ as e,CI as f,In as g,Jn as h,ia as i,Jt as j,vy as k,B_ as l,WR as m,Wi as n,Sa as o,ge as p,mj as q,L_ as r,Os as s,mo as t,Gt as u,Fs as v,Ht as w,Sr as x,$P as y,LI as z};
|