@runfusion/fusion 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/bin.js +2188 -323
  2. package/dist/client/assets/{AgentDetailView-CDZED6Dy.css → AgentDetailView-BMrHuWGs.css} +1 -1
  3. package/dist/client/assets/{AgentDetailView-zycSdnO8.js → AgentDetailView-CkuuGA1O.js} +1 -1
  4. package/dist/client/assets/AgentsView-CWFLMIDP.js +522 -0
  5. package/dist/client/assets/AgentsView-DETxUmHS.css +1 -0
  6. package/dist/client/assets/{ChatView-BOd-sxbT.js → ChatView-C_T91ebd.js} +1 -1
  7. package/dist/client/assets/{DevServerView-09GQf34f.js → DevServerView-ChWTzTvy.js} +1 -1
  8. package/dist/client/assets/{DirectoryPicker-CcdN1Zs7.js → DirectoryPicker-BMJIT7HD.js} +1 -1
  9. package/dist/client/assets/{DocumentsView-CS8aiwtz.js → DocumentsView-CjfVl8mZ.js} +1 -1
  10. package/dist/client/assets/{InsightsView-Bu9Cv8Ol.js → InsightsView-Rb735C9_.js} +1 -1
  11. package/dist/client/assets/{MemoryView-CtqgDtV9.js → MemoryView-LLc_uNtG.js} +1 -1
  12. package/dist/client/assets/NodesView-BYVG2yY-.css +1 -0
  13. package/dist/client/assets/{NodesView-BInPcedy.js → NodesView-BviqBWRA.js} +1 -1
  14. package/dist/client/assets/{PiExtensionsManager-COxkYM2m.js → PiExtensionsManager-CriZBkQe.js} +1 -1
  15. package/dist/client/assets/{PluginManager-CXUWZBOc.js → PluginManager-BywTPbLB.js} +1 -1
  16. package/dist/client/assets/{RoadmapsView-BbCexaoi.js → RoadmapsView-Dhl--4vY.js} +1 -1
  17. package/dist/client/assets/{SetupWizardModal-Cakxqkad.js → SetupWizardModal-CVtmwoJC.js} +1 -1
  18. package/dist/client/assets/{SkillsView-D3iqYCVf.js → SkillsView-CG9y4fsE.js} +1 -1
  19. package/dist/client/assets/{folder-open-kO5Hsk66.js → folder-open-BVDq27HP.js} +1 -1
  20. package/dist/client/assets/index-CikysL-d.js +644 -0
  21. package/dist/client/assets/index-Da1qmtc7.css +1 -0
  22. package/dist/client/assets/{upload-DHBQat92.js → upload-BDvpReDO.js} +1 -1
  23. package/dist/client/index.html +2 -2
  24. package/dist/extension.js +12 -10
  25. package/package.json +4 -4
  26. package/dist/client/assets/AgentsView-DoQkkDLf.css +0 -1
  27. package/dist/client/assets/AgentsView-pO7WiBS5.js +0 -522
  28. package/dist/client/assets/NodesView-DlQZHGXA.css +0 -1
  29. package/dist/client/assets/index-BiSuUXCa.css +0 -1
  30. package/dist/client/assets/index-y194HxzU.js +0 -644
@@ -1,644 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-CXUWZBOc.js","assets/vendor-react-K0fH_qHe.js","assets/DirectoryPicker-CcdN1Zs7.js","assets/folder-open-kO5Hsk66.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/PluginManager-D64RIzmL.css","assets/PiExtensionsManager-COxkYM2m.js","assets/PiExtensionsManager-CPgmJgDk.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-Cakxqkad.js","assets/AgentsView-pO7WiBS5.js","assets/upload-DHBQat92.js","assets/AgentsView-DoQkkDLf.css","assets/DocumentsView-CS8aiwtz.js","assets/DocumentsView-Co9to4Zp.css","assets/InsightsView-Bu9Cv8Ol.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-BInPcedy.js","assets/NodesView-DlQZHGXA.css","assets/ChatView-BOd-sxbT.js","assets/RoadmapsView-BbCexaoi.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-D3iqYCVf.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-CtqgDtV9.js","assets/MemoryView-DhinauGs.css","assets/DevServerView-09GQf34f.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
2
- import{r as a,j as e,a as Na,g as Rm,R as _m,c as yf}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 Im=(...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 kf=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 jf=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=jf(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 ul={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 wf=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Nf=a.createContext({}),Sf=()=>a.useContext(Nf),Cf=a.forwardRef(({color:t,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:l,iconNode:o,...d},m)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=Sf()??{},f=i??h?Number(s??u)*24/Number(n??c):s??u;return a.createElement("svg",{ref:m,...ul,width:n??c??ul.width,height:n??c??ul.height,stroke:t??g,strokeWidth:f,className:Im("lucide",p,r),...!l&&!wf(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 Ge=(t,n)=>{const s=a.forwardRef(({className:i,...r},l)=>a.createElement(Cf,{ref:l,iconNode:n,className:Im(`lucide-${kf(_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 Ef=[["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"}]],ws=Ge("activity",Ef);/**
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 Mf=[["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"}]],Br=Ge("archive",Mf);/**
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 Af=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],za=Ge("arrow-down",Af);/**
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 Pf=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],sa=Ge("arrow-left",Pf);/**
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 Tf=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Oa=Ge("arrow-right",Tf);/**
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 Rf=[["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"}]],$m=Ge("arrow-up-down",Rf);/**
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=Ge("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 If=[["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"}]],Dm=Ge("book-open",If);/**
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 $f=[["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=Ge("bot",$f);/**
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 Df=[["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"}]],lo=Ge("box",Df);/**
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 Ff=[["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=Ge("brain",Ff);/**
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 Lf=[["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"}]],Fm=Ge("calendar",Lf);/**
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 zf=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Of=Ge("check-check",zf);/**
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 Bf=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],En=Ge("check",Bf);/**
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 Uf=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zt=Ge("chevron-down",Uf);/**
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 Hf=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],zo=Ge("chevron-left",Hf);/**
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 qf=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],ln=Ge("chevron-right",qf);/**
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 Vf=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ds=Ge("chevron-up",Vf);/**
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 Wf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],is=Ge("circle-alert",Wf);/**
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 Kf=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],tn=Ge("circle-check-big",Kf);/**
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 Gf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Ur=Ge("circle-dot",Gf);/**
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 Jf=[["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"}]],Ic=Ge("circle-question-mark",Jf);/**
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 Yf=[["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=Ge("circle-x",Yf);/**
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 Qf=[["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"}]],Xf=Ge("clipboard-list",Qf);/**
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 Zf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Hi=Ge("clock",Zf);/**
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 eg=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Lm=Ge("code",eg);/**
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 tg=[["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"}]],ng=Ge("columns-3",tg);/**
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 sg=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],qi=Ge("copy",sg);/**
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 ig=[["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"}]],ag=Ge("cpu",ig);/**
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 rg=[["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"}]],lg=Ge("download",rg);/**
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 og=[["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"}]],oo=Ge("ellipsis",og);/**
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 cg=[["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"}]],dg=Ge("external-link",cg);/**
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 ug=[["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"}]],mg=Ge("eye-off",ug);/**
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 hg=[["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"}]],Oo=Ge("eye",hg);/**
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 pg=[["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"}]],Es=Ge("file-code",pg);/**
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 fg=[["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"}]],zm=Ge("file-diff",fg);/**
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 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:"M9 15h6",key:"cctwl0"}]],bg=Ge("file-minus",gg);/**
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 xg=[["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"}]],Om=Ge("file-pen",xg);/**
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 vg=[["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"}]],yg=Ge("file-plus",vg);/**
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 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:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],jg=Ge("file-question-mark",kg);/**
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 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:"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=Ge("file-text",wg);/**
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 Ng=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"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"}]],Sg=Ge("file-type",Ng);/**
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 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"}]],Bm=Ge("file",Cg);/**
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 Eg=[["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"}]],co=Ge("folder-git-2",Eg);/**
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 Mg=[["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"}]],$c=Ge("folder-root",Mg);/**
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 Ag=[["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"}]],An=Ge("folder",Ag);/**
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 Pg=[["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=Ge("funnel",Pg);/**
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 Tg=[["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=Ge("git-branch",Tg);/**
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 Rg=[["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=Ge("git-commit-horizontal",Rg);/**
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"}]],Um=Ge("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 Ig=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],ts=Ge("git-pull-request",Ig);/**
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 $g=[["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=Ge("globe",$g);/**
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 Dg=[["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"}]],Hm=Ge("grid-3x3",Dg);/**
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 Fg=[["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"}]],Bo=Ge("grip-vertical",Fg);/**
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 Lg=[["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"}]],zg=Ge("hard-drive",Lg);/**
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 Og=[["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"}]],Bg=Ge("heart",Og);/**
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 Ug=[["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"}]],_a=Ge("history",Ug);/**
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 Hg=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],Sa=Ge("inbox",Hg);/**
328
- * @license lucide-react v1.7.0 - ISC
329
- *
330
- * This source code is licensed under the ISC license.
331
- * See the LICENSE file in the root directory of this source tree.
332
- */const qg=[["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"}]],qm=Ge("key",qg);/**
333
- * @license lucide-react v1.7.0 - ISC
334
- *
335
- * This source code is licensed under the ISC license.
336
- * See the LICENSE file in the root directory of this source tree.
337
- */const Vg=[["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=Ge("layers",Vg);/**
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 Wg=[["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=Ge("layout-grid",Wg);/**
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 Kg=[["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=Ge("lightbulb",Kg);/**
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 Gg=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],Vi=Ge("link",Gg);/**
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 Jg=[["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"}]],Yg=Ge("list-plus",Jg);/**
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 Qg=[["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"}]],Hr=Ge("list-tree",Qg);/**
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 Xg=[["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"}]],uo=Ge("list",Xg);/**
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 Zg=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],lt=Ge("loader-circle",Zg);/**
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 eb=[["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"}]],qr=Ge("lock",eb);/**
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 tb=[["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"}]],Bi=Ge("mail",tb);/**
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 nb=[["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"}]],mo=Ge("map",nb);/**
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 sb=[["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=Ge("maximize-2",sb);/**
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 ib=[["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=Ge("message-square",ib);/**
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 ab=[["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=Ge("minimize-2",ab);/**
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 rb=[["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"}]],Vr=Ge("monitor",rb);/**
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 lb=[["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"}]],Vm=Ge("moon",lb);/**
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 ob=[["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"}]],cb=Ge("move",ob);/**
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 db=[["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"}]],ho=Ge("package",db);/**
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 ub=[["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"}]],mb=Ge("paperclip",ub);/**
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 hb=[["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=Ge("pause",hb);/**
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 pb=[["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=Ge("pencil",pb);/**
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 fb=[["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=Ge("play",fb);/**
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 gb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Vt=Ge("plus",gb);/**
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 bb=[["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"}]],Wm=Ge("radio",bb);/**
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 xb=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],Mn=Ge("refresh-cw",xb);/**
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 vb=[["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"}]],yb=Ge("rocket",vb);/**
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 kb=[["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"}]],jb=Ge("rotate-ccw",kb);/**
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 wb=[["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"}]],Km=Ge("save",wb);/**
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 Nb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],zi=Ge("search",Nb);/**
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 Sb=[["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=Ge("send",Sb);/**
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 Cb=[["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=Ge("server",Cb);/**
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 Eb=[["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"}]],Mb=Ge("settings-2",Eb);/**
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 Ab=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Ia=Ge("settings",Ab);/**
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 Pb=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]],Tb=Ge("shield",Pb);/**
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 Rb=[["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=Ge("sparkles",Rb);/**
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"}]],os=Ge("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 Ib=[["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"}]],Gm=Ge("sun",Ib);/**
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 $b=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],ns=Ge("target",$b);/**
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 Db=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],zs=Ge("terminal",Db);/**
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 Fb=[["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=Ge("text-wrap",Fb);/**
533
- * @license lucide-react v1.7.0 - ISC
534
- *
535
- * This source code is licensed under the ISC license.
536
- * See the LICENSE file in the root directory of this source tree.
537
- */const Lb=[["path",{d:"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"}]],Ht=Ge("trash-2",Lb);/**
538
- * @license lucide-react v1.7.0 - ISC
539
- *
540
- * This source code is licensed under the ISC license.
541
- * See the LICENSE file in the root directory of this source tree.
542
- */const zb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Ob=Ge("trending-up",zb);/**
543
- * @license lucide-react v1.7.0 - ISC
544
- *
545
- * This source code is licensed under the ISC license.
546
- * See the LICENSE file in the root directory of this source tree.
547
- */const Bb=[["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"}]],Uo=Ge("triangle-alert",Bb);/**
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 Ub=[["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"}]],Dc=Ge("unlink",Ub);/**
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 Hb=[["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=Ge("user",Hb);/**
558
- * @license lucide-react v1.7.0 - ISC
559
- *
560
- * This source code is licensed under the ISC license.
561
- * See the LICENSE file in the root directory of this source tree.
562
- */const qb=[["path",{d:"M16 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"}]],Vb=Ge("users",qb);/**
563
- * @license lucide-react v1.7.0 - ISC
564
- *
565
- * This source code is licensed under the ISC license.
566
- * See the LICENSE file in the root directory of this source tree.
567
- */const Wb=[["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"}]],Jm=Ge("webhook",Wb);/**
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 Kb=[["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"}]],po=Ge("workflow",Kb);/**
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 Gb=[["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"}]],Jb=Ge("wrench",Gb);/**
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 Yb=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Dt=Ge("x",Yb);/**
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 Qb=[["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=Ge("zap",Qb);class Wr 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(Uo,{size:40})}),e.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&e.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),e.jsxs("div",{className:"error-boundary__actions",children:[e.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),e.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Zn({children:t,onError:n}){return e.jsx(Wr,{level:"page",onError:n,children:t})}function ui({children:t,onError:n}){return e.jsx(Wr,{level:"modal",onError:n,children:t})}function Xb({children:t,onError:n}){return e.jsx(Wr,{level:"root",onError:n,children:t})}const Zb="modulepreload",ex=function(t){return"/"+t},Fc={},en=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=ex(c),c in Fc)return;Fc[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":Zb,u||(g.as="script"),g.crossOrigin="",g.href=c,m&&g.setAttribute("nonce",m),document.head.appendChild(g),u)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function l(o){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=o,window.dispatchEvent(d),!d.defaultPrevented)throw o}return r.then(o=>{for(const d of o||[])d.status==="rejected"&&l(d.reason);return n().catch(l)})},Ho="fn.authToken",Lc="token",tx="fn_token";let Oi,zc=!1;function nx(){try{const t=window.localStorage.getItem(Ho);return t&&t.length>0?t:void 0}catch{return}}function Ym(t){try{window.localStorage.setItem(Ho,t)}catch{}}function sx(){if(!(zc||typeof window>"u")){zc=!0;try{const t=new URL(window.location.href),n=t.searchParams.get(Lc);if(!n)return;Ym(n),t.searchParams.delete(Lc);const s=t.pathname+(t.search?t.search:"")+t.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Wi(){if(Oi!==void 0)return Oi;const t=sx();if(t)return Oi=t,t;const n=nx();if(n)return Oi=n,n}function WR(t){Oi=t,Ym(t)}function KR(){Oi=void 0;try{window.localStorage.removeItem(Ho)}catch{}}function Oc(t){return t==="ws:"?"http:":t==="wss:"?"https:":t}function ix(t){return t==="http:"||t==="https:"||t==="ws:"||t==="wss:"}function ax(t){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!ix(t.protocol))return!1;const s=t.hostname===n.hostname,i=t.port===n.port,r=Oc(t.protocol)===Oc(n.protocol);return s&&i&&r}function rx(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 As(t){const n=Wi();if(!n||typeof window>"u")return t;const s=rx(t);return!s||!ax(s.parsed)?t:(s.parsed.searchParams.set(tx,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ii(t){const n=Wi();if(!n)return t;const s=new Headers(t??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function lx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Wi();const t=window.fetch.bind(window);window.fetch=function(s,i){const r=Wi();if(!r)return t(s,i);const 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 d.has("Authorization")||d.set("Authorization",`Bearer ${r}`),t(s,{...i,headers:d})}}class ox extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function cx(t){const n=t.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Yn(t){return`/api${t}`}async function B(t,n={}){const s=Yn(t),i=Wi(),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")||cx(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 ox(h?.error||`Request failed for ${s}: ${l.status} ${l.statusText}`,l.status,h?.details)}return u}function dx(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 B(`/tasks${o}`)}async function Mr(t,n){const i=Yn(X(`/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 Qm(t,n){const{title:s,description:i,column:r,dependencies:l,breakIntoSubtasks:o,enabledWorkflowSteps:d,assignedAgentId:m,modelPresetId:c,modelProvider:u,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:x,summarize:y,reviewLevel:v,executionMode:M,priority:N}=t;return B(X("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:l,breakIntoSubtasks:o,enabledWorkflowSteps:d,assignedAgentId:m,modelPresetId:c,modelProvider:u,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:x,summarize:y,reviewLevel:v,executionMode:M,priority:N})})}function Ws(t,n,s){return B(X(`/tasks/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ux(t,n,s,i,r,l,o,d){return B(X("/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 mx(t,n,s){return B(X(`/tasks/${t}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function hx(t,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return B(X(`/tasks/${t}${r}`,n),{method:"DELETE"})}function px(t,n){return B(X(`/tasks/${t}/merge`,n),{method:"POST"})}function fx(t,n){return B(X(`/tasks/${t}/retry`,n),{method:"POST"})}function gx(t,n){return B(X(`/tasks/${t}/duplicate`,n),{method:"POST"})}function bx(t,n){return B(X(`/tasks/${t}/pause`,n),{method:"POST"})}function xx(t,n){return B(X(`/tasks/${t}/unpause`,n),{method:"POST"})}function vx(t,n){return B(X(`/tasks/${t}/archive`,n),{method:"POST"})}function yx(t,n){return B(X(`/tasks/${t}/unarchive`,n),{method:"POST"})}function kx(t){return B(X("/tasks/archive-all-done",t),{method:"POST"}).then(n=>n.archived)}function jx(t,n){return B(X(`/tasks/${t}/approve-plan`,n),{method:"POST"})}function wx(t,n){return B(X(`/tasks/${t}/reject-plan`,n),{method:"POST"})}function Nx(t){return B(X("/config",t))}function Ki(t){return B(X("/settings",t))}function Ca(t,n){return B(X("/settings",n),{method:"PUT",body:JSON.stringify(t)})}function GR(t){return B(X("/memory",t))}function JR(t,n){return B(X("/memory",n),{method:"PUT",body:JSON.stringify({content:t})})}function Bc(t){return B(X("/memory/files",t))}function Sx(t,n){const s=`path=${encodeURIComponent(t)}`;return B(X(`/memory/file?${s}`,n))}function Cx(t,n,s){return B(X("/memory/file",s),{method:"PUT",body:JSON.stringify({path:t,content:n})})}function Ex(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 B(X("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function YR(t){return B(X("/memory/insights",t))}function QR(t,n){return B(X("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:t})})}function XR(t){return B(X("/memory/extract",t),{method:"POST"})}function ZR(t){return B(X("/memory/audit",t))}function e_(t){return B(X("/memory/stats",t))}function Mx(t){return B(X("/memory/backend",t))}function Ax(t){return B(X("/memory/install-qmd",t),{method:"POST"})}function Px(t,n){return B(X("/memory/test",n),{method:"POST",body:JSON.stringify({query:t})})}function ia(){return B("/settings/global")}function Kt(t){return B("/settings/global",{method:"PUT",body:JSON.stringify(t)})}function Tx(t){return B(X("/settings/scopes",t))}function t_(t){return B(X("/settings/pi-extensions",t))}function n_(t,n){return B(X("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:t})})}function Rx(t,n){return B(X("/settings/test-ntfy",n),{method:"POST",body:t?JSON.stringify(t):void 0})}function s_(){return B("/pi-settings")}async function i_(t){return B("/pi-settings",{method:"PUT",body:JSON.stringify(t)})}async function a_(t){return B("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:t})})}async function r_(t){return B(X("/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(X(`/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 _x(t,n,s){return B(X(`/tasks/${t}/attachments/${n}`,s),{method:"DELETE"})}async function Uc(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=X(`/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 Ix(t,n,s,i){return B(X(`/tasks/${t}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function $x(t,n,s){return B(X(`/tasks/${t}/comments/${n}`,s),{method:"DELETE"})}function Dx(t,n){return B(X(`/tasks/${t}/documents`,n))}function Fx(t,n,s){return B(X(`/tasks/${t}/documents/${n}/revisions`,s))}async function l_(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 B(X(r,n))}function o_(t,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return B(X(r,t))}function Hc(t,n,s,i,r){return B(X(`/tasks/${t}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Lx(t,n,s){return B(X(`/tasks/${t}/documents/${n}`,s),{method:"DELETE"})}function zx(t,n,s){return B(X(`/tasks/${t}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Ox(t,n,s){return B(X(`/tasks/${t}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Bx(t,n){return B(X(`/tasks/${t}/spec/rebuild`,n),{method:"POST"})}function Ux(t,n,s){return B(X(`/tasks/${t}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Jn(){return B("/models")}function Hx(){return B("/usage")}function qx(){return B("/providers/claude-cli/status")}function Vx(t){return B("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:t})})}function ji(){return B("/auth/status")}function Xm(t){return B("/auth/login",{method:"POST",body:JSON.stringify({provider:t})})}function Zm(t){return B("/auth/logout",{method:"POST",body:JSON.stringify({provider:t})})}function eh(t,n){return B("/auth/api-key",{method:"POST",body:JSON.stringify({provider:t,apiKey:n})})}function th(t){return B("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:t})})}function Wx(t,n,s,i){return B("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s,labels:i})})}function Kx(t,n,s,i){return B(X("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,issueNumber:s})})}function Gx(t,n,s){return B("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s})})}function Jx(t,n,s,i){return B(X("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,prNumber:s})})}function Yx(t){return B(X("/git/remotes",t))}function nh(t){return B(X("/git/remotes/detailed",t))}function Qx(t,n,s){return B(X("/git/remotes",s),{method:"POST",body:JSON.stringify({name:t,url:n})})}function Xx(t,n){return B(X(`/git/remotes/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Zx(t,n,s){return B(X(`/git/remotes/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function ev(t,n,s){return B(X(`/git/remotes/${encodeURIComponent(t)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function tv(t,n,s){return B(X(`/tasks/${t}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function nv(t,n){return B(X(`/tasks/${t}/pr/refresh`,n),{method:"POST"})}async function sv(t,n){return(await B(X("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:t})})).results}function tr(t,n,s,i){return B(X("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:t,cols:n,rows:s})})}function qc(t,n){return B(X(`/terminal/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function iv(t){return B(X("/terminal/sessions",t))}function Cs(t){return B(X("/git/status",t))}function av(t,n){const s=t?`?limit=${t}`:"";return B(X(`/git/commits${s}`,n))}function Ar(t,n){return B(X(`/git/commits/${t}/diff`,n))}function rv(t){return B(X("/git/commits/ahead",t))}function lv(t,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const l=r.size>0?`?${r.toString()}`:"";return B(X(`/git/remotes/${encodeURIComponent(t)}/commits${l}`,i))}function ca(t){return B(X("/git/branches",t))}function ov(t,n,s){const i=`?limit=${n}`;return B(X(`/git/branches/${encodeURIComponent(t)}/commits${i}`,s))}function cv(t){return B(X("/git/worktrees",t))}function dv(t,n,s){return B(X("/git/branches",s),{method:"POST",body:JSON.stringify({name:t,base:n})})}function uv(t,n){return B(X(`/git/branches/${encodeURIComponent(t)}/checkout`,n),{method:"POST"})}function Vc(t,n,s){const i=n?"?force=true":"";return B(X(`/git/branches/${encodeURIComponent(t)}${i}`,s),{method:"DELETE"})}function mv(t,n){return B(X("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:t})})}function hv(t){return B(X("/git/pull",t),{method:"POST"})}function pv(t){return B(X("/git/push",t),{method:"POST"})}function nr(t){return B(X("/git/stashes",t))}function fv(t,n){return B(X("/git/stashes",n),{method:"POST",body:JSON.stringify({message:t})})}function gv(t,n,s){return B(X(`/git/stashes/${t}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function bv(t,n){return B(X(`/git/stashes/${t}`,n),{method:"DELETE"})}function xv(t){return B(X("/git/diff",t))}function Pi(t){return B(X("/git/changes",t))}function Wc(t,n){return B(X("/git/stage",n),{method:"POST",body:JSON.stringify({files:t})})}function vv(t,n){return B(X("/git/unstage",n),{method:"POST",body:JSON.stringify({files:t})})}function Kc(t,n){return B(X("/git/commit",n),{method:"POST",body:JSON.stringify({message:t})})}function yv(t,n){return B(X("/git/discard",n),{method:"POST",body:JSON.stringify({files:t})})}function kv(t){return B(X("/workspaces",t))}function jv(t,n,s){const i=new URLSearchParams({workspace:t});return n&&i.set("path",n),s&&i.set("projectId",s),B(`/files?${i.toString()}`)}function wv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),B(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Nv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),B(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Sv(t,n,s){const i=new URLSearchParams({q:t});return n&&i.set("workspace",n),s&&i.set("projectId",s),B(`/files/search?${i.toString()}`)}function Cv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),B(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ev(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),B(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Mv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),B(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Av(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),B(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function sh(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Pv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Tv(t,n,s){return B(X("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:t,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Rv(t,n,s,i){return B(X("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function _v(t,n,s){return B(X(`/planning/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ih(t,n,s){return B(X("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Iv(t,n,s){return B(X("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function $v(t,n,s){return B(X("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Dv(t,n,s){return B(X("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:t,subtasks:n})})}const fo=new Set;if(typeof window<"u"){const t=()=>{for(const n of Array.from(fo))try{n.close()}catch{}};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t)}function Fv(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=p=>{const f=p.lastEventId;if(!f)return!0;const b=Number.parseInt(f,10);return Number.isFinite(b)?m!==null&&b<=m?!1:(m=b,!0):!0},h=()=>{if(l)return;const p=Fv(t,m),f=new EventSource(As(p));r=f,f.onopen=()=>{o=0,c=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const x=b;u(x)&&n.onMessage?.(x)};for(const[b,x]of Object.entries(n.events??{}))f.addEventListener(b,y=>{const v=y;u(v)&&x(v)});f.onerror=()=>{if(l||r!==f)return;if(f.readyState===EventSource.CONNECTING){c||(c=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),o>=i){s.onFatalError?.("Connection lost");return}c=!0,s.onConnectionStateChange?.("reconnecting"),o+=1;const 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(),fo.delete(g)},isConnected:()=>!l&&r?.readyState===EventSource.OPEN};return fo.add(g),g}function Gc(t){const n=typeof t.source=="string"&&t.source.trim().length>0?t.source.trim():"root",s=n==="root"?".":n,i=t.name,r=typeof t.packagePath=="string"&&t.packagePath.trim().length>0?t.packagePath.trim():s,l=typeof t.confidence=="number"?t.confidence:1,o=n==="root"?"root":n,d=typeof t.packageName=="string"&&t.packageName.trim().length>0?t.packageName.trim():"project";return{name:t.name,command:t.command,scriptName:i,packagePath:r,confidence:l,cwd:s,source:n,workspaceName:typeof t.packageName=="string"?t.packageName:void 0,label:`${d} · ${i} (${o})`}}function Gi(t){const n=t.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof t.previewUrl=="string"?t.previewUrl:t.detectedUrl,r=typeof t.manualPreviewUrl=="string"?t.manualPreviewUrl:t.manualUrl;return{id:typeof t.id=="string"?t.id:"",name:typeof t.name=="string"&&t.name.length>0?t.name:"default",status:s,command:typeof t.command=="string"?t.command:"",scriptName:typeof t.scriptId=="string"?t.scriptId:"",cwd:typeof t.cwd=="string"?t.cwd:"",pid:t.pid,startedAt:t.startedAt,previewUrl:i,detectedUrl:typeof t.detectedUrl=="string"?t.detectedUrl:i,detectedPort:t.detectedPort,manualPreviewUrl:r,manualUrl:typeof t.manualUrl=="string"?t.manualUrl:r,logs:Array.isArray(t.logHistory)?t.logHistory:[],exitCode:t.exitCode}}function Lv(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 zv(t){const s=(Array.isArray(t.lines)?t.lines:[]).map((i,r)=>Lv(i,r+1));return{lines:s,totalLines:typeof t.totalLines=="number"&&Number.isFinite(t.totalLines)?t.totalLines:s.length}}function Ov(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 Jc(t){return Array.isArray(t)?t.map(Gc):(t.candidates??[]).map(Gc)}async function Bv(t){try{const n=await B(X("/dev-server/candidates",t));return Jc(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await B(X("/dev-server/detect",t));return Jc(s)}throw n}}function qo(t){return B(X("/dev-server/status",t)).then(Gi)}async function c_(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 B(X(`/dev-server/logs/history${i}`,n));return zv(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const l=await qo(n);return Ov(l.logs,t)}throw r}}function Uv(t,n){const s=t.cwd??t.packagePath??".",i=t.scriptName;return B(X("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:t.command,scriptName:i,scriptId:i,cwd:s,packagePath:t.packagePath})}).then(Gi)}function Hv(t){return B(X("/dev-server/stop",t),{method:"POST"}).then(Gi)}function qv(t){return B(X("/dev-server/restart",t),{method:"POST"}).then(Gi)}async function Vv(t,n){const s=typeof t=="string"?{url:t}:t;try{const i=await B(X("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Gi(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await B(X("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Gi(r)}throw i}}function d_(t){return Yn(X("/dev-server/logs/stream",t))}async function u_(t){try{return(await B(X("/devserver",t))).sessions??[]}catch{try{const n=await qo(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 m_(t,n){try{return await B(X(`/devserver/${encodeURIComponent(t)}`,n))}catch{try{const s=await qo(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 h_(t,n){try{return await B(X(`/devserver/${encodeURIComponent(t)}/start`,n),{method:"POST"})}catch{const s=await Uv({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 p_(t,n){try{return await B(X(`/devserver/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}catch{const s=await Hv(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 f_(t,n){try{return await B(X(`/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 g_(t,n,s){try{const i=await B(X(`/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 Vv({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function b_(t){try{return(await B(X("/devserver/detect",t))).candidates??[]}catch{try{return(await Bv(t)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function x_(t,n){return Yn(X(`/devserver/${encodeURIComponent(t)}/logs/stream`,n))}function Ha(t,n,s=25e3){const i=setInterval(()=>{Ak(t,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Wv(t,n){return Yn(X(`/planning/${encodeURIComponent(t)}/stream`,n))}function Kv(t,n,s,i){const r=Wv(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 Gv(t){return B(qa("/routines",t))}function Jv(t,n){return B(qa("/routines",n),{method:"POST",body:JSON.stringify(t)})}function Yc(t,n,s){return B(qa(`/routines/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Yv(t,n){await B(qa(`/routines/${t}`,n),{method:"DELETE"})}function Qv(t,n){return B(qa(`/routines/${t}/trigger`,n),{method:"POST"})}function Qc(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 B(`/activity${s}`)}function Xv(t){const n=X("/activity",t);return B(n,{method:"DELETE"})}function Kr(t){return B(X("/workflow-steps",t))}function Xc(t,n){return B(X("/workflow-steps",n),{method:"POST",body:JSON.stringify(t)})}function Zv(t,n,s){return B(X(`/workflow-steps/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ey(t,n){return B(X(`/workflow-steps/${t}`,n),{method:"DELETE"})}function Zc(t,n){return B(X(`/workflow-steps/${t}/refine`,n),{method:"POST"})}function ty(t,n){return B(X(`/tasks/${encodeURIComponent(t)}/workflow-results`,n))}function ny(){return B("/workflow-step-templates")}function sy(t,n){return B(X(`/workflow-step-templates/${encodeURIComponent(t)}/create`,n),{method:"POST"})}function Va(t){return B(X("/scripts",t))}function iy(t,n,s){return B(X("/scripts",s),{method:"POST",body:JSON.stringify({name:t,command:n})})}function ay(t,n){return B(X(`/scripts/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function ah(t,n,s){return(await B(X("/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 rh(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 ry(t,n){return B(X("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:t})})}function ly(t,n,s){return B(X(`/subtasks/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function oy(t,n){return Yn(X(`/subtasks/${encodeURIComponent(t)}/stream`,n))}function cy(t,n,s,i){let r=null,l=null;const o=()=>{r?.stop(),r=null},d=Ua(oy(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 dy(t,n,s,i){return B(X("/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 lh(t,n,s){return B(X("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function X(t,n){if(!n)return t;const s=t.includes("?")?"&":"?";return`${t}${s}projectId=${encodeURIComponent(n)}`}function uy(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 Gr(t,n){const{nodeId:s,localNodeId:i,...r}=n??{},l=uy(t,s,i);return B(l,r)}function aa(t,n){const s=new URLSearchParams;t?.state&&s.set("state",t.state),t?.role&&s.set("role",t.role),t?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return B(`/agents${i}`)}function oh(t,n){return B(X(`/agents/${encodeURIComponent(t)}`,n))}function my(t,n){return B(X("/agents",n),{method:"POST",body:JSON.stringify(t)})}function hy(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function v_(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function y_(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function k_(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function j_(t,n){return B(X(`/agents/${encodeURIComponent(t)}/memory/files`,n))}function w_(t,n,s){const i=`path=${encodeURIComponent(n)}`;return B(X(`/agents/${encodeURIComponent(t)}/memory/file?${i}`,s))}function N_(t,n,s,i){return B(X(`/agents/${encodeURIComponent(t)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function py(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function fy(t,n){return B(X(`/agents/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function S_(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 B(`/agents/${encodeURIComponent(t)}/runs${r}`)}function C_(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}`,s))}function E_(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}/logs`,s))}function M_(t,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return B(X(`/agents/${encodeURIComponent(t)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function A_(t,n){return B(X(`/agents/${encodeURIComponent(t)}/runs/stop`,n),{method:"POST"})}function gy(t){return B(X("/agents/stats",t))}function P_(t,n){return B(X(`/agents/${encodeURIComponent(t)}/chain-of-command`,n))}function T_(t,n){const s=new URLSearchParams;t&&s.set("projectId",t),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return B(`/agents/org-tree${i?`?${i}`:""}`)}function R_(t,n){return B(X(`/agents/${encodeURIComponent(t)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function ed(t,n,s){return B(X(`/tasks/${encodeURIComponent(t)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function __(t,n){return B(X(`/agents/${encodeURIComponent(t)}/tasks`,n))}function I_(){return B("/agents/companies")}function $_(t,n){return B(X("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:t})})}function D_(t,n){return B(X("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:t})})}function F_(t,n){return B(X(`/agents/generate/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function td(t){return B(X("/backups",t))}function by(t){return B(X("/backups",t),{method:"POST"})}function xy(t,n){const s=X("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(t)}`;return B(i)}function vy(t,n,s){return B(X("/settings/import",s),{method:"POST",body:JSON.stringify({data:t,scope:n?.scope??"both",merge:n?.merge??!0})})}function nd(){return B("/projects/across-nodes")}function Ma(t,n){B("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:t,message:n})}).catch(()=>{})}function sd(){return B("/nodes")}function yy(t){return B("/nodes",{method:"POST",body:JSON.stringify(t)})}function ky(t,n){return B(`/nodes/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function jy(t){return B(`/nodes/${encodeURIComponent(t)}`,{method:"DELETE"})}async function wy(t){const n=await B(`/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 L_(t,n,s,i){const r=s&&s!==i?s:void 0,l=new URLSearchParams;t&&l.set("path",t),n&&l.set("showHidden","true"),r&&l.set("nodeId",r);const o=Wi();o&&l.set("fn_token",o);const d=l.toString(),m=`/browse-directory${d?`?${d}`:""}`;return B(m)}function Ny(t){return B("/projects",{method:"POST",body:JSON.stringify(t)})}function ch(t){return B(`/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}function id(t){return B(`/projects/${encodeURIComponent(t)}/health`)}function Sy(t){return B(X("/executor/stats",t))}function ad(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 B(`/activity-feed${s}`)}function Cy(t){return B(`/projects/${encodeURIComponent(t)}/pause`,{method:"POST"})}function Ey(t){return B(`/projects/${encodeURIComponent(t)}/resume`,{method:"POST"})}function My(){return B("/global-concurrency")}function Ay(t){return B("/global-concurrency",{method:"PUT",body:JSON.stringify(t)})}function Py(t,n){return B(`/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function dh(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 B(`/tasks/${encodeURIComponent(t)}/diff${r}`)}function Ty(t){return B(X("/missions",t))}function Ry(t,n){return B(X("/missions",n),{method:"POST",body:JSON.stringify(t)})}function uh(t,n){return B(X(`/missions/${encodeURIComponent(t)}`,n))}function _y(t,n,s){return B(X(`/missions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Iy(t,n){return B(X(`/missions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function $y(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 B(X(`/missions/${encodeURIComponent(t)}/events${r}`,s))}function Dy(t){return B(X("/missions/health",t))}function Fy(t,n,s){return B(X(`/missions/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Ly(t,n,s){return B(X(`/missions/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function zy(t,n){return B(X(`/missions/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Oy(t,n,s){return B(X(`/missions/milestones/${encodeURIComponent(t)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function By(t,n,s){return B(X(`/missions/slices/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Uy(t,n){return B(X(`/missions/slices/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Hy(t,n){return B(X(`/missions/slices/${encodeURIComponent(t)}/activate`,n),{method:"POST"})}function qy(t,n,s){return B(X(`/missions/slices/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Vy(t,n,s){return B(X(`/missions/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wy(t,n){return B(X(`/missions/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Ky(t,n,s){return B(X(`/missions/features/${encodeURIComponent(t)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Gy(t,n){return B(X(`/missions/features/${encodeURIComponent(t)}/unlink-task`,n),{method:"POST"})}function Jy(t,n,s,i){return B(X(`/missions/features/${encodeURIComponent(t)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Yy(t,n){return B(X(`/missions/slices/${encodeURIComponent(t)}/triage-all`,n),{method:"POST"})}function ml(t,n){return B(X(`/missions/milestones/${encodeURIComponent(t)}/assertions`,n))}function Qy(t,n,s){return B(X(`/missions/milestones/${encodeURIComponent(t)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(t,n,s){return B(X(`/missions/assertions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(t,n,s){return B(X(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function ek(t,n,s){return B(X(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function tk(t,n){return B(X(`/missions/assertions/${encodeURIComponent(t)}/features`,n))}function hl(t,n){return B(X(`/missions/milestones/${encodeURIComponent(t)}/validation`,n))}function rd(t,n){return B(X(`/missions/milestones/${encodeURIComponent(t)}/validation-telemetry`,n))}function nk(t,n){return B(X(`/missions/features/${encodeURIComponent(t)}/validate`,n),{method:"POST"})}function ld(t,n){return B(X(`/missions/features/${encodeURIComponent(t)}/validation-loop`,n))}function sk(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 B(X(`/missions/features/${encodeURIComponent(t)}/validation-runs${r}`,s)).then(l=>l.runs)}function ik(t,n){return B(X(`/missions/validation-runs/${encodeURIComponent(t)}`,n))}function ak(t,n){return B(X(`/missions/${encodeURIComponent(t)}/resume`,n),{method:"POST"})}function rk(t,n){return B(X(`/missions/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}function lk(t,n){return B(X(`/missions/${encodeURIComponent(t)}/start`,n),{method:"POST"})}function ok(t,n,s){return B(X(`/missions/${encodeURIComponent(t)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function ck(t,n,s){return B(X("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:t,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function dk(t,n,s,i){return B(X("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function uk(t,n,s){return B(X(`/missions/interview/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function mh(t,n,s){return B(X("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function mk(t,n,s){return B(X("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function hk(t,n,s,i){const r=Yn(X(`/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 X(`/missions/milestones/${encodeURIComponent(t)}/interview${n}`,s)}function Ka(t,n,s){return X(`/missions/slices/${encodeURIComponent(t)}/interview${n}`,s)}function pk(t,n){return B(Wa(t,"/start",n),{method:"POST"})}function fk(t,n,s,i){return B(Wa(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function gk(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 bk(t,n,s){return B(Wa(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function xk(t,n){return B(Wa(t,"/skip",n),{method:"POST"})}function vk(t,n){return B(Ka(t,"/start",n),{method:"POST"})}function yk(t,n,s,i){return B(Ka(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function kk(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 jk(t,n,s){return B(Ka(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function wk(t,n){return B(Ka(t,"/skip",n),{method:"POST"})}async function Nk(t,n){try{return await B(X(`/missions/features/${encodeURIComponent(t)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function z_(t){return B(X("/roadmaps",t))}function O_(t,n){return B(X("/roadmaps",n),{method:"POST",body:JSON.stringify(t)})}function B_(t,n){return B(X(`/roadmaps/${encodeURIComponent(t)}`,n))}function U_(t,n,s){return B(X(`/roadmaps/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function H_(t,n){return B(X(`/roadmaps/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function q_(t,n,s){return B(X(`/roadmaps/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function V_(t,n,s){return B(X(`/roadmaps/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function W_(t,n){return B(X(`/roadmaps/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function K_(t,n,s){return B(X(`/roadmaps/milestones/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function G_(t,n,s){return B(X(`/roadmaps/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function J_(t,n){return B(X(`/roadmaps/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Y_(t,n,s){return B(X(`/roadmaps/${encodeURIComponent(t)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function Q_(t,n,s){return B(X(`/roadmaps/milestones/${encodeURIComponent(t)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function X_(t,n,s,i){return B(X(`/roadmaps/features/${encodeURIComponent(t)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function Z_(t,n){return B(X(`/roadmaps/${encodeURIComponent(t)}/handoff`,n))}function eI(t,n,s,i){return B(X(`/roadmaps/${encodeURIComponent(t)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function tI(t,n,s){return B(X(`/roadmaps/milestones/${encodeURIComponent(t)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function Ji(t){if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return[]}}async function hh(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 Sk(t,n){const s=await B(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ck(t,n){return B(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Ek(t,n){return B(`/ai-sessions/${encodeURIComponent(t)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Mk(t){await fetch(Yn(`/ai-sessions/${encodeURIComponent(t)}`),{method:"DELETE",headers:ii()})}function Ak(t,n){return B(X(`/ai-sessions/${encodeURIComponent(t)}/ping`,n),{method:"POST"})}function Pk(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 B(`/messages/inbox${i}`)}function Tk(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 B(`/messages/outbox${i}`)}function ph(t){return B(X("/messages/unread-count",t))}function Rk(t,n){return B(X("/messages",n),{method:"POST",body:JSON.stringify(t)})}function _k(t,n){return B(X(`/messages/${encodeURIComponent(t)}/read`,n),{method:"POST"})}function Ik(t){return B(X("/messages/read-all",t),{method:"POST"})}function $k(t,n){return B(X(`/messages/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Dk(t,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(t)}`;return B(X(i,s))}function Fk(t,n){return B(X(`/agents/${encodeURIComponent(t)}/mailbox`,n))}function nI(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 B(`/agents/${encodeURIComponent(t)}/reflections${r}`)}function sI(t,n){return B(X(`/agents/${encodeURIComponent(t)}/reflections`,n),{method:"POST"})}function iI(t,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return B(`/agents/${encodeURIComponent(t)}/performance${r}`)}function aI(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 B(`/agents/${encodeURIComponent(t)}/ratings${r}`)}function rI(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function lI(t,n){return B(X(`/agents/${encodeURIComponent(t)}/ratings/summary`,n))}function oI(t,n,s){return B(X(`/agents/${encodeURIComponent(t)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function cI(t,n){return B(X(`/agents/${encodeURIComponent(t)}/budget`,n))}function dI(t,n){return B(X(`/agents/${encodeURIComponent(t)}/budget/reset`,n),{method:"POST"})}async function uI(t){return B(X("/plugins",t))}async function mI(t,n){return B(X("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...t})})}async function hI(t,n){return B(X(`/plugins/${encodeURIComponent(t)}/enable`,n),{method:"POST"})}async function pI(t,n){return B(X(`/plugins/${encodeURIComponent(t)}/disable`,n),{method:"POST"})}async function fI(t,n){return B(X(`/plugins/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function gI(t,n){return B(X(`/plugins/${encodeURIComponent(t)}/settings`,n))}async function bI(t,n,s){return B(X(`/plugins/${encodeURIComponent(t)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function xI(t,n){return B(X(`/plugins/${encodeURIComponent(t)}/reload`,n),{method:"POST"})}async function Lk(t){return B(X("/plugins/ui-slots",t))}async function vI(t){return(await B(X("/skills/discovered",t))).skills}async function yI(t,n,s){return B(X("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:t,enabled:n})})}async function kI(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 B(X(`/skills/catalog${r}`,s))}async function jI(t,n){return(await B(X(`/skills/${encodeURIComponent(t)}/content`,n))).content}function wI(t,n){const s=new URLSearchParams;t&&s.set("projectId",t);const i=s.toString();return B(`/chat/sessions${i?`?${i}`:""}`)}async function zk(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 B(`/chat/sessions?${l.toString()}`)).sessions[0]??null}}function Ok(t,n){return B(X("/chat/sessions",n),{method:"POST",body:JSON.stringify(t)})}function NI(t,n,s){return B(X(`/chat/sessions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function SI(t,n){return B(X(`/chat/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function od(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 B(X(`/chat/sessions/${encodeURIComponent(t)}/messages${r?`?${r}`:""}`,s))}function Bk(t,n){return B(X(`/chat/sessions/${encodeURIComponent(t)}/cancel`,n),{method:"POST"})}function Uk(t,n,s,i,r){const l=Yn(X(`/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 y=`Request failed: ${c.status}`;try{y=JSON.parse(x).error||y}catch{}s.onError?.(y);return}if(!c.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const u=c.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const b=(x,y=!1)=>{g+=x;const v=g.split(`
588
- `);g=v.pop()||"",y&&g.length>0&&(v.push(g),g="");for(const M of v){const N=M.endsWith("\r")?M.slice(0,-1):M;if(N.startsWith("event:"))p=N.slice(6).trim();else if(N.startsWith("data:")){const A=N.slice(5);f.push(A.startsWith(" ")?A.slice(1):A)}else if(N===""){const A=f.join(`
589
- `);m(p,A),p="",f=[]}}if(y&&p&&f.length>0){const M=f.join(`
590
- `);m(p,M),p="",f=[]}};for(;;){const{done:x,value:y}=await u.read();if(x){b(h.decode(),!0);break}b(h.decode(y,{stream:!0}))}}catch(c){if(c instanceof DOMException&&c.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(c instanceof Error?c.message:"Connection error")}})(),{close:()=>{d=!0,o.abort()},isConnected:()=>!d}}function CI(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 B(X(`/insights${i}`,n))}function EI(t,n){return B(X(`/insights/${encodeURIComponent(t)}/dismiss`,n),{method:"POST"})}function MI(t="manual",n,s){return B(X("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:t,inputMetadata:n})})}function AI(t){return B(X("/insights/runs",t))}function PI(t,n){return B(X(`/insights/${encodeURIComponent(t)}/create-task`,n),{method:"POST"})}function Hk({onOpenScripts:t,onRunScript:n,projectId:s}){const[i,r]=a.useState(!1),[l,o]=a.useState({}),[d,m]=a.useState(!1),[c,u]=a.useState(-1),[h,g]=a.useState(null),p=a.useRef(null),f=a.useRef(null),b=a.useRef(null),x=a.useCallback(()=>{const P=window.visualViewport;return P&&P.width>0&&P.height>0?{width:P.width,height:P.height,offsetTop:P.offsetTop,offsetLeft:P.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),y=a.useCallback(()=>{const P=f.current;if(!P)return;const C=P.getBoundingClientRect(),R=b.current,{width:O,height:Z,offsetTop:I,offsetLeft:_}=x(),j=16,Q=16,Y=6,L=R?.offsetWidth||Math.max(C.width,260),D=Math.min(L,Math.max(O-j*2,160)),U=R?.offsetHeight||280,G=Math.min(U,Math.max(Z-Q*2,160)),E=C.top-I,J=C.bottom-I,ue=C.left-_,z=Z-J,te=E,F=z<G&&te>z,fe=Math.min(Math.max(ue,j),O-j-D)+_,V=F?Math.max(Q+I,E-G-Y+I):Math.min(J+Y+I,Z+I-Q-G);g({top:V,left:fe,width:D})},[x]),v=a.useMemo(()=>Object.entries(l).sort(([P],[C])=>P.localeCompare(C)),[l]),M=v.length>0,N=v.length+(M?1:0);a.useEffect(()=>{if(!i)return;let P=!1;return m(!0),Va(s).then(C=>{P||o(C)}).catch(()=>{P||o({})}).finally(()=>{P||m(!1)}),()=>{P=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const P=C=>{p.current&&!p.current.contains(C.target)&&f.current&&!f.current.contains(C.target)&&r(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[i]),a.useEffect(()=>{if(!i)return;const P=C=>{C.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[i]),a.useEffect(()=>{if(i){u(-1);const P=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(P)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const P=requestAnimationFrame(()=>{y()});return()=>cancelAnimationFrame(P)},[i,d,v.length,M,y]),a.useEffect(()=>{if(!i)return;const P=()=>y();window.addEventListener("resize",P),window.addEventListener("scroll",P,!0);const C=window.visualViewport;return C&&(C.addEventListener("resize",P),C.addEventListener("scroll",P)),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0),C&&(C.removeEventListener("resize",P),C.removeEventListener("scroll",P))}},[i,y]);const A=a.useCallback(P=>{switch(P.key){case"ArrowDown":P.preventDefault(),u(C=>C<N-1?C+1:0);break;case"ArrowUp":P.preventDefault(),u(C=>C>0?C-1:N-1);break;case"Enter":if(P.preventDefault(),c>=0)if(c<v.length){const[C,R]=v[c];S(C,R)}else M&&c===v.length&&k();break;case"Home":P.preventDefault(),u(0);break;case"End":P.preventDefault(),u(N-1);break}},[c,N,v,M]),w=a.useCallback(()=>{r(P=>!P)},[]),S=a.useCallback((P,C)=>{n(P,C),r(!1)},[n]),k=a.useCallback(()=>{t(),r(!1)},[t]);return e.jsxs("div",{className:"quick-scripts-dropdown",ref:p,children:[e.jsxs("button",{ref:f,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick: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:A,"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(lt,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts..."})]}):v.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:v.map(([P,C],R)=>e.jsxs("button",{className:`quick-scripts-dropdown__item ${c===R?"highlighted":""}`,onClick:()=>S(P,C),role:"option","aria-selected":c===R,"data-testid":`quick-script-item-${P}`,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:P}),e.jsx("span",{className:"quick-scripts-dropdown__item-command",title:C,children:C.length>50?`${C.slice(0,50)}...`:C})]})]},P))}),e.jsx("div",{className:"quick-scripts-dropdown__footer",children:e.jsxs("button",{className:`quick-scripts-dropdown__manage ${M&&c===v.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 Vk({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 cd=new Map,Wk=6e4;function fh(t){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[l,o]=a.useState(null),d=a.useRef(!1),m=a.useRef(!1),c=a.useCallback(u=>n.filter(h=>h.slot.slotId===u),[n]);return a.useEffect(()=>{const u=t??"default";let h=!1;async function g(){const p=cd.get(u);if(p&&Date.now()<p.expiresAt){if(h||m.current)return;s(p.slots),r(!1);return}!d.current&&r(!0),o(null);try{const b=await Lk(t);if(h||m.current)return;cd.set(u,{slots:b,expiresAt:Date.now()+Wk}),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}=fh(n);if(i||r||!t)return null;const l=s(t);return l.length===0?null:e.jsx(Wr,{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 Kk(){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 Jr(){const[t,n]=a.useState(Kk);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 gh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Gk({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=gh[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(En,{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 dd({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 Jk({onOpenSettings:t,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:l,onOpenActivityLog:o,onOpenMailbox:d,mailboxUnreadCount:m=0,onOpenSchedules:c,onOpenGitManager:u,onOpenNodes:h,showNodesButton:g,onOpenWorkflowSteps:p,onOpenScripts:f,onRunScript:b,onToggleTerminal:x,onOpenFiles:y,filesOpen:v,globalPaused:M,enginePaused:N,onToggleGlobalPause:A,onToggleEnginePause:w,view:S="board",onChangeView:k,showSkillsTab:P,showAgentsTab:C,searchQuery:R="",onSearchChange:O,projects:Z=[],currentProject:I,onSelectProject:_,onViewAllProjects:j,projectId:Q,isElectron:Y=!1,mobileNavEnabled:L,availableNodes:D=[],currentNode:U,onSelectNode:G,isRemote:E=!1,experimentalFeatures:J}){const ue=Jr(),z=ue==="mobile",F=z||ue==="tablet",fe=z&&L,[V,K]=a.useState(!1),[de,we]=a.useState(!1),[ve,Se]=a.useState(!1),[Pe,Oe]=a.useState(!1),[Ie,rt]=a.useState(!1),[Ee,_e]=a.useState(!1),[Be,et]=a.useState(!1),[De,Xe]=a.useState(!1),[re,ne]=a.useState(!1),[ge,le]=a.useState({}),[Te,ye]=a.useState(!1),He=a.useRef(null),nt=a.useRef(null),mt=a.useRef(null),he=a.useRef(null),ie=a.useRef(null),be=a.useRef(null),Me=a.useRef(!1),Ze=a.useRef(null),je=a.useRef(null),tt=a.useRef(null),Ce=a.useRef(null),qe=a.useMemo(()=>D.filter(Je=>Je.type==="remote"),[D]),ce=qe.length>0,Ue=a.useMemo(()=>Object.entries(ge).sort(([Je],[pt])=>Je.localeCompare(pt)),[ge]),Ve=a.useMemo(()=>!!(J?.insights||J?.roadmap||P||J?.memoryView||J?.devServerView),[J,P]);a.useEffect(()=>{Me.current=Ie},[Ie]),a.useEffect(()=>{if(!Ie||!F)return;let Je=!1;return ye(!0),Va(Q).then(pt=>{Je||le(pt)}).catch(()=>{Je||le({})}).finally(()=>{Je||ye(!1)}),()=>{Je=!0}},[Ie,F,Q]);const Ae=V||R.length>0,We=(de||R.length>0)&&!ve,xt=(S==="board"||S==="list")&&!z&&O&&!ve&&R.length===0,yt=(S==="board"||S==="list")&&!z&&O;a.useEffect(()=>{R===""&&Se(!1)},[R]),a.useEffect(()=>{if(!Pe)return;const Je=pt=>{nt.current&&!nt.current.contains(pt.target)&&He.current&&!He.current.contains(pt.target)&&Oe(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[Pe]),a.useEffect(()=>{if(!re)return;const Je=pt=>{he.current&&!he.current.contains(pt.target)&&mt.current&&!mt.current.contains(pt.target)&&ne(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[re]),a.useEffect(()=>{if(!Ee)return;const Je=pt=>{Ze.current&&!Ze.current.contains(pt.target)&&_e(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[Ee]),a.useEffect(()=>{const Je=pt=>{if(pt.key==="Escape"){if(Xe(!1),ne(!1),Me.current){rt(!1);return}Oe(!1),K(!1),_e(!1),et(!1)}};return document.addEventListener("keydown",Je),()=>document.removeEventListener("keydown",Je)},[]),a.useEffect(()=>{if(!Be)return;const Je=pt=>{je.current&&!je.current.contains(pt.target)&&et(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[Be]),a.useEffect(()=>{if(!De)return;const Je=pt=>{tt.current&&!tt.current.contains(pt.target)&&Ce.current&&!Ce.current.contains(pt.target)&&Xe(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[De]);const Ct=a.useCallback(()=>{K(Je=>!Je)},[]),Tt=a.useCallback(()=>{we(!0),Se(!1)},[]),Et=a.useCallback(()=>{we(!1),Se(!0),O&&O("")},[O]),Mt=a.useCallback(()=>{Oe(Je=>!Je)},[]),vt=a.useCallback(Je=>{Je&&Je(),Oe(!1),rt(!1)},[]),Ft=a.useCallback(()=>{K(!1),O&&O("")},[O]);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"})]}),z&&Z.length>1&&_&&e.jsxs("div",{className:"mobile-project-switch",ref:je,children:[e.jsx("button",{className:`mobile-project-switch-trigger${Be?" mobile-project-switch-trigger--open":""}`,onClick:()=>et(Je=>!Je),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:Z.map(Je=>{const pt=I?.id===Je.id,ze=gh[Je.status]?.color;return e.jsxs("button",{className:`mobile-project-switch-item${pt?" mobile-project-switch-item--current":""}`,onClick:()=>{_(Je),et(!1)},role:"option","aria-selected":pt,"data-testid":`mobile-project-switch-item-${Je.id}`,children:[e.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:ze||"var(--text-muted)"}}),e.jsxs("div",{className:"mobile-project-switch-info",children:[e.jsx("span",{className:"mobile-project-switch-name",children:Je.name}),e.jsx("span",{className:"mobile-project-switch-path",children:Je.path.split("/").slice(-2).join("/")})]}),pt&&e.jsx(En,{size:14,className:"mobile-project-switch-check"})]},Je.id)})})]}),!F&&Z.length>=1&&j&&e.jsx(Gk,{projects:Z,currentProject:I??null,onViewAll:j,onSelectProject:_}),ce&&e.jsxs("div",{className:`header-node-selector${z?" header-node-selector--mobile":""}`,ref:z?void 0:Ze,children:[e.jsx(Vk,{node:U??null,showDetails:!z}),!z&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`btn-icon node-selector-trigger${Ee?" node-selector-trigger--open":""}`,onClick:()=>_e(Je=>!Je),title:"Switch node","aria-label":"Switch node","aria-expanded":Ee,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:e.jsx(ln,{size:12,className:`node-selector-chevron${Ee?" node-selector-chevron--open":""}`})}),Ee&&e.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[e.jsxs("button",{className:`node-selector-option${E?"":" node-selector-option--active"}`,onClick:()=>{G?.(null),_e(!1)},role:"option","aria-selected":!E,"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(Je=>e.jsxs("button",{className:`node-selector-option${U?.id===Je.id?" node-selector-option--active":""}`,onClick:()=>{G?.(Je),_e(!1)},role:"option","aria-selected":U?.id===Je.id,"data-testid":`node-option-${Je.id}`,children:[e.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${Je.status}`}),e.jsx("span",{className:"node-selector-option-label",children:Je.name}),e.jsx("span",{className:"node-selector-option-status",children:Je.status})]},Je.id))]})]})]})]}),e.jsxs("div",{className:"header-actions",children:[fe&&k&&(S==="board"||S==="list")&&e.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>k("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board","data-testid":"mobile-view-toggle-board",children:e.jsx(ki,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>k("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list","data-testid":"mobile-view-toggle-list",children:e.jsx(uo,{size:16})})]}),O&&z&&(fe||S==="board"||S==="list")&&!Ae&&e.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Ct,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:e.jsx(zi,{size:16})}),xt&&e.jsx("button",{className:"btn-icon",onClick:Tt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:e.jsx(zi,{size:16})}),z&&fe&&l&&e.jsx("button",{className:"btn-icon",onClick:l,title:"View usage","data-testid":"mobile-header-usage-btn",children:e.jsx(ws,{size:16})}),!fe&&k&&e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>k("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:e.jsx(ki,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>k("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:e.jsx(uo,{size:16})}),C&&e.jsx("button",{className:`view-toggle-btn${S==="agents"?" active":""}`,onClick:()=>k("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":S==="agents",children:e.jsx(an,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="missions"?" active":""}`,onClick:()=>k("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":S==="missions",children:e.jsx(ns,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="chat"?" active":""}`,onClick:()=>k("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":S==="chat",children:e.jsx(Zs,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="documents"?" active":""}`,onClick:()=>k("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":S==="documents",children:e.jsx(xi,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="mailbox"?" active":""}`,onClick:()=>k("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":S==="mailbox",children:e.jsx(Bi,{size:16})}),Ve&&e.jsxs(e.Fragment,{children:[e.jsx("button",{ref:Ce,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(S)?" active":""}`,onClick:()=>Xe(Je=>!Je),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:tt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[J?.insights&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="insights"?" active":""}`,onClick:()=>{k("insights"),Xe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[e.jsx(On,{size:14}),e.jsx("span",{children:"Insights"})]}),J?.roadmap&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="roadmaps"?" active":""}`,onClick:()=>{k("roadmaps"),Xe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[e.jsx(mo,{size:14}),e.jsx("span",{children:"Roadmaps"})]}),P&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="skills"?" active":""}`,onClick:()=>{k("skills"),Xe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[e.jsx(jn,{size:14}),e.jsx("span",{children:"Skills"})]}),J?.memoryView&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="memory"?" active":""}`,onClick:()=>{k("memory"),Xe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[e.jsx(Nr,{size:14}),e.jsx("span",{children:"Memory"})]}),J?.devServerView&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="dev-server"||S==="devserver"?" active":""}`,onClick:()=>{k("devserver"),Xe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[e.jsx(Vr,{size:14}),e.jsx("span",{children:"Dev Server"}),e.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]})]})]})]}),!F&&l&&e.jsx("button",{className:"btn-icon",onClick:l,title:"View usage","data-testid":"desktop-header-usage-btn",children:e.jsx(ws,{size:16})}),!F&&o&&e.jsx("button",{className:"btn-icon",onClick:o,title:"View Activity Log",children:e.jsx(_a,{size:16})}),!F&&d&&e.jsxs("button",{className:`btn-icon${m>0?" btn-icon--has-indicator":""}`,onClick:d,title:`Mailbox${m>0?` (${m} unread)`:""}`,"data-testid":"header-mailbox-btn",children:[e.jsx(Bi,{size:16}),m>0&&e.jsx("span",{className:"header-badge","data-testid":"header-mailbox-badge",children:m>9?"9+":m})]}),!F&&!Y&&e.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:e.jsx(dd,{size:16})}),!F&&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})]}),!F&&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})}),!F&&y&&e.jsx("button",{className:`btn-icon${v?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:e.jsx(An,{size:16})}),!F&&u&&e.jsx("button",{className:"btn-icon",onClick:u,title:"Git Manager","data-testid":"git-manager-btn",children:e.jsx(Fs,{size:16})}),!F&&p&&e.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:e.jsx(po,{size:16})}),!F&&f&&b&&e.jsx(Hk,{onOpenScripts:f,onRunScript:b,projectId:Q}),!F&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{ref:mt,className:"btn-icon",onClick:()=>ne(Je=>!Je),title:"More actions","aria-label":"More actions","aria-expanded":re,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:e.jsx(oo,{size:16})}),re&&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(),ne(!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),ne(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[e.jsx(Hi,{size:14}),e.jsx("span",{children:"Automation"})]})]})]}),e.jsx("button",{className:`btn-icon${N?" btn-icon--paused":""}`,onClick:w,title:N?"Resume scheduling":"Pause scheduling",disabled:!!M,children:N?e.jsx(rn,{size:16}):e.jsx($s,{size:16})}),e.jsx("button",{className:`btn-icon${M?" btn-icon--stopped":""}`,onClick:A,title:M?"Start AI engine":"Stop AI engine",children:M?e.jsx(rn,{size:16}):e.jsx(os,{size:16})}),!F&&e.jsx("button",{className:"btn-icon",onClick:t,title:"Settings",children:e.jsx(Ia,{size:16})}),e.jsx(Ga,{slotId:"header-action",projectId:Q}),F&&!fe&&e.jsx("button",{ref:He,className:"btn-icon compact-overflow-trigger",onClick:Mt,title:"More header actions","aria-label":"More header actions","aria-expanded":Pe,"aria-haspopup":"menu",children:e.jsx(oo,{size:16})}),F&&!fe&&Pe&&e.jsxs("div",{ref:nt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[Z.length>=1&&j&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(j),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[e.jsx(Hm,{size:16}),e.jsx("span",{children:"Projects"})]}),y&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[e.jsx(An,{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"})]}),!Y&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(n),role:"menuitem",children:[e.jsx(dd,{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(Je=>!Je),role:"menuitem","aria-expanded":Ie,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:e.jsx(ln,{size:14,className:`mobile-overflow-chevron${Ie?" mobile-overflow-chevron--open":""}`})})]}),Ie&&e.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Te?e.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[e.jsx(lt,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts…"})]}):Ue.length>0?e.jsxs(e.Fragment,{children:[Ue.map(([Je,pt])=>e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Je,pt),Oe(!1),rt(!1)},role:"menuitem","data-testid":`overflow-script-item-${Je}`,children:[e.jsx(rn,{size:14}),e.jsx("span",{children:Je})]},Je)),f&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>vt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Es,{size:14}),e.jsx("span",{children:"Manage Scripts…"})]})]}):f&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>vt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Es,{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(Hi,{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(_a,{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(Bi,{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(ws,{size:16}),e.jsx("span",{children:"View Usage"})]}),p&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>vt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[e.jsx(po,{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"})]})]})]})]}),yt&&We&&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:R,onChange:Je=>O(Je.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:Et,"aria-label":"Close search",children:e.jsx(Dt,{size:14})})]})}),O&&z&&Ae&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{ref:ie,className:"header-search mobile-search-expanded",children:[e.jsx(zi,{size:14,className:"header-search-icon"}),e.jsx("input",{ref:be,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:R,onChange:Je=>O(Je.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:Ft,"aria-label":"Close search",children:e.jsx(Dt,{size:14})})]})})]})}const Yk={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},Qk={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:{}},Xk=Object.freeze(Object.keys(Yk)),Zk=Object.freeze(Object.keys(Qk));function ej(t){return Xk.includes(t)}function tj(t){return Zk.includes(t)}function xe(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}const nj=["off","minimal","low","medium","high"],bi=["triage","todo","in-progress","in-review","done","archived"],Vo=["low","normal","high","urgent"],cs="normal",sj=["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"],ds={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},ij={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"},go={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 aj(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 rj(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 lj(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 bh({prInfo:t,issueInfo:n,onIssueRefresh:s}){const i=()=>{t?.url&&window.open(t.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return e.jsxs(e.Fragment,{children:[t&&e.jsxs("span",{className:`card-github-badge card-github-badge--${t.status}`,title:`PR #${t.number}: ${t.title}`,onClick:i,children:[e.jsx(ts,{size:12}),e.jsxs("span",{children:["#",t.number]})]}),n&&e.jsxs("span",{className:`card-github-badge ${lj(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[e.jsx(Ur,{size:12}),e.jsxs("span",{children:["#",n.number]})]})]})}function ir(t,n){return`${t??"default"}:${n}`}class oj{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(As(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:ud(o,"prInfo")?o.prInfo??null:m?.prInfo,issueInfo:ud(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 oj;let cj=0;function ud(t,n){return Object.prototype.hasOwnProperty.call(t,n)}function xh(t){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${cj++}`);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 Pr(t,n,s,i){return t===void 0||!n?s:!i||n>=i?t??void 0:s}function dj({taskId:t,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:l}){const{badgeUpdates:o,subscribeToBadge:d,unsubscribeFromBadge:m}=xh(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=Pr(u?.prInfo,u?.timestamp,n,n?.lastCheckedAt??i),g=Pr(u?.issueInfo,u?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:e.jsx(bh,{prInfo:h,issueInfo:g})}const uj=a.memo(dj);uj.displayName="TaskCardBadge";const vs={data:new Map,pendingPromise:null,lastFetchTime:null},mj=5e3;function kr(t,n){return n?`${n}::${t}`:t}function hj(t,n){const s=vs.data.get(kr(t,n));if(!(!s||Date.now()-s.timestamp>mj))return s}function pj(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 sv(d,t)}catch(h){c=h instanceof Error?h:new Error(String(h));const g=xe(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,u),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(c)throw c;return{}},[t]),l=a.useCallback(async d=>{if(d.length===0)return;const c=Date.now()-5e3;if(d.every(g=>{const p=vs.data.get(kr(g,t));return p&&p.timestamp>c})&&vs.lastFetchTime&&vs.lastFetchTime>c)return;if(i.current&&(clearTimeout(i.current),i.current=null),vs.pendingPromise){s(!0);try{await vs.pendingPromise}finally{s(!1)}return}s(!0);const h=r(d);vs.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))vs.data.set(kr(f,t),{result:b,timestamp:p});vs.lastFetchTime=p}catch{}finally{vs.pendingPromise=null,s(!1)}},[r,t]),o=a.useCallback(d=>vs.data.get(kr(d,t)),[t]);return{fetchBatch:l,isLoading:n,lastFetchTime:vs.lastFetchTime,getBatchData:o}}const bo=new Map,fj=3e4;function vh(t,n,s,i){return`${t}:${n??""}:${s??""}:${i??""}`}function gj(t,n,s,i){const r=vh(t,n,s,i),l=bo.get(r);return l?Date.now()>l.expiresAt?(bo.delete(r),null):l.stats:null}function bj(t,n,s,i,r){const l=vh(t,n,s,i);bo.set(l,{stats:r,expiresAt:Date.now()+fj})}function xj(t,n,s,i,r={}){const l=r.enabled??!0,o=r.worktree,d=r.stepVersion,m=r.pollIntervalMs,[c,u]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!l){u(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!o;if(!t||!p&&!f){u(null),g(!1);return}const b=f?o:void 0,x=d!==void 0?String(d):void 0;let y=!1;async function v(N=!1){if(!N){const A=gj(t,i,b,x);if(A){y||(u(A),g(!1));return}}g(!0);try{const A=await dh(t,b,i);y||(u(A.stats),bj(t,i,b,x,A.stats))}catch{y||u(null)}finally{y||g(!1)}}v();let M;return m&&f&&(M=setInterval(()=>{v(!0)},m)),()=>{y=!0,M&&clearInterval(M)}},[t,n,s,i,l,o,d,m]),{stats:c,loading:h}}const vj=new Set(["failed","stuck-killed"]);function Tr(t,n,s){if(t.column!=="in-progress"||t.status&&vj.has(t.status)||!n||n<=0)return!1;const i=new Date(t.updatedAt).getTime();return(s??Date.now())-i>n}function yj(t){switch(t){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function kj(t){return t==="done"||t==="skipped"}function jj(t,n,s){const i=s?.get(t)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||t}function yh(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:jj(m,c,n),status:c?yj(c.status):"pending",source:"workflow",phase:c?.phase??"pre-merge"}}),l=[...s,...r],o=l.length,d=l.filter(m=>kj(m.status)).length;return{total:o,completed:d,items:l}}const xo=new Map;async function wj(t,n){const s=xo.get(t);if(s)return s;try{const i=await uh(t,n);return xo.set(t,i.title),i.title}catch{return t}}const md=12;function Nj(t){return t.length<=md?t:t.slice(0,md-3)+"..."}const vo=new Map;async function Sj(t,n){const s=vo.get(t);if(s)return s;try{const i=await oh(t,n);return vo.set(t,i.name),i.name}catch{return t}}function Cj(t){return typeof t=="string"&&Vo.includes(t)?t:cs}function Ej(t,n){return t.length<=n?t:t.slice(0,n-3)+"..."}const Mj=new Set(["triage","todo"]),hd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Aj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"};function pd(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 Pj(t,n){return t.length!==n.length?!1:t.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Tj(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function Rj(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function _j(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 Ij(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 $j(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 Dj(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 Fj(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&&$j(s.attachments,i.attachments)&&Dj(s.comments,i.comments)&&Tj(s.dependencies,i.dependencies)&&Pj(s.steps,i.steps)&&Rj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Ij(s.workflowStepResults,i.workflowStepResults)&&pd(s.prInfo,i.prInfo)&&pd(s.issueInfo,i.issueInfo)}function Lj({task:t,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:l,onUpdateTask:o,onArchiveTask:d,onUnarchiveTask:m,onDeleteTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:b}){const[x,y]=a.useState(!1),[v,M]=a.useState(!1),[N,A]=a.useState(!1),[w,S]=a.useState(t.description||""),[k,P]=a.useState(!1),[C,R]=a.useState(t.column==="in-progress"||t.column==="triage"&&t.steps.some(q=>q.status==="done"||q.status==="skipped")),[O,Z]=a.useState(null),[I,_]=a.useState(null),[j,Q]=a.useState(!1),Y=a.useRef(null),L=a.useRef(!1),D=a.useRef(null),U=a.useRef(null),[G,E]=a.useState(!1),{badgeUpdates:J,subscribeToBadge:ue,unsubscribeFromBadge:z}=xh(n),te=a.useRef(null),F=a.useRef(!1),fe=a.useCallback(q=>q instanceof Element?!!q.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{S(t.description||"")},[t.id,t.description]),a.useEffect(()=>{if(!j)return;const q=$=>{U.current&&!U.current.contains($.target)&&Q(!1)};return document.addEventListener("click",q),()=>document.removeEventListener("click",q)},[j]),a.useEffect(()=>{if(!t.missionId){Z(null);return}const q=xo.get(t.missionId);if(q){Z(q);return}let $=!1;return wj(t.missionId,n).then(pe=>{$||Z(pe)}),()=>{$=!0}},[t.missionId,n]),a.useEffect(()=>{if(!t.assignedAgentId){_(null);return}const q=vo.get(t.assignedAgentId);if(q){_(q);return}_(null);let $=!1;return Sj(t.assignedAgentId,n).then(pe=>{$||_(pe)}),()=>{$=!0}},[t.assignedAgentId,n]),a.useEffect(()=>{if(N&&Y.current){const q=Y.current;q.focus(),q.style.height="auto",q.style.height=q.scrollHeight+"px"}},[N]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){E(!0);return}const q=D.current;if(!q)return;const $=new IntersectionObserver(([pe])=>{E(pe?.isIntersecting??!0)},{rootMargin:"200px"});return $.observe(q),()=>$.disconnect()},[N,t.id]);const V=a.useCallback(q=>{q.dataTransfer.setData("text/plain",t.id),q.dataTransfer.effectAllowed="move",y(!0)},[t.id]),K=a.useCallback(()=>{y(!1)},[]),de=a.useCallback(q=>q.dataTransfer.types.includes("Files"),[]),we=a.useCallback(q=>{de(q)&&(q.preventDefault(),q.stopPropagation(),q.dataTransfer.dropEffect="copy",M(!0))},[de]),ve=a.useCallback(q=>{de(q)&&(q.preventDefault(),q.stopPropagation(),M(!1))},[de]),Se=a.useCallback(async q=>{if(!de(q))return;q.preventDefault(),q.stopPropagation(),M(!1);const $=Array.from(q.dataTransfer.files);for(const pe of $)try{await $a(t.id,pe,n),r(`Attached ${pe.name} to ${t.id}`,"success")}catch(ct){r(`Failed to attach ${pe.name}: ${xe(ct)}`,"error")}},[t.id,de,r]),Pe=a.useCallback(()=>{N||i(t)},[t,i,N]),Oe=a.useCallback(q=>{if(L.current){L.current=!1;return}fe(q.target)||Pe()},[Pe,fe]),Ie=a.useCallback(q=>{const $=q.touches[0];$&&(te.current={x:$.clientX,y:$.clientY,time:Date.now()},F.current=!1)},[]),rt=a.useCallback(q=>{if(!te.current)return;const $=q.touches[0];if(!$)return;const pe=Math.abs($.clientX-te.current.x),ct=Math.abs($.clientY-te.current.y);(pe>fd||ct>fd)&&(F.current=!0)},[]),Ee=a.useCallback(q=>{if(fe(q.target)||!te.current)return;const pe=Date.now()-te.current.time<zj,ct=!F.current;pe&&ct&&(L.current=!0,Pe()),te.current=null,F.current=!1},[Pe,fe]),_e=a.useCallback(async(q,$)=>{q.stopPropagation();try{const pe=await Mr($,n);i(pe)}catch{r(`Failed to load dependency ${$}`,"error")}},[i,r]),Be=t.status==="failed",et=t.paused===!0,De=Cj(t.priority),Xe=De!==cs,re=Tr(t,h,f),ne=t.column==="triage"&&t.status==="awaiting-approval",ge=t.column==="archived",le=!l&&!s&&!Be&&!et&&!re&&!ne&&(t.column==="in-progress"||hd.has(t.status)),Te=!s&&!et&&!N&&!ge,ye=Mj.has(t.column)&&!le&&!et&&!s&&o,He=!!(t.prInfo||t.issueInfo),nt=!!(t.assignedAgentId&&I===null),mt=a.useMemo(()=>yh(t,b),[t.steps,t.enabledWorkflowSteps,t.workflowStepResults,b]),he=mt.total>0&&(t.status==="executing"||t.column==="in-progress");a.useEffect(()=>{if(!He||!G){z(t.id);return}return ue(t.id),()=>{z(t.id)}},[He,G,ue,t.id,z]);const ie=J.get(`${n??"default"}:${t.id}`),be=t.column==="in-progress"||t.column==="in-review",Me=a.useMemo(()=>t.steps.map(q=>`${q.name}:${q.status}`).join("|"),[t.steps]),{stats:Ze}=xj(t.id,t.column,t.mergeDetails?.commitSha,n,{enabled:G,worktree:t.worktree,stepVersion:be?Me:void 0,pollIntervalMs:be?3e4:void 0}),je=a.useMemo(()=>hj(t.id,n),[t.id,n]),tt=a.useMemo(()=>{const q=ie?.prInfo,$=ie?.timestamp,pe=je?.result?.prInfo,ct=je?.timestamp?new Date(je.timestamp).toISOString():void 0,bt=t.prInfo,Nt=t.prInfo?.lastCheckedAt??t.updatedAt;let Bt=Pr(q,$,bt,Nt);const Lt=$&&$>=Nt?$:Nt;return pe&&ct&&(!Lt||ct>Lt)&&(Bt=pe),Bt},[ie,je,t.prInfo,t.updatedAt]),Ce=a.useMemo(()=>{const q=ie?.issueInfo,$=ie?.timestamp,pe=je?.result?.issueInfo,ct=je?.timestamp?new Date(je.timestamp).toISOString():void 0,bt=t.issueInfo,Nt=t.issueInfo?.lastCheckedAt??t.updatedAt;let Bt=Pr(q,$,bt,Nt);const Lt=$&&$>=Nt?$:Nt;return pe&&ct&&(!Lt||ct>Lt)&&(Bt=pe),Bt},[ie,je,t.issueInfo,t.updatedAt]),qe=a.useCallback(q=>{q?.stopPropagation(),!(!ye||k)&&(A(!0),S(t.description||""))},[ye,k,t.description]),ce=a.useCallback(()=>{A(!1),S(t.description||"")},[t.description]),Ue=a.useCallback(()=>w!==(t.description||""),[w,t.description]),Ve=a.useCallback(async()=>{if(!(!o||k)){if(!Ue()){ce();return}P(!0);try{await o(t.id,{description:w.trim()||void 0}),r(`Updated ${t.id}`,"success"),A(!1)}catch(q){r(`Failed to update ${t.id}: ${xe(q)}`,"error")}finally{P(!1)}}},[o,t.id,w,k,Ue,ce,r]),Ae=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey?(q.preventDefault(),Ve()):q.key==="Escape"&&(q.preventDefault(),ce())},[Ve,ce]),We=a.useCallback(()=>{setTimeout(()=>{const q=document.activeElement;q===Y.current||q?.closest(".card-editing-content")||(Ue()?Ve():ce())},0)},[Ue,Ve,ce]),xt=a.useCallback(q=>{ye&&(q.stopPropagation(),qe(q))},[ye,qe]),yt=a.useCallback(q=>{q.stopPropagation(),qe(q)},[qe]),Ct=a.useCallback(q=>{S(q.target.value);const $=q.target;$.style.height="auto",$.style.height=$.scrollHeight+"px"},[]),Tt=a.useCallback(q=>{q.stopPropagation(),d&&d(t.id).then(()=>{r(`Archived ${t.id}`,"success")}).catch($=>{r(`Failed to archive ${t.id}: ${xe($)}`,"error")})},[r,d,t.id]),Et=a.useCallback(q=>{q.stopPropagation(),m&&m(t.id).then(()=>{r(`Unarchived ${t.id}`,"success")}).catch($=>{r(`Failed to unarchive ${t.id}: ${xe($)}`,"error")})},[r,m,t.id]),Mt=a.useCallback(q=>{q.stopPropagation(),c&&window.confirm(`Delete ${t.id}?`)&&c(t.id).then(()=>{r(`Deleted ${t.id}`,"success")}).catch($=>{const pe=_j($);if(!pe||pe.dependentIds.length===0){r(`Failed to delete ${t.id}: ${xe($)}`,"error");return}const ct=pe.dependentIds.join(", ");window.confirm(`${t.id} is a dependency of ${ct}.
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(Nt=>{r(`Failed to delete ${t.id}: ${xe(Nt)}`,"error")})})},[r,c,t.id]),vt=a.useCallback(q=>{q.stopPropagation(),u?.(t,"changes")},[t,u]),Ft=a.useCallback(q=>{q.stopPropagation(),R($=>!$)},[]),Je=a.useCallback(q=>{q.stopPropagation(),t.missionId&&g&&g(t.missionId)},[t.missionId,g]),pt=a.useCallback(q=>{q.stopPropagation(),Q($=>!$)},[]),ze=a.useCallback((q,$)=>{q.stopPropagation(),Q(!1),p&&p(t.id,$).then(()=>{r(`Moved ${t.id} to ${ds[$]}`,"success")}).catch(pe=>{r(`Failed to move ${t.id}: ${xe(pe)}`,"error")})},[r,p,t.id]),at=`card${x?" dragging":""}${s?" queued":""}${le?" agent-active":""}${Be?" failed":""}${et?" paused":""}${re?" stuck":""}${ne?" awaiting-approval":""}${v?" file-drop-target":""}${N?" card-editing":""}${k?" card-saving":""}`;return N?e.jsx("div",{ref:D,className:at,"data-id":t.id,onDoubleClick:xt,children:e.jsxs("div",{className:"card-editing-content",children:[e.jsx("textarea",{ref:Y,className:"card-edit-desc-textarea",placeholder:"Task description",value:w,onChange:Ct,onKeyDown:Ae,onBlur:We,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:D,className:at,"data-id":t.id,draggable:Te,onDragStart:Te?V:void 0,onDragEnd:Te?K:void 0,onDragOver:we,onDragLeave:ve,onDrop:Se,onClick:Oe,onTouchStart:Ie,onTouchMove:rt,onTouchEnd:Ee,onDoubleClick:xt,children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"card-id",children:t.id}),et&&e.jsx("span",{className:"card-status-badge paused",children:"paused"}),!et&&t.status&&t.status!=="queued"&&e.jsx("span",{className:`card-status-badge card-status-badge--${t.column}${ne?" awaiting-approval":""}${hd.has(t.status)?" pulsing":""}${Be?" failed":""}${re?" stuck":""}`,children:re?"Stuck":ne?"Awaiting Approval":t.status}),re&&(et||!t.status||t.status==="queued")&&e.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),He&&e.jsx(bh,{prInfo:tt,issueInfo:Ce}),Xe&&e.jsx("span",{className:`card-priority-badge card-priority-badge--${De}`,children:De}),t.missionId&&e.jsxs("span",{className:"card-mission-badge",onClick:Je,title:`Mission: ${O??t.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.jsx(ns,{size:11}),Nj(O??t.missionId)]}),e.jsxs("div",{className:"card-header-actions",children:[ye&&e.jsx("button",{className:"card-edit-btn",onClick:yt,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:Mt,title:"Delete task","aria-label":"Delete task",children:e.jsx(Ht,{size:12})}),t.column==="done"&&d&&e.jsx("button",{className:"card-archive-btn",onClick:Tt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),t.column==="archived"&&m&&e.jsx("button",{className:"card-unarchive-btn",onClick:Et,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),t.column==="in-progress"&&p&&e.jsxs("div",{className:"card-send-back",ref:U,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:pt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":j,children:["Send back",e.jsx(zt,{size:10})]}),j&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:go["in-progress"].filter(q=>q!=="in-review").map(q=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:$=>ze($,q),children:ds[q]},q))})]}),t.column==="in-review"&&p&&e.jsxs("div",{className:"card-send-back",ref:U,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:pt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":j,children:["Move",e.jsx(zt,{size:10})]}),j&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:go["in-review"].map(q=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:$=>ze($,q),children:q==="done"?"Done (no merge)":ds[q]},q))})]}),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:bd(t.title,gd)||bd(t.description,gd)||t.id}),he&&(()=>{const q=mt.completed/mt.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:`${q}%`,backgroundColor:Aj[t.column]}})}),e.jsxs("span",{className:"card-progress-label",children:[mt.completed,"/",mt.total]})]}),e.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Ft,"aria-expanded":C,"aria-label":C?"Hide steps":"Show steps",children:[e.jsxs("span",{children:[mt.total," step",mt.total===1?"":"s"]}),e.jsx(zt,{size:14,className:`card-steps-toggle-icon${C?" expanded":""}`})]}),C&&e.jsx("div",{className:"card-steps-list",children:mt.items.map($=>e.jsxs("div",{className:"card-step-item",children:[e.jsx("span",{className:`card-step-dot card-step-dot--${$.status}`,"aria-hidden":"true"}),e.jsx("span",{className:`card-step-name${$.status==="done"?" completed":""}`,children:$.name}),$.source==="workflow"&&e.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${$.phase}`,title:"Workflow check",children:"workflow"})]},$.id))})]})})(),t.worktree&&(t.column==="in-progress"||t.column==="in-review")&&(()=>{const q=Ze?.filesChanged;return q==null||q===0?null:e.jsxs("button",{type:"button",className:"card-session-files",onClick:vt,disabled:!u,children:[e.jsx(An,{size:12}),e.jsxs("span",{children:[q," ",q===1?"file":"files"," changed"]})]})})(),t.column==="done"&&(()=>{const q=Ze?.filesChanged,$=t.mergeDetails?.filesChanged,pe=q??$;if(pe!=null&&pe>0)return e.jsxs("button",{type:"button",className:"card-session-files",onClick:vt,disabled:!u,children:[e.jsx(An,{size:12}),e.jsxs("span",{children:[pe," ",pe===1?"file":"files"," changed"]})]});const ct=t.modifiedFiles?.length;return ct!=null&&ct>0?e.jsxs("button",{type:"button",className:"card-session-files",onClick:vt,disabled:!u,children:[e.jsx(An,{size:12}),e.jsxs("span",{children:[ct," ",ct===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(q=>e.jsxs("span",{className:"card-dep-badge clickable",onClick:$=>void _e($,q),title:`Click to view ${q}`,children:[e.jsx(Vi,{size:12,style:{verticalAlign:"middle"}})," ",q]},q))}),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(Hi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),t.assignedAgentId&&e.jsx("div",{className:"card-agent-row",children:e.jsxs("span",{className:`card-agent-badge${nt?" 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:Ej(I??t.assignedAgentId,15)})]})}),e.jsx(Ga,{slotId:"task-card-badge",projectId:n})]})}const fd=10,zj=300,gd=140;function bd(t,n){return t?t.length>n?t.slice(0,n)+"…":t:""}const Rr=a.memo(Lj,Fj);Rr.displayName="TaskCard";function Oj({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(Xf,{size:14}):e.jsx(Fs,{size:14})}),e.jsx("span",{className:"worktree-label",children:t})]}),n.map(p=>e.jsx(Rr,{task:p,projectId:i,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id)),s.map(p=>e.jsx(Rr,{task:p,projectId:i,queued:!0,onOpenDetail:r,addToast:l,globalPaused:o,onUpdateTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:c,onOpenMission:u,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id))]})}const kh=a.memo(Oj);kh.displayName="WorktreeGroup";function xd(t){return t.toLowerCase().replace(/[-_./]/g,"")}function Bj(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 Uj(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 Hj(t,n){const s=xd(t),i=xd(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&&Bj(s,l)||s.length>=4&&Uj(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=>Hj(l,r))})}const Vj={sm:16,md:20,lg:24};function Wj({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 vd({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 yd({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 Kj({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 Gj({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 Jj({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 kd({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 Yj({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 Qj={anthropic:{component:Wj,color:"#d4a27f"},"claude-cli":{component:Yj,color:"#d4a27f",label:"Anthropic — via Claude CLI"},openai:{component:vd,color:"#10a37f"},"openai-codex":{component:vd,color:"#10a37f",label:"OpenAI Codex"},google:{component:yd,color:"#4285f4"},gemini:{component:yd,color:"#4285f4"},ollama:{component:Kj,color:"#fff"},minimax:{component:Gj,color:"#E73562"},zai:{component:Jj,color:"#1A6DFF"},kimi:{component:kd,color:"#6C5CE7"},moonshot:{component:kd,color:"#6C5CE7"}};function ss({provider:t,size:n="sm"}){const s=t.toLowerCase(),i=Qj[s],r=i?.component,l=i?.color??"var(--text-muted)",o=i?.label,d=Vj[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(ag,{size:d})})}function Gt({models:t,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:l,label:o,favoriteProviders:d=[],onToggleFavorite:m,favoriteModels:c=[],onToggleModelFavorite:u,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[b,x]=a.useState(""),[y,v]=a.useState(0),[M,N]=a.useState(null),[A,w]=a.useState(null),S=a.useRef(null),k=a.useRef(null),P=a.useRef(null),C=a.useRef(null),R=a.useRef(null),O=a.useMemo(()=>qj(t,b),[t,b]),Z=a.useMemo(()=>O.reduce((K,de)=>((K[de.provider]??=[]).push(de),K),{}),[O]),I=a.useMemo(()=>{const K=[];for(const de of c){const we=de.indexOf("/");if(we===-1)continue;const ve=de.slice(0,we),Se=de.slice(we+1),Pe=O.find(Oe=>Oe.provider===ve&&Oe.id===Se);Pe&&K.push({model:Pe,fullId:de})}return K},[c,O]),_=a.useMemo(()=>{const K=Object.entries(Z),de=new Set(d);return K.sort(([we],[ve])=>{const Se=de.has(we),Pe=de.has(ve);if(Se&&!Pe)return-1;if(!Se&&Pe)return 1;if(Se&&Pe){const Oe=d.indexOf(we),Ie=d.indexOf(ve);if(Oe!==Ie)return Oe-Ie}return we.localeCompare(ve)})},[Z,d]),j=typeof h=="string"&&h.length>0,Q=a.useMemo(()=>{if(!n||j&&n===h)return null;const K=n.indexOf("/");return K===-1?null:n.slice(0,K)},[j,h,n]),Y=a.useMemo(()=>{const K=[];return j&&K.push({type:"no-change",value:h,label:g}),K.push({type:"default",value:"",label:"Use default"}),K},[j,g,h]),L=a.useMemo(()=>{const K=[...Y];for(const{model:de,fullId:we}of I)K.push({type:"favorite",value:we,label:de.name,provider:de.provider});return _.forEach(([de,we])=>{K.push({type:"provider",value:`__group_${de}`,label:de,provider:de}),we.forEach(ve=>{K.push({type:"model",value:`${ve.provider}/${ve.id}`,label:ve.name,provider:ve.provider})})}),K},[I,_,Y]),D=a.useMemo(()=>{if(j&&n===h)return g;if(!n)return"Use default";const K=n.indexOf("/");if(K===-1)return n;const de=n.slice(0,K),we=n.slice(K+1);return t.find(Se=>Se.provider===de&&Se.id===we)?.name||n},[j,g,h,n,t]),U=a.useMemo(()=>L.findIndex(K=>K.value===n),[L,n]),G=a.useCallback(()=>{const K=window.visualViewport;return K&&K.height>0&&K.width>0?{width:K.width,height:K.height,offsetTop:K.offsetTop,offsetLeft:K.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),E=a.useCallback(()=>{const{height:K}=G(),de=typeof window.matchMedia=="function",we=de?window.matchMedia("(max-width: 640px)").matches:!1,ve=de?window.matchMedia("(max-width: 768px)").matches:!1;return K<=0?320:we?Math.min(K*.6,360):ve?Math.min(K*.7,420):320},[G]),J=a.useCallback(()=>{const K=k.current;if(!K)return;const de=K.getBoundingClientRect(),{width:we,height:ve,offsetTop:Se,offsetLeft:Pe}=G(),Oe=16,Ie=16,rt=4,Ee=E(),_e=de.bottom-Se,Be=de.top-Se,et=de.left-Pe,De=ve-_e,Xe=Be,re=Math.max(De-Ie-rt,160),ne=Math.max(Xe-Ie-rt,160),ge=De<Ee&&Xe>De,le=Math.max(Math.min(ge?ne:re,Ee),160),Te=Math.min(de.width,we-Oe*2),ye=Math.min(Math.max(et,Oe),we-Oe-Te)+Pe,He=ge?Math.max(Ie+Se,Be-le-rt+Se):Math.min(_e+rt+Se,ve+Se-Ie-le);N({top:He,left:ye,width:Te,maxHeight:le})},[G,E]);a.useEffect(()=>{w(document.body)},[]),a.useEffect(()=>{if(p){const K=L.findIndex((de,we)=>we>=(U>=0?U:0)&&de.type!=="provider");v(K>=0?K:0)}},[p,L,U]),a.useEffect(()=>{if(!p)return;J();const K=requestAnimationFrame(()=>C.current?.focus());return()=>cancelAnimationFrame(K)},[p,J]),a.useEffect(()=>{if(!p)return;const K=()=>J();window.addEventListener("resize",K),window.addEventListener("scroll",K,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",K),de.addEventListener("scroll",K)),()=>{window.removeEventListener("resize",K),window.removeEventListener("scroll",K,!0),de&&(de.removeEventListener("resize",K),de.removeEventListener("scroll",K))}},[p,J]),a.useEffect(()=>{if(!p)return;const K=de=>{const we=de.target,ve=S.current?.contains(we),Se=P.current?.contains(we);!ve&&!Se&&(f(!1),x(""))};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[p]);const ue=a.useCallback(K=>{switch(K.key){case"ArrowDown":if(K.preventDefault(),!p)f(!0);else{let de=y;for(let we=1;we<=L.length;we++){const ve=(y+we)%L.length;if(L[ve]?.type!=="provider"){de=ve;break}}v(de)}break;case"ArrowUp":if(K.preventDefault(),p){let de=y;for(let we=1;we<=L.length;we++){const ve=(y-we+L.length)%L.length;if(L[ve]?.type!=="provider"){de=ve;break}}v(de)}break;case"Enter":if(K.preventDefault(),p){const de=L[y];de&&de.type!=="provider"&&de.type!=="favorite"&&(s(de.value),f(!1),x(""))}else f(!0);break;case"Escape":K.preventDefault(),f(!1),x("");break;case"Tab":p&&(f(!1),x(""));break}},[p,y,L,s]),z=a.useCallback(K=>{s(K),f(!1),x("")},[s]),te=a.useCallback(()=>{x(""),C.current?.focus()},[]),F=a.useCallback(()=>{r||f(K=>!K)},[r]);a.useEffect(()=>{if(p&&R.current){const K=R.current.querySelector(`[data-index="${y}"]`);K&&typeof K.scrollIntoView=="function"&&K.scrollIntoView({block:"nearest"})}},[y,p]);const fe=b.length>0,V=p&&M?e.jsxs("div",{ref:P,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ue,style:{top:`${M.top}px`,left:`${M.left}px`,width:`${M.width}px`,maxHeight:`${M.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:K=>x(K.target.value),onClick:K=>K.stopPropagation()}),fe&&e.jsx("button",{type:"button",className:"model-combobox-clear",onClick:te,"aria-label":"Clear filter",children:"×"})]}),e.jsxs("div",{className:"model-combobox-results-count",children:[O.length," model",O.length!==1?"s":""]}),e.jsxs("div",{ref:R,className:"model-combobox-list",children:[Y.map((K,de)=>e.jsx("div",{"data-index":de,className:`model-combobox-option ${y===de?"model-combobox-option--highlighted":""} ${n===K.value?"model-combobox-option--selected":""}`,onClick:()=>z(K.value),onMouseEnter:()=>v(de),role:"option","aria-selected":n===K.value,children:e.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:K.label})},`${K.type}-${K.value}`)),I.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-combobox-divider"}),I.map(({model:K,fullId:de},we)=>{const ve=we+Y.length,Se=y===ve,Pe=n===de;return e.jsxs("div",{"data-index":ve,className:`model-combobox-option model-combobox-option--favorite ${Se?"model-combobox-option--highlighted":""} ${Pe?"model-combobox-option--selected":""}`,onClick:()=>z(de),onMouseEnter:()=>v(ve),role:"option","aria-selected":Pe,children:[e.jsx(ss,{provider:K.provider,size:"sm"}),e.jsx("span",{className:"model-combobox-option-text",children:K.name}),e.jsx("span",{className:"model-combobox-option-id",children:K.id}),u&&e.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Oe=>{Oe.stopPropagation(),u(de)},title:"Remove from favorites","aria-label":`Remove ${K.name} from favorites`,children:"★"})]},de)}),e.jsx("div",{className:"model-combobox-divider"})]}),_.map(([K,de])=>{const we=L.findIndex(Pe=>Pe.value===`__group_${K}`),ve=d.includes(K),Se=de.filter(Pe=>{const Oe=`${Pe.provider}/${Pe.id}`;return!c.includes(Oe)});return Se.length===0?null:e.jsxs("div",{className:"model-combobox-group",children:[e.jsxs("div",{className:"model-combobox-optgroup","data-index":we,children:[e.jsx(ss,{provider:K,size:"sm"}),e.jsx("span",{className:"model-combobox-optgroup-text",children:K}),m&&e.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ve?"model-combobox-optgroup-favorite--active":""}`,onClick:Pe=>{Pe.stopPropagation(),m(K)},title:ve?"Remove from favorites":"Add to favorites","aria-label":ve?`Remove ${K} from favorites`:`Add ${K} to favorites`,children:"★"})]}),Se.map(Pe=>{const Oe=`${Pe.provider}/${Pe.id}`,Ie=L.findIndex(Be=>Be.value===Oe),rt=y===Ie,Ee=n===Oe,_e=c.includes(Oe);return e.jsxs("div",{"data-index":Ie,className:`model-combobox-option ${rt?"model-combobox-option--highlighted":""} ${Ee?"model-combobox-option--selected":""}`,onClick:()=>z(Oe),onMouseEnter:()=>v(Ie),role:"option","aria-selected":Ee,children:[e.jsx("span",{className:"model-combobox-option-text",children:Pe.name}),e.jsx("span",{className:"model-combobox-option-id",children:Pe.id}),u&&e.jsx("button",{type:"button",className:`model-combobox-option-favorite ${_e?"model-combobox-option-favorite--active":""}`,onClick:Be=>{Be.stopPropagation(),u(Oe)},title:_e?"Remove from favorites":"Add to favorites","aria-label":_e?`Remove ${Pe.name} from favorites`:`Add ${Pe.name} to favorites`,children:_e?"★":"☆"})]},Oe)})]},K)}),O.length===0&&fe&&e.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:S,className:"model-combobox",onKeyDown:ue,children:e.jsxs("button",{ref:k,type:"button",id:l,className:"model-combobox-trigger",onClick:F,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":o,children:[Q&&e.jsx("span",{className:"model-combobox-trigger-icon",children:e.jsx(ss,{provider:Q,size:"sm"})}),e.jsx("span",{className:"model-combobox-trigger-text",children:D||i}),e.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),A&&V?Na.createPortal(V,A):null]})}function Wo(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(Wo(t,n))}function us(t,n,s){typeof window>"u"||window.localStorage.setItem(Wo(t,s),n)}function Da(t,n){typeof window>"u"||window.localStorage.removeItem(Wo(t,n))}const da="kb-quick-entry-text",Xj=["image/png","image/jpeg","image/gif","image/webp"];function pl(t,n){return t&&n?`${t}/${n}`:""}function fl(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 jh({onCreate:t,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:l,projectId:o,autoExpand:d=!0,favoriteProviders:m,favoriteModels:c,onToggleFavorite:u,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&In(da,o)||""),[f,b]=a.useState(!1),[x,y]=a.useState(!1),[v,M]=a.useState(!1),N=a.useRef(null),A=a.useRef(null),w=a.useRef(!1),S=a.useRef(o),[k,P]=a.useState([]),C=a.useRef([]),[R,O]=a.useState([]),[Z,I]=a.useState(!1),[_,j]=a.useState(""),[Q,Y]=a.useState(null),[L,D]=a.useState([]),[U,G]=a.useState(void 0),[E,J]=a.useState(!1),[ue,z]=a.useState(!1),[te,F]=a.useState(!1),[fe,V]=a.useState(null),[K,de]=a.useState(void 0),[we,ve]=a.useState(void 0),[Se,Pe]=a.useState(void 0),[Oe,Ie]=a.useState(void 0),[rt,Ee]=a.useState(void 0),[_e,Be]=a.useState(void 0),et=a.useRef(null),De=a.useRef(null),Xe=a.useRef(null),re=a.useRef(null),[ne,ge]=a.useState(null),[le,Te]=a.useState(null),ye=a.useRef(null),He=a.useRef(null),[nt,mt]=a.useState(null),[he]=a.useState(()=>typeof document<"u"?document.body:null),[ie,be]=a.useState(!1),[Me,Ze]=a.useState(null),[je,tt]=a.useState(i??[]),[Ce,qe]=a.useState([]),[ce,Ue]=a.useState([]),[Ve,Ae]=a.useState(null),[We,xt]=a.useState(void 0),[yt,Ct]=a.useState(!1),[Tt,Et]=a.useState(!1),[Mt,vt]=a.useState(!1),Ft=a.useRef(null),Je=a.useRef(null),[pt,ze]=a.useState(null),at=m??Ce,q=c??ce,$=!t;a.useEffect(()=>{if(i)tt(i),be(!1),Ze(null);else{let oe=!1;return be(!0),Ze(null),Jn().then($e=>{oe||(tt($e.models),m||qe($e.favoriteProviders),c||Ue($e.favoriteModels))}).catch($e=>{oe||Ze(xe($e)||"Failed to load models")}).finally(()=>{oe||be(!1)}),Ki(o).then($e=>{oe||Ae($e)}).catch(()=>{}),()=>{oe=!0}}},[i,m,c,o]);const pe=pl(K,we),ct=pl(Se,Oe),bt=pl(rt,_e),Nt=!!(K&&we),Bt=!!(Se&&Oe),Lt=!!(rt&&_e),wn=Number(Nt)+Number(Bt)+Number(Lt),hn=We?Ve?.modelPresets?.find(oe=>oe.id===We)?.name??"Models":wn>0?`${wn} model${wn===1?"":"s"}`:"Models",nn=a.useCallback((oe,$e)=>{if(!oe||!$e)return"Using default";const ot=je.find(jt=>jt.provider===oe&&jt.id===$e);return ot?`${ot.provider}/${ot.id}`:`${oe}/${$e}`},[je]);a.useEffect(()=>{p(In(da,o)||"")},[o]),a.useEffect(()=>{typeof window<"u"&&us(da,g,o)},[g,o]),a.useEffect(()=>{S.current!==o&&(S.current=o,D([]),G(void 0),Y(null),J(!1),ge(null))},[o]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{C.current=k},[k]),a.useEffect(()=>()=>{C.current.forEach(oe=>URL.revokeObjectURL(oe.previewUrl))},[]);const Pn=a.useCallback(()=>{const oe=N.current;if(!oe)return;oe.style.height="auto";const $e=Math.min(oe.scrollHeight,200);oe.style.height=`${$e}px`},[]);a.useEffect(()=>{x&&Pn()},[g,x,Pn]),a.useEffect(()=>{if(!f&&g===""&&N.current){const oe=setTimeout(()=>{N.current?.focus()},0);return()=>clearTimeout(oe)}},[f,g]),a.useEffect(()=>{Z||j("")},[Z]),a.useEffect(()=>{if(!Tt)return;const oe=$e=>{const ot=$e.target,jt=Ft.current?.contains(ot),St=Je.current?.contains(ot);!jt&&!St&&Et(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[Tt]),a.useEffect(()=>{if(!te)return;const oe=$e=>{const ot=$e.target,jt=et.current?.contains(ot),St=De.current?.contains(ot),cn=ot instanceof Element&&ot.closest?.(".model-combobox-dropdown--portal")!=null;!jt&&!St&&!cn&&(F(!1),V(null))};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[te]),a.useEffect(()=>{if(!E)return;const oe=$e=>{const ot=$e.target;Xe.current?.contains(ot)||re.current?.contains(ot)||(J(!1),ge(null))};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[E]);const on=a.useCallback(()=>{k.forEach(oe=>URL.revokeObjectURL(oe.previewUrl)),P([]),A.current&&(A.current.value=""),p(""),O([]),Y(null),J(!1),ge(null),de(void 0),ve(void 0),Pe(void 0),Ie(void 0),Ee(void 0),Be(void 0),xt(void 0),Ct(!1),I(!1),F(!1),Te(null),V(null),Et(!1),vt(!1),y(!1),M(!1),w.current=!0,N.current&&(N.current.style.height="auto"),typeof window<"u"&&Da(da,o)},[k,o]),Un=a.useCallback(oe=>{if(!oe||oe.length===0)return;const $e=[];for(let ot=0;ot<oe.length;ot++){const jt=oe[ot];Xj.includes(jt.type)&&$e.push({file:jt,previewUrl:URL.createObjectURL(jt)})}$e.length>0&&P(ot=>[...ot,...$e])},[]),gn=a.useCallback(oe=>{f||Un(oe.clipboardData?.files)},[Un,f]),Zt=a.useCallback(oe=>{P($e=>{const ot=$e[oe];return ot&&URL.revokeObjectURL(ot.previewUrl),$e.filter((jt,St)=>St!==oe)})},[]),Wt=a.useCallback(async()=>{const oe=g.trim();if(!(!oe||f||!t)){b(!0);try{const $e=await t({description:oe,column:"triage",dependencies:R.length?R:void 0,...Q?{assignedAgentId:Q}:{},modelPresetId:We,modelProvider:Nt?K:void 0,modelId:Nt?we:void 0,validatorModelProvider:Bt?Se:void 0,validatorModelId:Bt?Oe:void 0,planningModelProvider:Lt?rt:void 0,planningModelId:Lt?_e:void 0,...yt?{executionMode:"fast"}:{}});if($e&&k.length>0){const ot=[];for(const jt of k)try{await $a($e.id,jt.file,o)}catch{ot.push(jt.file.name)}ot.length>0&&n(`Failed to upload: ${ot.join(", ")}`,"error")}on()}catch($e){n(xe($e)||"Failed to create task","error")}finally{b(!1)}}},[g,f,t,R,Q,Nt,K,we,Bt,Se,Oe,Lt,rt,_e,k,o,n,on,yt]),Tn=a.useCallback(oe=>{if(oe.key==="Enter"){if(oe.shiftKey&&x)return;oe.preventDefault(),Wt()}else if(oe.key==="Escape"){if(oe.preventDefault(),fe){V(null);return}if(te){F(!1),Te(null);return}if(Z){I(!1);return}if(Tt){Et(!1);return}if(E){J(!1),ge(null);return}g.trim()&&(p(""),N.current&&(N.current.style.height="auto"),typeof window<"u"&&Da(da,o)),y(!1),M(!1),N.current?.blur()}},[Wt,g,x,Z,E,te,fe,Tt,o,M]),bn=a.useCallback(()=>{w.current&&(w.current=!1)},[]),sn=a.useCallback(()=>{d&&y(!0)},[d]),Hn=a.useCallback(oe=>{O($e=>$e.includes(oe)?$e.filter(ot=>ot!==oe):[...$e,oe])},[]),xn=a.useCallback(()=>{const oe=window.visualViewport;return oe&&oe.width>0&&oe.height>0?{width:oe.width,height:oe.height,offsetTop:oe.offsetTop,offsetLeft:oe.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),qt=a.useCallback(()=>{const oe=et.current;if(!oe)return;const $e=oe.getBoundingClientRect(),{width:ot,height:jt,offsetTop:St,offsetLeft:cn}=xn(),dn=16,mn=16,fn=4,vn=ot<=768,Sn=Math.min(vn?jt*.6:jt*.5,360),rs=vn?Math.min(ot-dn*2,360):Math.max($e.width,240),Vn=Math.min(rs,Math.max(ot-dn*2,200)),Cn=$e.top-St,Rn=$e.bottom-St,Qn=$e.left-cn,yn=jt-Rn,Wn=Cn,ps=Math.max(yn-mn-fn,160),Xn=Math.max(Wn-mn-fn,160),fs=yn<Sn&&Wn>yn,Fn=Math.max(Math.min(fs?Xn:ps,Sn),160),ae=Math.min(Math.max(Qn,dn),ot-dn-Vn)+cn,Qe=fs?Math.max(mn+St,Cn-Fn-fn+St):Math.min(Rn+fn+St,jt+St-mn-Fn);Te({top:Qe,left:ae,width:Vn,maxHeight:Fn})},[xn]),$n=a.useCallback(()=>{const oe=Ft.current?.querySelector(".refine-button");if(!oe)return;const $e=oe.getBoundingClientRect(),{width:ot,height:jt,offsetTop:St,offsetLeft:cn}=xn(),dn=8,mn=12,fn=4,vn=Math.min(200,Math.max(jt-mn*2,160)),Sn=Math.min(200,ot-dn*2),rs=$e.top-St,Vn=$e.bottom-St,Cn=$e.left-cn,Rn=jt-Vn,Qn=rs,yn=Rn<vn&&Qn>Rn,Wn=Math.min(Math.max(Cn,dn),ot-dn-Sn)+cn,ps=yn?Math.max(mn+St,rs-vn-fn+St):Math.min(Vn+fn+St,jt+St-mn-vn);ze({top:ps,left:Wn})},[xn]),qn=a.useCallback(()=>{const oe=ye.current;if(!oe)return;const $e=oe.getBoundingClientRect(),{width:ot,height:jt,offsetTop:St,offsetLeft:cn}=xn(),dn=16,mn=16,fn=4,vn=ot<=768,Sn=Math.min(vn?jt*.6:jt*.5,320),rs=vn?Math.min(ot-dn*2,360):Math.max($e.width,280),Vn=Math.min(rs,Math.max(ot-dn*2,240)),Cn=$e.top-St,Rn=$e.bottom-St,Qn=$e.left-cn,yn=jt-Rn,Wn=Cn,ps=Math.max(yn-mn-fn,200),Xn=Math.max(Wn-mn-fn,200),fs=yn<Sn&&Wn>yn,Fn=Math.max(Math.min(fs?Xn:ps,Sn),200),ae=Math.min(Math.max(Qn,dn),ot-dn-Vn)+cn,Qe=fs?Math.max(mn+St,Cn-Fn-fn+St):Math.min(Rn+fn+St,jt+St-mn-Fn);mt({top:Qe,left:ae,width:Vn,maxHeight:Fn})},[xn]),Nn=a.useCallback(()=>{const oe=Xe.current?.querySelector("button");if(!oe)return;const $e=oe.getBoundingClientRect(),{width:ot,height:jt,offsetTop:St,offsetLeft:cn}=xn(),dn=16,mn=16,fn=4,vn=ot<=768,Sn=Math.min(vn?jt*.6:jt*.5,320),rs=vn?Math.min(ot-dn*2,280):Math.max($e.width,240),Vn=Math.min(rs,Math.max(ot-dn*2,200)),Cn=$e.top-St,Rn=$e.bottom-St,Qn=$e.left-cn,yn=jt-Rn,Wn=Cn,ps=Math.max(yn-mn-fn,160),Xn=Math.max(Wn-mn-fn,160),fs=yn<Sn&&Wn>yn,Fn=Math.max(Math.min(fs?Xn:ps,Sn),160),ae=Math.min(Math.max(Qn,dn),ot-dn-Vn)+cn,Qe=fs?Math.max(mn+St,Cn-Fn-fn+St):Math.min(Rn+fn+St,jt+St-mn-Fn);ge({top:Qe,left:ae,width:Vn,maxHeight:Fn})},[xn]);a.useEffect(()=>{if(!te)return;const oe=()=>qt();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",oe),$e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),$e&&($e.removeEventListener("resize",oe),$e.removeEventListener("scroll",oe))}},[te,qt]),a.useEffect(()=>{if(!Tt)return;const oe=()=>$n();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",oe),$e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),$e&&($e.removeEventListener("resize",oe),$e.removeEventListener("scroll",oe))}},[Tt,$n]),a.useEffect(()=>{if(!Z)return;const oe=()=>qn();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",oe),$e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),$e&&($e.removeEventListener("resize",oe),$e.removeEventListener("scroll",oe))}},[Z,qn]),a.useEffect(()=>{if(!E)return;const oe=()=>Nn();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const $e=window.visualViewport;return $e&&($e.addEventListener("resize",oe),$e.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),$e&&($e.removeEventListener("resize",oe),$e.removeEventListener("scroll",oe))}},[E,Nn]);const Dn=a.useCallback(oe=>{const $e=fl(oe);Ee($e.provider),Be($e.modelId)},[]),se=a.useCallback(oe=>{const $e=fl(oe);de($e.provider),ve($e.modelId)},[]),Fe=a.useCallback(oe=>{const $e=fl(oe);Pe($e.provider),Ie($e.modelId)},[]),st=a.useCallback(async oe=>{if(u){u(oe);return}const $e=Ce,jt=$e.includes(oe)?$e.filter(St=>St!==oe):[oe,...$e];qe(jt);try{await Kt({favoriteProviders:jt,favoriteModels:ce})}catch{qe($e)}},[Ce,ce,u]),T=a.useCallback(async oe=>{if(h){h(oe);return}const $e=ce,jt=$e.includes(oe)?$e.filter(St=>St!==oe):[oe,...$e];Ue(jt);try{await Kt({favoriteProviders:Ce,favoriteModels:jt})}catch{Ue($e)}},[ce,Ce,h]),W=a.useCallback(()=>{const oe=g.trim();if(!oe){n("Enter a description first","error");return}r?.(oe),on()},[g,r,n,on]),ee=a.useCallback(()=>{const oe=g.trim();if(!oe){n("Enter a description first","error");return}l?.(oe),on()},[g,l,n,on]),me=a.useCallback(()=>{Wt()},[Wt]),ke=a.useCallback(async oe=>{const $e=g.trim();if(!(!$e||Mt)){Et(!1),vt(!0);try{const ot=await ah($e,oe,o);p(ot),n("Description refined with AI","success"),N.current&&(N.current.style.height="auto",N.current.style.height=`${Math.min(N.current.scrollHeight,200)}px`)}catch(ot){const jt=rh(ot);n(jt,"error")}finally{vt(!1)}}},[g,Mt,n,o]),Re=(oe,$e)=>oe.length>$e?oe.slice(0,$e)+"…":oe,dt=a.useCallback(async()=>{if(i){tt(i),Ze(null),be(!1);return}be(!0),Ze(null);try{const oe=await Jn();tt(oe.models),m||qe(oe.favoriteProviders),c||Ue(oe.favoriteModels)}catch(oe){Ze(xe(oe)||"Failed to load models")}finally{be(!1)}},[i,m,c]),Rt=a.useCallback(async()=>{if(L.length>0&&U===o){J(!0),Nn();return}z(!0);try{const oe=await aa(void 0,o);D(oe),G(o),J(!0),Nn()}catch(oe){const $e=xe(oe);n($e?`Failed to load agents: ${$e}`:"Failed to load agents","error"),J(!1)}finally{z(!1)}},[L.length,U,o,n,Nn]),kt=(Q?L.find(oe=>oe.id===Q):void 0)?.name??Q,ht=v,Ps=a.useCallback(()=>{M(oe=>{const $e=!oe;return y($e),$e})},[]);return e.jsxs("div",{className:`quick-entry-box ${v?"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:N,className:`quick-entry-input ${x?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:oe=>p(oe.target.value),onKeyDown:Tn,onPaste:gn,onFocus:sn,onBlur:bn,disabled:f||$,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":v})}),e.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Ps,"aria-expanded":v,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:v?"Collapse":"Expand",children:v?e.jsx(Ds,{size:14}):e.jsx(zt,{size:14})})]})}),e.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ht,"aria-hidden":!ht,children:[ht&&!f&&e.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:W,onMouseDown:oe=>oe.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:ee,onMouseDown:oe=>oe.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[e.jsx(Hr,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),e.jsxs("div",{className:"refine-trigger-wrap",ref:Ft,children:[e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Mt?"refine-button--loading":""}`,onClick:()=>{Et(oe=>{const $e=!oe;return $e?$n():ze(null),$e})},disabled:!g.trim()||Mt,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(On,{size:12,style:{verticalAlign:"middle"}}),Mt?"Refining...":"Refine"]}),Tt&&he&&pt&&Na.createPortal(e.jsxs("div",{ref:Je,className:"refine-menu refine-menu--portal",onMouseDown:oe=>oe.preventDefault(),style:{position:"fixed",top:`${pt.top}px`,left:`${pt.left}px`},children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>ke("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:()=>ke("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:()=>ke("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:()=>ke("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:ye,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{I(oe=>{const $e=!oe;return $e?(F(!1),Te(null),V(null),J(!1),qn()):mt(null),$e})},children:[e.jsx(Vi,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`${R.length} deps`:"Deps"]})}),Z&&he&&nt&&(()=>{const oe=_.toLowerCase(),$e=(oe?s.filter(ot=>ot.id.toLowerCase().includes(oe)||ot.title&&ot.title.toLowerCase().includes(oe)||ot.description&&ot.description.toLowerCase().includes(oe)):[...s]).sort((ot,jt)=>{const St=jt.createdAt.localeCompare(ot.createdAt);if(St!==0)return St;const cn=parseInt(ot.id.slice(ot.id.lastIndexOf("-")+1),10)||0;return(parseInt(jt.id.slice(jt.id.lastIndexOf("-")+1),10)||0)-cn});return Na.createPortal(e.jsxs("div",{ref:He,className:"dep-dropdown dep-dropdown--portal",onMouseDown:ot=>ot.preventDefault(),style:{position:"fixed",top:`${nt.top}px`,left:`${nt.left}px`,width:`${nt.width}px`,maxHeight:nt.maxHeight?`${nt.maxHeight}px`:void 0,overflowY:nt.maxHeight?"auto":void 0},children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:_,onChange:ot=>j(ot.target.value),onClick:ot=>ot.stopPropagation()}),$e.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):$e.map(ot=>e.jsxs("div",{className:`dep-dropdown-item${R.includes(ot.id)?" selected":""}`,onMouseDown:jt=>jt.preventDefault(),onClick:()=>Hn(ot.id),children:[e.jsx("span",{className:"dep-dropdown-id",children:ot.id}),e.jsx("span",{className:"dep-dropdown-title",children:Re(ot.title||ot.description||ot.id,60)})]},ot.id))]}),he)})(),e.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>A.current?.click(),children:[e.jsx(mb,{size:12,style:{verticalAlign:"middle"}}),k.length>0?`Attach (${k.length})`:"Attach"]}),e.jsxs("button",{ref:et,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{I(!1),J(!1),V(null),F(!0),qt()},children:[e.jsx(Nr,{size:12,style:{verticalAlign:"middle"}}),hn]}),e.jsx("div",{className:"agent-trigger-wrap",ref:Xe,children:e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{E?(J(!1),ge(null)):Rt()},"data-testid":"quick-entry-agent-button",children:[e.jsx(an,{size:12,style:{verticalAlign:"middle"}}),kt?` ${kt}`:" Agent"]})}),E&&he&&ne&&Na.createPortal(e.jsxs("div",{ref:re,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:oe=>oe.preventDefault(),style:{position:"fixed",top:`${ne.top}px`,left:`${ne.left}px`,width:`${ne.width}px`,maxHeight:ne.maxHeight?`${ne.maxHeight}px`:void 0,overflowY:ne.maxHeight?"auto":void 0},children:[e.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ue&&e.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ue&&L.filter(oe=>oe.state!=="terminated").map(oe=>e.jsxs("div",{className:`dep-dropdown-item${Q===oe.id?" selected":""}`,onMouseDown:$e=>$e.preventDefault(),onClick:()=>{Y(oe.id===Q?null:oe.id),J(!1),ge(null)},children:[e.jsx(an,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:oe.role}),e.jsx("span",{className:"dep-dropdown-title",children:oe.name})]},oe.id)),!ue&&L.filter(oe=>oe.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Q&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:oe=>oe.preventDefault(),onClick:()=>{Y(null),J(!1),ge(null)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),he),e.jsx("button",{type:"button",className:`btn btn-sm ${yt?"btn-primary":""}`,onClick:()=>Ct(oe=>!oe),onMouseDown:oe=>oe.preventDefault(),"aria-pressed":yt,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),e.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:me,onMouseDown:oe=>oe.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[e.jsx(Km,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),k.length>0&&e.jsx("div",{className:"inline-create-previews",children:k.map((oe,$e)=>e.jsxs("div",{className:"inline-create-preview",children:[e.jsx("img",{src:oe.previewUrl,alt:oe.file.name}),e.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Zt($e),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${$e}`,children:"×"})]},oe.previewUrl))}),te&&he&&le&&Na.createPortal(e.jsx("div",{ref:De,className:"model-nested-menu model-nested-menu--portal",onMouseDown:oe=>oe.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${le.top}px`,left:`${le.left}px`,width:`${le.width}px`,maxHeight:le.maxHeight?`${le.maxHeight}px`:void 0,overflowY:le.maxHeight?"auto":void 0},children:fe===null?e.jsxs("div",{className:"model-menu-items",children:[e.jsxs("button",{type:"button",className:`model-menu-item ${Lt?"model-menu-item--active":""}`,onClick:()=>V("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:Lt?nn(rt,_e):"Using default"}),e.jsx(ln,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${Nt?"model-menu-item--active":""}`,onClick:()=>V("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:Nt?nn(K,we):"Using default"}),e.jsx(ln,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${Bt?"model-menu-item--active":""}`,onClick:()=>V("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:Bt?nn(Se,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:()=>V(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:[fe==="plan"&&"Plan Model",fe==="executor"&&"Executor Model",fe==="validator"&&"Validator Model"]}),e.jsx(Gt,{models:je,value:fe==="plan"?bt:fe==="executor"?pe:ct,onChange:fe==="plan"?Dn:fe==="executor"?se:Fe,placeholder:"Using default",disabled:ie,id:`model-${fe}-select`,label:`${fe} model`,favoriteProviders:at,onToggleFavorite:st,favoriteModels:q,onToggleModelFavorite:T}),Me&&e.jsxs("div",{className:"model-submenu-error",children:[e.jsx("span",{children:Me}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:dt,children:"Retry"})]})]})}),he)]}),e.jsx("input",{ref:A,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:oe=>{Un(oe.target.files),oe.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),e.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function Zj(t){const n=t.replace(/\/+$/,"").split("/");return n[n.length-1]||t}function ew(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 tw(t,n,s){const i=t.filter(f=>f.worktree),r=t.filter(f=>!f.worktree),l=new Map;for(const f of i){const b=f.worktree,x=l.get(b)||[];x.push(f),l.set(b,x)}const o=new Map(n.map(f=>[f.id,f])),m=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(b=>{const x=o.get(b);return x&&(x.column==="done"||x.column==="in-review"||x.column==="archived")})),u=ew(m).map(f=>o.get(f)).filter(f=>f!==void 0&&m.includes(f)),h=[],g=Array.from(l.keys());for(const f of g)h.push({label:Zj(f),activeTasks:l.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=u.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const jd=100,gl=50,wd=25;function nw({column:t,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onOpenDetail:l,addToast:o,onQuickCreate:d,onNewTask:m,autoMerge:c,onToggleAutoMerge:u,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onArchiveAllDone:x,collapsed:y,onToggleCollapse:v,allTasks:M,availableModels:N,onPlanningMode:A,onSubtaskBreakdown:w,onOpenDetailWithTab:S,favoriteProviders:k,favoriteModels:P,onToggleFavorite:C,onToggleModelFavorite:R,isSearchActive:O,taskStuckTimeoutMs:Z,onOpenMission:I,lastFetchTimeMs:_,workflowStepNameLookup:j}){const[Q,Y]=a.useState(!1),[L,D]=a.useState(gl),U=rj(n.length),G=t==="archived",E=G&&y,J=!G&&!O&&t!=="in-progress"&&n.length>jd;a.useEffect(()=>{D(we=>t==="in-progress"||G||n.length<=jd?gl:Math.min(Math.max(we,gl),n.length))},[t,G,n.length]);const ue=a.useCallback(we=>{G||(we.preventDefault(),we.dataTransfer.dropEffect="move",Y(!0))},[G]),z=a.useCallback(we=>{we.currentTarget.contains(we.relatedTarget)||Y(!1)},[]),te=a.useCallback(async we=>{we.preventDefault(),Y(!1);const ve=we.dataTransfer.getData("text/plain");if(!ve)return;const Se=n.find(Pe=>Pe.id===ve);if(!(Se&&Se.column===t))try{await r(ve,t)}catch(Pe){o(xe(Pe),"error")}},[t,r,o,n]),F=a.useMemo(()=>t!=="in-progress"?[]:tw(n,n,i),[t,n,i]),fe=a.useMemo(()=>J?n.slice(0,L):n,[J,n,L]),V=Math.max(0,n.length-fe.length),K=a.useCallback(()=>{D(we=>Math.min(we+wd,n.length))},[n.length]),de=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(xe(ve)||"Failed to archive tasks","error")}},[x,n.length,o]);return e.jsxs("div",{className:`column${Q?" drag-over":""}${G?" column-archived":""}${E?" column-collapsed":""}`,"data-column":t,onDragOver:ue,onDragLeave:z,onDrop:te,children:[e.jsxs("div",{className:"column-header",children:[e.jsx("div",{className:`column-dot dot-${t}`}),e.jsx("h2",{children:ds[t]}),e.jsx("span",{className:`column-count${U?" 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:de,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:e.jsx(Br,{size:16})}),G&&v&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:v,title:y?"Expand archived tasks":"Collapse archived tasks","aria-label":y?"Expand archived tasks":"Collapse archived tasks",children:y?e.jsx(zt,{size:16}):e.jsx(Ds,{size:16})})]}),!E&&e.jsx("p",{className:"column-desc",children:ij[t]}),!E&&e.jsxs("div",{className:"column-body",children:[t==="triage"&&d&&e.jsx(jh,{onCreate:d,addToast:o,tasks:M??[],availableModels:N,onPlanningMode:A,onSubtaskBreakdown:w,projectId:s,autoExpand:!1,favoriteProviders:k,favoriteModels:P,onToggleFavorite:C,onToggleModelFavorite:R}),t==="in-progress"?F.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):F.map(we=>e.jsx(kh,{label:we.label,activeTasks:we.activeTasks,queuedTasks:we.queuedTasks,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onOpenDetailWithTab:S,taskStuckTimeoutMs:Z,onOpenMission:I,lastFetchTimeMs:_,workflowStepNameLookup:j},we.label)):n.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):e.jsxs(e.Fragment,{children:[fe.map(we=>e.jsx(Rr,{task:we,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onOpenDetailWithTab:S,taskStuckTimeoutMs:Z,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:_,workflowStepNameLookup:j},we.id)),J&&V>0&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:K,children:["Load ",Math.min(wd,V)," more (",V," remaining)"]})]}),e.jsx(Ga,{slotId:"board-column-footer",projectId:s})]})]})}const wh=a.memo(nw);wh.displayName="Column";function sw(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 iw(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}const Nd=new Map;function aw(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 rw({tasks:t,projectId:n,maxConcurrent:s,onMoveTask:i,onOpenDetail:r,addToast:l,onQuickCreate:o,onNewTask:d,autoMerge:m,onToggleAutoMerge:c,globalPaused:u,onUpdateTask:h,onArchiveTask:g,onUnarchiveTask:p,onDeleteTask:f,onArchiveAllDone:b,onLoadArchivedTasks:x,searchQuery:y="",availableModels:v,onPlanningMode:M,onSubtaskBreakdown:N,onOpenDetailWithTab:A,favoriteProviders:w,favoriteModels:S,onToggleFavorite:k,onToggleModelFavorite:P,taskStuckTimeoutMs:C,onOpenMission:R,lastFetchTimeMs:O}){const[Z,I]=a.useState(!0),_=a.useRef(!1),{fetchBatch:j}=pj(n),Q=a.useRef(null),[Y,L]=a.useState(Nd),D=y.trim()!=="",U=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),G=a.useCallback(()=>{I(ue=>{const z=!ue;return!z&&!_.current&&x&&(_.current=!0,x()),z})},[x]),E=a.useMemo(()=>{const ue=Object.fromEntries(bi.map(F=>[F,[]]));for(const F of t)ue[F.column].push(F);const z=U.current,te={};for(const F of bi){const fe=sw(ue[F]);te[F]=iw(z[F],fe)?z[F]:fe}return U.current=te,te},[t]);a.useEffect(()=>{let ue=!1;return Kr(n).then(z=>{if(ue)return;const te=new Map(z.map(F=>[F.id,F.name]));L(F=>aw(F,te)?F:te)}).catch(()=>{ue||L(z=>z.size===0?z:Nd)}),()=>{ue=!0}},[n]);const J=a.useMemo(()=>t.filter(ue=>ue.prInfo||ue.issueInfo).map(ue=>ue.id),[t]);return a.useEffect(()=>{if(J.length!==0)return Q.current&&clearTimeout(Q.current),Q.current=setTimeout(()=>{const ue=[];for(let z=0;z<J.length;z+=50)ue.push(J.slice(z,z+50));ue.forEach(z=>{j(z)})},500),()=>{Q.current&&clearTimeout(Q.current)}},[J,j]),e.jsx(e.Fragment,{children:e.jsx("main",{className:"board",id:"board",children:bi.map(ue=>e.jsx(wh,{column:ue,tasks:E[ue],projectId:n,maxConcurrent:s,onMoveTask:i,onOpenDetail:r,addToast:l,globalPaused:u,onUpdateTask:h,onArchiveTask:g,onUnarchiveTask:p,onDeleteTask:f,allTasks:t,availableModels:v,onOpenDetailWithTab:A,favoriteProviders:w,favoriteModels:S,onToggleFavorite:k,onToggleModelFavorite:P,isSearchActive:D,taskStuckTimeoutMs:C,onOpenMission:R,lastFetchTimeMs:O,workflowStepNameLookup:Y,...ue==="triage"?{onQuickCreate:o,onNewTask:d,onPlanningMode:M,onSubtaskBreakdown:N}:{},...ue==="in-review"?{autoMerge:m,onToggleAutoMerge:c}:{},...ue==="done"?{onArchiveAllDone:b}:{},...ue==="archived"?{collapsed:Z,onToggleCollapse:G}:{}},ue))})})}const ua={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Sd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),yo=["id","title","status","column","dependencies","progress"];function Cd(t){try{const n=In("kb-dashboard-list-columns",t);if(n){const i=JSON.parse(n).filter(r=>yo.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(yo)}function Ed(t){try{const n=In("kb-dashboard-hide-done",t);if(n!==null)return n==="true"}catch{}return!1}function Md(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 Ad(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 lw(t){return t.status==="executing"||t.column==="in-progress"}function Pd(t){const n=yh(t);return n.total===0||!lw(t)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function ow({tasks:t,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:l,onQuickCreate:o,availableModels:d,favoriteProviders:m=[],favoriteModels:c=[],onToggleFavorite:u,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:b,projectName:x,taskStuckTimeoutMs:y,searchQuery:v="",lastFetchTimeMs:M}){const[N,A]=a.useState("id"),[w,S]=a.useState("desc"),[k,P]=a.useState(null),[C,R]=a.useState(null),[O,Z]=a.useState(null),_=Jr()==="mobile",[j,Q]=a.useState(()=>Cd(b)),[Y,L]=a.useState(()=>Ed(b)),[D,U]=a.useState(()=>Md(b));a.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-columns",JSON.stringify([...j]),b)},[b,j]),a.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-hide-done",Y.toString(),b)},[Y,b]),a.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-collapsed",JSON.stringify([...D]),b)},[D,b]);const[G,E]=a.useState(!1),J=a.useRef(null),[ue,z]=a.useState(()=>Ad(b));a.useEffect(()=>{Q(Cd(b)),L(Ed(b)),U(Md(b)),z(Ad(b))},[b]),a.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-selected-tasks",JSON.stringify([...ue]),b)},[b,ue]);const te=a.useCallback(ie=>{z(be=>{const Me=new Set(be);return Me.has(ie)?Me.delete(ie):Me.add(ie),Me})},[]),F=a.useCallback(()=>{z(new Set)},[]),fe=a.useCallback(ie=>{Q(be=>{const Me=new Set(be);return Me.has(ie)?Me.size>1&&Me.delete(ie):Me.add(ie),Me})},[]);a.useEffect(()=>{if(!G)return;const ie=Me=>{J.current&&!J.current.contains(Me.target)&&E(!1)},be=Me=>{Me.key==="Escape"&&E(!1)};return document.addEventListener("mousedown",ie),document.addEventListener("keydown",be),()=>{document.removeEventListener("mousedown",ie),document.removeEventListener("keydown",be)}},[G]);const V={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},K=a.useCallback(ie=>{N===ie?S(be=>be==="asc"?"desc":"asc"):(A(ie),S("asc"))},[N]),de=a.useCallback(ie=>{Z(be=>be===ie?null:ie)},[]),we=a.useCallback(ie=>{U(be=>{const Me=new Set(be);return Me.has(ie)?Me.delete(ie):Me.add(ie),Me})},[]),ve=a.useCallback(()=>{Z(null)},[]),Se=a.useMemo(()=>{let ie=v?t.filter(je=>je.id.toLowerCase().includes(v.toLowerCase())||je.title&&je.title.toLowerCase().includes(v.toLowerCase())||je.description.toLowerCase().includes(v.toLowerCase())):[...t];Y&&!O&&(ie=ie.filter(je=>je.column!=="done"&&je.column!=="archived"));const Me=[...O?ie.filter(je=>je.column===O):ie].sort((je,tt)=>{let Ce=0;switch(N){case"id":Ce=je.id.localeCompare(tt.id);break;case"title":Ce=(je.title||je.description).localeCompare(tt.title||tt.description);break;case"status":Ce=(je.status||"").localeCompare(tt.status||"");break;case"column":Ce=je.column.localeCompare(tt.column);break}return w==="asc"?Ce:-Ce}),Ze={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Me.forEach(je=>Ze[je.column].push(je)),Ze},[t,v,N,w,Y,O]),Pe=a.useMemo(()=>Object.values(Se).reduce((ie,be)=>ie+be.length,0),[Se]),Oe=a.useMemo(()=>t.filter(ie=>ie.column==="done"||ie.column==="archived").length,[t]),Ie=a.useMemo(()=>Y?Oe:0,[Y,Oe]),rt=a.useCallback(()=>{const ie=Object.values(Se).flat().filter(be=>be.column!=="archived").map(be=>be.id);z(be=>{if(ie.every(Ze=>be.has(Ze))){const Ze=new Set(be);return ie.forEach(je=>Ze.delete(je)),Ze}else return new Set([...be,...ie])})},[Se]),Ee=a.useMemo(()=>{const ie=Object.values(Se).flat().filter(be=>be.column!=="archived");return ie.length===0?!1:ie.every(be=>ue.has(be.id))},[Se,ue]),_e=a.useMemo(()=>{const ie=Object.values(Se).flat().filter(Me=>Me.column!=="archived");if(ie.length===0)return!1;const be=ie.filter(Me=>ue.has(Me.id)).length;return be>0&&be<ie.length},[Se,ue]),[Be,et]=a.useState("__no_change__"),[De,Xe]=a.useState("__no_change__"),[re,ne]=a.useState(!1),ge=a.useCallback(async()=>{if(ue.size===0)return;const ie=Array.from(ue).filter(Me=>{const Ze=t.find(je=>je.id===Me);return Ze&&Ze.column!=="archived"});if(ie.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const be={taskIds:ie};if(Be!=="__no_change__")if(Be==="")be.modelProvider=null,be.modelId=null;else{const Me=Be.indexOf("/");Me!==-1&&(be.modelProvider=Be.slice(0,Me),be.modelId=Be.slice(Me+1))}if(De!=="__no_change__")if(De==="")be.validatorModelProvider=null,be.validatorModelId=null;else{const Me=De.indexOf("/");Me!==-1&&(be.validatorModelProvider=De.slice(0,Me),be.validatorModelId=De.slice(Me+1))}if(Object.keys(be).length===1){i("No changes to apply","info");return}ne(!0);try{const Me=await ux(be.taskIds,be.modelProvider,be.modelId,be.validatorModelProvider,be.validatorModelId,void 0,void 0,b);f&&Me.updated.length>0&&f(Me.updated),i(`Updated ${Me.count} task${Me.count===1?"":"s"}`,"success"),F(),et("__no_change__"),Xe("__no_change__")}catch(Me){i(xe(Me)||"Failed to update models","error")}finally{ne(!1)}},[ue,t,Be,De,b,i,F,f]),le=a.useCallback(ie=>{s(ie)},[s]),Te=a.useCallback((ie,be)=>{if(be.paused){ie.preventDefault();return}ie.dataTransfer.setData("text/plain",be.id),ie.dataTransfer.effectAllowed="move",P(be.id)},[]),ye=a.useCallback(()=>{P(null),R(null)},[]),He=a.useCallback((ie,be)=>{ie.preventDefault(),ie.dataTransfer.dropEffect="move",R(be)},[]),nt=a.useCallback(()=>{R(null)},[]),mt=a.useCallback(async(ie,be)=>{ie.preventDefault(),R(null);const Me=ie.dataTransfer.getData("text/plain");if(Me){if(be==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Me,be)}catch(Ze){i(xe(Ze),"error")}}},[n,i]),he=ie=>N!==ie?e.jsx($m,{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:J,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>E(ie=>!ie),"aria-expanded":G,"aria-haspopup":"menu",children:[e.jsx(ng,{size:14}),"Columns"]}),G&&e.jsx("div",{className:"list-column-dropdown",role:"menu",children:yo.map(ie=>{const be=j.has(ie),Me=be&&j.size===1;return e.jsxs("label",{className:`list-column-dropdown-item${Me?" disabled":""}`,role:"menuitem",title:Me?"At least one column must be visible":"",children:[e.jsx("input",{type:"checkbox",checked:be,onChange:()=>fe(ie),disabled:Me}),e.jsx("span",{children:V[ie]})]},ie)})})]}),e.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>L(ie=>!ie),"aria-pressed":Y,title:Y?"Show done tasks":"Hide done tasks",children:[Y?e.jsx(Oo,{size:14}):e.jsx(mg,{size:14}),Y?"Show Done":"Hide Done"]}),e.jsxs("div",{className:"list-stats",children:[O?`${Pe} of ${t.length} tasks in ${ds[O]}`:`${Pe} of ${t.length} tasks`,Ie>0&&!O&&e.jsxs("span",{className:"list-stats-hidden",children:[" (",Ie," hidden)"]}),O&&e.jsx("button",{className:"btn btn-sm",onClick:ve,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),ue.size>0&&e.jsxs("div",{className:"list-selection-stats",children:[e.jsxs("span",{className:"selection-count",children:[ue.size," selected"]}),e.jsx("button",{className:"btn btn-sm btn-link",onClick:F,children:"Clear"})]}),ue.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(Gt,{models:d,value:Be,onChange:et,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(Gt,{models:d,value:De,onChange:Xe,label:"Validator Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:m,onToggleFavorite:u,favoriteModels:c,onToggleModelFavorite:h})}),e.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ge,disabled:re||Be==="__no_change__"&&De==="__no_change__",children:re?"Applying...":"Apply"})]}),l?e.jsx("button",{className:"btn btn-task-create btn-sm",onClick:l,children:"+ New Task"}):null]}),e.jsx("div",{className:"list-drop-zones",children:bi.map(ie=>{const be=t.filter(tt=>tt.column===ie).length,Me=ie==="done"||ie==="archived",Ze=Y&&Me?0:be,je=Y&&Me&&be>0;return e.jsxs("div",{className:`list-drop-zone${C===ie?" drag-over":""}${O===ie?" active":""}`,onClick:()=>de(ie),onDragOver:tt=>He(tt,ie),onDragLeave:nt,onDrop:tt=>mt(tt,ie),"data-column":ie,children:[e.jsx("span",{className:"drop-zone-dot",style:{background:ua[ie]}}),e.jsx("span",{className:"drop-zone-label",children:ds[ie]}),e.jsx("span",{className:"drop-zone-count",children:je?`${Ze} of ${be}`:be})]},ie)})}),e.jsxs("div",{className:"list-table-container",children:[e.jsx("div",{className:"list-quick-entry-above-table",children:e.jsx(jh,{onCreate:o??(async()=>i("Task creation not available","error")),addToast:i,tasks:t,availableModels:d,onPlanningMode:g,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:m,favoriteModels:c,onToggleFavorite:u,onToggleModelFavorite:h})}),Pe===0?e.jsx("div",{className:"list-empty",children:v?"No tasks match your filter":"No tasks yet"}):_?e.jsx("div",{className:"list-cards",children:bi.map(ie=>{if(O&&ie!==O||Y&&(ie==="done"||ie==="archived")&&!O)return null;const be=Se[ie],Me=be.length===0;if(v&&Me)return null;const Ze=D.has(ie);return e.jsxs(a.Fragment,{children:[e.jsxs("div",{className:`list-card-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>we(ie),"aria-expanded":!Ze,role:"button",tabIndex:0,onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&(je.preventDefault(),we(ie))},children:[e.jsx(ln,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${ie}`}),e.jsx("span",{className:"list-section-title",children:ds[ie]}),e.jsx("span",{className:"list-section-count",children:be.length})]}),!Ze&&e.jsx(e.Fragment,{children:Me?e.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):be.map(je=>{const tt=je.status==="failed",Ce=je.paused===!0,qe=Tr(je,y,M),ce=!r&&!tt&&!Ce&&!qe&&(je.column==="in-progress"||Sd.has(je.status)),Ue=typeof je.status=="string"&&je.status.trim().length>0,Ve=!!(je.dependencies&&je.dependencies.length>0),Ae=Pd(je),We=Ae.hasProgress,xt=ue.size>0;return e.jsxs("div",{className:`list-card${ce?" agent-active":""}${xt?" list-card--selectable":""}`,onClick:()=>le(je),"data-id":je.id,children:[xt&&e.jsx("label",{className:"list-card-checkbox",onClick:yt=>yt.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:ue.has(je.id),onChange:yt=>{yt.stopPropagation(),te(je.id)},onClick:yt=>yt.stopPropagation(),disabled:je.column==="archived","aria-label":`Select ${je.id}`})}),e.jsxs("div",{className:"list-card-row",children:[e.jsx("span",{className:"list-card-id",children:je.id}),e.jsx("span",{className:"list-card-spacer"}),qe?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ue?e.jsx("span",{className:`list-status-badge list-status-badge--${je.column}${tt?" failed":""}${ce?" pulsing":""}`,children:je.status}):null]}),e.jsx("div",{className:"list-card-row",children:e.jsx("div",{className:"list-card-title",children:je.title||je.description})}),(Ve||We)&&e.jsxs("div",{className:"list-card-row list-card-meta",children:[Ve&&e.jsxs("span",{className:"list-dep-badge",title:je.dependencies.join(", "),children:[e.jsx(Vi,{size:12})," ",je.dependencies.length]}),We&&e.jsxs("div",{className:"list-progress",children:[e.jsx("div",{className:"list-progress-bar",children:e.jsx("div",{className:"list-progress-fill",style:{width:`${Ae.percent}%`,backgroundColor:ua[je.column]}})}),e.jsx("span",{className:"list-progress-label",children:Ae.label})]})]})]},je.id)})})]},ie)})}):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:Ee,ref:ie=>{ie&&(ie.indeterminate=_e)},onChange:rt,"aria-label":"Select all visible tasks"})}),j.has("id")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("id"),children:["ID ",he("id")]}),j.has("title")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("title"),children:["Title ",he("title")]}),j.has("status")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("status"),children:["Status ",he("status")]}),j.has("column")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("column"),children:["Column ",he("column")]}),j.has("dependencies")&&e.jsx("th",{className:"list-header-cell",children:"Dependencies"}),j.has("progress")&&e.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),e.jsx("tbody",{children:bi.map(ie=>{if(O&&ie!==O||Y&&(ie==="done"||ie==="archived")&&!O)return null;const be=Se[ie],Me=be.length===0;if(v&&Me)return null;const Ze=D.has(ie);return e.jsxs(a.Fragment,{children:[e.jsx("tr",{className:`list-section-header${Ze?" list-section-header--collapsed":""}`,onClick:()=>we(ie),"aria-expanded":!Ze,children:e.jsxs("th",{colSpan:j.size+1,className:"list-section-cell",children:[e.jsx(ln,{size:14,className:`list-section-chevron${Ze?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${ie}`}),e.jsx("span",{className:"list-section-title",children:ds[ie]}),e.jsx("span",{className:"list-section-count",children:be.length})]})}),!Ze&&e.jsx(e.Fragment,{children:Me?e.jsx("tr",{className:"list-section-empty",children:e.jsx("td",{colSpan:j.size+1,className:"list-empty-cell",children:"No tasks"})}):be.map(je=>{const tt=je.status==="failed",Ce=je.paused===!0,qe=Tr(je,y,M),ce=!r&&!tt&&!Ce&&!qe&&(je.column==="in-progress"||Sd.has(je.status)),Ue=k===je.id;return e.jsxs("tr",{className:`list-row${tt?" failed":""}${Ce?" paused":""}${qe?" stuck":""}${ce?" agent-active":""}${Ue?" dragging":""}`,onClick:()=>le(je),draggable:!Ce,onDragStart:Ve=>Te(Ve,je),onDragEnd:ye,"data-id":je.id,children:[e.jsx("td",{className:"list-cell list-cell-checkbox",children:e.jsx("input",{type:"checkbox",checked:ue.has(je.id),onChange:Ve=>{Ve.stopPropagation(),te(je.id)},onClick:Ve=>Ve.stopPropagation(),disabled:je.column==="archived","aria-label":`Select ${je.id}`})}),j.has("id")&&e.jsx("td",{className:"list-cell list-cell-id",children:je.id}),j.has("title")&&e.jsx("td",{className:"list-cell list-cell-title",children:je.title||je.description}),j.has("status")&&e.jsx("td",{className:"list-cell",children:qe?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):je.status?e.jsx("span",{className:`list-status-badge list-status-badge--${je.column}${tt?" failed":""}${ce?" pulsing":""}`,children:je.status}):e.jsx("span",{className:"list-status-badge",children:"-"})}),j.has("column")&&e.jsx("td",{className:"list-cell",children:e.jsx("span",{className:"list-column-badge",style:{background:`${ua[je.column]}20`,color:ua[je.column]},children:ds[je.column]})}),j.has("dependencies")&&e.jsx("td",{className:"list-cell list-cell-deps",children:je.dependencies&&je.dependencies.length>0?e.jsxs("span",{className:"list-dep-badge",title:je.dependencies.join(", "),children:[e.jsx(Vi,{size:12})," ",je.dependencies.length]}):"-"}),j.has("progress")&&e.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ve=Pd(je);return Ve.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:`${Ve.percent}%`,backgroundColor:ua[je.column]}})}),e.jsx("span",{className:"list-progress-label",children:Ve.label})]}):"-"})()})]},je.id)})})]},ie)})})]})]})]})}const cw={active:{label:"Active",color:"var(--success)",icon:rn},paused:{label:"Paused",color:"var(--warning)",icon:$s},errored:{label:"Error",color:"var(--color-error)",icon:is},initializing:{label:"Initializing",color:"var(--info)",icon:lt}};function dw(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 uw(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 mw(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 hw({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=cw[t.status],g=h.icon,p=a.useCallback(()=>{s(t)},[s,t]),f=a.useCallback(N=>{N.stopPropagation(),i(t)},[i,t]),b=a.useCallback(N=>{N.stopPropagation(),r(t)},[r,t]),x=a.useCallback(N=>{if(N.stopPropagation(),!c){u(!0);return}l(t),u(!1)},[c,l,t]),y=t.status==="paused",v=t.status==="errored",M=t.status==="initializing";return e.jsxs("div",{className:`project-card ${m?"project-card-loading":""} ${v?"project-card-errored":""}`,onClick:p,"data-project-id":t.id,role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),p())},children:[e.jsxs("div",{className:"project-card-header",children:[e.jsx("div",{className:"project-card-icon",children:e.jsx(An,{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:uw(t.path)})]}),e.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[e.jsx(g,{size:12,className:M?"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:dw(t.lastActivityAt||n?.lastActivityAt)})]}),e.jsxs("div",{className:"project-card-actions",children:[y?e.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:m,title:"Resume project","aria-label":"Resume project",children:[e.jsx(rn,{size:14}),e.jsx("span",{children:"Resume"})]}):e.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:m||M,title:M?"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:p,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(Ht,{size:14}),e.jsx("span",{children:c?"Confirm":""})]})]})]})]})}const pw=a.memo(hw,mw);function fw(){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(An,{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(ws,{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(tn,{size:20,className:"project-skeleton-icon"})}),e.jsx("div",{className:"project-skeleton project-skeleton--value"}),e.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),e.jsxs("div",{className:"project-overview__stat-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon",children:e.jsx(is,{size:20,className:"project-skeleton-icon"})}),e.jsx("div",{className:"project-skeleton project-skeleton--value"}),e.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),e.jsxs("div",{className:"project-overview__filters-skeleton",children:[e.jsx("div",{className:"project-skeleton project-skeleton--tab"}),e.jsx("div",{className:"project-skeleton project-skeleton--tab"}),e.jsx("div",{className:"project-skeleton project-skeleton--tab"}),e.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),e.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((t,n)=>e.jsxs("div",{className:"project-card project-card--skeleton",children:[e.jsxs("div",{className:"project-card-skeleton__header",children:[e.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),e.jsxs("div",{className:"project-skeleton__text-group",children:[e.jsx("div",{className:"project-skeleton project-skeleton--title"}),e.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),e.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),e.jsxs("div",{className:"project-card-skeleton__health",children:[e.jsx("div",{className:"project-skeleton project-skeleton--metric"}),e.jsx("div",{className:"project-skeleton project-skeleton--metric"}),e.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),e.jsxs("div",{className:"project-card-skeleton__footer",children:[e.jsx("div",{className:"project-skeleton project-skeleton--activity"}),e.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const gw=1e4,Td=5;function bw(t){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[l,o]=a.useState(null),d=a.useRef(null),m=a.useRef(null),c=a.useRef(!1),u=a.useCallback(async()=>{if(t.length===0){s({}),c.current||(c.current=!0),r(!1);return}m.current&&m.current.abort(),m.current=new AbortController,!c.current&&r(!0),o(null);try{const p={};for(let f=0;f<t.length;f+=Td){const b=t.slice(f,f+Td),x=await Promise.allSettled(b.map(async y=>{try{return await id(y)}catch{return null}}));if(b.forEach((y,v)=>{const M=x[v];p[y]=M.status==="fulfilled"?M.value:null}),m.current?.signal.aborted)return}s(p),c.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;o(p instanceof Error?p.message:"Failed to fetch health data"),c.current=!0}finally{r(!1)}},[t]),h=a.useCallback(async g=>{try{const p=await id(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(c.current=!1,u(),()=>{m.current&&m.current.abort()}),[u]),a.useEffect(()=>{if(t.length!==0)return d.current&&clearInterval(d.current),d.current=setInterval(()=>{u()},gw),()=>{d.current&&(clearInterval(d.current),d.current=null)}},[u,t.length]),{healthMap:n,loading:i,error:l,refresh:u,refreshProject:h}}function xw({projects:t,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:l,onRemoveProject:o,nodes:d=[]}){const[m,c]=a.useState("all"),[u,h]=a.useState(null),[g,p]=a.useState("activity"),[f,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const Z=localStorage.getItem("kb-dashboard-recent-projects");if(Z)try{const I=JSON.parse(Z);y(I)}catch{}},[]);const[x,y]=a.useState([]),v=a.useMemo(()=>t.map(Z=>Z.id),[t]),{healthMap:M,loading:N}=bw(v),A=a.useMemo(()=>t.map(Z=>({project:Z,health:M[Z.id]||null})),[t,M]),w=a.useMemo(()=>{let Z=[...A];return m!=="all"&&(Z=Z.filter(({project:I})=>I.status===m)),u!==null&&(Z=Z.filter(({project:I})=>I.nodeId===u)),Z},[A,m,u]),S=a.useMemo(()=>{const Z=[...w];return Z.sort((I,_)=>{let j=0;switch(g){case"name":j=I.project.name.localeCompare(_.project.name);break;case"activity":{const Q=I.project.lastActivityAt||I.health?.lastActivityAt||I.project.updatedAt,Y=_.project.lastActivityAt||_.health?.lastActivityAt||_.project.updatedAt;j=new Date(Y).getTime()-new Date(Q).getTime();break}case"status":{const Q={errored:0,initializing:1,paused:2,active:3};j=Q[I.project.status]-Q[_.project.status];break}}return f==="asc"?j:-j}),Z},[w,g,f]),k=a.useMemo(()=>{const Z=t.length,I=t.filter(U=>U.status==="active").length,_=t.filter(U=>U.status==="errored").length,j=new Set;t.forEach(U=>{U.nodeId&&j.add(U.nodeId)});const Q=j.size||(Z>0?1:0);let Y=0,L=0,D=0;return Object.values(M).forEach(U=>{U&&(Y+=U.activeTaskCount,L+=U.totalTasksCompleted,D+=U.inFlightAgentCount)}),{totalProjects:Z,activeProjects:I,erroredProjects:_,totalNodes:Q,totalActiveTasks:Y,totalCompletedTasks:L,totalInFlightAgents:D}},[t,M]),P=a.useMemo(()=>({all:t.length,active:t.filter(Z=>Z.status==="active").length,paused:t.filter(Z=>Z.status==="paused").length,errored:t.filter(Z=>Z.status==="errored").length}),[t]),C=a.useMemo(()=>{const Z=new Map;return t.forEach(I=>{const _=I.nodeId,j=Z.get(_);if(j)j.count++;else{const Y=d.find(L=>L.id===_)?.name??I._sourceNodeName??"Local";Z.set(_,{name:Y,count:1})}}),Array.from(Z.entries()).map(([I,{name:_,count:j}])=>({nodeId:I??null,name:_,count:j}))},[t,d]),R=a.useCallback(Z=>{const I=[Z.id,...x.filter(_=>_!==Z.id)].slice(0,3);y(I),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(I)),s(Z)},[s,x]);return n||N&&t.length>0&&Object.keys(M).length===0?e.jsx(fw,{}):t.length===0?e.jsx("div",{className:"project-overview project-overview--empty",children:e.jsxs("div",{className:"project-empty-state",children:[e.jsx("div",{className:"project-empty-state__icon",children:e.jsx(Sa,{size:48})}),e.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),e.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),e.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:i,children:[e.jsx(Vt,{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(An,{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(ws,{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(tn,{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(is,{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(Vt,{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:P.all})]}),e.jsxs("button",{className:`project-filter-tab ${m==="active"?"active":""}`,onClick:()=>c("active"),children:["Active",e.jsx("span",{className:"project-filter-count",children:P.active})]}),e.jsxs("button",{className:`project-filter-tab ${m==="paused"?"active":""}`,onClick:()=>c("paused"),children:["Paused",e.jsx("span",{className:"project-filter-count",children:P.paused})]}),e.jsxs("button",{className:`project-filter-tab ${m==="errored"?"active":""} ${P.errored>0?"has-errors":""}`,onClick:()=>c("errored"),children:["Errored",e.jsx("span",{className:"project-filter-count",children:P.errored})]})]}),C.length>1&&e.jsxs("div",{className:"project-node-filter",children:[e.jsx(Cr,{size:14}),e.jsxs("select",{value:u??"",onChange:Z=>{h(Z.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[e.jsx("option",{value:"",children:"All Nodes"}),C.map(({nodeId:Z,name:I,count:_})=>e.jsxs("option",{value:Z??"",children:[I," (",_,")"]},Z??"local"))]})]}),e.jsxs("div",{className:"project-sort",children:[e.jsx(Sr,{size:14}),e.jsxs("select",{value:`${g}-${f}`,onChange:Z=>{const[I,_]=Z.target.value.split("-");p(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($m,{size:14})]})]}),e.jsx("div",{className:"project-grid",children:S.map(({project:Z,health:I})=>{const _=d.find(Q=>Q.id===Z.nodeId),j=_?void 0:Z._sourceNodeName;return e.jsx(pw,{project:Z,health:I,node:_,nodeNameFallback:j,onSelect:R,onPause:r,onResume:l,onRemove:o},Z.id)})}),S.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 vw=45e3,yw=3e3,kw=2e3,jw=1500,Rd="fusion:sse-client-id";let Ti=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 Nh(){if(!(typeof window>"u")){if(Ti)return Ti;try{const t=window.sessionStorage.getItem(Rd);if(t)return Ti=t,t;const n=_d();return window.sessionStorage.setItem(Rd,n),Ti=n,n}catch{return Ti=_d(),Ti}}}function Sh(t){if(!(typeof window>"u"))try{return{parsed:new URL(t,window.location.origin),preserveRelativePath:t.startsWith("/")}}catch{return}}function Ch(t){return t.origin===window.location.origin&&t.pathname==="/api/events"}function ww(t){const n=Nh();if(!n)return t;const s=Sh(t);return!s||!Ch(s.parsed)?t:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Ko(t,n){const s=Nh();if(!s)return;const i=Sh(t);if(!i||!Ch(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),As(`${r.pathname}${r.search}${r.hash}`)}function Nw(t){if(typeof window>"u")return;const n=Ko(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 Yr(t){t.keepaliveTimer&&(clearInterval(t.keepaliveTimer),t.keepaliveTimer=null)}function Id(t){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Ko(t.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),jw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function Sw(t){Yr(t),Ko(t.url,"keepalive")&&(Id(t),t.keepaliveTimer=window.setInterval(()=>{Id(t)},kw))}if(typeof window<"u"){const t=()=>{for(const s of Array.from(ei.values()))if(!s.closed){if(Yr(s),Nw(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,Go(i))};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t),window.addEventListener("pageshow",n)}function Ea(t){t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),t.heartbeatTimer=setTimeout(()=>{Eh(t)},vw)}function Eh(t){if(t.heartbeatTimer&&(clearTimeout(t.heartbeatTimer),t.heartbeatTimer=null),t.es&&(t.es.close(),t.es=null),Yr(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&&Go(t)},yw)}}function Go(t){if(t.es||t.closed)return;t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=null);const n=new EventSource(As(ww(t.url)));t.es=n,Sw(t),n.addEventListener("open",()=>{Ea(t);const s=t.hasOpenedOnce;t.hasOpenedOnce=!0;for(const i of t.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of t.subscribers)i.onError?.(s);Eh(t)}),n.addEventListener("message",()=>Ea(t)),n.addEventListener("heartbeat",()=>Ea(t)),Mh(t),Ea(t)}function Mh(t){if(!t.es)return;const n=new Set;for(const s of t.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(t.nativeListeners.has(s))continue;const i=r=>{Ea(t);const l=r;for(const o of t.subscribers){const d=o.events.get(s);if(d)for(const m of d)m(l)}};t.nativeListeners.set(s,i),t.es.addEventListener(s,i)}}function Cw(t){t.closed=!0,t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),Yr(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),Go(s),Mh(s);let r=!0;return()=>{if(!r)return;r=!1;const l=ei.get(t);l&&(l.subscribers.delete(i),l.subscribers.size===0&&Cw(l))}}const Jo="kb-planning-last-description",Yo="kb-subtask-last-description",Qo="kb-mission-last-goal";function Ew(t,n){us(Jo,t,n)}function Mw(t){return In(Jo,t)||""}function Ri(t){Da(Jo,t)}function Aw(t,n){us(Yo,t,n)}function Pw(t){return In(Yo,t)||""}function bl(t){Da(Yo,t)}function Tw(t,n){us(Qo,t,n)}function Rw(t){return In(Qo,t)||""}function Ys(t){Da(Qo,t)}function _w(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 Iw(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 $w(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 Ns({entries:t,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=$w(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?_w(l):void 0,h=l.question&&u!==void 0?Iw(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 $d="fusion-tab-id";function Dw(){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($d);if(t)return t;const n=Dw();return window.sessionStorage.setItem($d,n),n}function Qr(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(Sk(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=Ck(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=As(`/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(Ek(t,n)),i(!1),l(null)}finally{d(!1)}}},[t,n]);return{isLockedByOther:s,currentHolder:r,takeControl:m,isLoading:o}}const Fw="fusion:ai-session-sync",Dd="fusion:ai-session-sync",Lw=3e4,zw=6e4;function Rs(){return Date.now()}function Ow(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Fd(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 Bw{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=Ow(),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:Rs()})}broadcastUpdate(n){const s=n.timestamp??Rs();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??Rs();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=Rs();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=Rs();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Rs();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(Fw),this.channel.onmessage=s=>{const i=Fd(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Dd||!s.newValue))try{const i=JSON.parse(s.newValue),r=Fd(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Rs();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Lw)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Rs();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(Dd,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:Rs()});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=Rs(),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>zw;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 Bw;function ra(){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 Uw(t,n){return t&&n?`${t}/${n}`:""}function Hw(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 Vw({isOpen:t,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:l}){const[o,d]=a.useState(""),[m,c]=a.useState({type:"initial"}),[u,h]=a.useState(null),[g,p]=a.useState([]),[f,b]=a.useState([]),[x,y]=a.useState(null),[v,M]=a.useState(!1),N=a.useRef(!1),[A,w]=a.useState(""),[S,k]=a.useState(!0),[P,C]=a.useState(!1),[R,O]=a.useState(!1),[Z,I]=a.useState(!1),_=a.useRef(null),j=a.useRef(null),Q=a.useRef(null),Y=a.useRef(null),[L,D]=a.useState(l??null),U=a.useMemo(()=>Si(),[]),{isLockedByOther:G,takeControl:E,isLoading:J}=Qr(t?L:null),{activeTabMap:ue,broadcastUpdate:z,broadcastCompleted:te,broadcastLock:F,broadcastUnlock:fe,broadcastHeartbeat:V}=ra(),[K,de]=a.useState(void 0),[we,ve]=a.useState(void 0),[Se,Pe]=a.useState([]),[Oe,Ie]=a.useState(!0),[rt,Ee]=a.useState(null),[_e,Be]=a.useState([]),[et,De]=a.useState([]),Xe=Uw(K,we);a.useEffect(()=>{(async()=>{try{Ie(!0);const qe=await Jn();Pe(qe.models),Be(qe.favoriteProviders),De(qe.favoriteModels)}catch(qe){Ee(xe(qe)||"Failed to load models")}finally{Ie(!1)}})()},[]);const re=a.useCallback(Ce=>{Be(qe=>{const ce=qe,Ve=ce.includes(Ce)?ce.filter(Ae=>Ae!==Ce):[Ce,...ce];return Kt({favoriteProviders:Ve,favoriteModels:et}).catch(()=>{Be(ce)}),Ve})},[et]),ne=a.useCallback(Ce=>{De(qe=>{const ce=qe,Ve=ce.includes(Ce)?ce.filter(Ae=>Ae!==Ce):[Ce,...ce];return Kt({favoriteProviders:_e,favoriteModels:Ve}).catch(()=>{De(ce)}),Ve})},[_e]),ge=a.useCallback((Ce,qe)=>{if(!Ce||!qe)return"Using default";const ce=Se.find(Ue=>Ue.provider===Ce&&Ue.id===qe);return ce?`${ce.provider}/${ce.id}`:`${Ce}/${qe}`},[Se]),le=a.useCallback(Ce=>{j.current?.close();const qe=hk(Ce,i,{onThinking:ce=>{w(Ue=>Ue+ce),z({sessionId:Ce,status:"generating",needsInput:!1,owningTabId:U,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onQuestion:ce=>{C(!1),O(!1),Ys(i),c({type:"question",sessionId:Ce,question:ce}),w(""),M(!0),z({sessionId:Ce,status:"awaiting_input",needsInput:!0,owningTabId:U,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onSummary:ce=>{C(!1),O(!1),Ys(i),c({type:"summary",sessionId:Ce,summary:ce}),y(ce),w(""),M(!0),z({sessionId:Ce,status:"complete",needsInput:!1,owningTabId:U,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onError:ce=>{const Ue=ce||"Session failed while contacting the AI.";C(!1),O(!1),h(null),c({type:"error",sessionId:Ce,errorMessage:Ue}),w(""),M(!0),Q.current=Ce,z({sessionId:Ce,status:"error",needsInput:!1,owningTabId:U,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null}),te({sessionId:Ce,status:"error"})},onComplete:()=>{C(!1),O(!1),Q.current=null,te({sessionId:Ce,status:"complete"})},onConnectionStateChange:ce=>{C(ce==="reconnecting")}});j.current=qe},[te,z,o,i,U]),Te=a.useCallback(async Ce=>{const qe=Ce??o;if(qe.trim()){h(null),w(""),p([]),b([]),C(!1),c({type:"loading"});try{const{sessionId:ce}=await ck(qe.trim(),i,K&&we?{modelProvider:K,modelId:we}:void 0);Q.current=ce,D(ce),Ys(i),le(ce),p([])}catch(ce){C(!1),h(xe(ce)||"Failed to start interview session"),c({type:"initial"}),Q.current=null,D(null)}}},[le,o,K,we,i]);a.useEffect(()=>{t&&m.type==="initial"&&_.current?.focus()},[t,m.type]),a.useEffect(()=>{if(t&&r&&!N.current&&m.type==="initial"){d(r);const Ce=setTimeout(()=>{N.current=!0,Te(r)},0);return()=>clearTimeout(Ce)}else if(t&&!r&&!N.current&&m.type==="initial"){const Ce=Rw(i);Ce&&d(Ce)}},[t,r,m.type,Te]),a.useEffect(()=>{t||(N.current=!1,C(!1),O(!1),D(null))},[t]),a.useEffect(()=>{if(!t||!l||m.type!=="initial")return;let Ce=!1;return ti(l).then(qe=>{if(Ce||!qe)return;const ce=Ji(qe.conversationHistory);if(b(ce),D(qe.id),p(ce.map(Ue=>Ue.response).filter(Ue=>!!(Ue&&typeof Ue=="object"&&!Array.isArray(Ue)))),qe.status==="awaiting_input"&&qe.currentQuestion)try{Ys(i);const Ue=JSON.parse(qe.currentQuestion);Q.current=qe.id,M(!0),c({type:"question",sessionId:qe.id,question:Ue})}catch{h("Failed to restore session question.")}else if(qe.status==="complete"&&qe.result)try{Ys(i);const Ue=JSON.parse(qe.result);Q.current=qe.id,M(!0),y(Ue),c({type:"summary",sessionId:qe.id,summary:Ue})}catch{h("Failed to restore session result.")}else qe.status==="generating"?(Q.current=qe.id,M(!0),qe.thinkingOutput&&w(qe.thinkingOutput),c({type:"loading"}),le(qe.id)):qe.status==="error"&&(Q.current=qe.id,M(!0),h(null),c({type:"error",sessionId:qe.id,errorMessage:qe.error??"The session encountered an error."}))}).catch(()=>{Ce||h("Failed to resume session.")}),()=>{Ce=!0}},[le,t,l,m.type,i]),a.useEffect(()=>{if(!t){Y.current&&(fe(Y.current,U),Y.current=null);return}if(L&&Y.current!==L){Y.current&&fe(Y.current,U),F(L,U),Y.current=L;return}!L&&Y.current&&(fe(Y.current,U),Y.current=null)},[F,fe,t,L,U]),a.useEffect(()=>{if(!t||!L||Y.current!==L)return;V(U);const Ce=setInterval(()=>{V(U)},3e4);return()=>{clearInterval(Ce)}},[V,t,L,U]),a.useEffect(()=>()=>{j.current?.close(),j.current=null,Y.current&&(fe(Y.current,U),Y.current=null)},[fe,U]),a.useEffect(()=>{if(!t)return;const Ce=qe=>{(m.type==="question"||m.type==="summary")&&(qe.preventDefault(),qe.returnValue=""),j.current?.close()};return window.addEventListener("beforeunload",Ce),()=>window.removeEventListener("beforeunload",Ce)},[t,m]);const ye=a.useCallback(()=>{j.current?.close(),j.current=null,n()},[n]),He=a.useCallback(async()=>{if(o&&Tw(o,i),!(v&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(j.current?.close(),j.current=null,m.type==="question"||m.type==="summary"||m.type==="error")try{await mh(m.sessionId,i,U)}catch{}d(""),c({type:"initial"}),h(null),p([]),b([]),y(null),w(""),C(!1),O(!1),M(!1),I(!1),de(void 0),ve(void 0),Q.current=null,D(null),n()}},[o,v,m,n,i,U]);a.useEffect(()=>{if(!t)return;const Ce=qe=>{qe.key==="Escape"&&(v?confirm("Are you sure you want to close? Your interview progress will be lost.")&&He():He())};return document.addEventListener("keydown",Ce),()=>document.removeEventListener("keydown",Ce)},[t,v,He]);const nt=a.useCallback(async Ce=>{if(m.type!=="question")return;const{sessionId:qe}=m;h(null),p(ce=>[...ce,Ce]),b(ce=>[...ce,{question:m.question,response:Ce}]),c({type:"loading"}),w("");try{le(qe),await dk(qe,Ce,i,U),M(!0)}catch(ce){j.current?.close(),j.current=null,h(xe(ce)||"Failed to submit response"),c({type:"question",sessionId:qe,question:m.question})}},[m,i,U,le]),mt=a.useCallback(async()=>{if(m.type!=="error")return;const Ce=m.sessionId;h(null),O(!0),w(""),c({type:"loading"}),le(Ce);try{Q.current=Ce,D(Ce),await uk(Ce,i,U)}catch(qe){let ce=qe;if((xe(qe)||"").includes("not in an error state"))try{const Ve=await ti(Ce);if(!Ve)throw new Error("Failed to refresh interview session.");const Ae=Ji(Ve.conversationHistory);if(b(Ae),p(Ae.map(We=>We.response).filter(We=>!!(We&&typeof We=="object"&&!Array.isArray(We)))),Q.current=Ve.id,D(Ve.id),M(!0),Ve.status==="generating")w(Ve.thinkingOutput??""),c({type:"loading"}),j.current?.isConnected()||le(Ve.id);else if(Ve.status==="awaiting_input"){if(!Ve.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Ys(i);const We=JSON.parse(Ve.currentQuestion);c({type:"question",sessionId:Ve.id,question:We}),j.current?.isConnected()||le(Ve.id)}else if(Ve.status==="complete"){if(!Ve.result)throw new Error("Interview session is complete but has no result.");Ys(i);const We=JSON.parse(Ve.result);y(We),c({type:"summary",sessionId:Ve.id,summary:We})}else Ve.status==="error"&&c({type:"error",sessionId:Ve.id,errorMessage:Ve.error??"Retry failed. Please try again."});C(!1);return}catch(Ve){ce=Ve}j.current?.close(),j.current=null,c({type:"error",sessionId:Ce,errorMessage:xe(ce)||"Retry failed. Please try again."}),C(!1)}finally{O(!1)}},[le,i,U,m]),he=a.useCallback(async()=>{if(m.type==="summary"){h(null),I(!0);try{const Ce=await mk(m.sessionId,x||void 0,i);s(Ce),Ys(i),j.current?.close(),j.current=null,d(""),c({type:"initial"}),h(null),p([]),b([]),y(null),w(""),C(!1),O(!1),M(!1),I(!1),Q.current=null,D(null),n()}catch(Ce){h(xe(Ce)||"Failed to create mission"),I(!1)}}},[m,x,s,n,i]),ie=()=>m.type==="question"?Math.min(g.length+1,6):6,be=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",Me=L?ue.get(L):null,Ze=Me&&Me.tabId!==U,je=!!(Ze&&!Me.stale),tt=G&&(!Ze||Me.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:Ce=>Ce.target===Ce.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(ns,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Plan Mission with AI"})]}),e.jsxs("div",{className:"modal-header-actions",children:[be&&e.jsx("button",{className:"modal-send-to-background",onClick:ye,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(Dt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[u&&e.jsx("div",{className:"form-error planning-error",children:u}),P&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),je&&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:Ce=>d(Ce.target.value),onKeyDown:Ce=>{Ce.key==="Enter"&&!Ce.shiftKey&&o.trim()&&(Ce.preventDefault(),Te())}})]}),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((Ce,qe)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>d(Ce),children:Ce.length>45?Ce.slice(0,45)+"...":Ce},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(Gt,{id:"mission-interview-modal-model",label:"Planning Model",value:Xe,onChange:Ce=>{const{provider:qe,modelId:ce}=Hw(Ce);de(qe),ve(ce)},models:Se,disabled:Oe,favoriteProviders:_e,onToggleFavorite:re,favoriteModels:et,onToggleModelFavorite:ne}),rt&&e.jsxs("div",{className:"form-hint form-hint-error",children:[rt," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Ie(!0);const Ce=await Jn();Pe(Ce.models),Be(Ce.favoriteProviders),De(Ce.favoriteModels),Ee(null)}catch(Ce){Ee(xe(Ce)||"Failed to load models")}finally{Ie(!1)}})()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${K&&we?"model-badge-custom":"model-badge-default"}`,children:ge(K,we)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Te(),disabled:!o.trim(),children:[e.jsx(ns,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),m.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(lt,{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:()=>k(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&A&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:A})})]})]}),m.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{entries:f}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:m.errorMessage}),e.jsxs("div",{className:"ai-error-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:()=>void mt(),disabled:R,children:[R?e.jsx(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:He,disabled:R,children:"Cancel"})]})]})]})}),m.type==="question"&&e.jsx(Ww,{question:m.question,progress:ie(),historyEntries:f,onSubmit:nt}),m.type==="summary"&&x&&e.jsx(Kw,{summary:x,historyEntries:f,onSummaryChange:y,onApprove:he,onStartOver:()=>{c({type:"initial"}),M(!1),y(null),p([]),b([]),D(null),j.current?.close(),j.current=null},isCreating:Z}),G&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(qr,{size:16}),e.jsx("span",{children:tt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),tt&&e.jsx("button",{type:"button",onClick:()=>{E()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}function Ww({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(Ns,{entries:s}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-question-panel",children:[e.jsxs("div",{className:"planning-progress",children:[e.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(u=>e.jsx("div",{className:`planning-progress-step ${u<=n?"active":""}`},u))}),e.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),e.jsxs("div",{className:"planning-question-content",children:[e.jsx("h4",{className:"planning-question-text",children:t.question}),t.description&&e.jsx("p",{className:"planning-question-desc",children:t.description}),e.jsxs("div",{className:"planning-options",children:[t.type==="text"&&e.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:o,onChange:u=>d(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&o.trim()&&(u.preventDefault(),m())}}),t.type==="single_select"&&t.options&&e.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:t.options.map(u=>e.jsxs("label",{className:"planning-option planning-option--radio",children:[e.jsx("input",{type:"radio",name:t.id,value:u.id,checked:r[t.id]===u.id,onChange:()=>l({[t.id]:u.id})}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id))}),t.type==="multi_select"&&t.options&&e.jsx("div",{className:"planning-checkbox-group",children:t.options.map(u=>{const h=r[t.id]||[];return e.jsxs("label",{className:"planning-option planning-option--checkbox",children:[e.jsx("input",{type:"checkbox",value:u.id,checked:h.includes(u.id),onChange:g=>{const p=g.target.checked?[...h,u.id]:h.filter(f=>f!==u.id);l({[t.id]:p})}}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id)})}),t.type==="confirm"&&e.jsxs("div",{className:"planning-confirm-group",children:[e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!0?"selected":""}`,onClick:()=>l({[t.id]:!0}),children:[e.jsx(tn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Dt,{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 Kw({summary:t,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:l}){const[o,d]=a.useState(()=>new Set(t.milestones.map((N,A)=>A))),[m,c]=a.useState(()=>{const N=new Set;return t.milestones.forEach((A,w)=>{A.slices.forEach((S,k)=>N.add(`${w}-${k}`))}),N}),u=N=>{d(A=>{const w=new Set(A);return w.has(N)?w.delete(N):w.add(N),w})},h=N=>{c(A=>{const w=new Set(A);return w.has(N)?w.delete(N):w.add(N),w})},g=(N,A)=>{const w=[...t.milestones];w[N]={...w[N],...A},s({...t,milestones:w})},p=(N,A,w)=>{const S=[...t.milestones],k=[...S[N].slices];k[A]={...k[A],...w},S[N]={...S[N],slices:k},s({...t,milestones:S})},f=(N,A,w,S)=>{const k=[...t.milestones],P=[...k[N].slices],C=[...P[A].features];C[w]={...C[w],...S},P[A]={...P[A],features:C},k[N]={...k[N],slices:P},s({...t,milestones:k})},b=N=>{const A=t.milestones.filter((w,S)=>S!==N);s({...t,milestones:A})},x=(N,A)=>{const w=[...t.milestones];w[N]={...w[N],slices:w[N].slices.filter((S,k)=>k!==A)},s({...t,milestones:w})},y=(N,A,w)=>{const S=[...t.milestones],k=[...S[N].slices];k[A]={...k[A],features:k[A].features.filter((P,C)=>C!==w)},S[N]={...S[N],slices:k},s({...t,milestones:S})},v=(N,A)=>{const w=[...t.milestones],S=[...w[N].slices];S[A]={...S[A],features:[...S[A].features,{title:"New feature",description:""}]},w[N]={...w[N],slices:S},s({...t,milestones:w})},M=t.milestones.reduce((N,A)=>N+A.slices.reduce((w,S)=>w+S.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(Ns,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(tn,{size:24,className:"icon-success"}),e.jsx("h4",{children:"Mission Plan Ready"}),e.jsxs("p",{className:"text-muted",children:[t.milestones.length," milestones, ",M," 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:N=>s({...t,missionTitle:N.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:N=>s({...t,missionDescription:N.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Roadmap"}),e.jsx("div",{className:"roadmap-list",children:t.milestones.map((N,A)=>e.jsxs("div",{className:"roadmap-card",children:[e.jsxs("div",{className:"roadmap-card-header",onClick:()=>u(A),children:[o.has(A)?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:N.title,onChange:w=>g(A,{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(A)},title:"Remove milestone",children:e.jsx(Ht,{size:14,className:"icon-text-secondary"})})]}),o.has(A)&&e.jsxs("div",{className:"roadmap-card-body",children:[e.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:N.description||"",onChange:w=>g(A,{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:N.verification||"",onChange:w=>g(A,{verification:w.target.value})})]}),N.slices.map((w,S)=>{const k=`${A}-${S}`;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(ho,{size:14,className:"icon-slice"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:P=>p(A,S,{title:P.target.value}),onClick:P=>P.stopPropagation()}),N.slices.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:P=>{P.stopPropagation(),x(A,S)},title:"Remove slice",children:e.jsx(Ht,{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:P=>p(A,S,{verification:P.target.value})})]}),w.features.map((P,C)=>e.jsxs("div",{className:"roadmap-feature-row",children:[e.jsx(lo,{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:P.title,onChange:R=>f(A,S,C,{title:R.target.value})}),P.description&&e.jsx("p",{className:"roadmap-feature-text",children:P.description}),P.acceptanceCriteria&&e.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",P.acceptanceCriteria]})]}),e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>y(A,S,C),title:"Remove feature",children:e.jsx(Ht,{size:12,className:"icon-text-secondary"})})]},C)),e.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>v(A,S),children:[e.jsx(Vt,{size:12}),"Add Feature"]})]})]},S)})]})]},A))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:r,disabled:l,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Start Over"]}),e.jsx("button",{className:"btn btn-primary",onClick:i,disabled:l||t.milestones.length===0,children:l?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function Gw({isOpen:t,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:l,missionContext:o,projectId:d,resumeSessionId:m}){const[c,u]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[b,x]=a.useState([]),[y,v]=a.useState(null),[M,N]=a.useState(""),[A,w]=a.useState(!0),[S,k]=a.useState(!1),[P,C]=a.useState(!1),R=a.useRef(null),O=a.useRef(null),Z=a.useRef(null),I=a.useRef(null),[_,j]=a.useState(null),Q=a.useMemo(()=>Si(),[]);Qr(t?_:null);const{activeTabMap:Y,broadcastUpdate:L,broadcastCompleted:D,broadcastLock:U,broadcastUnlock:G,broadcastHeartbeat:E}=ra(),J=i==="milestone"?pk:vk,ue=i==="milestone"?fk:yk,z=i==="milestone"?gk:kk,te=i==="milestone"?bk:jk,F=i==="milestone"?xk:wk,fe=i==="milestone"?"Milestone":"Slice",V=i==="milestone"?"milestone_interview":"slice_interview",K=a.useCallback(De=>{O.current?.close();const Xe=z(De,d,{onThinking:re=>{N(ne=>ne+re),L({sessionId:De,status:"generating",needsInput:!1,owningTabId:Q,type:V,title:l,projectId:d??null})},onQuestion:re=>{k(!1),de(),u({type:"question",sessionId:De,question:re}),N(""),L({sessionId:De,status:"awaiting_input",needsInput:!0,owningTabId:Q,type:V,title:l,projectId:d??null})},onSummary:re=>{k(!1),de(),u({type:"summary",sessionId:De,summary:re}),v(re),N(""),L({sessionId:De,status:"complete",needsInput:!1,owningTabId:Q,type:V,title:l,projectId:d??null})},onError:re=>{const ne=re||"Session failed while contacting the AI.";k(!1),g(null),u({type:"error",sessionId:De,errorMessage:ne}),N(""),Z.current=De,L({sessionId:De,status:"error",needsInput:!1,owningTabId:Q,type:V,title:l,projectId:d??null}),D({sessionId:De,status:"error"})},onComplete:()=>{k(!1),Z.current=null,D({sessionId:De,status:"complete"})},onConnectionStateChange:re=>{k(re==="reconnecting")}});O.current=Xe},[D,L,z,V,d,Q,l]),de=()=>{v(null),f([]),x([]),N("")},we=a.useCallback(async()=>{g(null),de(),k(!1),u({type:"loading"});try{const{sessionId:De}=await J(r,d);Z.current=De,j(De),K(De)}catch(De){k(!1),g(xe(De)||`Failed to start ${fe.toLowerCase()} interview`),u({type:"initial"}),Z.current=null,j(null)}},[K,d,J,r,fe]),ve=a.useCallback(async()=>{g(null),C(!0);try{await F(r,d),s(),u({type:"applied"})}catch(De){g(xe(De)||`Failed to skip ${fe.toLowerCase()} interview`),C(!1)}},[s,d,F,r,fe]);a.useEffect(()=>{t&&c.type==="initial"&&R.current?.focus()},[t,c.type]),a.useEffect(()=>{if(!t||!m||c.type!=="initial")return;let De=!1;return ti(m).then(Xe=>{if(De||!Xe)return;const re=Ji(Xe.conversationHistory);if(x(re),j(Xe.id),f(re.map(ne=>ne.response).filter(ne=>!!(ne&&typeof ne=="object"&&!Array.isArray(ne)))),Xe.status==="awaiting_input"&&Xe.currentQuestion)try{const ne=JSON.parse(Xe.currentQuestion);Z.current=Xe.id,u({type:"question",sessionId:Xe.id,question:ne})}catch{g("Failed to restore session question.")}else if(Xe.status==="complete"&&Xe.result)try{const ne=JSON.parse(Xe.result);Z.current=Xe.id,v(ne),u({type:"summary",sessionId:Xe.id,summary:ne})}catch{g("Failed to restore session result.")}else Xe.status==="generating"?(Z.current=Xe.id,Xe.thinkingOutput&&N(Xe.thinkingOutput),u({type:"loading"}),K(Xe.id)):Xe.status==="error"&&(Z.current=Xe.id,g(null),u({type:"error",sessionId:Xe.id,errorMessage:Xe.error??"The session encountered an error."}))}).catch(()=>{De||g("Failed to resume session.")}),()=>{De=!0}},[K,t,m,c.type]),a.useEffect(()=>{t||(k(!1),j(null))},[t]),a.useEffect(()=>{if(!(!t||!_)){if(I.current!==_){I.current&&G(I.current,Q),U(_,Q),I.current=_;return}!_&&I.current&&(G(I.current,Q),I.current=null)}},[U,G,t,_,Q]),a.useEffect(()=>{if(!t||!_||I.current!==_)return;E(Q);const De=setInterval(()=>{E(Q)},3e4);return()=>{clearInterval(De)}},[E,t,_,Q]),a.useEffect(()=>()=>{O.current?.close(),O.current=null,I.current&&(G(I.current,Q),I.current=null)},[G,Q]);const Se=a.useCallback(()=>{O.current?.close(),O.current=null,n()},[n]),Pe=a.useCallback(async()=>{O.current?.close(),O.current=null,de(),u({type:"initial"}),g(null),Z.current=null,j(null),n()},[n]),Oe=a.useCallback(async De=>{if(c.type!=="question")return;const{sessionId:Xe}=c;g(null),f(re=>[...re,De]),x(re=>[...re,{question:c.question,response:De}]),u({type:"loading"}),N("");try{K(Xe),await ue(Xe,De,d,Q)}catch(re){O.current?.close(),O.current=null,g(xe(re)||"Failed to submit response"),u({type:"question",sessionId:Xe,question:c.question})}},[K,d,ue,Q,c]),Ie=a.useCallback(async()=>{if(c.type==="summary"){g(null),C(!0);try{await te(c.sessionId,y||void 0,d),s(),u({type:"applied"})}catch(De){g(xe(De)||"Failed to apply interview results"),C(!1)}}},[te,y,s,d,c]),rt=()=>c.type==="question"?Math.min(p.length+1,6):6,Ee=c.type==="loading"||c.type==="question"||c.type==="summary"||c.type==="error",_e=_?Y.get(_):null,et=!!(_e&&_e.tabId!==Q&&!_e.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:De=>De.target===De.currentTarget&&Pe(),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 ",fe,": ",l]})]}),e.jsxs("div",{className:"modal-header-actions",children:[Ee&&e.jsx("button",{className:"modal-send-to-background",onClick:Se,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:Pe,"aria-label":"Close",children:e.jsx(Dt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[h&&e.jsx("div",{className:"form-error planning-error",children:h}),S&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),et&&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 ",fe," 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 we(),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:P,children:[P?e.jsx(lt,{size:16,className:"spin"}):null,"Use Mission Context"]}),e.jsx("button",{className:"btn",onClick:Pe,children:"Cancel"})]})]}),c.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(lt,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:M?"AI is thinking...":"Preparing next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&M&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:M})})]})]}),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(Ns,{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:Pe,children:"Cancel"})})]})]})}),c.type==="question"&&e.jsx(Jw,{question:c.question,progress:rt(),historyEntries:b,onSubmit:Oe}),c.type==="summary"&&y&&e.jsx(Yw,{summary:y,historyEntries:b,onSummaryChange:v,onApply:Ie,onCancel:Pe,isApplying:P}),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(tn,{size:48,className:"icon-success"}),e.jsxs("h4",{children:[fe," 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 Jw({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(Ns,{entries:s}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-question-panel",children:[e.jsxs("div",{className:"planning-progress",children:[e.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(u=>e.jsx("div",{className:`planning-progress-step ${u<=n?"active":""}`},u))}),e.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),e.jsxs("div",{className:"planning-question-content",children:[e.jsx("h4",{className:"planning-question-text",children:t.question}),t.description&&e.jsx("p",{className:"planning-question-desc",children:t.description}),e.jsxs("div",{className:"planning-options",children:[t.type==="text"&&e.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:o,onChange:u=>d(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&o.trim()&&(u.preventDefault(),m())}}),t.type==="single_select"&&t.options&&e.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:t.options.map(u=>e.jsxs("label",{className:"planning-option planning-option--radio",children:[e.jsx("input",{type:"radio",name:t.id,value:u.id,checked:r[t.id]===u.id,onChange:()=>l({[t.id]:u.id})}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id))}),t.type==="multi_select"&&t.options&&e.jsx("div",{className:"planning-checkbox-group",children:t.options.map(u=>{const h=r[t.id]||[];return e.jsxs("label",{className:"planning-option planning-option--checkbox",children:[e.jsx("input",{type:"checkbox",value:u.id,checked:h.includes(u.id),onChange:g=>{const p=g.target.checked?[...h,u.id]:h.filter(f=>f!==u.id);l({[t.id]:p})}}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:u.label}),u.description&&e.jsx("span",{className:"planning-option-desc",children:u.description})]})]},u.id)})}),t.type==="confirm"&&e.jsxs("div",{className:"planning-confirm-group",children:[e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!0?"selected":""}`,onClick:()=>l({[t.id]:!0}),children:[e.jsx(tn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Dt,{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 Yw({summary:t,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:l}){const[o,d]=a.useState(t),[m,c]=a.useState(!0),u=(h,g)=>{const p={...o,[h]:g};d(p),s(p)};return e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{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(lt,{size:16,className:"spin"}):null,"Apply"]}),e.jsx("button",{className:"btn",onClick:r,disabled:l,children:"Cancel"})]})]})}const ma={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"},archived:{bg:"var(--mission-archived-bg)",text:"var(--mission-archived-text)"}},Ld={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)"}},zd={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)"}},Od={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)"}},Qw=3;function Xw(t){return t==="completed"?"planned":t==="needs_update"?"needs_update":"not_started"}function Bd({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 Ud(t){return t?t.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const xl={title:"",description:"",status:"planning",autopilotEnabled:!1},vl={title:"",description:"",status:"planning",dependencies:[]},yl={title:"",description:"",status:"pending"},kl={title:"",description:"",acceptanceCriteria:"",status:"defined"},Zw=3600*1e3;function _r(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 eN(t){if(!t)return"healthy";const n=typeof t.lastErrorAt=="string"&&Date.now()-new Date(t.lastErrorAt).getTime()<=Zw,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 tN(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 nN(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 jl(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 Ah=["feature_triaged","feature_completed"],Ph=["slice_activated","slice_completed","milestone_completed"],Th=["mission_started","mission_paused","mission_resumed","mission_completed"],Rh=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Hd(t,n){switch(n){case"errors":return t==="error"||t==="warning";case"state_changes":return Th.includes(t);case"tasks":return Ah.includes(t);case"slices":return Ph.includes(t);case"autopilot":return Rh.includes(t);default:return!0}}function sN(t){return t==="error"||t==="warning"?"mission-event__type--error":Th.includes(t)?"mission-event__type--state":Ah.includes(t)?"mission-event__type--task":Ph.includes(t)?"mission-event__type--slice":Rh.includes(t)?"mission-event__type--autopilot":"mission-event__type--default"}function iN(t){return t.replace(/_/g," ")}function aN(t,n){return n?t==="watching"?`Watching since ${_r(n)}`:`Last activation ${_r(n)}`:null}function rN({isOpen:t,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:l,availableTasks:o=[],resumeSessionId:d,targetMissionId:m,milestoneSliceResumeSessionId:c,onMilestoneSliceResumeFetchError:u}){const h=n||t,[g,p]=a.useState([]),[f,b]=a.useState(null),[x,y]=a.useState(!0),[v,M]=a.useState(!1),[N,A]=a.useState(!1),[w,S]=a.useState(null),[k,P]=a.useState(xl),[C,R]=a.useState(!1),[O,Z]=a.useState(new Set),[I,_]=a.useState(new Set),[j,Q]=a.useState(null),[Y,L]=a.useState(vl),[D,U]=a.useState(!1),[G,E]=a.useState(null),[J,ue]=a.useState(yl),[z,te]=a.useState(!1),[F,fe]=a.useState(null),[V,K]=a.useState(null),[de,we]=a.useState(kl),[ve,Se]=a.useState(!1),[Pe,Oe]=a.useState(null),[Ie,rt]=a.useState(null),[Ee,_e]=a.useState(""),[Be,et]=a.useState(!1),[De,Xe]=a.useState([]),[re,ne]=a.useState(void 0),ge=re??d,[le,Te]=a.useState(null),[ye,He]=a.useState(null),[nt,mt]=a.useState(null);a.useEffect(()=>{h&&ge&&et(!0)},[h,ge]),a.useEffect(()=>{if(!h||ge)return;let H=!1;return hh(r).then(Ne=>{if(H)return;const Le=Ne.filter(ft=>ft.type==="mission_interview"&&(ft.status==="awaiting_input"||ft.status==="error"));Xe(Le)}).catch(Ne=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ne)}),()=>{H=!0}},[h,r,ge]),a.useEffect(()=>{if(!h||!c)return;let H=!1;return ti(c).then(Ne=>{if(!(H||!Ne))try{const Le=JSON.parse(Ne.inputPayload||"{}");Le.targetId&&Le.targetType&&Te({type:Le.targetType,id:Le.targetId,title:Le.targetTitle||Ne.title,resumeSessionId:c})}catch{Te({type:"milestone",id:"",title:Ne.title,resumeSessionId:c})}}).catch(Ne=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ne),u?.())}),()=>{H=!0}},[h,c,u]);const[he,ie]=a.useState(null),[be,Me]=a.useState(new Map),[Ze,je]=a.useState(null),[tt,Ce]=a.useState({title:"",assertion:"",status:"pending"}),[qe,ce]=a.useState(!1),[Ue,Ve]=a.useState(null),[Ae,We]=a.useState(new Map),[xt,yt]=a.useState(new Set),[Ct,Tt]=a.useState(new Set),[Et,Mt]=a.useState(null),[vt,Ft]=a.useState(new Map),[Je,pt]=a.useState(null),[ze,at]=a.useState(null),[q,$]=a.useState(!0),[pe,ct]=a.useState(new Set),[bt,Nt]=a.useState(new Map),[Bt,Lt]=a.useState(null),[wn,hn]=a.useState(new Map),[nn,Pn]=a.useState(null),[on,Un]=a.useState(new Map),[gn,Zt]=a.useState(new Map),[Wt,Tn]=a.useState("structure"),[bn,sn]=a.useState([]),Hn=a.useRef([]),xn=a.useRef([]),qt=a.useRef(null),$n=a.useRef(null),qn=a.useRef("structure"),Nn=a.useRef("all"),[Dn,se]=a.useState(!1),[Fe,st]=a.useState(0),[T,W]=a.useState("all"),[ee,me]=a.useState(new Set),ke=a.useRef(null),Re=a.useRef(null);xn.current=g,qt.current=f,$n.current=Je,qn.current=Wt,Nn.current=T;const dt=a.useCallback((H="auto")=>{const Ne=Re.current;if(Ne&&typeof Ne.scrollIntoView=="function"){Ne.scrollIntoView({block:"end",behavior:H});return}const Le=ke.current;Le&&(Le.scrollTop=Le.scrollHeight)},[]),Rt=a.useCallback(()=>{const H=ke.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),pn=a.useCallback(async H=>{if(H.length===0){Zt(new Map);return}const Ne=await Dy(r);Zt(Le=>{const ft=new Map(Le);for(const[Yt,At]of Object.entries(Ne))tN(At)&&ft.set(Yt,At);return ft})},[r]),kt=a.useCallback(async()=>{try{y(!0);const H=await Ty(r);p(H),pn(H)}catch(H){i(xe(H)||"Failed to load missions","error")}finally{y(!1)}},[i,r,pn]),ht=a.useCallback(async H=>{try{M(!0);const Ne=await uh(H,r);if(b(Ne),Ne.milestones.length>0){const Le=Ne.milestones[0].id;pt(Le),$(!0),Z(new Set([Le])),ml(Le,r).then(ft=>{Me(Yt=>{const At=new Map(Yt);return At.set(Le,ft),At})}).catch(()=>{}),hl(Le,r).then(ft=>{Ft(Yt=>{const At=new Map(Yt);return At.set(Le,ft),At})}).catch(()=>{}),Ne.milestones[0].slices.length>0&&_(new Set([Ne.milestones[0].slices[0].id]))}else pt(null),at(null)}catch(Ne){i(xe(Ne)||"Failed to load mission details","error")}finally{M(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Je){at(null);return}let H=!1;return at(null),rd(Je,r).then(Ne=>{if(!H){if(!jl(Ne)){at(null);return}at(Ne),Ft(Le=>{const ft=new Map(Le);return ft.set(Je,Ne.rollup),ft})}}).catch(()=>{H||at(null)}),()=>{H=!0}},[h,Je,r]),a.useEffect(()=>{$(!0)},[Je]);const Ps=a.useCallback(H=>{!H||H!==$n.current||rd(H,r).then(Ne=>{$n.current!==H||!jl(Ne)||(at(Ne),Ft(Le=>{const ft=new Map(Le);return ft.set(H,Ne.rollup),ft}))}).catch(()=>{})},[r]),oe=a.useCallback(async(H,Ne)=>{const Le=Ne?.append??!1,ft=Le?Hn.current.length:0;Le||(se(!0),me(new Set));try{const Yt=await $y(H,{limit:50,offset:ft,eventType:void 0},r),At=Yt.events.filter(Ut=>Hd(Ut.eventType,T));sn(Ut=>{if(!Le)return At;const Ke=new Set(Ut.map(gt=>gt.id)),Ye=[...Ut];for(const gt of At)Ke.has(gt.id)||Ye.push(gt);return Ye}),st(Yt.total),Le||requestAnimationFrame(()=>{dt("auto")})}catch(Yt){i(xe(Yt)||"Failed to load mission activity","error")}finally{Le||se(!1)}},[i,T,r,dt]);a.useEffect(()=>{Hn.current=bn},[bn]),a.useEffect(()=>{h&&(kt(),b(null),pt(null),at(null),sn([]),st(0),Tn("structure"),W("all"),me(new Set))},[h,kt]);const $e=a.useRef(null);a.useEffect(()=>{h&&m&&$e.current!==m&&g.length>0&&($e.current=m,ht(m))},[h,m,g,ht]),a.useEffect(()=>{h||($e.current=null)},[h]),a.useEffect(()=>{!h||!f||Wt!=="activity"||oe(f.id)},[Wt,h,oe,f,T]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const Ne=`/api/events${H.size>0?`?${H.toString()}`:""}`,Le=()=>{pn(xn.current)},ft=_n=>{Le();const un=_n;if(un.data)try{const _t=JSON.parse(un.data);_t?.id&&p(di=>di.map(xs=>xs.id===_t.id?{...xs,..._t}:xs))}catch{}qt.current&&ht(qt.current.id)},Yt=_n=>{Le(),qt.current&&ht(qt.current.id)},At=()=>{Le(),qt.current&&ht(qt.current.id)},Ut=_n=>{Le(),qt.current&&ht(qt.current.id)},Ke=_n=>{const un=_n;if(un.data)try{const _t=JSON.parse(un.data);_t&&_t.featureId&&(oi(_t.featureId),Ei(_t.featureId),_t.milestoneId&&Ps(_t.milestoneId))}catch{}},Ye=_n=>{const un=_n;if(un.data)try{const _t=JSON.parse(un.data);_t&&_t.featureId&&(oi(_t.featureId),Ei(_t.featureId),_t.milestoneId&&Ps(_t.milestoneId),qt.current&&ht(qt.current.id))}catch{}},gt=_n=>{const un=_n;if(un.data)try{const _t=JSON.parse(un.data);_t&&_t.milestoneId&&(Js(_t.milestoneId),Ps(_t.milestoneId))}catch{}},Qt=_n=>{const un=_n;if(un.data)try{const _t=JSON.parse(un.data);_t&&_t.milestoneId&&(ri(_t.milestoneId),Js(_t.milestoneId),Ps(_t.milestoneId))}catch{}};return Os(Ne,{events:{"mission:updated":ft,"slice:updated":Yt,"feature:updated":At,"milestone:updated":Ut,"mission:event":_n=>{Le();const un=qt.current;if(!un||qn.current!=="activity")return;const _t=Rt(),di=_n;if(di.data)try{const xs=JSON.parse(di.data);if(!nN(xs)||xs.missionId!==un.id||!Hd(xs.eventType,Nn.current))return;sn(Hs=>{const cl=Hs.filter(dl=>dl.id!==xs.id);return[xs,...cl].slice(0,100)}),st(Hs=>Hs+1),_t&&requestAnimationFrame(()=>{const Hs=ke.current;Hs&&(Hs.scrollTop=0)})}catch{}},"validator-run:started":Ke,"validator-run:completed":Ye,"milestone:validation:updated":gt,"assertion:created":Qt,"assertion:updated":Qt,"assertion:deleted":Qt,"assertion:linked":Qt,"assertion:unlinked":Qt,"fix-feature:created":_n=>{const un=_n;if(un.data)try{const _t=JSON.parse(un.data);if(_t&&_t.sourceFeatureId){oi(_t.sourceFeatureId);const di=_t?.feature?.sliceId,xs=qt.current;if(di&&xs){const Hs=xs.milestones.find(cl=>cl.slices.some(dl=>dl.id===di));Hs&&Ps(Hs.id)}qt.current&&ht(qt.current.id)}}catch{}}}})},[h,Rt,ht,pn,r,Ps]);const ot=a.useCallback(()=>{A(!0),S(null),P(xl)},[]),jt=a.useCallback(H=>{S(H.id),A(!1),P({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),St=a.useCallback(()=>{S(null),A(!1),P(xl)},[]),cn=a.useCallback(async()=>{if(!k.title.trim()){i("Mission title is required","error");return}try{if(R(!0),N)await Ry({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 _y(w,H,r),i("Mission updated","success"),f?.id===w&&await ht(w)}await kt(),St()}catch(H){i(xe(H)||"Failed to save mission","error")}finally{R(!1)}},[k,N,w,i,kt,ht,f,St,r]),dn=a.useCallback(async H=>{try{await Iy(H,r),i("Mission deleted","success"),f?.id===H&&b(null),await kt(),ie(null)}catch(Ne){i(xe(Ne)||"Failed to delete mission","error")}},[i,kt,f,r]),mn=a.useCallback(()=>{U(!0),Q(null),L(vl)},[]),fn=a.useCallback(H=>{Q(H.id),U(!1),L({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),vn=a.useCallback(()=>{Q(null),U(!1),L(vl)},[]),Sn=a.useCallback(async()=>{if(!Y.title.trim()){i("Milestone title is required","error");return}try{R(!0),D&&f?(await Fy(f.id,{title:Y.title.trim(),description:Y.description.trim()||void 0,dependencies:Y.dependencies},r),i("Milestone created","success")):j&&(await Ly(j,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status,dependencies:Y.dependencies},r),i("Milestone updated","success")),await ht(f.id),vn()}catch(H){i(xe(H)||"Failed to save milestone","error")}finally{R(!1)}},[Y,D,j,f,i,ht,vn,k.title,r]),rs=a.useCallback(async H=>{try{await zy(H,r),i("Milestone deleted","success"),await ht(f.id),ie(null)}catch(Ne){i(xe(Ne)||"Failed to delete milestone","error")}},[i,ht,f,r]),Vn=a.useCallback(H=>{pt(H),$(!0),Z(Ne=>{const Le=new Set(Ne);return!Le.has(H)?(Le.add(H),ml(H,r).then(Yt=>{Me(At=>{const Ut=new Map(At);return Ut.set(H,Yt),Ut})}).catch(()=>{}),hl(H,r).then(Yt=>{Ft(At=>{const Ut=new Map(At);return Ut.set(H,Yt),Ut})}).catch(()=>{})):Le.delete(H),Le})},[r]),Cn=a.useCallback(H=>{fe(H),te(!0),E(null),ue(yl)},[]),Rn=a.useCallback(H=>{E(H.id),te(!1),ue({title:H.title,description:H.description||"",status:H.status})},[]),Qn=a.useCallback(()=>{E(null),te(!1),fe(null),ue(yl)},[]),yn=a.useCallback(async()=>{if(!J.title.trim()){i("Slice title is required","error");return}try{R(!0),z&&F?(await Oy(F,{title:J.title.trim(),description:J.description.trim()||void 0},r),i("Slice created","success")):G&&(await By(G,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status},r),i("Slice updated","success")),await ht(f.id),Qn()}catch(H){i(xe(H)||"Failed to save slice","error")}finally{R(!1)}},[J,z,G,F,f,i,ht,Qn,r]),Wn=a.useCallback(async H=>{try{await Uy(H,r),i("Slice deleted","success"),await ht(f.id),ie(null)}catch(Ne){i(xe(Ne)||"Failed to delete slice","error")}},[i,ht,f,r]),ps=a.useCallback(async H=>{try{await Hy(H,r),i("Slice activated","success"),await ht(f.id)}catch(Ne){i(xe(Ne)||"Failed to activate slice","error")}},[i,ht,f,r]),Xn=a.useCallback(H=>{_(Ne=>{const Le=new Set(Ne);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),fs=a.useCallback(H=>{Oe(H),Se(!0),K(null),we(kl)},[]),Fn=a.useCallback(H=>{K(H.id),Se(!1),we({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),ae=a.useCallback(()=>{K(null),Se(!1),Oe(null),we(kl)},[]),Qe=a.useCallback(async()=>{if(!de.title.trim()){i("Feature title is required","error");return}try{R(!0),ve&&Pe?(await qy(Pe,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):V&&(await Vy(V,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0,status:de.status},r),i("Feature updated","success")),await ht(f.id),ae()}catch(H){i(xe(H)||"Failed to save feature","error")}finally{R(!1)}},[de,ve,V,Pe,f,i,ht,ae,r]),ut=a.useCallback(async H=>{try{await Wy(H,r),i("Feature deleted","success"),await ht(f.id),ie(null)}catch(Ne){i(xe(Ne)||"Failed to delete feature","error")}},[i,ht,f,r]),It=a.useCallback(async()=>{if(!Ie||!Ee.trim()){i("Task ID is required","error");return}try{await Ky(Ie,Ee.trim(),r),i("Feature linked to task","success"),await ht(f.id),rt(null),_e("")}catch(H){i(xe(H)||"Failed to link feature to task","error")}},[Ie,Ee,i,ht,f,r]),Ss=a.useCallback(async H=>{try{await Gy(H,r),i("Feature unlinked from task","success"),await ht(f.id)}catch(Ne){i(xe(Ne)||"Failed to unlink feature","error")}},[i,ht,f,r]),gs=a.useCallback(async H=>{try{R(!0),await Jy(H,void 0,void 0,r),i("Feature triaged — task created","success"),await ht(f.id)}catch(Ne){i(xe(Ne)||"Failed to triage feature","error")}finally{R(!1)}},[i,ht,f,r]),sl=a.useCallback(async H=>{mt(H);try{const Ne=await Nk(H,r);He({featureId:H,enrichedDescription:Ne.description})}catch{await gs(H)}finally{mt(null)}},[gs,r]),Xa=a.useCallback(async()=>{ye&&(He(null),await gs(ye.featureId))},[gs,ye]),il=a.useCallback(()=>{He(null)},[]),al=a.useCallback(async H=>{try{R(!0);const Ne=await Yy(H,r);i(`Triaged ${Ne.count} feature${Ne.count!==1?"s":""}`,"success"),await ht(f.id)}catch(Ne){i(xe(Ne)||"Failed to triage slice features","error")}finally{R(!1)}},[i,ht,f,r]),ri=a.useCallback(async H=>{try{const Ne=await ml(H,r);Me(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch{}},[r]),Js=a.useCallback(async H=>{try{const Ne=await hl(H,r);Ft(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch{}},[r]),bc=a.useCallback(async H=>{if(!tt.title.trim()||!tt.assertion.trim()){i("Title and assertion text are required","error");return}try{R(!0),await Qy(H,{title:tt.title.trim(),assertion:tt.assertion.trim(),status:tt.status},r),i("Assertion created","success"),await ri(H),await Js(H),ce(!1),Ce({title:"",assertion:"",status:"pending"})}catch(Ne){i(xe(Ne)||"Failed to create assertion","error")}finally{R(!1)}},[tt,i,ri,Js,r]),Us=a.useCallback(H=>{je(H.id),Ce({title:H.title,assertion:H.assertion,status:H.status})},[]),li=a.useCallback(()=>{je(null),ce(!1),Ce({title:"",assertion:"",status:"pending"})},[]),rl=a.useCallback(async(H,Ne)=>{if(!tt.title.trim()||!tt.assertion.trim()){i("Title and assertion text are required","error");return}try{R(!0),await Xy(H,{title:tt.title.trim(),assertion:tt.assertion.trim(),status:tt.status},r),i("Assertion updated","success"),await ri(Ne),await Js(Ne),li()}catch(Le){i(xe(Le)||"Failed to update assertion","error")}finally{R(!1)}},[tt,i,ri,Js,li,r]),Ts=a.useCallback(async H=>{try{const Ne=await tk(H,r);We(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch{}},[r]),xc=a.useCallback(async H=>{const Ne=Ue!==H;Ve(Le=>Le===H?null:H),Ne&&await Ts(H)},[Ue,Ts]),vc=a.useCallback(H=>{Ve(H),Ts(H),requestAnimationFrame(()=>{const Ne=document.querySelector(`[data-mission-assertion-id="${H}"]`);Ne instanceof HTMLElement&&typeof Ne.scrollIntoView=="function"&&Ne.scrollIntoView({behavior:"smooth",block:"center"})})},[Ts]),cf=a.useCallback(async(H,Ne)=>{try{yt(Le=>new Set(Le).add(Ne)),await Zy(H,Ne,r),i("Feature linked to assertion","success"),await Ts(Ne),Mt(null)}catch(Le){i(xe(Le)||"Failed to link feature","error")}finally{yt(Le=>{const ft=new Set(Le);return ft.delete(Ne),ft})}},[i,Ts,r]),df=a.useCallback(async(H,Ne)=>{const Le=`${H}-${Ne}`;try{Tt(ft=>new Set(ft).add(Le)),await ek(H,Ne,r),i("Feature unlinked from assertion","success"),await Ts(Ne)}catch(ft){i(xe(ft)||"Failed to unlink feature","error")}finally{Tt(ft=>{const Yt=new Set(ft);return Yt.delete(Le),Yt})}},[i,Ts,r]),uf=a.useCallback(async H=>{try{ct(Le=>new Set(Le).add(H)),await nk(H,r),i("Validation triggered","success");const Ne=await ld(H,r);Nt(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch(Ne){i(xe(Ne)||"Failed to trigger validation","error")}finally{ct(Ne=>{const Le=new Set(Ne);return Le.delete(H),Le})}},[i,r]),oi=a.useCallback(async H=>{try{const Ne=await ld(H,r);Nt(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch{}},[r]),Ei=a.useCallback(async H=>{try{const Ne=await sk(H,{limit:10},r);hn(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch{}},[r]),Za=a.useCallback(H=>{const Ne=qt.current;if(Ne){for(const Le of Ne.milestones)for(const ft of Le.slices)if(ft.features.find(At=>At.id===H)){Z(At=>{const Ut=new Set(At);return Ut.add(Le.id),Ut}),_(At=>{const Ut=new Set(At);return Ut.add(ft.id),Ut}),Lt(H),pt(Le.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]),yc=a.useCallback(async H=>{try{const Ne=await ik(H,r);Un(Le=>{const ft=new Map(Le);return ft.set(H,Ne),ft})}catch{}},[r]),mf=a.useCallback(async H=>{Bt===H?Lt(null):(Lt(H),await oi(H),await Ei(H))},[Bt,oi,Ei]),hf=a.useCallback(async H=>{nn===H?Pn(null):(Pn(H),await yc(H))},[nn,yc]),kc=a.useCallback(async H=>{try{await ak(H,r),i("Mission resumed","success"),await ht(H),kt()}catch(Ne){i(xe(Ne)||"Failed to resume mission","error")}},[i,ht,kt,r]),jc=a.useCallback(async H=>{try{const Le=(await rk(H,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Le} task${Le!==1?"s":""} paused)`,"success"),await ht(H),kt()}catch(Ne){i(xe(Ne)||"Failed to stop mission","error")}},[i,ht,kt,r]),wc=a.useCallback(async H=>{try{await lk(H,r),i("Mission started — first slice activated","success"),await ht(H),kt()}catch(Ne){i(xe(Ne)||"Failed to start mission","error")}},[i,ht,kt,r]),pf=a.useCallback(async(H,Ne)=>{try{await ok(H,{enabled:Ne},r),i(Ne?"Autopilot enabled":"Autopilot disabled","success"),await ht(H),kt()}catch(Le){i(xe(Le)||"Failed to update autopilot","error")}},[i,ht,kt,r]),Nc=a.useCallback(H=>{Tn("structure"),pt(null),at(null),sn([]),st(0),W("all"),me(new Set),ht(H.id)},[ht]),ff=a.useCallback(()=>{b(null),pt(null),at(null),Tn("structure"),sn([]),st(0),W("all"),me(new Set),kt()},[kt]),ll=bn.length<Fe,Mi=f?.autopilotState??"inactive",Sc=Mi==="watching"||Mi==="activating",Cc=aN(Mi,f?.lastAutopilotActivityAt),er=a.useMemo(()=>!ze||!Je||!jl(ze)?null:ze.rollup.milestoneId===Je?ze:null,[Je,ze]),gf=a.useMemo(()=>{const H=new Map;for(const Ne of er?.validationTelemetry.validationRounds??[]){const Le=H.get(Ne.featureId);(!Le||Ne.startedAt>Le.startedAt)&&H.set(Ne.featureId,Ne)}return H},[er]),bf=a.useCallback(()=>{!f||Dn||!ll||oe(f.id,{append:!0})},[Dn,ll,oe,f]),xf=a.useCallback(H=>{me(Ne=>{const Le=new Set(Ne);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),ol=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),cn())},[cn]),Ec=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Sn())},[Sn]),Mc=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),yn())},[yn]),Ac=a.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Qe())},[Qe]),vf=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const H=Ne=>{Ne.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const Pc=e.jsxs("div",{ref:vf,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[e.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[e.jsxs("div",{className:"mission-manager__header-title",children:[f?e.jsx("button",{className:"mission-manager__back-btn",onClick:ff,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:e.jsx(zo,{size:18})}):null,e.jsx(ns,{size:18,className:"mission-manager__header-icon"}),e.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&e.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:e.jsx(Dt,{size:18})})]}),e.jsx("div",{className:"mission-manager__body",children:x?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(lt,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading missions..."})]}):v?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(lt,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading mission details..."})]}):f?e.jsxs("div",{className:"mission-detail",children:[e.jsxs("div",{className:"mission-detail__header",children:[e.jsxs("div",{className:"mission-detail__title-row",children:[e.jsxs("div",{className:"mission-detail__title-text",children:[Sc&&e.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),e.jsx("h3",{className:"mission-detail__title",children:f.title})]}),e.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(ma[f.status]||ma.planning).bg,color:(ma[f.status]||ma.planning).text},children:f.status})]}),f.description&&e.jsx("p",{className:"mission-detail__description",children:f.description}),e.jsx("div",{className:"mission-detail__meta",children:e.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),e.jsxs("div",{className:"mission-detail__autopilot",children:[e.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[e.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[e.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:H=>pf(f.id,H.target.checked),"aria-label":"Autopilot"}),e.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:e.jsx("span",{className:"mission-toggle__thumb"})}),e.jsxs("span",{className:"mission-toggle__label",children:[e.jsx(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:[Sc&&e.jsx("span",{className:"mission-detail__autopilot-pulse"}),Mi]})]}),Cc&&e.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Cc})]}),e.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>jc(f.id),title:"Stop mission","aria-label":"Stop mission",children:e.jsx(os,{size:14})}),f.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>kc(f.id),title:"Resume mission","aria-label":"Resume mission",children:e.jsx(rn,{size:14})}),f.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>wc(f.id),title:"Start mission","aria-label":"Start mission",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>jt(f),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:()=>ie({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:e.jsx(Ht,{size:14})})]})]}),w===f.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:H=>P({...k,title:H.target.value}),onKeyDown:ol,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:H=>P({...k,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:k.status,onChange:H=>P({...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=>P({...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:cn,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[e.jsx("button",{className:`mission-btn ${Wt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Tn("structure"),role:"tab","aria-selected":Wt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),e.jsxs("button",{className:`mission-btn ${Wt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Tn("activity"),role:"tab","aria-selected":Wt==="activity","data-testid":"mission-tab-activity",children:["Activity (",Fe,")"]})]}),Wt==="structure"?e.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(H=>{const Ne=er?.rollup.milestoneId===H.id?er:null,Le=Ne?.rollup??vt.get(H.id),ft=Ne?.validationTelemetry.validationRounds??[],Yt=Ne?.fixFeatures??[],At=Od[Le?.state??"not_started"]??Od.not_started,Ut=Le&&(Le.state==="blocked"||Le.state==="failed")?Ne?.validationTelemetry.validationRounds.find(Ke=>Ke.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:O.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:Ld[H.status].bg,color:Ld[H.status].text},children:H.status}),e.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),e.jsx(Bd,{state:Xw(H.interviewState)}),Le&&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:Ud(Le.state)}),Le.totalAssertions>0&&e.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Le.passedAssertions??0} of ${Le.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Le.passedAssertions??0)/Le.totalAssertions*100}%`,backgroundColor:(Le.passedAssertions??0)===Le.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>Te({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:Ke=>Ke.stopPropagation(),children:[e.jsx("button",{className:"mission-icon-btn",onClick:()=>Cn(H.id),title:"Add slice",children:e.jsx(Vt,{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:()=>ie({type:"milestone",id:H.id}),title:"Delete milestone",children:e.jsx(Ht,{size:14})})]})]}),O.has(H.id)&&e.jsxs("div",{className:"mission-milestone__body",children:[(D||j===H.id)&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:Ke=>L({...Y,title:Ke.target.value}),onKeyDown:Ec,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:Ke=>L({...Y,description:Ke.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Sn,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),j?"Update":"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vn,children:"Cancel"})]})]}),Ne&&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:[Ne.validationTelemetry.totalRuns," rounds",Ne.validationTelemetry.lastValidatorStatus?` · Last ${Ne.validationTelemetry.lastValidatorStatus}`:""]})]}),Ut&&e.jsxs("div",{className:"mission-blocked-reason",children:[e.jsx("strong",{children:"Blocked reason:"})," ",Ut]}),ft.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:()=>$(Ke=>!Ke),title:q?"Hide validation rounds":"Show validation rounds",children:[q?e.jsx(zt,{size:12}):e.jsx(ln,{size:12}),"Validation rounds (",ft.length,")"]}),q&&e.jsx("div",{className:"mission-validation-rounds__list",children:ft.map(Ke=>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--${Ke.validatorStatus}`,children:Ke.validatorStatus}),e.jsx("span",{className:"mission-validation-round__feature",children:Ke.featureTitle}),e.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ke.implementationAttempt," · validator #",Ke.validatorAttempt]})]}),e.jsxs("div",{className:"mission-validation-round__links",children:[e.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ke.failedAssertionIds.length>0?e.jsx("div",{className:"mission-validation-round__chip-list",children:Ke.failedAssertionIds.map(Ye=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>vc(Ye),title:`Jump to assertion ${Ye}`,children:Ye},`${Ke.roundId}-${Ye}`))}):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:"}),Ke.generatedFixFeatureIds.length>0?e.jsx("div",{className:"mission-validation-round__chip-list",children:Ke.generatedFixFeatureIds.map(Ye=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Za(Ye),title:`Jump to fix feature ${Ye}`,children:Ye},`${Ke.roundId}-${Ye}`))}):e.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ke.blockedReason&&e.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ke.blockedReason})]},Ke.roundId))})]}),Yt.length>0&&e.jsxs("div",{className:"mission-fix-features",children:[e.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),e.jsx("div",{className:"mission-fix-features__list",children:Yt.map(Ke=>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(Ke.id),title:`Jump to feature ${Ke.id}`,children:Ke.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:ar[Ke.status].bg,color:ar[Ke.status].text},children:Ke.status}),Ke.loopState&&e.jsx("span",{className:`mission-loop-state mission-loop-state--${Ke.loopState}`,children:Ke.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(Ke.sourceFeatureId),title:`Jump to source feature ${Ke.sourceFeatureId}`,children:Ke.sourceFeatureId}),e.jsx("span",{children:"Run:"}),e.jsx("span",{className:"mission-fix-feature__run",children:Ke.runId})]}),Ke.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:Ke.failedAssertionIds.map(Ye=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>vc(Ye),title:`Jump to assertion ${Ye}`,children:Ye},`${Ke.id}-${Ye}`))})]})]},Ke.id))})]})]}),e.jsxs("div",{className:"mission-slices",children:[H.slices.map(Ke=>e.jsxs("div",{className:"mission-slice",children:[e.jsxs("div",{className:"mission-slice__header",onClick:()=>Xn(Ke.id),children:[e.jsx("button",{className:"mission-slice__expand",children:I.has(Ke.id)?e.jsx(zt,{size:16}):e.jsx(ln,{size:16})}),e.jsx(ho,{size:16,className:"mission-slice__icon"}),e.jsx("span",{className:"mission-slice__title",children:Ke.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:zd[Ke.status].bg,color:zd[Ke.status].text},children:Ke.status}),e.jsxs("span",{className:"mission-slice__count",children:[Ke.features?.length||0," features"]}),e.jsx(Bd,{state:Ke.planState??"not_started"}),Ke.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>Te({type:"slice",id:Ke.id,title:Ke.title}),title:"Plan slice","aria-label":"Plan slice",children:e.jsx(xi,{size:14})}),e.jsxs("div",{className:"mission-slice__actions",onClick:Ye=>Ye.stopPropagation(),children:[Ke.status==="pending"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ps(Ke.id),title:"Activate slice",children:e.jsx(rn,{size:14})}),Ke.status==="active"&&Ke.features?.some(Ye=>Ye.status==="defined")&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>al(Ke.id),title:"Triage all features",disabled:C,children:C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(jn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>fs(Ke.id),title:"Add feature",children:e.jsx(Vt,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Rn(Ke),title:"Edit slice",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"slice",id:Ke.id}),title:"Delete slice",children:e.jsx(Ht,{size:14})})]})]}),I.has(Ke.id)&&e.jsxs("div",{className:"mission-slice__body",children:[z&&F===H.id&&!G&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:J.title,onChange:Ye=>ue({...J,title:Ye.target.value}),onKeyDown:Mc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:Ye=>ue({...J,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:yn,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),G===Ke.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:J.title,onChange:Ye=>ue({...J,title:Ye.target.value}),onKeyDown:Mc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:Ye=>ue({...J,description:Ye.target.value}),rows:2}),e.jsxs("select",{value:J.status,onChange:Ye=>ue({...J,status:Ye.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(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-features",children:[Ke.features?.map(Ye=>e.jsxs("div",{className:"mission-feature","data-mission-feature-id":Ye.id,children:[e.jsxs("div",{className:"mission-feature__header",children:[e.jsx("button",{className:"mission-feature__expand",onClick:()=>mf(Ye.id),title:Bt===Ye.id?"Collapse details":"Expand to show run history",children:Bt===Ye.id?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})}),e.jsx(lo,{size:14,className:"mission-feature__icon"}),e.jsx("span",{className:"mission-feature__title",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&&Ye.loopState!=="idle"&&e.jsxs("span",{className:`mission-loop-state mission-loop-state--${Ye.loopState}`,title:`Loop state: ${Ye.loopState}`,children:[Ye.loopState==="implementing"&&"⏳",Ye.loopState==="validating"&&"🔄",Ye.loopState==="needs_fix"&&"🔧",Ye.loopState==="passed"&&"✅",Ye.loopState==="blocked"&&"🚫"]}),Ye.generatedFromFeatureId&&e.jsx("button",{className:"mission-feature__lineage",onClick:()=>Za(Ye.generatedFromFeatureId),title:`Generated from feature: ${Ye.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ye.loopState==="validating"||Ye.loopState==="needs_fix")&&(()=>{const gt=bt.get(Ye.id),Qt=gf.get(Ye.id),bs=gt?.implementationAttemptCount??Qt?.implementationAttempt??Ye.implementationAttemptCount??0,ci=gt?.retryBudgetRemaining??Math.max(0,Qw-bs);return e.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",bs," · ",ci," ",ci===1?"retry":"retries"," left"]})})(),Ye.loopState==="implementing"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>uf(Ye.id),title:"Validate feature",disabled:pe.has(Ye.id),children:pe.has(Ye.id)?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(On,{size:14})}),Ye.taskId&&e.jsx("span",{className:"mission-feature__task-link",onClick:()=>l?.(Ye.taskId),title:"Click to view task",children:Ye.taskId}),e.jsxs("div",{className:"mission-feature__actions",children:[Ye.status==="defined"&&!Ye.taskId&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>sl(Ye.id),title:"Triage — create task",disabled:C||nt===Ye.id,children:nt===Ye.id?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(jn,{size:14})}),Ye.taskId?e.jsx("button",{className:"mission-icon-btn",onClick:()=>Ss(Ye.id),title:"Unlink task",children:e.jsx(Dc,{size:14})}):Ye.status!=="defined"?e.jsx("button",{className:"mission-icon-btn",onClick:()=>rt(Ye.id),title:"Link to task",children:e.jsx(Vi,{size:14})}):null,e.jsx("button",{className:"mission-icon-btn",onClick:()=>Fn(Ye),title:"Edit feature",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"feature",id:Ye.id}),title:"Delete feature",children:e.jsx(Ht,{size:14})})]})]}),Ye.description&&e.jsx("p",{className:"mission-feature__description",children:Ye.description}),Ye.acceptanceCriteria&&e.jsxs("p",{className:"mission-feature__criteria",children:[e.jsx("strong",{children:"Acceptance:"})," ",Ye.acceptanceCriteria]}),ye?.featureId===Ye.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:ye.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(lt,{size:14,className:"spinner"}):null,"Create Task"]}),e.jsx("button",{className:"btn",onClick:il,disabled:C,children:"Cancel"})]})]}),V===Ye.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:gt=>we({...de,title:gt.target.value}),onKeyDown:Ac,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:gt=>we({...de,description:gt.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:gt=>we({...de,acceptanceCriteria:gt.target.value}),rows:2}),e.jsxs("select",{value:de.status,onChange:gt=>we({...de,status:gt.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:Qe,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ae,children:"Cancel"})]})]}),Bt===Ye.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"})}),(wn.get(Ye.id)??[]).map(gt=>e.jsxs("div",{className:"mission-run",children:[e.jsxs("div",{className:"mission-run__header",onClick:()=>hf(gt.id),children:[e.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${gt.status}`,title:gt.status,children:gt.status}),e.jsx("span",{className:"mission-run__time",children:new Date(gt.startedAt).toLocaleString()}),gt.completedAt&&e.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(gt.completedAt).getTime()-new Date(gt.startedAt).getTime())/1e3),"s"]}),gt.triggerType&&e.jsx("span",{className:"mission-run__trigger",children:gt.triggerType}),e.jsx("button",{className:"mission-icon-btn",title:nn===gt.id?"Hide details":"Show details",children:nn===gt.id?e.jsx(zt,{size:12}):e.jsx(ln,{size:12})})]}),nn===gt.id&&on.get(gt.id)&&e.jsxs("div",{className:"mission-run__details",children:[gt.summary&&e.jsx("p",{className:"mission-run__summary",children:gt.summary}),gt.blockedReason&&e.jsxs("p",{className:"mission-run__blocked-reason",children:[e.jsx("strong",{children:"Blocked:"})," ",gt.blockedReason]}),on.get(gt.id)?.failures&&on.get(gt.id).failures.length>0&&e.jsxs("div",{className:"mission-run__failures",children:[e.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),on.get(gt.id).failures.map(Qt=>e.jsxs("div",{className:"mission-run__failure",children:[e.jsx("span",{className:"mission-run__failure-message",children:Qt.message}),Qt.expected&&e.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Qt.expected]}),Qt.actual&&e.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Qt.actual]})]},Qt.id))]}),(!on.get(gt.id)?.failures||on.get(gt.id).failures.length===0)&&e.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},gt.id)),(!wn.get(Ye.id)||wn.get(Ye.id).length===0)&&e.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ye.id)),ve&&Pe===Ke.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:Ye=>we({...de,title:Ye.target.value}),onKeyDown:Ac,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:Ye=>we({...de,description:Ye.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:Ye=>we({...de,acceptanceCriteria:Ye.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Qe,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ae,children:"Cancel"})]})]}),!ve&&(!Ke.features||Ke.features.length===0)&&e.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[e.jsx(lo,{size:16}),e.jsx("span",{children:"No fix features generated."})]})]})]})]},Ke.id)),H.slices.length===0&&!z&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(ho,{size:16}),e.jsx("span",{children:"No slices yet"})]}),e.jsxs("div",{className:"mission-assertions",children:[e.jsxs("div",{className:"mission-assertions__header",children:[e.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Le&&e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:At.bg,color:At.text},children:Ud(Le.state)}),Le&&Le.totalAssertions>0&&e.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Le.passedAssertions??0} of ${Le.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Le.passedAssertions??0)/Le.totalAssertions*100}%`,backgroundColor:(Le.passedAssertions??0)===Le.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>{ce(!0),je(null),Ce({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:e.jsx(Vt,{size:14})})]}),qe&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:tt.title,onChange:Ke=>Ce({...tt,title:Ke.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:tt.assertion,onChange:Ke=>Ce({...tt,assertion:Ke.target.value}),rows:2}),e.jsxs("select",{value:tt.status,onChange:Ke=>Ce({...tt,status:Ke.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:()=>bc(H.id),disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{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(be.get(H.id))?be.get(H.id):[]).map(Ke=>e.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ke.id,children:[e.jsx("div",{className:"mission-assertion__header",children:Ze===Ke.id?e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:tt.title,onChange:Ye=>Ce({...tt,title:Ye.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text",value:tt.assertion,onChange:Ye=>Ce({...tt,assertion:Ye.target.value}),rows:2}),e.jsxs("select",{value:tt.status,onChange:Ye=>Ce({...tt,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:()=>rl(Ke.id,H.id),disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{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[Ke.status]??lr.pending).bg,color:(lr[Ke.status]??lr.pending).text},children:Ke.status}),e.jsx("span",{className:"mission-assertion__title",children:Ke.title}),(()=>{const gt=Ae.get(Ke.id)?.length??0;return gt>0?e.jsxs("span",{className:"mission-assertion__linked-count",title:`${gt} linked feature${gt!==1?"s":""}`,children:["(",gt," linked)"]}):null})(),e.jsx("button",{className:"mission-icon-btn",onClick:()=>xc(Ke.id),title:"Toggle details",children:Ue===Ke.id?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Us(Ke),title:"Edit assertion",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"assertion",id:Ke.id}),title:"Delete assertion",children:e.jsx(Ht,{size:14})})]})}),Ue===Ke.id&&e.jsxs("div",{className:"mission-assertion__body",children:[e.jsx("p",{className:"mission-assertion__text",children:Ke.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()=>{Ue!==Ke.id&&await xc(Ke.id),Mt(Et===Ke.id?null:Ke.id)},title:"Link a feature",children:[e.jsx(Vi,{size:12}),"Link Feature"]})]}),Et===Ke.id&&e.jsx("div",{className:"mission-assertion__feature-picker",children:e.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ye=new Set((Ae.get(Ke.id)??[]).map(Qt=>Qt.id)),gt=[];return f?.milestones.forEach(Qt=>Qt.slices.forEach(bs=>gt.push(...bs.features.filter(ci=>!Ye.has(ci.id))))),gt.length===0?e.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):gt.map(Qt=>e.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>cf(Qt.id,Ke.id),disabled:xt.has(Ke.id),children:[e.jsx("span",{className:"mission-assertion__feature-picker-title",children:Qt.title}),xt.has(Ke.id)&&e.jsx(lt,{size:12,className:"spinner"})]},Qt.id))})()})}),(()=>{const Ye=Ae.get(Ke.id)??[];return Ye.length===0?e.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ye.map(gt=>{const Qt=`${gt.id}-${Ke.id}`,bs=Ct.has(Qt);return e.jsxs("div",{className:"mission-assertion__linked-feature",children:[e.jsx("span",{className:"mission-assertion__linked-feature-title",children:gt.title}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>df(gt.id,Ke.id),disabled:bs,title:"Unlink feature",children:bs?e.jsx(lt,{size:12,className:"spinner"}):e.jsx(Dc,{size:12})})]},gt.id)})})()]})]})]},Ke.id)),(!be.get(H.id)||be.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)}),f&&!D&&j===null&&e.jsxs("button",{className:"mission-add-btn",onClick:mn,children:[e.jsx(Vt,{size:16}),"Add Milestone"]}),D&&j===null&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:H=>L({...Y,title:H.target.value}),onKeyDown:Ec,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:H=>L({...Y,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:Sn,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:vn,children:"Cancel"})]})]}),f.milestones.length===0&&!D&&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:T,onChange:H=>W(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:[bn.length," of ",Fe]})]}),!Dn&&ll&&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:bf,"data-testid":"mission-activity-load-more",children:"Load more"})}),Dn?e.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[e.jsx(lt,{size:18,className:"spinner"}),e.jsx("span",{children:"Loading mission activity..."})]}):bn.length===0?e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(ws,{size:18}),e.jsx("span",{children:"No events yet."})]}):e.jsxs("div",{ref:ke,className:"mission-events","data-testid":"mission-activity-events",children:[bn.map(H=>{const Ne=!!(H.metadata&&Object.keys(H.metadata).length>0),Le=ee.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 ${sN(H.eventType)}`,children:iN(H.eventType)}),e.jsx("span",{className:"mission-event__time",children:_r(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()}),Ne&&e.jsxs("div",{className:"mission-event__metadata",children:[e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>xf(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[Le?"Hide":"Show"," metadata"]}),Le&&e.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),e.jsx("div",{ref:Re})]})]})]}):e.jsxs("div",{className:"mission-list",children:[N&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:H=>P({...k,title:H.target.value}),onKeyDown:ol,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:H=>P({...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(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),g.map(H=>{const Ne=H,Le=f,ft=Le&&Le.id===Ne.id,Yt=ma[Ne.status]||{bg:"",text:""},At=Ne.summary,Ut=gn.get(Ne.id),Ke=eN(Ut),Ye=!!(At&&(At.totalMilestones>0||At.totalFeatures>0)),gt=Ut?.totalTasks??0,Qt=Ut?.tasksCompleted??0,bs=Ut?.tasksFailed??0,ci=Ut?.estimatedCompletionPercent??At?.progressPercent??0,_n=Ye||gt>0||bs>0||!!Ut?.lastActivityAt,un=Ne.status==="active"&&(Ut?.currentMilestoneId||Ut?.currentSliceId)?"Current milestone/slice in progress":null;return e.jsxs("div",{className:`mission-list__item ${ft?"mission-list__item--selected":""}`,onClick:()=>Nc(H),children:[e.jsxs("div",{className:"mission-list__item-content",children:[e.jsxs("div",{className:"mission-list__item-header",children:[e.jsx(ns,{size:16,className:"mission-list__item-icon"}),e.jsx("span",{className:"mission-list__item-title",children:Ne.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--${Ke}`,"data-testid":`mission-health-badge-${Ne.id}`,"aria-label":`Mission health: ${Ke}`}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yt.bg,color:Yt.text},children:Ne.status})]}),Ne.description&&e.jsx("p",{className:"mission-list__item-description",children:Ne.description}),un&&e.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",un]}),_n&&e.jsxs("div",{className:"mission-list__item-summary",children:[Ye&&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-${Ne.id}`,children:[Qt,"/",gt," tasks"]}),bs>0&&e.jsxs("button",{className:"mission-list__item-failed",onClick:_t=>{_t.stopPropagation(),Nc(H)},"data-testid":`mission-failed-${Ne.id}`,title:"View mission failures",children:[bs," failed"]}),e.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ne.id}`,children:["Activity ",_r(Ut?.lastActivityAt)]}),e.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Ke}`,children:e.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${ci}%`}})})]})]}),e.jsxs("div",{className:"mission-list__item-actions",onClick:_t=>_t.stopPropagation(),children:[Ne.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>jc(Ne.id),title:"Stop mission",children:e.jsx(os,{size:14})}),Ne.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>kc(Ne.id),title:"Resume mission",children:e.jsx(rn,{size:14})}),Ne.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>wc(Ne.id),title:"Start mission",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>jt(H),title:"Edit mission",children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ie({type:"mission",id:Ne.id}),title:"Delete mission",children:e.jsx(Ht,{size:14})})]})]},Ne.id)}),w&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:H=>P({...k,title:H.target.value}),onKeyDown:ol,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:H=>P({...k,description:H.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:k.status,onChange:H=>P({...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=>P({...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:cn,disabled:C,children:[C?e.jsx(lt,{size:14,className:"spinner"}):e.jsx(En,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),g.length===0&&!N&&e.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[e.jsx(ns,{size:32}),e.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!N&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[De.length>0&&e.jsxs("div",{className:"mission-resume-prompt",children:[e.jsx(is,{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:()=>{ne(H.id),et(!0),Xe([])},children:[H.status==="error"?e.jsx(Mn,{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:()=>et(!0),children:[e.jsx(On,{size:16}),"Plan with AI"]}),e.jsxs("button",{className:"mission-add-btn",onClick:ot,children:[e.jsx(Vt,{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 dn(he.id):he.type==="milestone"?await rs(he.id):he.type==="slice"?await Wn(he.id):he.type==="feature"&&await ut(he.id)},children:"Delete"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ie(null),children:"Cancel"})]})]})}),Ie&&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:Ee,onChange:H=>_e(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:()=>_e(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),_e("")},children:"Cancel"})]})]})})]}),Tc=e.jsx(Vw,{isOpen:Be,onClose:()=>et(!1),onMissionCreated:()=>{kt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:ge}),Rc=le?e.jsx(Gw,{isOpen:!0,onClose:()=>Te(null),onApplied:()=>{Te(null),f&&ht(f.id)},targetType:le.type,targetId:le.id,targetTitle:le.title,missionContext:f?.title,projectId:r,resumeSessionId:le.resumeSessionId}):null;return n?e.jsxs(e.Fragment,{children:[Pc,Tc,Rc]}):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:Pc}),Tc,Rc]})}const or=2e3;function lN({recipient:t,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:l,addToast:o,isLoadingAgents:d=!1}){const[m,c]=a.useState(t?.id??""),[u,h]=a.useState(t?.type??"agent"),[g,p]=a.useState(""),[f,b]=a.useState(!1),[x,y]=a.useState(null),v=m.trim()!==""&&g.trim().length>0&&g.length<=or,M=a.useCallback(async()=>{if(!(!v||f)){b(!0),y(null);try{const A=u==="agent"?"user-to-agent":"system";await Rk({toId:m.trim(),toType:u,content:g.trim(),type:A,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(A){const w=xe(A)||"Failed to send message";y(w),o?.(w,"error")}finally{b(!1)}}},[v,f,m,u,g,n,i,r,o]),N=a.useCallback(A=>{c(A),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(Dt,{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:A=>N(A.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(A=>e.jsx("option",{value:A.id,children:A.name||A.id},A.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:A=>p(A.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(is,{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:M,disabled:!v||f,"data-testid":"message-composer-send",children:f?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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 oN(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 cN(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 qd(t,n=80){return t.length<=n?t:`${t.slice(0,n)}…`}function dN(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 uN({projectId:t,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[l,o]=a.useState(null),[d,m]=a.useState(null),[c,u]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[b,x]=a.useState([]),[y,v]=a.useState(!1),[M,N]=a.useState(null),[A,w]=a.useState(null),[S,k]=a.useState(null),[P,C]=a.useState("inbox"),[R,O]=a.useState(null),[Z,I]=a.useState([]),_=a.useMemo(()=>new Map(Z.map(V=>[V.id,V.name??""])),[Z]),j=a.useCallback((V,K)=>oN(V,K,_),[_]),Q=a.useCallback(async()=>{g(!0);try{const V=await Pk({limit:50},t);o(V),u(V.unreadCount),s?.(V.unreadCount)}catch{}finally{g(!1)}},[t,s]),Y=a.useCallback(async()=>{g(!0);try{const V=await Tk({limit:50},t);m(V)}catch{}finally{g(!1)}},[t]),L=a.useCallback(async V=>{g(!0);try{const K=await Fk(V,t);O(K)}catch{}finally{g(!1)}},[t]),D=a.useCallback(async()=>{try{const V=await aa(void 0,t);I(V)}catch{}},[t]),U=a.useCallback(async()=>{try{const V=await ph(t);u(V.unreadCount),s?.(V.unreadCount)}catch{}},[t,s]);a.useEffect(()=>{i==="inbox"?Q():i==="outbox"?Y():i==="agents"&&D()},[i,Q,Y,D]),a.useEffect(()=>{S&&L(S)},[S,L]),a.useEffect(()=>{U()},[U]),a.useEffect(()=>{D()},[D]),a.useEffect(()=>{if(typeof EventSource>"u")return;const V=t?`?projectId=${encodeURIComponent(t)}`:"",K=()=>{U(),i==="inbox"?Q():i==="outbox"&&Y(),S&&L(S)};return Os(`/api/events${V}`,{events:{"message:sent":K,"message:received":K,"message:read":K,"message:deleted":K}})},[t,i,S,U,Q,Y,L]);const G=a.useCallback(async V=>{if(f(V),!V.read)try{const K=await _k(V.id,t);K&&o(we=>we&&{...we,messages:we.messages.map(ve=>ve.id===K.id?K:ve),unreadCount:Math.max(0,we.unreadCount-1)});const de=Math.max(0,c-1);u(de),s?.(de)}catch{}try{const K=await Dk(V.fromId,V.fromType,t);x(K)}catch{x([V])}},[t,c,s]),E=a.useCallback(()=>{f(null),x([])},[]),J=a.useCallback(async()=>{try{const V=await Ik(t);u(0),s?.(0),o(K=>K&&{...K,messages:K.messages.map(de=>({...de,read:!0})),unreadCount:0}),n?.(`Marked ${V.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[t,n,s]),ue=a.useCallback(async V=>{try{await $k(V,t),f(null),x([]),i==="inbox"?Q():i==="outbox"?Y():S&&L(S),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[t,i,S,Q,Y,L,n]),z=a.useCallback(V=>{N({id:V.fromId,type:V.fromType}),w({messageId:V.id,preview:qd(V.content,120)}),v(!0)},[]),te=a.useCallback(()=>{v(!1),N(null),w(null),n?.("Message sent","success"),i==="outbox"?Y():i==="agents"&&S&&L(S),U()},[i,Y,S,L,n,U]),F=a.useCallback(()=>{N(i==="agents"&&S?{id:S,type:"agent"}:null),w(null),v(!0)},[i,S]),fe=a.useCallback(()=>{v(!1),N(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(Bi,{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:F,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:J,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[e.jsx(Of,{size:14}),e.jsx("span",{children:"Mark all read"})]}),e.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?Q():i==="outbox"?Y():S&&L(S)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?e.jsx(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14})})]})]}),e.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[e.jsx(Sa,{size:14}),e.jsx("span",{children:"Inbox"}),c>0&&e.jsx("span",{className:"mailbox-tab-badge",children:c})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[e.jsx(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"),f(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:[p&&!y&&e.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[e.jsxs("div",{className:"mailbox-message-detail-header",children:[e.jsx("button",{className:"btn btn-sm btn-secondary",onClick:E,"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:cN(p.type)}),e.jsx("span",{className:"mailbox-message-time",children:_i(p.createdAt)})]}),e.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>z(p),"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:()=>ue(p.id),"data-testid":"mailbox-delete",children:[e.jsx(Ht,{size:14}),e.jsx("span",{children:"Delete"})]})]})]}),e.jsxs("div",{className:"mailbox-message-participants",children:[e.jsxs("div",{className:"mailbox-participant",children:[e.jsx("span",{className:"mailbox-participant-label",children:"From:"}),e.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?e.jsx(an,{size:14}):e.jsx(Ai,{size:14}),j(p.fromId,p.fromType)]})]}),e.jsxs("div",{className:"mailbox-participant",children:[e.jsx("span",{className:"mailbox-participant-label",children:"To:"}),e.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?e.jsx(an,{size:14}):e.jsx(Ai,{size:14}),j(p.toId,p.toType)]})]})]}),b.length>1&&e.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[e.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(V=>{const K=V.metadata?.replyTo?.messageId,de=K?b.find(we=>we.id===K):void 0;return e.jsxs("div",{className:`mailbox-conversation-msg ${V.id===p.id?"current":""}`,children:[e.jsxs("div",{className:"mailbox-conversation-msg-header",children:[e.jsx("span",{children:j(V.fromId,V.fromType)}),e.jsx("span",{className:"mailbox-message-time",children:_i(V.createdAt)})]}),K&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${V.id}`,children:["↪ Replying to ",de?qd(de.content,60):`message ${K}`]}),e.jsx("div",{className:"mailbox-conversation-msg-body",children:V.content})]},V.id)})]}),b.length<=1&&e.jsxs(e.Fragment,{children:[p.metadata?.replyTo?.messageId&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),e.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),y&&e.jsx(lN,{recipient:M,replyContext:A,agents:Z,projectId:t,onSend:te,onCancel:fe,addToast:n}),!p&&!y&&e.jsxs(e.Fragment,{children:[i==="inbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!l&&e.jsx(wl,{}),l&&l.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[e.jsx(Sa,{size:32}),e.jsx("p",{children:"No messages in your inbox"})]}),l&&l.messages.length>0&&e.jsx("div",{className:"mailbox-conversations","data-testid":"mailbox-conversations",children:dN(l.messages).map(V=>e.jsxs("div",{className:`mailbox-conversation-group ${V.unreadCount>0?"unread":""}`,onClick:()=>G(V.latestMessage),"data-testid":`mailbox-conversation-${V.key}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:V.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:j(V.fromId,V.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:_i(V.latestMessage.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[V.latestMessage.content.slice(0,80),V.latestMessage.content.length>80?"…":""]})]}),V.unreadCount>0&&e.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${V.key}`,children:V.unreadCount>9?"9+":V.unreadCount})]},V.key))})]}),i==="outbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!d&&e.jsx(wl,{}),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(V=>e.jsxs("div",{className:"mailbox-item",onClick:()=>G(V),"data-testid":`mailbox-item-${V.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:V.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: ",j(V.toId,V.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:_i(V.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[V.content.slice(0,80),V.content.length>80?"…":""]})]})]},V.id))]}),i==="agents"&&e.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:Z.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:S??"",onChange:V=>{k(V.target.value||null),C("inbox")},"data-testid":"mailbox-agent-select",children:[e.jsx("option",{value:"",children:"Select an agent…"}),Z.map(V=>e.jsx("option",{value:V.id,children:V.name||V.id},V.id))]})}),e.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:F,"data-testid":"mailbox-compose-btn",children:[e.jsx(Zs,{size:14}),e.jsx("span",{children:"Compose"})]})]}),S&&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 ${P==="inbox"?"active":""}`,onClick:()=>C("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[e.jsx(Sa,{size:12}),e.jsx("span",{children:"Inbox"}),R&&R.unreadCount>0&&e.jsx("span",{className:"mailbox-tab-badge",children:R.unreadCount})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${P==="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:[!S&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(an,{size:32}),e.jsx("p",{children:"Select an agent to view their mailbox"})]}),S&&h&&!R&&e.jsx(wl,{}),S&&R&&P==="inbox"&&R.inbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(Sa,{size:32}),e.jsx("p",{children:"No received messages for this agent"})]}),S&&R&&P==="outbox"&&R.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"})]}),S&&R&&P==="inbox"&&R.inbox.map(V=>e.jsxs("div",{className:`mailbox-item ${V.read?"":"unread"}`,onClick:()=>G(V),"data-testid":`mailbox-item-${V.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:V.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:j(V.fromId,V.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:_i(V.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[V.content.slice(0,80),V.content.length>80?"…":""]})]})]},V.id)),S&&R&&P==="outbox"&&R.outbox.map(V=>e.jsxs("div",{className:"mailbox-item",onClick:()=>G(V),"data-testid":`mailbox-item-${V.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:V.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: ",j(V.toId,V.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:_i(V.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[V.content.slice(0,80),V.content.length>80?"…":""]})]})]},V.id))]})]})})]})]})]})}function wl(){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 mN(t,n){const s={};return(t[t.length-1]===""?[...t,""]:t).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const hN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,pN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fN={};function Vd(t,n){return(fN.jsx?pN:hN).test(t)}const gN=/[ \t\n\f\r]/g;function bN(t){return typeof t=="object"?t.type==="text"?Wd(t.value):!1:Wd(t)}function Wd(t){return t.replace(gN,"")===""}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 ko(t){return t.toLowerCase()}class as{constructor(n,s){this.attribute=s,this.property=n}}as.prototype.attribute="";as.prototype.booleanish=!1;as.prototype.boolean=!1;as.prototype.commaOrSpaceSeparated=!1;as.prototype.commaSeparated=!1;as.prototype.defined=!1;as.prototype.mustUseProperty=!1;as.prototype.number=!1;as.prototype.overloadedBoolean=!1;as.prototype.property="";as.prototype.spaceSeparated=!1;as.prototype.space=void 0;let xN=0;const Pt=Ci(),kn=Ci(),jo=Ci(),it=Ci(),Xt=Ci(),Ui=Ci(),ls=Ci();function Ci(){return 2**++xN}const wo=Object.freeze(Object.defineProperty({__proto__:null,boolean:Pt,booleanish:kn,commaOrSpaceSeparated:ls,commaSeparated:Ui,number:it,overloadedBoolean:jo,spaceSeparated:Xt},Symbol.toStringTag,{value:"Module"})),Nl=Object.keys(wo);class Xo extends as{constructor(n,s,i,r){let l=-1;if(super(n,s),Kd(this,"space",r),typeof i=="number")for(;++l<Nl.length;){const o=Nl[l];Kd(this,Nl[l],(i&wo[o])===wo[o])}}}Xo.prototype.defined=!0;function Kd(t,n,s){s&&(t[n]=s)}function la(t){const n={},s={};for(const[i,r]of Object.entries(t.properties)){const l=new Xo(i,t.transform(t.attributes||{},i),r,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(l.mustUseProperty=!0),n[i]=l,s[ko(i)]=i,s[ko(l.attribute)]=i}return new Ja(n,s,t.space)}const Ih=la({properties:{ariaActiveDescendant:null,ariaAtomic:kn,ariaAutoComplete:null,ariaBusy:kn,ariaChecked:kn,ariaColCount:it,ariaColIndex:it,ariaColSpan:it,ariaControls:Xt,ariaCurrent:null,ariaDescribedBy:Xt,ariaDetails:null,ariaDisabled:kn,ariaDropEffect:Xt,ariaErrorMessage:null,ariaExpanded:kn,ariaFlowTo:Xt,ariaGrabbed:kn,ariaHasPopup:null,ariaHidden:kn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Xt,ariaLevel:it,ariaLive:null,ariaModal:kn,ariaMultiLine:kn,ariaMultiSelectable:kn,ariaOrientation:null,ariaOwns:Xt,ariaPlaceholder:null,ariaPosInSet:it,ariaPressed:kn,ariaReadOnly:kn,ariaRelevant:null,ariaRequired:kn,ariaRoleDescription:Xt,ariaRowCount:it,ariaRowIndex:it,ariaRowSpan:it,ariaSelected:kn,ariaSetSize:it,ariaSort:null,ariaValueMax:it,ariaValueMin:it,ariaValueNow:it,ariaValueText:null,role:null},transform(t,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function $h(t,n){return n in t?t[n]:n}function Dh(t,n){return $h(t,n.toLowerCase())}const vN=la({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ui,acceptCharset:Xt,accessKey:Xt,action:null,allow:null,allowFullScreen:Pt,allowPaymentRequest:Pt,allowUserMedia:Pt,alt:null,as:null,async:Pt,autoCapitalize:null,autoComplete:Xt,autoFocus:Pt,autoPlay:Pt,blocking:Xt,capture:null,charSet:null,checked:Pt,cite:null,className:Xt,cols:it,colSpan:null,content:null,contentEditable:kn,controls:Pt,controlsList:Xt,coords:it|Ui,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Pt,defer:Pt,dir:null,dirName:null,disabled:Pt,download:jo,draggable:kn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Pt,formTarget:null,headers:Xt,height:it,hidden:jo,high:it,href:null,hrefLang:null,htmlFor:Xt,httpEquiv:Xt,id:null,imageSizes:null,imageSrcSet:null,inert:Pt,inputMode:null,integrity:null,is:null,isMap:Pt,itemId:null,itemProp:Xt,itemRef:Xt,itemScope:Pt,itemType:Xt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Pt,low:it,manifest:null,max:null,maxLength:it,media:null,method:null,min:null,minLength:it,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:it,pattern:null,ping:Xt,placeholder:null,playsInline:Pt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Pt,referrerPolicy:null,rel:Xt,required:Pt,reversed:Pt,rows:it,rowSpan:it,sandbox:Xt,scope:null,scoped:Pt,seamless:Pt,selected:Pt,shadowRootClonable:Pt,shadowRootDelegatesFocus:Pt,shadowRootMode:null,shape:null,size:it,sizes:null,slot:null,span:it,spellCheck:kn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:it,step:null,style:null,tabIndex:it,target:null,title:null,translate:null,type:null,typeMustMatch:Pt,useMap:null,value:kn,width:it,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Xt,axis:null,background:null,bgColor:null,border:it,borderColor:null,bottomMargin:it,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:it,leftMargin:it,link:null,longDesc:null,lowSrc:null,marginHeight:it,marginWidth:it,noResize:Pt,noHref:Pt,noShade:Pt,noWrap:Pt,object:null,profile:null,prompt:null,rev:null,rightMargin:it,rules:null,scheme:null,scrolling:kn,standby:null,summary:null,text:null,topMargin:it,valueType:null,version:null,vAlign:null,vLink:null,vSpace:it,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Pt,disableRemotePlayback:Pt,prefix:null,property:null,results:it,security:null,unselectable:null},space:"html",transform:Dh}),yN=la({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:ls,accentHeight:it,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:it,amplitude:it,arabicForm:null,ascent:it,attributeName:null,attributeType:null,azimuth:it,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:it,by:null,calcMode:null,capHeight:it,className:Xt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:it,diffuseConstant:it,direction:null,display:null,dur:null,divisor:it,dominantBaseline:null,download:Pt,dx:null,dy:null,edgeMode:null,editable:null,elevation:it,enableBackground:null,end:null,event:null,exponent:it,externalResourcesRequired:null,fill:null,fillOpacity:it,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Ui,g2:Ui,glyphName:Ui,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:it,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:it,horizOriginX:it,horizOriginY:it,id:null,ideographic:it,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:it,k:it,k1:it,k2:it,k3:it,k4:it,kernelMatrix:ls,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:it,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:it,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:it,overlineThickness:it,paintOrder:null,panose1:null,path:null,pathLength:it,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Xt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:it,pointsAtY:it,pointsAtZ:it,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ls,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ls,rev:ls,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ls,requiredFeatures:ls,requiredFonts:ls,requiredFormats:ls,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:it,specularExponent:it,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:it,strikethroughThickness:it,string:null,stroke:null,strokeDashArray:ls,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:it,strokeOpacity:it,strokeWidth:null,style:null,surfaceScale:it,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ls,tabIndex:it,tableValues:null,target:null,targetX:it,targetY:it,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ls,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:it,underlineThickness:it,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:it,values:null,vAlphabetic:it,vMathematical:it,vectorEffect:null,vHanging:it,vIdeographic:it,version:null,vertAdvY:it,vertOriginX:it,vertOriginY:it,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:it,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:$h}),Fh=la({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,n){return"xlink:"+n.slice(5).toLowerCase()}}),Lh=la({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Dh}),zh=la({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),kN={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"},jN=/[A-Z]/g,Gd=/-[a-z]/g,wN=/^data[-\w.:]+$/i;function NN(t,n){const s=ko(n);let i=n,r=as;if(s in t.normal)return t.property[t.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&wN.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(Gd,CN);i="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!Gd.test(l)){let o=l.replace(jN,SN);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}r=Xo}return new r(i,n)}function SN(t){return"-"+t.toLowerCase()}function CN(t){return t.charAt(1).toUpperCase()}const EN=_h([Ih,vN,Fh,Lh,zh],"html"),Zo=_h([Ih,yN,Fh,Lh,zh],"svg");function MN(t){return t.join(" ").trim()}var Ii={},Sl,Jd;function AN(){if(Jd)return Sl;Jd=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",p="declaration";function f(x,y){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];y=y||{};var v=1,M=1;function N(I){var _=I.match(n);_&&(v+=_.length);var j=I.lastIndexOf(m);M=~j?I.length-j:M+I.length}function A(){var I={line:v,column:M};return function(_){return _.position=new w(I),P(),_}}function w(I){this.start=I,this.end={line:v,column:M},this.source=y.source}w.prototype.content=x;function S(I){var _=new Error(y.source+":"+v+":"+M+": "+I);if(_.reason=I,_.filename=y.source,_.line=v,_.column=M,_.source=x,!y.silent)throw _}function k(I){var _=I.exec(x);if(_){var j=_[0];return N(j),x=x.slice(j.length),_}}function P(){k(s)}function C(I){var _;for(I=I||[];_=R();)_!==!1&&I.push(_);return I}function R(){var I=A();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 S("End of comment missing");var j=x.slice(2,_-2);return M+=2,N(j),x=x.slice(_),M+=2,I({type:g,comment:j})}}function O(){var I=A(),_=k(i);if(_){if(R(),!k(r))return S("property missing ':'");var j=k(l),Q=I({type:p,property:b(_[0].replace(t,h)),value:j?b(j[0].replace(t,h)):h});return k(o),Q}}function Z(){var I=[];C(I);for(var _;_=O();)_!==!1&&(I.push(_),C(I));return I}return P(),Z()}function b(x){return x?x.replace(d,h):h}return Sl=f,Sl}var Yd;function PN(){if(Yd)return Ii;Yd=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(AN());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 ha={},Qd;function TN(){if(Qd)return ha;Qd=1,Object.defineProperty(ha,"__esModule",{value:!0}),ha.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,l=function(c){return!c||s.test(c)||t.test(c)},o=function(c,u){return u.toUpperCase()},d=function(c,u){return"".concat(u,"-")},m=function(c,u){return u===void 0&&(u={}),l(c)?c:(c=c.toLowerCase(),u.reactCompat?c=c.replace(r,d):c=c.replace(i,d),c.replace(n,o))};return ha.camelCase=m,ha}var pa,Xd;function RN(){if(Xd)return pa;Xd=1;var t=pa&&pa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=t(PN()),s=TN();function i(r,l){var o={};return!r||typeof r!="string"||(0,n.default)(r,function(d,m){d&&m&&(o[(0,s.camelCase)(d,l)]=m)}),o}return i.default=i,pa=i,pa}var _N=RN();const IN=Rm(_N),Oh=Bh("end"),ec=Bh("start");function Bh(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 $N(t){const n=ec(t),s=Oh(t);if(n&&s)return{start:n,end:s}}function Aa(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?Zd(t.position):"start"in t||"end"in t?Zd(t):"line"in t||"column"in t?No(t):""}function No(t){return eu(t&&t.line)+":"+eu(t&&t.column)}function Zd(t){return No(t&&t.start)+"-"+No(t&&t.end)}function eu(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=Aa(l.place)||"1:1",this.place=l.place||void 0,this.reason=this.message,this.ruleId=l.ruleId||void 0,this.source=l.source||void 0,this.stack=o&&l.cause&&typeof l.cause.stack=="string"?l.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}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 tc={}.hasOwnProperty,DN=new Map,FN=/[A-Z]/g,LN=new Set(["table","tbody","thead","tfoot","tr"]),zN=new Set(["td","th"]),Uh="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function ON(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=GN(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=KN(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"?Zo:EN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},l=Hh(r,t,void 0);return l&&typeof l!="string"?l:r.create(t,r.Fragment,{children:l||void 0},void 0)}function Hh(t,n,s){if(n.type==="element")return BN(t,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return UN(t,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return qN(t,n,s);if(n.type==="mdxjsEsm")return HN(t,n);if(n.type==="root")return VN(t,n,s);if(n.type==="text")return WN(t,n)}function BN(t,n,s){const i=t.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=Zo,t.schema=r),t.ancestors.push(n);const l=Vh(t,n.tagName,!1),o=JN(t,n);let d=sc(t,n);return LN.has(n.tagName)&&(d=d.filter(function(m){return typeof m=="string"?!bN(m):!0})),qh(t,o,l,n),nc(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function UN(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 HN(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=Zo,t.schema=r),t.ancestors.push(n);const l=n.name===null?t.Fragment:Vh(t,n.name,!0),o=YN(t,n),d=sc(t,n);return qh(t,o,l,n),nc(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function VN(t,n,s){const i={};return nc(i,sc(t,n)),t.create(n,t.Fragment,i,s)}function WN(t,n){return n.value}function qh(t,n,s,i){typeof s!="string"&&s!==t.Fragment&&t.passNode&&(n.node=i)}function nc(t,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(t.children=s)}}function KN(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 GN(t,n){return s;function s(i,r,l,o){const d=Array.isArray(l.children),m=ec(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 JN(t,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&tc.call(n.properties,r)){const l=QN(t,r,n.properties[r]);if(l){const[o,d]=l;t.tableCellAlignToStyle&&o==="align"&&typeof d=="string"&&zN.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 YN(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 sc(t,n){const s=[];let i=-1;const r=t.passKeys?new Map:DN;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=Hh(t,l,o);d!==void 0&&s.push(d)}return s}function QN(t,n,s){const i=NN(t.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?mN(s):MN(s)),i.property==="style"){let r=typeof s=="object"?s:XN(t,String(s));return t.stylePropertyNameCase==="css"&&(r=ZN(r)),["style",r]}return[t.elementAttributeNameCase==="react"&&i.space?kN[i.property]||i.property:i.attribute,s]}}function XN(t,n){try{return IN(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=Uh+"#cannot-parse-style-attribute",r}}function Vh(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=Vd(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=Vd(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return tc.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=Uh+"#cannot-handle-mdx-estrees-without-createevaluater",s}function ZN(t){const n={};let s;for(s in t)tc.call(t,s)&&(n[e1(s)]=t[s]);return n}function e1(t){let n=t.replace(FN,t1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function t1(t){return"-"+t.toLowerCase()}const Cl={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"]},n1={};function ic(t,n){const s=n1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Wh(t,i,r)}function Wh(t,n,s){if(s1(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 tu(t.children,n,s)}return Array.isArray(t)?tu(t,n,s):""}function tu(t,n,s){const i=[];let r=-1;for(;++r<t.length;)i[r]=Wh(t[r],n,s);return i.join("")}function s1(t){return!!(t&&typeof t=="object")}const nu=document.createElement("i");function ac(t){const n="&"+t+";";nu.innerHTML=n;const s=nu.textContent;return s.charCodeAt(s.length-1)===59&&t!=="semi"||s===n?!1:s}function ms(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 ks(t,n){return t.length>0?(ms(t,t.length,0,n),t):n}const su={}.hasOwnProperty;function Kh(t){const n={};let s=-1;for(;++s<t.length;)i1(n,t[s]);return n}function i1(t,n){let s;for(s in n){const r=(su.call(t,s)?t[s]:void 0)||(t[s]={}),l=n[s];let o;if(l)for(o in l){su.call(r,o)||(r[o]=[]);const d=l[o];a1(r[o],Array.isArray(d)?d:d?[d]:[])}}}function a1(t,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?t:i).push(n[s]);ms(t,0,0,i)}function Gh(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 Ms(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Gn=ai(/[A-Za-z]/),zn=ai(/[\dA-Za-z]/),r1=ai(/[#-'*+\--9=?A-Z^-~]/);function Ir(t){return t!==null&&(t<32||t===127)}const So=ai(/\d/),l1=ai(/[\dA-Fa-f]/),o1=ai(/[!-/:-@[-`{-~]/);function wt(t){return t!==null&&t<-2}function Jt(t){return t!==null&&(t<0||t===32)}function $t(t){return t===-2||t===-1||t===32}const Xr=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 oa(t){const n=[];let s=-1,i=0,r=0;for(;++s<t.length;){const l=t.charCodeAt(s);let o="";if(l===37&&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 $t(m)?(t.enter(s),d(m)):n(m)}function d(m){return $t(m)&&l++<r?(t.consume(m),d):(t.exit(s),n(m))}}const c1={tokenize:d1};function d1(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 wt(d)?(t.consume(d),t.exit("chunkText"),l):(t.consume(d),o)}}const u1={tokenize:m1},iu={tokenize:h1};function m1(t){const n=this,s=[];let i=0,r,l,o;return d;function d(M){if(i<s.length){const N=s[i];return n.containerState=N[1],t.attempt(N[0].continuation,m,c)(M)}return c(M)}function m(M){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&v();const N=n.events.length;let A=N,w;for(;A--;)if(n.events[A][0]==="exit"&&n.events[A][1].type==="chunkFlow"){w=n.events[A][1].end;break}y(i);let S=N;for(;S<n.events.length;)n.events[S][1].end={...w},S++;return ms(n.events,A+1,0,n.events.slice(N)),n.events.length=S,c(M)}return d(M)}function c(M){if(i===s.length){if(!r)return g(M);if(r.currentConstruct&&r.currentConstruct.concrete)return f(M);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},t.check(iu,u,h)(M)}function u(M){return r&&v(),y(i),g(M)}function h(M){return n.parser.lazy[n.now().line]=i!==s.length,o=n.now().offset,f(M)}function g(M){return n.containerState={},t.attempt(iu,p,f)(M)}function p(M){return i++,s.push([n.currentConstruct,n.containerState]),g(M)}function f(M){if(M===null){r&&v(),y(0),t.consume(M);return}return r=r||n.parser.flow(n.now()),t.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:l}),b(M)}function b(M){if(M===null){x(t.exit("chunkFlow"),!0),y(0),t.consume(M);return}return wt(M)?(t.consume(M),x(t.exit("chunkFlow")),i=0,n.interrupt=void 0,d):(t.consume(M),b)}function x(M,N){const A=n.sliceStream(M);if(N&&A.push(null),M.previous=l,l&&(l.next=M),l=M,r.defineSkip(M.start),r.write(A),n.parser.lazy[M.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 S=n.events.length;let k=S,P,C;for(;k--;)if(n.events[k][0]==="exit"&&n.events[k][1].type==="chunkFlow"){if(P){C=n.events[k][1].end;break}P=!0}for(y(i),w=S;w<n.events.length;)n.events[w][1].end={...C},w++;ms(n.events,k+1,0,n.events.slice(S)),n.events.length=w}}function y(M){let N=s.length;for(;N-- >M;){const A=s[N];n.containerState=A[1],A[0].exit.call(n,t)}s.length=M}function v(){r.write([null]),l=void 0,r=void 0,n.containerState._closeFlow=void 0}}function h1(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 Yi(t){if(t===null||Jt(t)||wi(t))return 1;if(Xr(t))return 2}function Zr(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 Co={name:"attention",resolveAll:p1,tokenize:f1};function p1(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};au(h,-m),au(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=ks(c,[["enter",t[i][1],n],["exit",t[i][1],n]])),c=ks(c,[["enter",r,n],["enter",o,n],["exit",o,n],["enter",l,n]]),c=ks(c,Zr(n.parser.constructs.insideSpan.null,t.slice(i+1,s),n)),c=ks(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=ks(c,[["enter",t[s][1],n],["exit",t[s][1],n]])):u=0,ms(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 f1(t,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Yi(i);let l;return o;function o(m){return l=m,t.enter("attentionSequence"),d(m)}function d(m){if(m===l)return t.consume(m),d;const c=t.exit("attentionSequence"),u=Yi(m),h=!u||u===2&&r||s.includes(m),g=!r||r===2&&u||s.includes(i);return c._open=!!(l===42?h:h&&(r||!g)),c._close=!!(l===42?g:g&&(u||!h)),n(m)}}function au(t,n){t.column+=n,t.offset+=n,t._bufferIndex+=n}const g1={name:"autolink",tokenize:b1};function b1(t,n,s){let i=0;return r;function r(p){return t.enter("autolink"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.enter("autolinkProtocol"),l}function l(p){return Gn(p)?(t.consume(p),o):p===64?s(p):c(p)}function o(p){return p===43||p===45||p===46||zn(p)?(i=1,d(p)):c(p)}function d(p){return p===58?(t.consume(p),i=0,m):(p===43||p===45||p===46||zn(p))&&i++<32?(t.consume(p),d):(i=0,c(p))}function m(p){return p===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),n):p===null||p===32||p===60||Ir(p)?s(p):(t.consume(p),m)}function c(p){return p===64?(t.consume(p),u):r1(p)?(t.consume(p),c):s(p)}function u(p){return zn(p)?h(p):s(p)}function h(p){return p===46?(t.consume(p),i=0,u):p===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),n):g(p)}function g(p){if((p===45||zn(p))&&i++<63){const f=p===45?g:h;return t.consume(p),f}return s(p)}}const Ya={partial:!0,tokenize:x1};function x1(t,n,s){return i;function i(l){return $t(l)?Ot(t,r,"linePrefix")(l):r(l)}function r(l){return l===null||wt(l)?n(l):s(l)}}const Jh={continuation:{tokenize:y1},exit:k1,name:"blockQuote",tokenize:v1};function v1(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 $t(o)?(t.enter("blockQuotePrefixWhitespace"),t.consume(o),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),n):(t.exit("blockQuotePrefix"),n(o))}}function y1(t,n,s){const i=this;return r;function r(o){return $t(o)?Ot(t,l,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):l(o)}function l(o){return t.attempt(Jh,n,s)(o)}}function k1(t){t.exit("blockQuote")}const Yh={name:"characterEscape",tokenize:j1};function j1(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 o1(l)?(t.enter("characterEscapeValue"),t.consume(l),t.exit("characterEscapeValue"),t.exit("characterEscape"),n):s(l)}}const Qh={name:"characterReference",tokenize:w1};function w1(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=l1,u):(t.enter("characterReferenceValue"),l=7,o=So,u(h))}function u(h){if(h===59&&r){const g=t.exit("characterReferenceValue");return o===zn&&!ac(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 ru={partial:!0,tokenize:S1},lu={concrete:!0,name:"codeFenced",tokenize:N1};function N1(t,n,s){const i=this,r={partial:!0,tokenize:A};let l=0,o=0,d;return m;function m(w){return c(w)}function c(w){const S=i.events[i.events.length-1];return l=S&&S[1].type==="linePrefix"?S[2].sliceSerialize(S[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"),$t(w)?Ot(t,h,"whitespace")(w):h(w))}function h(w){return w===null||wt(w)?(t.exit("codeFencedFence"),i.interrupt?n(w):t.check(ru,b,N)(w)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||wt(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),h(w)):$t(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Ot(t,p,"whitespace")(w)):w===96&&w===d?s(w):(t.consume(w),g)}function p(w){return w===null||wt(w)?h(w):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||wt(w)?(t.exit("chunkString"),t.exit("codeFencedFenceMeta"),h(w)):w===96&&w===d?s(w):(t.consume(w),f)}function b(w){return t.attempt(r,N,x)(w)}function x(w){return t.enter("lineEnding"),t.consume(w),t.exit("lineEnding"),y}function y(w){return l>0&&$t(w)?Ot(t,v,"linePrefix",l+1)(w):v(w)}function v(w){return w===null||wt(w)?t.check(ru,b,N)(w):(t.enter("codeFlowValue"),M(w))}function M(w){return w===null||wt(w)?(t.exit("codeFlowValue"),v(w)):(t.consume(w),M)}function N(w){return t.exit("codeFenced"),n(w)}function A(w,S,k){let P=0;return C;function C(_){return w.enter("lineEnding"),w.consume(_),w.exit("lineEnding"),R}function R(_){return w.enter("codeFencedFence"),$t(_)?Ot(w,O,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):O(_)}function O(_){return _===d?(w.enter("codeFencedFenceSequence"),Z(_)):k(_)}function Z(_){return _===d?(P++,w.consume(_),Z):P>=o?(w.exit("codeFencedFenceSequence"),$t(_)?Ot(w,I,"whitespace")(_):I(_)):k(_)}function I(_){return _===null||wt(_)?(w.exit("codeFencedFence"),S(_)):k(_)}}}function S1(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 El={name:"codeIndented",tokenize:E1},C1={partial:!0,tokenize:M1};function E1(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):wt(c)?t.attempt(C1,o,m)(c):(t.enter("codeFlowValue"),d(c))}function d(c){return c===null||wt(c)?(t.exit("codeFlowValue"),o(c)):(t.consume(c),d)}function m(c){return t.exit("codeIndented"),n(c)}}function M1(t,n,s){const i=this;return r;function r(o){return i.parser.lazy[i.now().line]?s(o):wt(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):wt(o)?r(o):s(o)}}const A1={name:"codeText",previous:T1,resolve:P1,tokenize:R1};function P1(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 T1(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function R1(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)):wt(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||wt(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 _1{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const l=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&fa(this.left,i),l.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),fa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),fa(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const s=this.left.splice(n,Number.POSITIVE_INFINITY);fa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);fa(this.left,s.reverse())}}}function fa(t,n){let s=0;if(n.length<1e4)t.push(...n);else for(;s<n.length;)t.push(...n.slice(s,s+1e4)),s+=1e4}function Xh(t){const n={};let s=-1,i,r,l,o,d,m,c;const u=new _1(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,I1(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 ms(t,0,Number.POSITIVE_INFINITY,u.slice(0)),!c}function I1(t,n){const s=t.get(n)[1],i=t.get(n)[2];let r=n-1;const l=[];let o=s._tokenizer;o||(o=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const d=o.events,m=[],c={};let u,h,g=-1,p=s,f=0,b=0;const x=[b];for(;p;){for(;t.get(++r)[1]!==p;);l.push(r),p._tokenizer||(u=i.sliceStream(p),p.next||u.push(null),h&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(u),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<d.length;)d[g][0]==="exit"&&d[g-1][0]==="enter"&&d[g][1].type===d[g-1][1].type&&d[g][1].start.line!==d[g][1].end.line&&(b=g+1,x.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):x.pop(),g=x.length;g--;){const y=d.slice(x[g],x[g+1]),v=l.pop();m.push([v,v+y.length-1]),t.splice(v,2,y)}for(m.reverse(),g=-1;++g<m.length;)c[f+m[g][0]]=f+m[g][1],f+=m[g][1]-m[g][0]-1;return c}const $1={resolve:F1,tokenize:L1},D1={partial:!0,tokenize:z1};function F1(t){return Xh(t),t}function L1(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):wt(d)?t.check(D1,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 z1(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||wt(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 Zh(t,n,s,i,r,l,o,d,m){const c=m||Number.POSITIVE_INFINITY;let u=0;return h;function h(y){return y===60?(t.enter(i),t.enter(r),t.enter(l),t.consume(y),t.exit(l),g):y===null||y===32||y===41||Ir(y)?s(y):(t.enter(i),t.enter(o),t.enter(d),t.enter("chunkString",{contentType:"string"}),b(y))}function g(y){return y===62?(t.enter(l),t.consume(y),t.exit(l),t.exit(r),t.exit(i),n):(t.enter(d),t.enter("chunkString",{contentType:"string"}),p(y))}function p(y){return y===62?(t.exit("chunkString"),t.exit(d),g(y)):y===null||y===60||wt(y)?s(y):(t.consume(y),y===92?f:p)}function f(y){return y===60||y===62||y===92?(t.consume(y),p):p(y)}function b(y){return!u&&(y===null||y===41||Jt(y))?(t.exit("chunkString"),t.exit(d),t.exit(o),t.exit(i),n(y)):u<c&&y===40?(t.consume(y),u++,b):y===41?(t.consume(y),u--,b):y===null||y===32||y===40||Ir(y)?s(y):(t.consume(y),y===92?x:b)}function x(y){return y===40||y===41||y===92?(t.consume(y),b):b(y)}}function ep(t,n,s,i,r,l){const o=this;let d=0,m;return c;function c(p){return t.enter(i),t.enter(r),t.consume(p),t.exit(r),t.enter(l),u}function u(p){return d>999||p===null||p===91||p===93&&!m||p===94&&!d&&"_hiddenFootnoteSupport"in o.parser.constructs?s(p):p===93?(t.exit(l),t.enter(r),t.consume(p),t.exit(r),t.exit(i),n):wt(p)?(t.enter("lineEnding"),t.consume(p),t.exit("lineEnding"),u):(t.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||wt(p)||d++>999?(t.exit("chunkString"),u(p)):(t.consume(p),m||(m=!$t(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(t.consume(p),d++,h):h(p)}}function tp(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):wt(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||wt(g)?(t.exit("chunkString"),c(g)):(t.consume(g),g===92?h:u)}function h(g){return g===o||g===92?(t.consume(g),u):u(g)}}function Pa(t,n){let s;return i;function i(r){return wt(r)?(t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),s=!0,i):$t(r)?Ot(t,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const O1={name:"definition",tokenize:U1},B1={partial:!0,tokenize:H1};function U1(t,n,s){const i=this;let r;return l;function l(p){return t.enter("definition"),o(p)}function o(p){return ep.call(i,t,d,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function d(p){return r=Ms(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(t.enter("definitionMarker"),t.consume(p),t.exit("definitionMarker"),m):s(p)}function m(p){return Jt(p)?Pa(t,c)(p):c(p)}function c(p){return Zh(t,u,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(B1,h,h)(p)}function h(p){return $t(p)?Ot(t,g,"whitespace")(p):g(p)}function g(p){return p===null||wt(p)?(t.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function H1(t,n,s){return i;function i(d){return Jt(d)?Pa(t,r)(d):s(d)}function r(d){return tp(t,l,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function l(d){return $t(d)?Ot(t,o,"whitespace")(d):o(d)}function o(d){return d===null||wt(d)?n(d):s(d)}}const q1={name:"hardBreakEscape",tokenize:V1};function V1(t,n,s){return i;function i(l){return t.enter("hardBreakEscape"),t.consume(l),r}function r(l){return wt(l)?(t.exit("hardBreakEscape"),n(l)):s(l)}}const W1={name:"headingAtx",resolve:K1,tokenize:G1};function K1(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"},ms(t,i,s-i+1,[["enter",r,n],["enter",l,n],["exit",l,n],["exit",r,n]])),t}function G1(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||Jt(u)?(t.exit("atxHeadingSequence"),d(u)):s(u)}function d(u){return u===35?(t.enter("atxHeadingSequence"),m(u)):u===null||wt(u)?(t.exit("atxHeading"),n(u)):$t(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||Jt(u)?(t.exit("atxHeadingText"),d(u)):(t.consume(u),c)}}const J1=["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"],ou=["pre","script","style","textarea"],Y1={concrete:!0,name:"htmlFlow",resolveTo:Z1,tokenize:eS},Q1={partial:!0,tokenize:nS},X1={partial:!0,tokenize:tS};function Z1(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 eS(t,n,s){const i=this;let r,l,o,d,m;return c;function c(E){return u(E)}function u(E){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(E),h}function h(E){return E===33?(t.consume(E),g):E===47?(t.consume(E),l=!0,b):E===63?(t.consume(E),r=3,i.interrupt?n:D):Gn(E)?(t.consume(E),o=String.fromCharCode(E),x):s(E)}function g(E){return E===45?(t.consume(E),r=2,p):E===91?(t.consume(E),r=5,d=0,f):Gn(E)?(t.consume(E),r=4,i.interrupt?n:D):s(E)}function p(E){return E===45?(t.consume(E),i.interrupt?n:D):s(E)}function f(E){const J="CDATA[";return E===J.charCodeAt(d++)?(t.consume(E),d===J.length?i.interrupt?n:O:f):s(E)}function b(E){return Gn(E)?(t.consume(E),o=String.fromCharCode(E),x):s(E)}function x(E){if(E===null||E===47||E===62||Jt(E)){const J=E===47,ue=o.toLowerCase();return!J&&!l&&ou.includes(ue)?(r=1,i.interrupt?n(E):O(E)):J1.includes(o.toLowerCase())?(r=6,J?(t.consume(E),y):i.interrupt?n(E):O(E)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(E):l?v(E):M(E))}return E===45||zn(E)?(t.consume(E),o+=String.fromCharCode(E),x):s(E)}function y(E){return E===62?(t.consume(E),i.interrupt?n:O):s(E)}function v(E){return $t(E)?(t.consume(E),v):C(E)}function M(E){return E===47?(t.consume(E),C):E===58||E===95||Gn(E)?(t.consume(E),N):$t(E)?(t.consume(E),M):C(E)}function N(E){return E===45||E===46||E===58||E===95||zn(E)?(t.consume(E),N):A(E)}function A(E){return E===61?(t.consume(E),w):$t(E)?(t.consume(E),A):M(E)}function w(E){return E===null||E===60||E===61||E===62||E===96?s(E):E===34||E===39?(t.consume(E),m=E,S):$t(E)?(t.consume(E),w):k(E)}function S(E){return E===m?(t.consume(E),m=null,P):E===null||wt(E)?s(E):(t.consume(E),S)}function k(E){return E===null||E===34||E===39||E===47||E===60||E===61||E===62||E===96||Jt(E)?A(E):(t.consume(E),k)}function P(E){return E===47||E===62||$t(E)?M(E):s(E)}function C(E){return E===62?(t.consume(E),R):s(E)}function R(E){return E===null||wt(E)?O(E):$t(E)?(t.consume(E),R):s(E)}function O(E){return E===45&&r===2?(t.consume(E),j):E===60&&r===1?(t.consume(E),Q):E===62&&r===4?(t.consume(E),U):E===63&&r===3?(t.consume(E),D):E===93&&r===5?(t.consume(E),L):wt(E)&&(r===6||r===7)?(t.exit("htmlFlowData"),t.check(Q1,G,Z)(E)):E===null||wt(E)?(t.exit("htmlFlowData"),Z(E)):(t.consume(E),O)}function Z(E){return t.check(X1,I,G)(E)}function I(E){return t.enter("lineEnding"),t.consume(E),t.exit("lineEnding"),_}function _(E){return E===null||wt(E)?Z(E):(t.enter("htmlFlowData"),O(E))}function j(E){return E===45?(t.consume(E),D):O(E)}function Q(E){return E===47?(t.consume(E),o="",Y):O(E)}function Y(E){if(E===62){const J=o.toLowerCase();return ou.includes(J)?(t.consume(E),U):O(E)}return Gn(E)&&o.length<8?(t.consume(E),o+=String.fromCharCode(E),Y):O(E)}function L(E){return E===93?(t.consume(E),D):O(E)}function D(E){return E===62?(t.consume(E),U):E===45&&r===2?(t.consume(E),D):O(E)}function U(E){return E===null||wt(E)?(t.exit("htmlFlowData"),G(E)):(t.consume(E),U)}function G(E){return t.exit("htmlFlow"),n(E)}}function tS(t,n,s){const i=this;return r;function r(o){return wt(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 nS(t,n,s){return i;function i(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),t.attempt(Ya,n,s)}}const sS={name:"htmlText",tokenize:iS};function iS(t,n,s){const i=this;let r,l,o;return d;function d(D){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(D),m}function m(D){return D===33?(t.consume(D),c):D===47?(t.consume(D),A):D===63?(t.consume(D),M):Gn(D)?(t.consume(D),k):s(D)}function c(D){return D===45?(t.consume(D),u):D===91?(t.consume(D),l=0,f):Gn(D)?(t.consume(D),v):s(D)}function u(D){return D===45?(t.consume(D),p):s(D)}function h(D){return D===null?s(D):D===45?(t.consume(D),g):wt(D)?(o=h,Q(D)):(t.consume(D),h)}function g(D){return D===45?(t.consume(D),p):h(D)}function p(D){return D===62?j(D):D===45?g(D):h(D)}function f(D){const U="CDATA[";return D===U.charCodeAt(l++)?(t.consume(D),l===U.length?b:f):s(D)}function b(D){return D===null?s(D):D===93?(t.consume(D),x):wt(D)?(o=b,Q(D)):(t.consume(D),b)}function x(D){return D===93?(t.consume(D),y):b(D)}function y(D){return D===62?j(D):D===93?(t.consume(D),y):b(D)}function v(D){return D===null||D===62?j(D):wt(D)?(o=v,Q(D)):(t.consume(D),v)}function M(D){return D===null?s(D):D===63?(t.consume(D),N):wt(D)?(o=M,Q(D)):(t.consume(D),M)}function N(D){return D===62?j(D):M(D)}function A(D){return Gn(D)?(t.consume(D),w):s(D)}function w(D){return D===45||zn(D)?(t.consume(D),w):S(D)}function S(D){return wt(D)?(o=S,Q(D)):$t(D)?(t.consume(D),S):j(D)}function k(D){return D===45||zn(D)?(t.consume(D),k):D===47||D===62||Jt(D)?P(D):s(D)}function P(D){return D===47?(t.consume(D),j):D===58||D===95||Gn(D)?(t.consume(D),C):wt(D)?(o=P,Q(D)):$t(D)?(t.consume(D),P):j(D)}function C(D){return D===45||D===46||D===58||D===95||zn(D)?(t.consume(D),C):R(D)}function R(D){return D===61?(t.consume(D),O):wt(D)?(o=R,Q(D)):$t(D)?(t.consume(D),R):P(D)}function O(D){return D===null||D===60||D===61||D===62||D===96?s(D):D===34||D===39?(t.consume(D),r=D,Z):wt(D)?(o=O,Q(D)):$t(D)?(t.consume(D),O):(t.consume(D),I)}function Z(D){return D===r?(t.consume(D),r=void 0,_):D===null?s(D):wt(D)?(o=Z,Q(D)):(t.consume(D),Z)}function I(D){return D===null||D===34||D===39||D===60||D===61||D===96?s(D):D===47||D===62||Jt(D)?P(D):(t.consume(D),I)}function _(D){return D===47||D===62||Jt(D)?P(D):s(D)}function j(D){return D===62?(t.consume(D),t.exit("htmlTextData"),t.exit("htmlText"),n):s(D)}function Q(D){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(D),t.exit("lineEnding"),Y}function Y(D){return $t(D)?Ot(t,L,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):L(D)}function L(D){return t.enter("htmlTextData"),o(D)}}const rc={name:"labelEnd",resolveAll:oS,resolveTo:cS,tokenize:dS},aS={tokenize:uS},rS={tokenize:mS},lS={tokenize:hS};function oS(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&&ms(t,0,t.length,s),t}function cS(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=ks(d,t.slice(l+1,l+i+3)),d=ks(d,[["enter",u,n]]),d=ks(d,Zr(n.parser.constructs.insideSpan.null,t.slice(l+i+4,o-3),n)),d=ks(d,[["exit",u,n],t[o-2],t[o-1],["exit",c,n]]),d=ks(d,t.slice(o+1)),d=ks(d,[["exit",m,n]]),ms(t,l,t.length,d),t}function dS(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(Ms(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(aS,u,o?u:h)(g):g===91?t.attempt(rS,u,o?c:h)(g):o?u(g):h(g)}function c(g){return t.attempt(lS,u,h)(g)}function u(g){return n(g)}function h(g){return l._balanced=!0,s(g)}}function uS(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 Jt(h)?Pa(t,l)(h):l(h)}function l(h){return h===41?u(h):Zh(t,o,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function o(h){return Jt(h)?Pa(t,m)(h):u(h)}function d(h){return s(h)}function m(h){return h===34||h===39||h===40?tp(t,c,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):u(h)}function c(h){return Jt(h)?Pa(t,u)(h):u(h)}function u(h){return h===41?(t.enter("resourceMarker"),t.consume(h),t.exit("resourceMarker"),t.exit("resource"),n):s(h)}}function mS(t,n,s){const i=this;return r;function r(d){return ep.call(i,t,l,o,"reference","referenceMarker","referenceString")(d)}function l(d){return i.parser.defined.includes(Ms(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(d):s(d)}function o(d){return s(d)}}function hS(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 pS={name:"labelStartImage",resolveAll:rc.resolveAll,tokenize:fS};function fS(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 gS={name:"labelStartLink",resolveAll:rc.resolveAll,tokenize:bS};function bS(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 Ml={name:"lineEnding",tokenize:xS};function xS(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:vS};function vS(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||wt(c))?(t.exit("thematicBreak"),n(c)):s(c)}function m(c){return c===r?(t.consume(c),i++,m):(t.exit("thematicBreakSequence"),$t(c)?Ot(t,d,"whitespace")(c):d(c))}}const es={continuation:{tokenize:wS},exit:SS,name:"list",tokenize:jS},yS={partial:!0,tokenize:CS},kS={partial:!0,tokenize:NS};function jS(t,n,s){const i=this,r=i.events[i.events.length-1];let l=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,o=0;return d;function d(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:So(p)){if(i.containerState.type||(i.containerState.type=f,t.enter(f,{_container:!0})),f==="listUnordered")return t.enter("listItemPrefix"),p===42||p===45?t.check(jr,s,c)(p):c(p);if(!i.interrupt||p===49)return t.enter("listItemPrefix"),t.enter("listItemValue"),m(p)}return s(p)}function m(p){return So(p)&&++o<10?(t.consume(p),m):(!i.interrupt||o<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(t.exit("listItemValue"),c(p)):s(p)}function c(p){return t.enter("listItemMarker"),t.consume(p),t.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,t.check(Ya,i.interrupt?s:u,t.attempt(yS,g,h))}function u(p){return i.containerState.initialBlankLine=!0,l++,g(p)}function h(p){return $t(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=l+i.sliceSerialize(t.exit("listItemPrefix"),!0).length,n(p)}}function wS(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||!$t(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(kS,n,o)(d))}function o(d){return i.containerState._closeFlow=!0,i.interrupt=void 0,Ot(t,t.attempt(es,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function NS(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 SS(t){t.exit(this.containerState.type)}function CS(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!$t(l)&&o&&o[1].type==="listItemPrefixWhitespace"?n(l):s(l)}}const cu={name:"setextUnderline",resolveTo:ES,tokenize:MS};function ES(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 MS(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"),$t(c)?Ot(t,m,"lineSuffix")(c):m(c))}function m(c){return c===null||wt(c)?(t.exit("setextHeadingLine"),n(c)):s(c)}}const AS={tokenize:PS};function PS(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($1,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 TS={resolveAll:sp()},RS=np("string"),_S=np("text");function np(t){return{resolveAll:sp(t==="text"?IS:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[t],l=s.attempt(r,o,d);return o;function o(u){return c(u)?l(u):d(u)}function d(u){if(u===null){s.consume(u);return}return s.enter("data"),s.consume(u),m}function m(u){return c(u)?(s.exit("data"),l(u)):(s.consume(u),m)}function c(u){if(u===null)return!0;const h=r[u];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function sp(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 IS(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 $S={42:es,43:es,45:es,48:es,49:es,50:es,51:es,52:es,53:es,54:es,55:es,56:es,57:es,62:Jh},DS={91:O1},FS={[-2]:El,[-1]:El,32:El},LS={35:W1,42:jr,45:[cu,jr],60:Y1,61:cu,95:jr,96:lu,126:lu},zS={38:Qh,92:Yh},OS={[-5]:Ml,[-4]:Ml,[-3]:Ml,33:pS,38:Qh,42:Co,60:[g1,sS],91:gS,92:[q1,Yh],93:rc,95:Co,96:A1},BS={null:[Co,TS]},US={null:[42,95]},HS={null:[]},qS=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:US,contentInitial:DS,disable:HS,document:$S,flow:LS,flowInitial:FS,insideSpan:BS,string:zS,text:OS},Symbol.toStringTag,{value:"Module"}));function VS(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:S(A),check:S(w),consume:v,enter:M,exit:N,interrupt:S(w,{interrupt:!0})},c={code:null,containerState:{},defineSkip:b,events:[],now:f,parser:t,previous:null,sliceSerialize:g,sliceStream:p,write:h};let u=n.tokenize.call(c,m);return n.resolveAll&&l.push(n),c;function h(R){return o=ks(o,R),x(),o[o.length-1]!==null?[]:(k(n,0),c.events=Zr(l,c.events,c),c.events)}function g(R,O){return KS(p(R),O)}function p(R){return WS(o,R)}function f(){const{_bufferIndex:R,_index:O,line:Z,column:I,offset:_}=i;return{_bufferIndex:R,_index:O,line:Z,column:I,offset:_}}function b(R){r[R.line]=R.column,C()}function x(){let R;for(;i._index<o.length;){const O=o[i._index];if(typeof O=="string")for(R=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===R&&i._bufferIndex<O.length;)y(O.charCodeAt(i._bufferIndex));else y(O)}}function y(R){u=u(R)}function v(R){wt(R)?(i.line++,i.column=1,i.offset+=R===-3?2:1,C()):R!==-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=R}function M(R,O){const Z=O||{};return Z.type=R,Z.start=f(),c.events.push(["enter",Z,c]),d.push(Z),Z}function N(R){const O=d.pop();return O.end=f(),c.events.push(["exit",O,c]),O}function A(R,O){k(R,O.from)}function w(R,O){O.restore()}function S(R,O){return Z;function Z(I,_,j){let Q,Y,L,D;return Array.isArray(I)?G(I):"tokenize"in I?G([I]):U(I);function U(z){return te;function te(F){const fe=F!==null&&z[F],V=F!==null&&z.null,K=[...Array.isArray(fe)?fe:fe?[fe]:[],...Array.isArray(V)?V:V?[V]:[]];return G(K)(F)}}function G(z){return Q=z,Y=0,z.length===0?j:E(z[Y])}function E(z){return te;function te(F){return D=P(),L=z,z.partial||(c.currentConstruct=z),z.name&&c.parser.constructs.disable.null.includes(z.name)?ue():z.tokenize.call(O?Object.assign(Object.create(c),O):c,m,J,ue)(F)}}function J(z){return R(L,D),_}function ue(z){return D.restore(),++Y<Q.length?E(Q[Y]):j}}}function k(R,O){R.resolveAll&&!l.includes(R)&&l.push(R),R.resolve&&ms(c.events,O,c.events.length-O,R.resolve(c.events.slice(O),c)),R.resolveTo&&(c.events=R.resolveTo(c.events,c))}function P(){const R=f(),O=c.previous,Z=c.currentConstruct,I=c.events.length,_=Array.from(d);return{from:I,restore:j};function j(){i=R,c.previous=O,c.currentConstruct=Z,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 WS(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 KS(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 GS(t){const i={constructs:Kh([qS,...(t||{}).extensions||[]]),content:r(c1),defined:[],document:r(u1),flow:r(AS),lazy:{},string:r(RS),text:r(_S)};return i;function r(l){return o;function o(d){return VS(i,l,d)}}}function JS(t){for(;!Xh(t););return t}const du=/[\0\t\n\r]/g;function YS(){let t=1,n="",s=!0,i;return r;function r(l,o,d){const m=[];let c,u,h,g,p;for(l=n+(typeof l=="string"?l.toString():new TextDecoder(o||void 0).decode(l)),h=0,n="",s&&(l.charCodeAt(0)===65279&&h++,s=void 0);h<l.length;){if(du.lastIndex=h,c=du.exec(l),g=c&&c.index!==void 0?c.index:l.length,p=l.charCodeAt(g),!c){n=l.slice(h);break}if(p===10&&h===g&&i)m.push(-3),i=void 0;else switch(i&&(m.push(-5),i=void 0),h<g&&(m.push(l.slice(h,g)),t+=g-h),p){case 0:{m.push(65533),t++;break}case 9:{for(u=Math.ceil(t/4)*4,m.push(-2);t++<u;)m.push(-1);break}case 10:{m.push(-4),t=1;break}default:i=!0,t=1}h=g+1}return d&&(i&&m.push(-5),n&&m.push(n),m.push(null)),m}}const QS=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function XS(t){return t.replace(QS,ZS)}function ZS(t,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),l=r===120||r===88;return Gh(s.slice(l?2:1),l?16:10)}return ac(s)||t}const ip={}.hasOwnProperty;function e0(t,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),t0(s)(JS(GS(s).document().write(YS()(t,n,!0))))}function t0(t){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l(rt),autolinkProtocol:P,autolinkEmail:P,atxHeading:l(Se),blockQuote:l(V),characterEscape:P,characterReference:P,codeFenced:l(K),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:l(K,o),codeText:l(de,o),codeTextData:P,data:P,codeFlowValue:P,definition:l(we),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:l(ve),hardBreakEscape:l(Pe),hardBreakTrailing:l(Pe),htmlFlow:l(Oe,o),htmlFlowData:P,htmlText:l(Oe,o),htmlTextData:P,image:l(Ie),label:o,link:l(rt),listItem:l(_e),listItemValue:g,listOrdered:l(Ee,h),listUnordered:l(Ee),paragraph:l(Be),reference:E,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:l(Se),strong:l(et),thematicBreak:l(Xe)},exit:{atxHeading:m(),atxHeadingSequence:A,autolink:m(),autolinkEmail:fe,autolinkProtocol:F,blockQuote:m(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:ue,characterReferenceMarkerNumeric:ue,characterReferenceValue:z,characterReference:te,codeFenced:m(x),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:C,codeIndented:m(y),codeText:m(_),codeTextData:C,data:C,definition:m(),definitionDestinationString:N,definitionLabelString:v,definitionTitleString:M,emphasis:m(),hardBreakEscape:m(O),hardBreakTrailing:m(O),htmlFlow:m(Z),htmlFlowData:C,htmlText:m(I),htmlTextData:C,image:m(Q),label:L,labelText:Y,lineEnding:R,link:m(j),listItem:m(),listOrdered:m(),listUnordered:m(),paragraph:m(),referenceString:J,resourceDestinationString:D,resourceTitleString:U,resource:G,setextHeading:m(k),setextHeadingLineSequence:S,setextHeadingText:w,strong:m(),thematicBreak:m()}};ap(n,(t||{}).mdastExtensions||[]);const s={};return i;function i(re){let ne={type:"root",children:[]};const ge={stack:[ne],tokenStack:[],config:n,enter:d,exit:c,buffer:o,resume:u,data:s},le=[];let Te=-1;for(;++Te<re.length;)if(re[Te][1].type==="listOrdered"||re[Te][1].type==="listUnordered")if(re[Te][0]==="enter")le.push(Te);else{const ye=le.pop();Te=r(re,ye,Te)}for(Te=-1;++Te<re.length;){const ye=n[re[Te][0]];ip.call(ye,re[Te][1].type)&&ye[re[Te][1].type].call(Object.assign({sliceSerialize:re[Te][2].sliceSerialize},ge),re[Te][1])}if(ge.tokenStack.length>0){const ye=ge.tokenStack[ge.tokenStack.length-1];(ye[1]||uu).call(ge,void 0,ye[0])}for(ne.position={start:Qs(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:Qs(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Te=-1;++Te<n.transforms.length;)ne=n.transforms[Te](ne)||ne;return ne}function r(re,ne,ge){let le=ne-1,Te=-1,ye=!1,He,nt,mt,he;for(;++le<=ge;){const ie=re[le];switch(ie[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ie[0]==="enter"?Te++:Te--,he=void 0;break}case"lineEndingBlank":{ie[0]==="enter"&&(He&&!he&&!Te&&!mt&&(mt=le),he=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:he=void 0}if(!Te&&ie[0]==="enter"&&ie[1].type==="listItemPrefix"||Te===-1&&ie[0]==="exit"&&(ie[1].type==="listUnordered"||ie[1].type==="listOrdered")){if(He){let be=le;for(nt=void 0;be--;){const Me=re[be];if(Me[1].type==="lineEnding"||Me[1].type==="lineEndingBlank"){if(Me[0]==="exit")continue;nt&&(re[nt][1].type="lineEndingBlank",ye=!0),Me[1].type="lineEnding",nt=be}else if(!(Me[1].type==="linePrefix"||Me[1].type==="blockQuotePrefix"||Me[1].type==="blockQuotePrefixWhitespace"||Me[1].type==="blockQuoteMarker"||Me[1].type==="listItemIndent"))break}mt&&(!nt||mt<nt)&&(He._spread=!0),He.end=Object.assign({},nt?re[nt][1].start:ie[1].end),re.splice(nt||le,0,["exit",He,ie[2]]),le++,ge++}if(ie[1].type==="listItemPrefix"){const be={type:"listItem",_spread:!1,start:Object.assign({},ie[1].start),end:void 0};He=be,re.splice(le,0,["enter",be,ie[2]]),le++,ge++,mt=void 0,he=!0}}}return re[ne][1]._spread=ye,ge}function l(re,ne){return ge;function ge(le){d.call(this,re(le),le),ne&&ne.call(this,le)}}function o(){this.stack.push({type:"fragment",children:[]})}function d(re,ne,ge){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([ne,ge||void 0]),re.position={start:Qs(ne.start),end:void 0}}function m(re){return ne;function ne(ge){re&&re.call(this,ge),c.call(this,ge)}}function c(re,ne){const ge=this.stack.pop(),le=this.tokenStack.pop();if(le)le[0].type!==re.type&&(ne?ne.call(this,re,le[0]):(le[1]||uu).call(this,re,le[0]));else throw new Error("Cannot close `"+re.type+"` ("+Aa({start:re.start,end:re.end})+"): it’s not open");ge.position.end=Qs(re.end)}function u(){return ic(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(re){if(this.data.expectingFirstListItemValue){const ne=this.stack[this.stack.length-2];ne.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.lang=re}function f(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.meta=re}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function y(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.value=re.replace(/(\r?\n|\r)$/g,"")}function v(re){const ne=this.resume(),ge=this.stack[this.stack.length-1];ge.label=ne,ge.identifier=Ms(this.sliceSerialize(re)).toLowerCase()}function M(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.title=re}function N(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.url=re}function A(re){const ne=this.stack[this.stack.length-1];if(!ne.depth){const ge=this.sliceSerialize(re).length;ne.depth=ge}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function S(re){const ne=this.stack[this.stack.length-1];ne.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function k(){this.data.setextHeadingSlurpLineEnding=void 0}function P(re){const ge=this.stack[this.stack.length-1].children;let le=ge[ge.length-1];(!le||le.type!=="text")&&(le=De(),le.position={start:Qs(re.start),end:void 0},ge.push(le)),this.stack.push(le)}function C(re){const ne=this.stack.pop();ne.value+=this.sliceSerialize(re),ne.position.end=Qs(re.end)}function R(re){const ne=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ge=ne.children[ne.children.length-1];ge.position.end=Qs(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(ne.type)&&(P.call(this,re),C.call(this,re))}function O(){this.data.atHardBreak=!0}function Z(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.value=re}function I(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.value=re}function _(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.value=re}function j(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const ne=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=ne,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Q(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const ne=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=ne,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function Y(re){const ne=this.sliceSerialize(re),ge=this.stack[this.stack.length-2];ge.label=XS(ne),ge.identifier=Ms(ne).toLowerCase()}function L(){const re=this.stack[this.stack.length-1],ne=this.resume(),ge=this.stack[this.stack.length-1];if(this.data.inReference=!0,ge.type==="link"){const le=re.children;ge.children=le}else ge.alt=ne}function D(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.url=re}function U(){const re=this.resume(),ne=this.stack[this.stack.length-1];ne.title=re}function G(){this.data.inReference=void 0}function E(){this.data.referenceType="collapsed"}function J(re){const ne=this.resume(),ge=this.stack[this.stack.length-1];ge.label=ne,ge.identifier=Ms(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function ue(re){this.data.characterReferenceType=re.type}function z(re){const ne=this.sliceSerialize(re),ge=this.data.characterReferenceType;let le;ge?(le=Gh(ne,ge==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):le=ac(ne);const Te=this.stack[this.stack.length-1];Te.value+=le}function te(re){const ne=this.stack.pop();ne.position.end=Qs(re.end)}function F(re){C.call(this,re);const ne=this.stack[this.stack.length-1];ne.url=this.sliceSerialize(re)}function fe(re){C.call(this,re);const ne=this.stack[this.stack.length-1];ne.url="mailto:"+this.sliceSerialize(re)}function V(){return{type:"blockquote",children:[]}}function K(){return{type:"code",lang:null,meta:null,value:""}}function de(){return{type:"inlineCode",value:""}}function we(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ve(){return{type:"emphasis",children:[]}}function Se(){return{type:"heading",depth:0,children:[]}}function Pe(){return{type:"break"}}function Oe(){return{type:"html",value:""}}function Ie(){return{type:"image",title:null,url:"",alt:null}}function rt(){return{type:"link",title:null,url:"",children:[]}}function Ee(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function _e(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function Be(){return{type:"paragraph",children:[]}}function et(){return{type:"strong",children:[]}}function De(){return{type:"text",value:""}}function Xe(){return{type:"thematicBreak"}}}function Qs(t){return{line:t.line,column:t.column,offset:t.offset}}function ap(t,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?ap(t,i):n0(t,i)}}function n0(t,n){let s;for(s in n)if(ip.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 uu(t,n){throw t?new Error("Cannot close `"+t.type+"` ("+Aa({start:t.start,end:t.end})+"): a different token (`"+n.type+"`, "+Aa({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Aa({start:n.start,end:n.end})+") is still open")}function s0(t){const n=this;n.parser=s;function s(i){return e0(i,{...n.data("settings"),...t,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function i0(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 a0(t,n){const s={type:"element",tagName:"br",properties:{},children:[]};return t.patch(n,s),[t.applyData(n,s),{type:"text",value:`
596
- `}]}function r0(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 l0(t,n){const s={type:"element",tagName:"del",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function o0(t,n){const s={type:"element",tagName:"em",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function c0(t,n){const s=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=oa(i.toLowerCase()),l=t.footnoteOrder.indexOf(i);let o,d=t.footnoteCounts.get(i);d===void 0?(d=0,t.footnoteOrder.push(i),o=t.footnoteOrder.length):o=l+1,d+=1,t.footnoteCounts.set(i,d);const m={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(d>1?"-"+d:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(o)}]};t.patch(n,m);const c={type:"element",tagName:"sup",properties:{},children:[m]};return t.patch(n,c),t.applyData(n,c)}function d0(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 u0(t,n){if(t.options.allowDangerousHtml){const s={type:"raw",value:n.value};return t.patch(n,s),t.applyData(n,s)}}function rp(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 m0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return rp(t,n);const r={src:oa(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const l={type:"element",tagName:"img",properties:r,children:[]};return t.patch(n,l),t.applyData(n,l)}function h0(t,n){const s={src:oa(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return t.patch(n,i),t.applyData(n,i)}function p0(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 f0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return rp(t,n);const r={href:oa(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const l={type:"element",tagName:"a",properties:r,children:t.all(n)};return t.patch(n,l),t.applyData(n,l)}function g0(t,n){const s={href:oa(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:t.all(n)};return t.patch(n,i),t.applyData(n,i)}function b0(t,n,s){const i=t.all(n),r=s?x0(s):lp(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 x0(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=lp(s[i])}return n}function lp(t){const n=t.spread;return n??t.children.length>1}function v0(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 y0(t,n){const s={type:"element",tagName:"p",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function k0(t,n){const s={type:"root",children:t.wrap(t.all(n))};return t.patch(n,s),t.applyData(n,s)}function j0(t,n){const s={type:"element",tagName:"strong",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function w0(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=ec(n.children[1]),m=Oh(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 N0(t,n,s){const i=s?s.children:void 0,l=(i?i.indexOf(n):1)===0?"th":"td",o=s&&s.type==="table"?s.align:void 0,d=o?o.length:n.children.length;let m=-1;const c=[];for(;++m<d;){const h=n.children[m],g={},p=o?o[m]:void 0;p&&(g.align=p);let f={type:"element",tagName:l,properties:g,children:[]};h&&(f.children=t.all(h),t.patch(h,f),f=t.applyData(h,f)),c.push(f)}const u={type:"element",tagName:"tr",properties:{},children:t.wrap(c,!0)};return t.patch(n,u),t.applyData(n,u)}function S0(t,n){const s={type:"element",tagName:"td",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}const mu=9,hu=32;function C0(t){const n=String(t),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const l=[];for(;i;)l.push(pu(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return l.push(pu(n.slice(r),r>0,!1)),l.join("")}function pu(t,n,s){let i=0,r=t.length;if(n){let l=t.codePointAt(i);for(;l===mu||l===hu;)i++,l=t.codePointAt(i)}if(s){let l=t.codePointAt(r-1);for(;l===mu||l===hu;)r--,l=t.codePointAt(r-1)}return r>i?t.slice(i,r):""}function E0(t,n){const s={type:"text",value:C0(String(n.value))};return t.patch(n,s),t.applyData(n,s)}function M0(t,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(n,s),t.applyData(n,s)}const A0={blockquote:i0,break:a0,code:r0,delete:l0,emphasis:o0,footnoteReference:c0,heading:d0,html:u0,imageReference:m0,image:h0,inlineCode:p0,linkReference:f0,link:g0,listItem:b0,list:v0,paragraph:y0,root:k0,strong:j0,table:w0,tableCell:S0,tableRow:N0,text:E0,thematicBreak:M0,toml:cr,yaml:cr,definition:cr,footnoteDefinition:cr};function cr(){}const op=-1,el=0,Ta=1,$r=2,lc=3,oc=4,cc=5,dc=6,cp=7,dp=8,fu=typeof self=="object"?self:globalThis,P0=(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 el:case op:return s(o,r);case Ta:{const d=s([],r);for(const m of o)d.push(i(m));return d}case $r:{const d=s({},r);for(const[m,c]of o)d[i(m)]=i(c);return d}case lc:return s(new Date(o),r);case oc:{const{source:d,flags:m}=o;return s(new RegExp(d,m),r)}case cc:{const d=s(new Map,r);for(const[m,c]of o)d.set(i(m),i(c));return d}case dc:{const d=s(new Set,r);for(const m of o)d.add(i(m));return d}case cp:{const{name:d,message:m}=o;return s(new fu[d](m),r)}case dp: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 fu[l](o),r)};return i},gu=t=>P0(new Map,t)(0),$i="",{toString:T0}={},{keys:R0}=Object,ga=t=>{const n=typeof t;if(n!=="object"||!t)return[el,n];const s=T0.call(t).slice(8,-1);switch(s){case"Array":return[Ta,$i];case"Object":return[$r,$i];case"Date":return[lc,$i];case"RegExp":return[oc,$i];case"Map":return[cc,$i];case"Set":return[dc,$i];case"DataView":return[Ta,s]}return s.includes("Array")?[Ta,s]:s.includes("Error")?[cp,s]:[$r,s]},dr=([t,n])=>t===el&&(n==="function"||n==="symbol"),_0=(t,n,s,i)=>{const r=(o,d)=>{const m=i.push(o)-1;return s.set(d,m),m},l=o=>{if(s.has(o))return s.get(o);let[d,m]=ga(o);switch(d){case el:{let u=o;switch(m){case"bigint":d=dp,u=o.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+m);u=null;break;case"undefined":return r([op],o)}return r([d,u],o)}case Ta:{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 $r:{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 R0(o))(t||!dr(ga(o[g])))&&u.push([l(g),l(o[g])]);return h}case lc:return r([d,o.toISOString()],o);case oc:{const{source:u,flags:h}=o;return r([d,{source:u,flags:h}],o)}case cc:{const u=[],h=r([d,u],o);for(const[g,p]of o)(t||!(dr(ga(g))||dr(ga(p))))&&u.push([l(g),l(p)]);return h}case dc:{const u=[],h=r([d,u],o);for(const g of o)(t||!dr(ga(g)))&&u.push(l(g));return h}}const{message:c}=o;return r([d,{name:m,message:c}],o)};return l},bu=(t,{json:n,lossy:s}={})=>{const i=[];return _0(!(n||s),!!n,new Map,i)(t),i},Dr=typeof structuredClone=="function"?(t,n)=>n&&("json"in n||"lossy"in n)?gu(bu(t,n)):structuredClone(t):(t,n)=>gu(bu(t,n));function I0(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 $0(t,n){return"Back to reference "+(t+1)+(n>1?"-"+n:"")}function D0(t){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",s=t.options.footnoteBackContent||I0,i=t.options.footnoteBackLabel||$0,r=t.options.footnoteLabel||"Footnotes",l=t.options.footnoteLabelTagName||"h2",o=t.options.footnoteLabelProperties||{className:["sr-only"]},d=[];let m=-1;for(;++m<t.footnoteOrder.length;){const c=t.footnoteById.get(t.footnoteOrder[m]);if(!c)continue;const u=t.all(c),h=String(c.identifier).toUpperCase(),g=oa(h.toLowerCase());let p=0;const f=[],b=t.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){f.length>0&&f.push({type:"text",value:" "});let v=typeof s=="string"?s:s(m,p);typeof v=="string"&&(v={type:"text",value:v}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(m,p),className:["data-footnote-backref"]},children:Array.isArray(v)?v:[v]})}const x=u[u.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const v=x.children[x.children.length-1];v&&v.type==="text"?v.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...f)}else u.push(...f);const y={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:t.wrap(u,!0)};t.patch(c,y),d.push(y)}if(d.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:l,properties:{...Dr(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 tl=(function(t){if(t==null)return O0;if(typeof t=="function")return nl(t);if(typeof t=="object")return Array.isArray(t)?F0(t):L0(t);if(typeof t=="string")return z0(t);throw new Error("Expected function, string, or object as test")});function F0(t){const n=[];let s=-1;for(;++s<t.length;)n[s]=tl(t[s]);return nl(i);function i(...r){let l=-1;for(;++l<n.length;)if(n[l].apply(this,r))return!0;return!1}}function L0(t){const n=t;return nl(s);function s(i){const r=i;let l;for(l in t)if(r[l]!==n[l])return!1;return!0}}function z0(t){return nl(n);function n(s){return s&&s.type===t}}function nl(t){return n;function n(s,i,r){return!!(B0(s)&&t.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function O0(){return!0}function B0(t){return t!==null&&typeof t=="object"&&"type"in t}const up=[],U0=!0,Eo=!1,H0="skip";function mp(t,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const l=tl(r),o=i?-1:1;d(t,void 0,[])();function d(m,c,u){const h=m&&typeof m=="object"?m:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(m.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=up,f,b,x;if((!n||l(m,c,u[u.length-1]||void 0))&&(p=q0(s(m,u)),p[0]===Eo))return p;if("children"in m&&m.children){const y=m;if(y.children&&p[0]!==H0)for(b=(i?y.children.length:-1)+o,x=u.concat(y);b>-1&&b<y.children.length;){const v=y.children[b];if(f=d(v,b,x)(),f[0]===Eo)return f;b=typeof f[1]=="number"?f[1]:b+o}}return p}}}function q0(t){return Array.isArray(t)?t:typeof t=="number"?[U0,t]:t==null?up:[t]}function uc(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),mp(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 Mo={}.hasOwnProperty,V0={};function W0(t,n){const s=n||V0,i=new Map,r=new Map,l=new Map,o={...A0,...s.handlers},d={all:c,applyData:G0,definitionById:i,footnoteById:r,footnoteCounts:l,footnoteOrder:[],handlers:o,one:m,options:s,patch:K0,wrap:Y0};return uc(t,function(u){if(u.type==="definition"||u.type==="footnoteDefinition"){const h=u.type==="definition"?i:r,g=String(u.identifier).toUpperCase();h.has(g)||h.set(g,u)}}),d;function m(u,h){const g=u.type,p=d.handlers[g];if(Mo.call(d.handlers,g)&&p)return p(d,u,h);if(d.options.passThrough&&d.options.passThrough.includes(g)){if("children"in u){const{children:b,...x}=u,y=Dr(x);return y.children=d.all(u),y}return Dr(u)}return(d.options.unknownHandler||J0)(d,u,h)}function c(u){const h=[];if("children"in u){const g=u.children;let p=-1;for(;++p<g.length;){const f=d.one(g[p],u);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=xu(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=xu(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function K0(t,n){t.position&&(n.position=$N(t))}function G0(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,Dr(l)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function J0(t,n){const s=n.data||{},i="value"in n&&!(Mo.call(s,"hProperties")||Mo.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 Y0(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 xu(t){let n=0,s=t.charCodeAt(n);for(;s===9||s===32;)n++,s=t.charCodeAt(n);return t.slice(n)}function vu(t,n){const s=W0(t,n),i=s.one(t,void 0),r=D0(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 Q0(t,n){return t&&"run"in t?async function(s,i){const r=vu(s,{file:i,...n});await t.run(r,i)}:function(s,i){return vu(s,{file:i,...t||n})}}function yu(t){if(t)throw t}var Al,ku;function X0(){if(ku)return Al;ku=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 Al=function m(){var c,u,h,g,p,f,b=arguments[0],x=1,y=arguments.length,v=!1;for(typeof b=="boolean"&&(v=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});x<y;++x)if(c=arguments[x],c!=null)for(u in c)h=d(b,u),g=d(c,u),b!==g&&(v&&g&&(l(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&l(h)?h:{},o(b,{name:u,newValue:m(v,f,g)})):typeof g<"u"&&o(b,{name:u,newValue:g}));return b},Al}var Z0=X0();const Pl=Rm(Z0);function Ao(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 eC(){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?tC(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 tC(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:nC,dirname:sC,extname:iC,join:aC,sep:"/"};function nC(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 sC(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 iC(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 aC(...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?".":rC(s)}function rC(t){Qa(t);const n=t.codePointAt(0)===47;let s=lC(t,!n);return s.length===0&&!n&&(s="."),s.length>0&&t.codePointAt(t.length-1)===47&&(s+="/"),n?"/"+s:s}function lC(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 oC={cwd:cC};function cC(){return"/"}function Po(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function dC(t){if(typeof t=="string")t=new URL(t);else if(!Po(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 uC(t)}function uC(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 hp{constructor(n){let s;n?Po(n)?s={path:n}:typeof n=="string"||mC(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":oC.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){_l(n,"basename"),Rl(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){ju(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(Rl(n,"extname"),ju(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){Po(n)&&(n=dC(n)),_l(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){_l(n,"stem"),Rl(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 Rl(t,n){if(t&&t.includes(Is.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Is.sep+"`")}function _l(t,n){if(!t)throw new Error("`"+n+"` cannot be empty")}function ju(t,n){if(!t)throw new Error("Setting `"+n+"` requires `path` to be set too")}function mC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const hC=(function(t){const i=this.constructor.prototype,r=i[t],l=function(){return r.apply(l,arguments)};return Object.setPrototypeOf(l,i),l}),pC={}.hasOwnProperty;class mc extends hC{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=eC()}copy(){const n=new mc;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Pl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Dl("data",this.frozen),this.namespace[n]=s,this):pC.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Dl("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 Il("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Il("process",this.parser||this.Parser),$l("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 p=h,f=i.stringify(p,g);bC(f)?g.value=f:g.result=f,c(u,g)});function c(u,h){u||!h?o(u):l?l(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),Il("processSync",this.parser||this.Parser),$l("processSync",this.compiler||this.Compiler),this.process(n,r),Nu("processSync","process",s),i;function r(l,o){s=!0,yu(l),i=o}}run(n,s,i){wu(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 p=h||n;u?d(u):o?o(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,l),Nu("runSync","run",i),r;function l(o,d){yu(o),r=d,i=!0}}stringify(n,s){this.freeze();const i=ur(s),r=this.compiler||this.Compiler;return $l("stringify",r),wu(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Dl("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=Pl(!0,r.settings,c.settings))}function d(c){let u=-1;if(c!=null)if(Array.isArray(c))for(;++u<c.length;){const h=c[u];l(h)}else throw new TypeError("Expected a list of plugins, not `"+c+"`")}function m(c,u){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===c){g=h;break}if(g===-1)i.push([c,...u]);else if(u.length>0){let[p,...f]=u;const b=i[g][1];Ao(b)&&Ao(p)&&(p=Pl(!0,b,p)),i[g]=[c,p,...f]}}}}const fC=new mc().freeze();function Il(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function $l(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Dl(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 wu(t){if(!Ao(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Nu(t,n,s){if(!s)throw new Error("`"+t+"` finished async. Use `"+n+"` instead")}function ur(t){return gC(t)?t:new hp(t)}function gC(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function bC(t){return typeof t=="string"||xC(t)}function xC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const vC="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Su=[],Cu={allowDangerousHtml:!0},yC=/^(https?|ircs?|mailto|xmpp)$/i,kC=[{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=jC(t),s=wC(t);return NC(n.runSync(n.parse(s),s),t)}function jC(t){const n=t.rehypePlugins||Su,s=t.remarkPlugins||Su,i=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...Cu}:Cu;return fC().use(s0).use(s).use(Q0,i).use(n)}function wC(t){const n=t.children||"",s=new hp;return typeof n=="string"&&(s.value=n),s}function NC(t,n){const s=n.allowedElements,i=n.allowElement,r=n.components,l=n.disallowedElements,o=n.skipHtml,d=n.unwrapDisallowed,m=n.urlTransform||SC;for(const u of kC)Object.hasOwn(n,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+vC+u.id,void 0);return uc(t,c),ON(t,{Fragment:e.Fragment,components:r,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function c(u,h,g){if(u.type==="raw"&&g&&typeof h=="number")return o?g.children.splice(h,1):g.children[h]={type:"text",value:u.value},h;if(u.type==="element"){let p;for(p in Cl)if(Object.hasOwn(Cl,p)&&Object.hasOwn(u.properties,p)){const f=u.properties[p],b=Cl[p];(b===null||b.includes(u.tagName))&&(u.properties[p]=m(String(f||""),p,u))}}if(u.type==="element"){let p=s?!s.includes(u.tagName):l?l.includes(u.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(u,h,g)),p&&g&&typeof h=="number")return d&&u.children?g.children.splice(h,1,...u.children):g.children.splice(h,1),h}}}function SC(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||yC.test(t.slice(0,n))?t:""}function Eu(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 CC(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function EC(t,n,s){const r=tl((s||{}).ignore||[]),l=MC(n);let o=-1;for(;++o<l.length;)mp(t,"text",d);function d(c,u){let h=-1,g;for(;++h<u.length;){const p=u[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return m(c,u)}function m(c,u){const h=u[u.length-1],g=l[o][0],p=l[o][1];let f=0;const x=h.children.indexOf(c);let y=!1,v=[];g.lastIndex=0;let M=g.exec(c.value);for(;M;){const N=M.index,A={index:M.index,input:M.input,stack:[...u,c]};let w=p(...M,A);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=N+1:(f!==N&&v.push({type:"text",value:c.value.slice(f,N)}),Array.isArray(w)?v.push(...w):w&&v.push(w),f=N+M[0].length,y=!0),!g.global)break;M=g.exec(c.value)}return y?(f<c.value.length&&v.push({type:"text",value:c.value.slice(f)}),h.children.splice(x,1,...v)):v=[c],x+v.length}}function MC(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([AC(r[0]),PC(r[1])])}return n}function AC(t){return typeof t=="string"?new RegExp(CC(t),"g"):t}function PC(t){return typeof t=="function"?t:function(){return t}}const Fl="phrasing",Ll=["autolink","link","image","label"];function TC(){return{transforms:[LC],enter:{literalAutolink:_C,literalAutolinkEmail:zl,literalAutolinkHttp:zl,literalAutolinkWww:zl},exit:{literalAutolink:FC,literalAutolinkEmail:DC,literalAutolinkHttp:IC,literalAutolinkWww:$C}}}function RC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Fl,notInConstruct:Ll},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Fl,notInConstruct:Ll},{character:":",before:"[ps]",after:"\\/",inConstruct:Fl,notInConstruct:Ll}]}}function _C(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function zl(t){this.config.enter.autolinkProtocol.call(this,t)}function IC(t){this.config.exit.autolinkProtocol.call(this,t)}function $C(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 DC(t){this.config.exit.autolinkEmail.call(this,t)}function FC(t){this.exit(t)}function LC(t){EC(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,zC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,OC]],{ignore:["link","linkReference"]})}function zC(t,n,s,i,r){let l="";if(!pp(r)||(/^w/i.test(n)&&(s=n+s,n="",l="http://"),!BC(s)))return!1;const o=UC(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 OC(t,n,s,i){return!pp(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function BC(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 UC(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=Eu(t,"(");let l=Eu(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 pp(t,n){const s=t.input.charCodeAt(t.index-1);return(t.index===0||wi(s)||Xr(s))&&(!n||s!==47)}fp.peek=QC;function HC(){this.buffer()}function qC(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function VC(){this.buffer()}function WC(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function KC(t){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ms(this.sliceSerialize(t)).toLowerCase(),s.label=n}function GC(t){this.exit(t)}function JC(t){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ms(this.sliceSerialize(t)).toLowerCase(),s.label=n}function YC(t){this.exit(t)}function QC(){return"["}function fp(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 XC(){return{enter:{gfmFootnoteCallString:HC,gfmFootnoteCall:qC,gfmFootnoteDefinitionLabelString:VC,gfmFootnoteDefinition:WC},exit:{gfmFootnoteCallString:KC,gfmFootnoteCall:GC,gfmFootnoteDefinitionLabelString:JC,gfmFootnoteDefinition:YC}}}function ZC(t){let n=!1;return t&&t.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:fp},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?gp:eE))),c(),m}}function eE(t,n,s){return n===0?t:gp(t,n,s)}function gp(t,n,s){return(s?"":" ")+t}const tE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];bp.peek=rE;function nE(){return{canContainEols:["delete"],enter:{strikethrough:iE},exit:{strikethrough:aE}}}function sE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:tE}],handlers:{delete:bp}}}function iE(t){this.enter({type:"delete",children:[]},t)}function aE(t){this.exit(t)}function bp(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 rE(){return"~"}function lE(t){return t.length}function oE(t,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||lE,l=[],o=[],d=[],m=[];let c=0,u=-1;for(;++u<t.length;){const b=[],x=[];let y=-1;for(t[u].length>c&&(c=t[u].length);++y<t[u].length;){const v=cE(t[u][y]);if(s.alignDelimiters!==!1){const M=r(v);x[y]=M,(m[y]===void 0||M>m[y])&&(m[y]=M)}b.push(v)}o[u]=b,d[u]=x}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<c;)l[h]=Mu(i[h]);else{const b=Mu(i);for(;++h<c;)l[h]=b}h=-1;const g=[],p=[];for(;++h<c;){const b=l[h];let x="",y="";b===99?(x=":",y=":"):b===108?x=":":b===114&&(y=":");let v=s.alignDelimiters===!1?1:Math.max(1,m[h]-x.length-y.length);const M=x+"-".repeat(v)+y;s.alignDelimiters!==!1&&(v=x.length+v+y.length,v>m[h]&&(m[h]=v),p[h]=v),g[h]=M}o.splice(1,0,g),d.splice(1,0,p),u=-1;const f=[];for(;++u<o.length;){const b=o[u],x=d[u];h=-1;const y=[];for(;++h<c;){const v=b[h]||"";let M="",N="";if(s.alignDelimiters!==!1){const A=m[h]-(x[h]||0),w=l[h];w===114?M=" ".repeat(A):w===99?A%2?(M=" ".repeat(A/2+.5),N=" ".repeat(A/2-.5)):(M=" ".repeat(A/2),N=M):N=" ".repeat(A)}s.delimiterStart!==!1&&!h&&y.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&v==="")&&(s.delimiterStart!==!1||h)&&y.push(" "),s.alignDelimiters!==!1&&y.push(M),y.push(v),s.alignDelimiters!==!1&&y.push(N),s.padding!==!1&&y.push(" "),(s.delimiterEnd!==!1||h!==c-1)&&y.push("|")}f.push(s.delimiterEnd===!1?y.join("").replace(/ +$/,""):y.join(""))}return f.join(`
607
- `)}function cE(t){return t==null?"":String(t)}function Mu(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 dE(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()),uE);return r(),o}function uE(t,n,s){return">"+(s?"":" ")+t}function mE(t,n){return Au(t,n.inConstruct,!0)&&!Au(t,n.notInConstruct,!1)}function Au(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 Pu(t,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
608
- `&&mE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
609
- `}function hE(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 pE(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 fE(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 gE(t,n,s,i){const r=fE(s),l=t.value||"",o=r==="`"?"GraveAccent":"Tilde";if(pE(t,s)){const h=s.enter("codeIndented"),g=s.indentLines(l,bE);return h(),g}const d=s.createTracker(i),m=r.repeat(Math.max(hE(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 bE(t,n,s){return(s?"":" ")+t}function hc(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 xE(t,n,s,i){const r=hc(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 vE(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 Fr(t,n,s){const i=Yi(t),r=Yi(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}xp.peek=yE;function xp(t,n,s,i){const r=vE(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=Fr(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=Fr(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+La(h));const p=o.move(r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+p}function yE(t,n,s){return s.options.emphasis||"*"}function kE(t,n){let s=!1;return uc(t,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Eo}),!!((!t.depth||t.depth<3)&&ic(t)&&(n.options.setext||s))}function jE(t,n,s,i){const r=Math.max(Math.min(6,t.depth||1),1),l=s.createTracker(i);if(kE(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}vp.peek=wE;function vp(t){return t.value||""}function wE(){return"<"}yp.peek=NE;function yp(t,n,s,i){const r=hc(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 NE(){return"!"}kp.peek=SE;function kp(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 SE(){return"!"}jp.peek=CE;function jp(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 CE(){return"`"}function wp(t,n){const s=ic(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))}Np.peek=EE;function Np(t,n,s,i){const r=hc(s),l=r==='"'?"Quote":"Apostrophe",o=s.createTracker(i);let d,m;if(wp(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 EE(t,n,s){return wp(t,s)?"<":"["}Sp.peek=ME;function Sp(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 ME(){return"["}function pc(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 AE(t){const n=pc(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 PE(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 Cp(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 TE(t,n,s,i){const r=s.enter("list"),l=s.bulletCurrent;let o=t.ordered?PE(s):pc(s);const d=t.ordered?o==="."?")":".":AE(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),Cp(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 RE(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 _E(t,n,s,i){const r=RE(s);let l=s.bulletCurrent||pc(s);n&&n.type==="list"&&n.ordered&&(l=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(t))+l);let o=l.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||t.spread))&&(o=Math.ceil(o/4)*4);const d=s.createTracker(i);d.move(l+" ".repeat(o-l.length)),d.shift(o);const m=s.enter("listItem"),c=s.indentLines(s.containerFlow(t,d.current()),u);return m(),c;function u(h,g,p){return g?(p?"":" ".repeat(o))+h:(p?l:l+" ".repeat(o-l.length))+h}}function IE(t,n,s,i){const r=s.enter("paragraph"),l=s.enter("phrasing"),o=s.containerPhrasing(t,i);return l(),r(),o}const $E=tl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function DE(t,n,s,i){return(t.children.some(function(o){return $E(o)})?s.containerPhrasing:s.containerFlow).call(s,t,i)}function FE(t){const n=t.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Ep.peek=LE;function Ep(t,n,s,i){const r=FE(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=Fr(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=Fr(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+La(h));const p=o.move(r+r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+p}function LE(t,n,s){return s.options.strong||"*"}function zE(t,n,s,i){return s.safe(t.value,i)}function OE(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 BE(t,n,s){const i=(Cp(s)+(s.options.ruleSpaces?" ":"")).repeat(OE(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Mp={blockquote:dE,break:Pu,code:gE,definition:xE,emphasis:xp,hardBreak:Pu,heading:jE,html:vp,image:yp,imageReference:kp,inlineCode:jp,link:Np,linkReference:Sp,list:TE,listItem:_E,paragraph:IE,root:DE,strong:Ep,text:zE,thematicBreak:BE};function UE(){return{enter:{table:HE,tableData:Tu,tableHeader:Tu,tableRow:VE},exit:{codeText:WE,table:qE,tableData:Ol,tableHeader:Ol,tableRow:Ol}}}function HE(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 VE(t){this.enter({type:"tableRow",children:[]},t)}function Ol(t){this.exit(t)}function Tu(t){this.enter({type:"tableCell",children:[]},t)}function WE(t){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,KE));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(t)}function KE(t,n){return n==="|"?n:t}function GE(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(p,f,b,x){return c(u(p,b,x),p.align)}function d(p,f,b,x){const y=h(p,b,x),v=c([y]);return v.slice(0,v.indexOf(`
620
- `))}function m(p,f,b,x){const y=b.enter("tableCell"),v=b.enter("phrasing"),M=b.containerPhrasing(p,{...x,before:l,after:l});return v(),y(),M}function c(p,f){return oE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function u(p,f,b){const x=p.children;let y=-1;const v=[],M=f.enter("table");for(;++y<x.length;)v[y]=h(x[y],f,b);return M(),v}function h(p,f,b){const x=p.children;let y=-1;const v=[],M=f.enter("tableRow");for(;++y<x.length;)v[y]=m(x[y],p,f,b);return M(),v}function g(p,f,b){let x=Mp.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function JE(){return{exit:{taskListCheckValueChecked:Ru,taskListCheckValueUnchecked:Ru,paragraph:QE}}}function YE(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:XE}}}function Ru(t){const n=this.stack[this.stack.length-2];n.type,n.checked=t.type==="taskListCheckValueChecked"}function QE(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 XE(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=Mp.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 ZE(){return[TC(),XC(),nE(),UE(),JE()]}function e2(t){return{extensions:[RC(),ZC(t),sE(),GE(t),YE()]}}const t2={tokenize:l2,partial:!0},Ap={tokenize:o2,partial:!0},Pp={tokenize:c2,partial:!0},Tp={tokenize:d2,partial:!0},n2={tokenize:u2,partial:!0},Rp={name:"wwwAutolink",tokenize:a2,previous:Ip},_p={name:"protocolAutolink",tokenize:r2,previous:$p},Gs={name:"emailAutolink",tokenize:i2,previous:Dp},Bs={};function s2(){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,Rp];Bs[119]=[Gs,Rp];function i2(t,n,s){const i=this;let r,l;return o;function o(h){return!To(h)||!Dp.call(i,i.previous)||fc(i.events)?s(h):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),d(h))}function d(h){return To(h)?(t.consume(h),d):h===64?(t.consume(h),m):s(h)}function m(h){return h===46?t.check(n2,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 a2(t,n,s){const i=this;return r;function r(o){return o!==87&&o!==119||!Ip.call(i,i.previous)||fc(i.events)?s(o):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(t2,t.attempt(Ap,t.attempt(Pp,l),s),s)(o))}function l(o){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),n(o)}}function r2(t,n,s){const i=this;let r="",l=!1;return o;function o(h){return(h===72||h===104)&&$p.call(i,i.previous)&&!fc(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||Ir(h)||Jt(h)||wi(h)||Xr(h)?s(h):t.attempt(Ap,t.attempt(Pp,u),s)(h)}function u(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),n(h)}}function l2(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 o2(t,n,s){let i,r,l;return o;function o(c){return c===46||c===95?t.check(Tp,m,d)(c):c===null||Jt(c)||wi(c)||c!==45&&Xr(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 c2(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(Tp,n,l)(o):o===null||Jt(o)||wi(o)?n(o):(t.consume(o),r)}function l(o){return o===41&&i++,t.consume(o),r}}function d2(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||Jt(d)||wi(d)?n(d):s(d)}function r(d){return d===null||d===40||d===91||Jt(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 u2(t,n,s){return i;function i(l){return t.consume(l),r}function r(l){return zn(l)?s(l):n(l)}}function Ip(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Jt(t)}function $p(t){return!Gn(t)}function Dp(t){return!(t===47||To(t))}function To(t){return t===43||t===45||t===46||t===95||zn(t)}function fc(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 m2={tokenize:y2,partial:!0};function h2(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:b2,continuation:{tokenize:x2},exit:v2}},text:{91:{name:"gfmFootnoteCall",tokenize:g2},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:p2,resolveTo:f2}}}}function p2(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=Ms(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 f2(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 g2(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||Jt(h))return s(h);if(h===93){t.exit("chunkString");const g=t.exit("gfmFootnoteCallString");return r.includes(Ms(i.sliceSerialize(g)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),n):s(h)}return Jt(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 b2(t,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l,o=0,d;return m;function m(f){return t.enter("gfmFootnoteDefinition")._container=!0,t.enter("gfmFootnoteDefinitionLabel"),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionLabelMarker"),c}function c(f){return f===94?(t.enter("gfmFootnoteDefinitionMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionMarker"),t.enter("gfmFootnoteDefinitionLabelString"),t.enter("chunkString").contentType="string",u):s(f)}function u(f){if(o>999||f===93&&!d||f===null||f===91||Jt(f))return s(f);if(f===93){t.exit("chunkString");const b=t.exit("gfmFootnoteDefinitionLabelString");return l=Ms(i.sliceSerialize(b)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),g}return Jt(f)||(d=!0),o++,t.consume(f),f===92?h:u}function h(f){return f===91||f===92||f===93?(t.consume(f),o++,u):u(f)}function g(f){return f===58?(t.enter("definitionMarker"),t.consume(f),t.exit("definitionMarker"),r.includes(l)||r.push(l),Ot(t,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function x2(t,n,s){return t.check(Ya,n,t.attempt(m2,n,s))}function v2(t){t.exit("gfmFootnoteDefinition")}function y2(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 k2(t){let s=(t||{}).singleTilde;const i={name:"strikethrough",tokenize:l,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(o,d){let m=-1;for(;++m<o.length;)if(o[m][0]==="enter"&&o[m][1].type==="strikethroughSequenceTemporary"&&o[m][1]._close){let c=m;for(;c--;)if(o[c][0]==="exit"&&o[c][1].type==="strikethroughSequenceTemporary"&&o[c][1]._open&&o[m][1].end.offset-o[m][1].start.offset===o[c][1].end.offset-o[c][1].start.offset){o[m][1].type="strikethroughSequence",o[c][1].type="strikethroughSequence";const u={type:"strikethrough",start:Object.assign({},o[c][1].start),end:Object.assign({},o[m][1].end)},h={type:"strikethroughText",start:Object.assign({},o[c][1].end),end:Object.assign({},o[m][1].start)},g=[["enter",u,d],["enter",o[c][1],d],["exit",o[c][1],d],["enter",h,d]],p=d.parser.constructs.insideSpan.null;p&&ms(g,g.length,0,Zr(p,o.slice(c+1,m),d)),ms(g,g.length,0,[["exit",h,d],["enter",o[m][1],d],["exit",o[m][1],d],["exit",u,d]]),ms(o,c-1,m-c+3,g),m=c+g.length-2;break}}for(m=-1;++m<o.length;)o[m][1].type==="strikethroughSequenceTemporary"&&(o[m][1].type="data");return o}function l(o,d,m){const c=this.previous,u=this.events;let h=0;return g;function g(f){return c===126&&u[u.length-1][1].type!=="characterEscape"?m(f):(o.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const b=Yi(c);if(f===126)return h>1?m(f):(o.consume(f),h++,p);if(h<2&&!s)return m(f);const x=o.exit("strikethroughSequenceTemporary"),y=Yi(f);return x._open=!y||y===2&&!!b,x._close=!b||b===2&&!!y,d(f)}}}class j2{constructor(){this.map=[]}add(n,s,i){w2(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 w2(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 N2(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 S2(){return{flow:{null:{name:"table",tokenize:C2,resolveAll:E2}}}}function C2(t,n,s){const i=this;let r=0,l=0,o;return d;function d(C){let R=i.events.length-1;for(;R>-1;){const I=i.events[R][1].type;if(I==="lineEnding"||I==="linePrefix")R--;else break}const O=R>-1?i.events[R][1].type:null,Z=O==="tableHead"||O==="tableRow"?w:m;return Z===w&&i.parser.lazy[i.now().line]?s(C):Z(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):wt(C)?l>1?(l=0,i.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(C),t.exit("lineEnding"),p):s(C):$t(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||Jt(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 p(C){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(C):(t.enter("tableDelimiterRow"),o=!1,$t(C)?Ot(t,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):f(C))}function f(C){return C===45||C===58?x(C):C===124?(o=!0,t.enter("tableCellDivider"),t.consume(C),t.exit("tableCellDivider"),b):A(C)}function b(C){return $t(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"),y):C===45?(l+=1,y(C)):C===null||wt(C)?N(C):A(C)}function y(C){return C===45?(t.enter("tableDelimiterFiller"),v(C)):A(C)}function v(C){return C===45?(t.consume(C),v):C===58?(o=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(C),t.exit("tableDelimiterMarker"),M):(t.exit("tableDelimiterFiller"),M(C))}function M(C){return $t(C)?Ot(t,N,"whitespace")(C):N(C)}function N(C){return C===124?f(C):C===null||wt(C)?!o||r!==l?A(C):(t.exit("tableDelimiterRow"),t.exit("tableHead"),n(C)):A(C)}function A(C){return s(C)}function w(C){return t.enter("tableRow"),S(C)}function S(C){return C===124?(t.enter("tableCellDivider"),t.consume(C),t.exit("tableCellDivider"),S):C===null||wt(C)?(t.exit("tableRow"),n(C)):$t(C)?Ot(t,S,"whitespace")(C):(t.enter("data"),k(C))}function k(C){return C===null||C===124||Jt(C)?(t.exit("data"),S(C)):(t.consume(C),C===92?P:k)}function P(C){return C===92||C===124?(t.consume(C),k):k(C)}}function E2(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 j2;for(;++s<t.length;){const p=t[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(d=!1,m!==0&&(_u(g,n,m,c,u),u=void 0,m=0),c={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",c,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,l=[0,0,0,0],o=[0,s+1,0,0],d&&(d=!1,u={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",u,n]])),r=f.type==="tableDelimiterRow"?2:u?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,o[2]===0&&(l[1]!==0&&(o[0]=o[1],h=mr(g,n,l,r,void 0,h),l=[0,0,0,0]),o[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(l[1]!==0&&(o[0]=o[1],h=mr(g,n,l,r,void 0,h)),l=o,o=[l[1],s,0,0])):f.type==="tableHead"?(d=!0,m=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(m=s,l[1]!==0?(o[0]=o[1],h=mr(g,n,l,r,s,h)):o[1]!==0&&(h=mr(g,n,o,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.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 p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=N2(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]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,b=s[3]-s[2]-1;t.add(f,b,[])}}t.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(l.end=Object.assign({},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 M2={name:"tasklistCheck",tokenize:P2};function A2(){return{text:{91:M2}}}function P2(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 Jt(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 wt(m)?n(m):$t(m)?t.check({tokenize:T2},n,s)(m):s(m)}}function T2(t,n,s){return Ot(t,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function R2(t){return Kh([s2(),h2(),k2(t),S2(),A2()])}const _2={};function si(t){const n=this,s=t||_2,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),l=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),o=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(R2(s)),l.push(ZE()),o.push(e2(s))}const Iu=500,$u=100;function Bl(t){return t.length>Iu?t.slice(-Iu):t}function Fp(t,n,s){const[i,r]=a.useState([]),[l,o]=a.useState(!1),[d,m]=a.useState(!1),[c,u]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),x=a.useRef(t),y=a.useRef(s),v=a.useRef(n),M=a.useRef(0);(x.current!==t||y.current!==s||v.current!==n)&&(x.current=t,y.current=s,v.current=n,b.current++,f.current=!0,r([]),o(!1),m(!1),u(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!t||!n){p.current&&(p.current(),p.current=null);return}const S=b.current,k=++M.current;f.current=!1;const P=t,C=s;async function R(){if(!P)return;o(!0),g(!1);try{const Z=await Uc(P,C,{limit:$u});if(f.current||b.current!==S||M.current!==k)return;r(Bl(Z.entries)),m(Z.hasMore),u(Z.total)}catch{if(f.current||b.current!==S||M.current!==k)return;r([]),m(!1),u(null)}finally{!f.current&&b.current===S&&M.current===k&&o(!1)}const O=C?`?projectId=${encodeURIComponent(C)}`:"";p.current=Os(`/api/tasks/${P}/logs/stream${O}`,{events:{"agent:log":Z=>{if(!(f.current||b.current!==S))try{const I=JSON.parse(Z.data);r(_=>Bl([..._,I])),u(_=>_!==null?_+1:null)}catch{}}}})}return R(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[t,n,s]);const A=a.useCallback(async()=>{if(!t||h)return;const S=b.current,k=i.length,P=t;g(!0);try{const C=await Uc(P,s,{limit:$u,offset:k});if(f.current||b.current!==S)return;r(R=>{const O=[...C.entries,...R];return Bl(O)}),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:A,hasMore:d,total:c,loadingMore:h}}function I2(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 Du={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})},$2=50;function Lp(t){return[t.taskId,t.timestamp,t.agent??"",t.type,t.text,t.detail??""].join("|")}function D2(t){const n=new Map;return t.map(s=>{const i=Lp(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function F2({entries:t,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:l=!1,onLoadMore:o,loadingMore:d=!1,totalCount:m=null}){const c=a.useRef(null),u=a.useRef(0),h=a.useRef(0),g=a.useRef(null),[p,f]=a.useState(!0),[b,x]=a.useState(!1),y=a.useMemo(()=>D2(t),[t]);a.useLayoutEffect(()=>{const k=c.current;if(!k)return;const P=t.length,C=u.current,R=h.current,O=y[y.length-1]??null,Z=g.current!==O;if(P>C){const I=k.scrollTop<=$2;if(Z)if(I)k.scrollTop=0;else{const _=k.scrollHeight-R;_>0&&(k.scrollTop+=_)}}u.current=P,h.current=k.scrollHeight,g.current=O},[t,y]);const v=a.useCallback(k=>{k.key==="Escape"&&b&&x(!1)},[b]);if(a.useEffect(()=>{if(b)return document.addEventListener("keydown",v),()=>{document.removeEventListener("keydown",v)}},[b,v]),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 M=[...t].reverse(),N=[...y].reverse(),A=s?.provider&&s?.modelId,w=i?.provider&&i?.modelId,S=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:"}),A?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ss,{provider:s.provider,size:"sm"}),e.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):e.jsx("span",{className:"model-badge-default",children:"Using default"})]}),e.jsxs("div",{className:"agent-log-model-group",children:[e.jsx("span",{className:"agent-log-model-label",children:"Validator:"}),w?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ss,{provider:i.provider,size:"sm"}),e.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):e.jsx("span",{className:"model-badge-default",children:"Using default"})]}),e.jsxs("div",{className:"agent-log-model-group",children:[e.jsx("span",{className:"agent-log-model-label",children:"Planning/Triage:"}),S?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ss,{provider:r.provider,size:"sm"}),e.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):e.jsx("span",{className:"model-badge-default",children:"Using default"})]}),e.jsxs("div",{className:"agent-log-model-header-toggle",children:[e.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>f(k=>!k),"aria-label":p?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":p,"data-testid":"agent-log-mode-toggle",title:p?"Show raw text":"Show formatted markdown",children:p?"Markdown":"Plain"}),e.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>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"]}),M.map((k,P)=>{const C=N[P]??`${Lp(k)}|fallback`,R=M[P-1],O=k.type==="tool"||k.type==="tool_result"||k.type==="tool_error",Z=k.agent?O||P===0||R&&(R.agent!==k.agent||R.type!==k.type):!1,I=Z?e.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:I2(k.timestamp)}):null,_=Z?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:[_,p?e.jsx(ni,{remarkPlugins:[si],components:Du,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:[_,p?e.jsx(ni,{remarkPlugins:[si],components:Du,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(lt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function Qi(t){return t??void 0}function hr(t){return{provider:Qi(t.modelProvider),modelId:Qi(t.modelId)}}function pr(t){return{provider:Qi(t.validatorModelProvider),modelId:Qi(t.validatorModelId)}}function fr(t){return{provider:Qi(t.planningModelProvider),modelId:Qi(t.planningModelId)}}function L2(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function z2(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 O2(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 Ul(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 Hl(t){return t.provider&&t.modelId?`${t.provider}/${t.modelId}`:""}function ql(t,n){return t.provider===n.provider&&t.modelId===n.modelId}function B2(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 U2({task:t,addToast:n,onTaskUpdated:s,settings:i}){const[r,l]=a.useState([]),[o,d]=a.useState([]),[m,c]=a.useState([]),[u,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(()=>hr(t)),[x,y]=a.useState(()=>hr(t)),[v,M]=a.useState(()=>pr(t)),[N,A]=a.useState(()=>pr(t)),[w,S]=a.useState(()=>fr(t)),[k,P]=a.useState(()=>fr(t)),[C,R]=a.useState(()=>t.thinkingLevel??null),[O,Z]=a.useState(()=>t.thinkingLevel??null),[I,_]=a.useState(null),j=a.useRef(t.id);a.useEffect(()=>{h(!0),p(null),Jn().then(ve=>{l(ve.models),d(ve.favoriteProviders),c(ve.favoriteModels)}).catch(ve=>{p(ve.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const Q=a.useCallback(async ve=>{const Se=o,Oe=Se.includes(ve)?Se.filter(Ie=>Ie!==ve):[ve,...Se];d(Oe);try{await Kt({favoriteProviders:Oe,favoriteModels:m})}catch{d(Se),n("Failed to update favorites","error")}},[o,m,n]),Y=a.useCallback(async ve=>{const Se=m,Oe=Se.includes(ve)?Se.filter(Ie=>Ie!==ve):[ve,...Se];c(Oe);try{await Kt({favoriteProviders:o,favoriteModels:Oe})}catch{c(Se),n("Failed to update model favorites","error")}},[m,o,n]);a.useEffect(()=>{j.current=t.id;const ve=hr(t),Se=pr(t),Pe=fr(t);b(ve),y(ve),M(Se),A(Se),S(Pe),P(Pe);const Oe=t.thinkingLevel??null;R(Oe),Z(Oe),_(null)},[t.id,t.modelProvider,t.modelId,t.validatorModelProvider,t.validatorModelId,t.planningModelProvider,t.planningModelId,t.thinkingLevel]);const L=a.useMemo(()=>Hl(f),[f]),D=a.useMemo(()=>Hl(v),[v]),U=a.useMemo(()=>Hl(w),[w]),G=a.useMemo(()=>L2(t,i),[t,i]),E=a.useMemo(()=>z2(t,i),[t,i]),J=a.useMemo(()=>O2(t,i),[t,i]),ue=I!==null,z=a.useCallback(async(ve,Se)=>{const Pe=t.id,Oe=x,Ie=N,rt=k;_(ve);try{const Ee=s?ve==="executor"?{modelProvider:Se.provider??null,modelId:Se.modelId??null}:ve==="validator"?{validatorModelProvider:Se.provider??null,validatorModelId:Se.modelId??null}:{planningModelProvider:Se.provider??null,planningModelId:Se.modelId??null}:{modelProvider:(ve==="executor"?Se:x).provider??null,modelId:(ve==="executor"?Se:x).modelId??null,validatorModelProvider:(ve==="validator"?Se:N).provider??null,validatorModelId:(ve==="validator"?Se:N).modelId??null,planningModelProvider:(ve==="planning"?Se:k).provider??null,planningModelId:(ve==="planning"?Se:k).modelId??null},_e=await Ws(Pe,Ee);if(j.current!==Pe)return;const Be=hr(_e),et=pr(_e),De=fr(_e);y(Be),b(Be),A(et),M(et),P(De),S(De),s?.(_e),n(B2(ve,{executor:Be,validator:et,planning:De}[ve]),"success")}catch(Ee){if(j.current!==Pe)return;ve==="executor"?b(Oe):ve==="validator"?M(Ie):S(rt),n(xe(Ee)||"Failed to save model settings","error")}finally{j.current===Pe&&_(null)}},[t.id,x,N,k,n,s]),te=a.useCallback(ve=>{const Se=Ul(ve);b(Se),!ql(Se,x)&&z("executor",Se)},[x,z]),F=a.useCallback(ve=>{const Se=Ul(ve);M(Se),!ql(Se,N)&&z("validator",Se)},[N,z]),fe=a.useCallback(ve=>{const Se=Ul(ve);S(Se),!ql(Se,k)&&z("planning",Se)},[k,z]),V=a.useCallback(async ve=>{const Se=t.id,Pe=O,Oe=ve===""?null:ve;R(Oe),_("thinking");try{const Ie=await Ws(Se,{thinkingLevel:Oe});if(j.current!==Se)return;const rt=Ie.thinkingLevel??null;Z(rt),R(rt),s?.(Ie);const Ee=i?.defaultThinkingLevel??"off";n(rt===null?`Thinking level set to default (${Ee})`:`Thinking level set to ${rt}`,"success")}catch(Ie){if(j.current!==Se)return;R(Pe),n(xe(Ie)||"Failed to save thinking level","error")}finally{j.current===Se&&_(null)}},[t.id,O,i,n,s]),K=!x.provider&&!x.modelId,de=!N.provider&&!N.modelId,we=!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),p(null),Jn().then(ve=>{l(ve.models),d(ve.favoriteProviders),c(ve.favoriteModels)}).catch(ve=>p(ve.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?e.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),e.jsx("div",{className:"model-selector-current",children:K?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",G.provider&&G.modelId?` (${G.provider}/${G.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[x.provider&&e.jsx(ss,{provider:x.provider,size:"sm"}),x.provider,"/",x.modelId]})}),e.jsx(Gt,{id:"executorModel",label:"Executor Model",value:L,onChange:te,models:r,disabled:ue,placeholder:"Select executor model…",favoriteProviders:o,onToggleFavorite:Q,favoriteModels:m,onToggleModelFavorite:Y}),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:de?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",E.provider&&E.modelId?` (${E.provider}/${E.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[N.provider&&e.jsx(ss,{provider:N.provider,size:"sm"}),N.provider,"/",N.modelId]})}),e.jsx(Gt,{id:"validatorModel",label:"Validator Model",value:D,onChange:F,models:r,disabled:ue,placeholder:"Select validator model…",favoriteProviders:o,onToggleFavorite:Q,favoriteModels:m,onToggleModelFavorite:Y}),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:we?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",J.provider&&J.modelId?` (${J.provider}/${J.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&e.jsx(ss,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),e.jsx(Gt,{id:"planningModel",label:"Planning Model",value:U,onChange:fe,models:r,disabled:ue,placeholder:"Select planning model…",favoriteProviders:o,onToggleFavorite:Q,favoriteModels:m,onToggleModelFavorite:Y}),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:O===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:O})}),e.jsxs("select",{id:"thinkingLevel",value:C??"",onChange:ve=>V(ve.target.value),disabled:ue,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:K&&de&&we&&O===null?"Using global default models.":"Model settings are up to date."})]})]})}const H2={open:e.jsx(Ur,{size:16}),closed:e.jsx(Ba,{size:16}),merged:e.jsx(Um,{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(""),[p,f]=a.useState(""),[b,x]=a.useState(!1),[y,v]=a.useState(!1),[M,N]=a.useState(null),A=a.useCallback(async()=>{if(h.trim()){x(!0);try{const P=await tv(t,{title:h.trim(),body:p.trim()||void 0},n);o(P),u(!1),g(""),f(""),m(`Created PR #${P.number}`,"success")}catch(P){m(xe(P)||"Failed to create PR","error")}finally{x(!1)}}},[t,h,p,n,o,m]),w=a.useCallback(async()=>{if(s){v(!0);try{const P=await nv(t,n);N(P),d(P.prInfo),m("PR status refreshed","success")}catch(P){m(xe(P)||"Failed to refresh PR","error")}finally{v(!1)}}},[t,s,n,d,m]);if(!s)return i==="creating-pr"?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):c?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),e.jsxs("div",{className:"pr-form",children:[e.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:P=>g(P.target.value),disabled:b,className:"pr-input"}),e.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:P=>f(P.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:A,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u(!0),disabled:!l,title:l?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[e.jsx(Vt,{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 S=H2[s.status]??e.jsx(Ur,{size:16}),k=M?.blockingReasons??[];return e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(ts,{size:16,className:"pr-section-icon"}),"Pull Request"]}),e.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[e.jsxs("div",{className:"pr-header",children:[e.jsx("span",{className:"pr-status-icon",children:S}),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:y,title:"Refresh PR status",children:e.jsx(Mn,{size:14,style:{verticalAlign:"middle",opacity:y?.5:1}})})]}),e.jsx("div",{className:"pr-title",children:s.title}),e.jsxs("div",{className:"pr-meta",children:[e.jsx("span",{children:s.headBranch}),e.jsx("span",{className:"pr-meta-arrow",children:"→"}),e.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&e.jsx("div",{className:"pr-hint pr-hint--info",children: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(dg,{size:14}),"View on GitHub"]})]})]})]})}const Fu=2e3;function V2(t){const n=t.updatedAt||t.createdAt,s=new Date(n).toLocaleString();return t.updatedAt?`${s} (edited)`:s}function W2(t){return t==="agent"||t==="system"}function K2({task:t,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[l,o]=a.useState(""),[d,m]=a.useState(null),[c,u]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),b=a.useMemo(()=>[...t.comments||[]].sort((S,k)=>new Date(k.createdAt).getTime()-new Date(S.createdAt).getTime()),[t.comments]),x=l.length>Fu;async function y(){const S=l.trim();if(S){g(!0);try{const k=await zx(t.id,S,r);o(""),n?.(k),s("Comment added","success")}catch(k){s(xe(k)||"Failed to add comment","error")}finally{g(!1)}}}async function v(S){const k=c.trim();if(k){g(!0);try{const P=await Ix(t.id,S,k,r);m(null),u(""),n?.(P),s("Comment updated","success")}catch(P){s(xe(P)||"Failed to update comment","error")}finally{g(!1)}}}async function M(S){f(S);try{const k=await $x(t.id,S,r);n?.(k),s("Comment deleted","success")}catch(k){s(xe(k)||"Failed to delete comment","error")}finally{f(null)}}function N(S){S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),y())}return e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Comments"}),b.length===0?e.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):e.jsx("div",{className:"detail-activity-list",children:b.map(S=>{const k=S.author===i,P=d===S.id,C=W2(S.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:S.author}),e.jsx("span",{className:"detail-log-timestamp",children:V2(S)})]}),k&&!P?e.jsxs("div",{className:"comments-actions-row",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{m(S.id),u(S.text)},children:"Edit"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void M(S.id),disabled:p===S.id,children:p===S.id?"Deleting…":"Delete"})]}):null]}),P?e.jsxs("div",{className:"comments-edit-form",children:[e.jsx("textarea",{value:c,onChange:R=>u(R.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 v(S.id),disabled:h||!c.trim(),children:"Save"})]})]}):e.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:S.text})]},S.id)})}),e.jsxs("div",{className:"comments-compose-form",children:[e.jsx("textarea",{value:l,onChange:S=>o(S.target.value),onKeyDown:N,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," / ",Fu]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(),disabled:h||!l.trim()||x,children:h?"Posting…":"Add Comment"})]})]})]})}function G2(t){return t?t.slice(0,7):"Unknown"}function J2({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:G2(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 zp(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 Lu(t,n=60){if(!t||t.length<=n)return t;if(n<4)return t.slice(0,n);const s="...",i=t.lastIndexOf("/");if(i===-1){const u=Math.max(1,n-s.length);return t.slice(0,u)+s}const r=[];for(let u=1;u<t.length;u++)t[u]==="/"&&r.push(u);const l=n-s.length;let o=null,d=-1;for(let u=r.length-1;u>=0;u--){const h=r[u],g=t.slice(h);if(g.length>l)continue;const p=l-g.length;for(let f=0;f<r.length;f++){const b=r[f],x=t.slice(0,b);x.length<=p&&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 Y2(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Q2({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)},[]),p=a.useCallback(()=>{c(x=>x!==null&&x<s.length-1?x+1:x)},[]);if(a.useEffect(()=>{if(!t)return;const x=y=>{if(y.key==="Escape"){o();return}y.key==="ArrowUp"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),g()),y.key==="ArrowDown"&&(y.metaKey||y.ctrlKey)&&(y.preventDefault(),p())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t,o,g,p]),!t)return null;const f=m!==null?s[m]:null,b=l==="done";return e.jsx("div",{className:"modal-overlay open",onClick:o,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal changes-diff-modal",onClick: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(Es,{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(zo,{size:14})}),e.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:m!==null?`${m+1}/${s.length}`:`—/${s.length}`}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:p,disabled:m===null||m>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:e.jsx(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(Mn,{size:14}),"Refresh"]}),e.jsx("button",{className:"modal-close",onClick:o,"aria-label":"Close",children:e.jsx(Dt,{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,y)=>e.jsxs("button",{className:`changes-diff-file-item ${m===y?"selected":""}`,onClick:()=>c(y),title:x.path,children:[e.jsx("span",{className:`changes-file-status changes-file-status--${x.status}`,children:Y2(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:f?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"changes-diff-file-header-bar",children:[e.jsx("span",{className:"changes-diff-file-header-name",children:f.path}),e.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",f.additions," -",f.deletions]})]}),f.patch?e.jsx("div",{className:"changes-diff-viewer",children:e.jsx("pre",{className:`changes-diff-patch ${u?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:e.jsx("code",{children:zp(f.patch)})})}):e.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):e.jsxs("div",{className:"changes-diff-empty",children:[e.jsx(Es,{size:48,opacity:.3}),e.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function zu(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function X2({taskId:t,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:l}){const[o,d]=a.useState([]),[m,c]=a.useState({filesChanged:0,additions:0,deletions:0}),[u,h]=a.useState(!0),[g,p]=a.useState(null),[f,b]=a.useState(new Set),[x,y]=a.useState(null),[v,M]=a.useState(!0),[N,A]=a.useState(!1),w=i==="done",S=w&&!!r?.commitSha,k=i==="in-progress"||i==="in-review"||S,P=a.useCallback(async()=>{if(!k){h(!1);return}try{h(!0),p(null);const I=await dh(t,void 0,s),_=I.files.map(j=>({path:j.path,status:j.status,additions:j.additions,deletions:j.deletions,patch:j.patch}));d(_),c(I.stats),_.length>0&&(b(new Set([_[0].path])),y(0))}catch(I){p(xe(I)||"Failed to load diff")}finally{h(!1)}},[t,s,k]);a.useEffect(()=>{P()},[P]);const C=I=>{b(_=>{const j=new Set(_);if(j.has(I))j.delete(I);else{j.add(I);const Q=o.findIndex(Y=>Y.path===I);Q!==-1&&y(Q)}return j})},R=I=>{if(I<0||I>=o.length)return;const _=o[I].path;b(new Set([_])),y(I)},O=x!==null&&x>0,Z=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(is,{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(Es,{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&&!S){const I=r?.filesChanged,_=r?.insertions,j=r?.deletions,Q=I!=null||_!=null||j!=null;return e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Es,{size:24}),e.jsx("p",{children:"Detailed file changes unavailable."}),e.jsx("span",{className:"task-changes-state-hint",children:Q?`Merge summary: ${I??0} file${(I??0)===1?"":"s"} changed, +${_??0} additions, -${j??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(Es,{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:zu("unknown")}),e.jsx("span",{className:"changes-file-path",title:I,children:Lu(I)})]})},I))})]}):e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Es,{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(Es,{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:()=>O&&R(x-1),disabled:!O,title:"Previous file","aria-label":"Previous file",children:e.jsx(zo,{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:()=>Z&&R(x+1),disabled:!Z,title:"Next file","aria-label":"Next file",children:e.jsx(ln,{size:14})})]}),e.jsx("button",{className:`btn btn-sm ${v?"btn-primary":""}`,onClick:()=>M(I=>!I),title:v?"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:P,disabled:u,children:"Refresh"}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>A(!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 _=f.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:zu(I.status)}),e.jsx("span",{className:"changes-file-path",title:I.path,children:Lu(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 ${v?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:e.jsx("code",{children:zp(I.patch)})})})]},I.path)})}),e.jsx(Q2,{isOpen:N,taskId:t,files:o,stats:m,mergeDetails:r,column:i,onClose:()=>A(!1),onRefresh:P})]})}function Ro(t){return{executorValue:t?.executorProvider&&t?.executorModelId?`${t.executorProvider}/${t.executorModelId}`:"",validatorValue:t?.validatorProvider&&t?.validatorModelId?`${t.validatorProvider}/${t.validatorModelId}`:""}}function Z2(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function eM(t,n){const s=Z2(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 Ou=["image/png","image/jpeg","image/gif","image/webp"];function tM(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 Op({mode:t,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:l,onDependenciesChange:o,priority:d,onPriorityChange:m,executorModel:c,onExecutorModelChange:u,validatorModel:h,onValidatorModelChange:g,planningModel:p,onPlanningModelChange:f,thinkingLevel:b,onThinkingLevelChange:x,presetMode:y,onPresetModeChange:v,selectedPresetId:M,onSelectedPresetIdChange:N,selectedWorkflowSteps:A,onWorkflowStepsChange:w,onDefaultOnApplied:S,pendingImages:k,onImagesChange:P,tasks:C,projectId:R,disabled:O=!1,addToast:Z,isActive:I=!0,onAutoSaveDescription:_,onPlanningMode:j,onSubtaskBreakdown:Q,onClose:Y,renderBelowPrimary:L,hideDependencies:D,reviewLevel:U,onReviewLevelChange:G}){const E=(D?!1:l.length>0)||k.length>0||A.length>0||y!=="default"||(d??cs)!==cs||c!==""||h!==""||(p||"")!==""||(b||"")!==""||U!==void 0,[J,ue]=a.useState(!1),[z,te]=a.useState(E),[F,fe]=a.useState(""),[V,K]=a.useState([]),[de,we]=a.useState([]),[ve,Se]=a.useState([]),[Pe,Oe]=a.useState(!1),[Ie,rt]=a.useState(null),[Ee,_e]=a.useState([]),[Be,et]=a.useState("idle"),[De,Xe]=a.useState(!1),[re,ne]=a.useState(!1),[ge,le]=a.useState(!1),Te=a.useRef(null),ye=a.useRef(null),He=a.useRef(null),nt=a.useRef(null),mt=a.useRef(null),he=a.useRef(null),ie=a.useRef(null),be=a.useRef(!1),Me=a.useRef(E),Ze=a.useRef(n.trim()),je=a.useRef(n.trim());a.useEffect(()=>{I&&(Oe(!0),Jn().then($=>{K($.models),we($.favoriteProviders),Se($.favoriteModels)}).catch(()=>{}).finally(()=>Oe(!1)),Ki(R).then($=>rt($)).catch(()=>rt(null)),Kr(R).then($=>_e($.filter(pe=>pe.enabled))).catch(()=>_e([])))},[I,R]);const tt=Ie?.modelPresets||[],Ce=tt.find($=>$.id===M),qe=(D?!1:l.length>0)||k.length>0||A.length>0||y!=="default"||(d??cs)!==cs||c!==""||h!==""||(p||"")!==""||(b||"")!==""||U!==void 0;a.useEffect(()=>{if(t!=="create"||!I||!Ie?.autoSelectModelPreset)return;const $=(Ie.defaultPresetBySize,void 0);if($){const pe=Ro($);N($.id),v("preset"),u(pe.executorValue),g(pe.validatorValue)}},[I,Ie,tt,t]);const ce=a.useRef(!1);a.useEffect(()=>{if(t!=="create"||!I||ce.current||Ee.length===0)return;const $=Ee.filter(ct=>ct.defaultOn);if($.length===0)return;ce.current=!0;const pe=$.map(ct=>ct.id);w(pe),S?.(pe)},[t,I,Ee]),a.useEffect(()=>{I||(ce.current=!1)},[I]),a.useEffect(()=>{qe&&!Me.current&&te(!0),Me.current=qe},[qe]),a.useEffect(()=>{z||(ue(!1),fe(""))},[z]),a.useEffect(()=>{t!=="edit"||!I||nt.current&&(nt.current.focus(),nt.current.select())},[t,I]),a.useEffect(()=>{if(!J)return;const $=pe=>{ye.current&&!ye.current.contains(pe.target)&&ue(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[J]),a.useEffect(()=>{(t!=="edit"||O)&&le(!1)},[t,O]),a.useEffect(()=>{if(t!=="edit"){et("idle");return}const $=n.trim();Ze.current=$,je.current=$,et("idle")},[t]),a.useEffect(()=>{if(t!=="edit"||!_||!I)return;const $=n.trim(),pe=Ze.current;if($===pe||$===je.current){he.current&&(clearTimeout(he.current),he.current=null),be.current||et("idle");return}return he.current&&clearTimeout(he.current),he.current=setTimeout(async()=>{if(!be.current){be.current=!0,et("saving");try{await _($),je.current=$,et("saved"),ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{et("idle"),ie.current=null},2e3)}catch{et("idle")}finally{be.current=!1,he.current=null}}},1500),()=>{he.current&&(clearTimeout(he.current),he.current=null)}},[t,n,_,I]),a.useEffect(()=>()=>{he.current&&clearTimeout(he.current),ie.current&&clearTimeout(ie.current)},[]),a.useEffect(()=>{if(!De)return;const $=pe=>{Te.current&&!Te.current.contains(pe.target)&&Xe(!1)};return document.addEventListener("mousedown",$),()=>document.removeEventListener("mousedown",$)},[De]);const Ue=a.useCallback($=>{const pe=$.clipboardData?.items;if(pe)for(let ct=0;ct<pe.length;ct++){const bt=pe[ct];if(bt.type.startsWith("image/")){const Nt=bt.getAsFile();if(Nt&&Ou.includes(Nt.type)){$.preventDefault(),P([...k,{file:Nt,previewUrl:URL.createObjectURL(Nt)}]);return}}}},[k,P]),Ve=a.useCallback($=>{$.preventDefault();const pe=$.dataTransfer.files;for(let ct=0;ct<pe.length;ct++){const bt=pe[ct];if(Ou.includes(bt.type)){P([...k,{file:bt,previewUrl:URL.createObjectURL(bt)}]);return}}},[k,P]),Ae=a.useCallback($=>{const pe=k[$];pe&&URL.revokeObjectURL(pe.previewUrl),P(k.filter((ct,bt)=>bt!==$))},[k,P]),We=a.useCallback($=>{o(l.includes($)?l.filter(pe=>pe!==$):[...l,$])},[l,o]),xt=($,pe)=>$.length>pe?$.slice(0,pe)+"…":$,yt=a.useCallback($=>{s($.target.value);const pe=$.target;pe.style.height="auto",pe.style.height=pe.scrollHeight+"px"},[s]),Ct=a.useCallback(()=>{le($=>!$)},[]),Tt=a.useCallback($=>{!ge||$.key!=="Escape"||($.preventDefault(),$.stopPropagation(),le(!1))},[ge]),Et=a.useCallback(async $=>{const pe=n.trim();if(!(!pe||re)){ne(!0);try{const ct=await ah(pe,$,R);s(ct),Xe(!1),Z("Description refined with AI","success"),He.current&&(He.current.style.height="auto",He.current.style.height=He.current.scrollHeight+"px")}catch(ct){const bt=rh(ct);Z(bt,"error")}finally{ne(!1)}}},[n,re,Z,s,R]),Mt=a.useCallback(async $=>{const pe=de,bt=pe.includes($)?pe.filter(Nt=>Nt!==$):[$,...pe];we(bt);try{await Kt({favoriteProviders:bt,favoriteModels:ve})}catch{we(pe)}},[de,ve]),vt=a.useCallback(async $=>{const pe=ve,bt=pe.includes($)?pe.filter(Nt=>Nt!==$):[$,...pe];Se(bt);try{await Kt({favoriteProviders:de,favoriteModels:bt})}catch{Se(pe)}},[ve,de]),Ft=a.useCallback($=>{if($<=0)return;const pe=[...A];[pe[$-1],pe[$]]=[pe[$],pe[$-1]],w(pe)},[A,w]),Je=a.useCallback($=>{if($>=A.length-1)return;const pe=[...A];[pe[$],pe[$+1]]=[pe[$+1],pe[$]],w(pe)},[A,w]),pt=a.useCallback($=>{w(A.filter(pe=>pe!==$))},[A,w]),ze=new Map;for(const $ of Ee)ze.set($.id,{name:$.name,description:$.description});const at=C.filter($=>!l.includes($.id)).sort(($,pe)=>{const ct=pe.createdAt.localeCompare($.createdAt);if(ct!==0)return ct;const bt=parseInt($.id.slice($.id.lastIndexOf("-")+1),10)||0;return(parseInt(pe.id.slice(pe.id.lastIndexOf("-")+1),10)||0)-bt}),q=F?at.filter($=>$.id.toLowerCase().includes(F.toLowerCase())||$.title&&$.title.toLowerCase().includes(F.toLowerCase())||$.description&&$.description.toLowerCase().includes(F.toLowerCase())):at;return e.jsxs("div",{className:"task-form",onDrop:Ve,onDragOver:$=>$.preventDefault(),onPaste:Ue,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:nt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:$=>r($.target.value),disabled:O})]}),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${ge?" description--fullscreen":""}`,ref:Te,onKeyDown:Tt,children:[ge&&e.jsxs("div",{className:"description-fullscreen-header",children:[e.jsx("span",{children:"Editing Description"}),e.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Ct,"aria-label":"Collapse description",title:"Collapse description",children:e.jsx(Ks,{size:14})})]}),e.jsx("textarea",{ref:He,autoFocus:t==="create",id:"task-form-description",value:n,onChange:yt,placeholder:"What needs to be done?",rows:t==="edit"?8:5,disabled:O||re}),(()=>{const $=!!n.trim()&&!O;return e.jsxs(e.Fragment,{children:[!ge&&e.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${$?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ct,"aria-label":"Expand description",title:"Expand description",children:e.jsx(Xs,{size:14})}),$&&e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${re?"refine-button--loading":""}`,onClick:()=>Xe(pe=>!pe),disabled:re,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(On,{size:12,style:{verticalAlign:"middle"}}),re?"Refining...":"Refine"]})]})})(),De&&e.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:$=>$.preventDefault(),children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>Et("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:()=>Et("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:()=>Et("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:()=>Et("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"&&(j||Q)&&e.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[j&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const $=n.trim();if(!$){Z("Enter a description first","error");return}Y?.(),j($)},disabled:O||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),Q&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const $=n.trim();if(!$){Z("Enter a description first","error");return}Y?.(),Q($)},disabled:O||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),L,e.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>te($=>!$),"aria-expanded":z,"aria-controls":"task-form-more-options",disabled:O,"data-testid":"task-form-more-options-toggle",children:[e.jsx("span",{children:"More options"}),z?e.jsx(Ds,{size:14}):e.jsx(zt,{size:14})]}),e.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${z?"":" collapsed"}`,"aria-hidden":!z,"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(($,pe)=>e.jsxs("div",{className:"inline-create-preview",children:[e.jsx("img",{src:$.previewUrl,alt:$.file.name}),e.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Ae(pe),disabled:O,title:"Remove image",children:"×"})]},$.previewUrl))}),e.jsx("input",{ref:mt,type:"file",accept:"image/*",onChange:$=>{const pe=$.target.files?.[0];pe&&(P([...k,{file:pe,previewUrl:URL.createObjectURL(pe)}]),$.target.value="")},style:{display:"none"}}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>mt.current?.click(),disabled:O,children:"Attach Screenshot"}),e.jsx("small",{children:"You can also paste images or drag & drop"})]}),!D&&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:ye,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ue($=>!$),disabled:O,children:l.length>0?`${l.length} selected`:"Add dependencies"}),J&&e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:F,onChange:$=>fe($.target.value),onClick:$=>$.stopPropagation()}),q.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):q.map($=>e.jsxs("div",{className:`dep-dropdown-item${l.includes($.id)?" selected":""}`,onClick:()=>We($.id),onMouseDown:pe=>pe.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:$.id}),e.jsx("span",{className:"dep-dropdown-title",children:xt($.title||$.description||$.id,30)})]},$.id))]})]}),l.length>0&&e.jsx("div",{className:"selected-deps",children:l.map($=>e.jsxs("span",{className:"dep-chip",children:[$,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>We($),disabled:O,children:"×"})]},$))})]})}),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??cs,onChange:$=>m($.target.value),disabled:O,children:Vo.map($=>e.jsx("option",{value:$,children:$[0].toUpperCase()+$.slice(1)},$))})]}),Pe?e.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):V.length===0?e.jsx("small",{children:"No models available. Configure authentication in Settings."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),e.jsxs("select",{id:"model-preset",value:y==="preset"?M:y,onChange:$=>{const pe=$.target.value;if(pe==="default"){v("default"),N(""),u(""),g("");return}if(pe==="custom"){v("custom"),N("");return}const ct=tt.find(Nt=>Nt.id===pe),bt=Ro(ct);v("preset"),N(pe),u(bt.executorValue),g(bt.validatorValue)},disabled:O,children:[e.jsx("option",{value:"default",children:"Use default"}),tt.length>0?e.jsx("option",{disabled:!0,children:"──────────"}):null,tt.map($=>e.jsx("option",{value:$.id,children:$.name},$.id)),e.jsx("option",{value:"custom",children:"Custom"})]})]}),y==="preset"&&Ce?e.jsxs("small",{children:["Using preset: ",Ce.name]}):null,y==="preset"?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>v("custom"),disabled:O,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(Gt,{id:"executor-model",label:"Executor Model",value:c,onChange:$=>{v("custom"),N(""),u($)},models:V,disabled:O||y==="preset",favoriteProviders:de,onToggleFavorite:Mt,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(Gt,{id:"validator-model",label:"Validator Model",value:h,onChange:$=>{v("custom"),N(""),g($)},models:V,disabled:O||y==="preset",favoriteProviders:de,onToggleFavorite:Mt,favoriteModels:ve,onToggleModelFavorite:vt})]}),f&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),e.jsx(Gt,{id:"planning-model",label:"Planning Model",value:p||"",onChange:$=>{v("custom"),N(""),f($)},models:V,disabled:O||y==="preset",favoriteProviders:de,onToggleFavorite:Mt,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:$=>x($.target.value),disabled:O||y==="preset",children:[e.jsxs("option",{value:"",children:["Default (",Ie?.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"})]})]}),G&&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:U??"",onChange:$=>G($.target.value===""?0:parseInt($.target.value,10)),disabled:O,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:Ee.length>0&&Ee.map($=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${$.id}`,children:[e.jsx("input",{type:"checkbox",checked:A.includes($.id),onChange:pe=>{w(pe.target.checked?[...A,$.id]:A.filter(ct=>ct!==$.id))},disabled:O}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[$.name,tM($.phase||"pre-merge",$.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:$.description})]})]},$.id))})]}),A.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:"}),A.map(($,pe)=>{const ct=ze.get($);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${$}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:pe+1}),e.jsx("span",{className:"workflow-step-order-name",children:ct?.name||$}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ft(pe),disabled:O||pe===0,"data-testid":`workflow-step-move-up-${$}`,title:"Move up",children:e.jsx(Ds,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Je(pe),disabled:O||pe===A.length-1,"data-testid":`workflow-step-move-down-${$}`,title:"Move down",children:e.jsx(zt,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pt($),disabled:O,"data-testid":`workflow-step-remove-${$}`,title:"Remove",children:e.jsx(Dt,{size:14})})]})]},$)})]})]})]})]})}const Bu={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 nM(t){switch(t){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return t}}function sM(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 iM(t){return t?new Date(t).toLocaleString():null}function aM(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 rM({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 lM({taskId:t,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:l,isTaskInProgress:o,onWorkflowStepsChange:d}){const[m,c]=a.useState({}),[u,h]=a.useState({}),[g,p]=a.useState(null),[f,b]=a.useState([]),[x,y]=a.useState(!1),v=n.some(E=>E.status==="pending"),{entries:M}=Fp(t,!!o&&v,l);a.useEffect(()=>{let E=!1;return Kr(l).then(J=>{E||b(J.filter(ue=>ue.enabled))}).catch(()=>{E||b([])}),()=>{E=!0}},[l]);const N=i??[],A=a.useMemo(()=>[...f.map(J=>({id:J.id,name:J.name,description:J.description,phase:J.phase||"pre-merge"})),{id:"browser-verification",name:"Browser Verification",description:"Verify web application functionality using browser automation (agent-browser)",phase:"pre-merge"}],[f]),w=a.useMemo(()=>new Map(A.map(E=>[E.id,E])),[A]),S=E=>{c(J=>({...J,[E]:!J[E]}))},k=E=>{h(J=>{const ue=J[E]??"markdown";return{...J,[E]:ue==="markdown"?"plain":"markdown"}})},P=E=>{p(E)},C=()=>{p(null)};a.useEffect(()=>{if(!g)return;const E=J=>{J.key==="Escape"&&C()};return document.addEventListener("keydown",E),()=>{document.removeEventListener("keydown",E)}},[g]);const R=a.useCallback((E,J)=>{if(d){if(J){if(N.includes(E)){d(N);return}d([...N,E]);return}d(N.filter(ue=>ue!==E))}},[d,N]),O=a.useCallback(E=>{if(!d||E<=0)return;const J=[...N];[J[E-1],J[E]]=[J[E],J[E-1]],d(J)},[d,N]),Z=a.useCallback(E=>{if(!d||E>=N.length-1)return;const J=[...N];[J[E],J[E+1]]=[J[E+1],J[E]],d(J)},[d,N]),I=a.useCallback(E=>{d&&d(N.filter(J=>J!==E))},[d,N]),_=n.length>0,j=N.length>0;a.useEffect(()=>{r||y(!1)},[r]);const Q=a.useMemo(()=>N.map(E=>{const J=w.get(E);return{id:E,name:J?.name||E,description:J?.description||"Step definition not found.",phase:J?.phase||"pre-merge"}}),[N,w]),Y=()=>!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:A.map(E=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":E.id==="browser-verification"?"browser-verification-checkbox":`workflow-step-checkbox-${E.id}`,children:[e.jsx("input",{type:"checkbox",checked:N.includes(E.id),onChange:J=>R(E.id,J.target.checked)}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[E.name,gr(E.phase,E.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:E.description})]})]},E.id))})]}),N.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:"}),N.map((E,J)=>{const ue=w.get(E);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${E}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:J+1}),e.jsx("span",{className:"workflow-step-order-name",children:ue?.name||E}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(J),disabled:J===0,"data-testid":`workflow-step-move-up-${E}`,title:"Move up",children:e.jsx(Ds,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Z(J),disabled:J===N.length-1,"data-testid":`workflow-step-move-down-${E}`,title:"Move down",children:e.jsx(zt,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>I(E),"data-testid":`workflow-step-remove-${E}`,title:"Remove",children:e.jsx(Dt,{size:14})})]})]},E)})]})]}),L=()=>{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 E=n.filter(F=>F.status==="passed").length,J=n.filter(F=>F.status==="failed").length,ue=n.filter(F=>F.status==="skipped").length,z=n.filter(F=>F.status==="pending").length,te=[`${n.length} step${n.length!==1?"s":""}`];return E>0&&te.push(`${E} passed`),J>0&&te.push(`${J} failed`),ue>0&&te.push(`${ue} skipped`),z>0&&te.push(`${z} 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:te.join(" · ")}),n.map((F,fe)=>{const V=F.phase||"pre-merge",K=m[F.workflowStepId]??!1;return e.jsxs("div",{className:`workflow-result-item workflow-result-item--${F.status}`,"data-testid":`workflow-result-item-${F.workflowStepId}`,children:[e.jsxs("div",{className:"workflow-result-header",children:[e.jsxs("div",{className:"workflow-result-name",children:[F.workflowStepName,gr(V,F.workflowStepId,"workflow-result-phase")]}),e.jsx("span",{className:`workflow-result-badge workflow-result-badge--${F.status}`,"data-testid":`workflow-result-badge-${F.workflowStepId}`,children:nM(F.status)})]}),e.jsxs("div",{className:"workflow-result-meta",children:[F.startedAt&&e.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",iM(F.startedAt)]}),F.completedAt&&e.jsx("span",{className:"workflow-result-duration",children:sM(F.startedAt,F.completedAt)})]}),F.status==="pending"&&F.startedAt?e.jsx(rM,{entries:M,startedAt:F.startedAt,stepId:F.workflowStepId}):F.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:()=>S(F.workflowStepId),"data-testid":`workflow-result-toggle-${F.workflowStepId}`,children:K?"Hide output":"Show output"}),!K&&e.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${F.workflowStepId}`,children:aM(F.output)}),K&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>k(F.workflowStepId),"data-testid":`workflow-result-mode-toggle-${F.workflowStepId}`,title:(u[F.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(u[F.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),e.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>P(F.workflowStepId),"data-testid":`workflow-result-expand-${F.workflowStepId}`,title:"Expand output",children:e.jsx(Xs,{size:12})})]})]}),K&&e.jsx("div",{className:`workflow-result-output${(u[F.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${F.workflowStepId}`,children:(u[F.workflowStepId]??"markdown")==="markdown"?e.jsx("div",{className:"markdown-body",children:e.jsx(ni,{remarkPlugins:[si],components:Bu,children:F.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:F.output})})]}):null]},`${F.workflowStepId}-${fe}`)})]})},D=r?e.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>y(E=>!E),"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(En,{size:14}),"Done"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ln,{size:14}),"Edit"]})}):null,U=!s&&!_&&j,G=r&&_;return e.jsxs("div",{className:"workflow-results-tab","data-task-id":t,children:[U?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:[Q.length," step",Q.length===1?"":"s"]})]}),D]}),e.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Q.map(E=>e.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${E.id}`,children:[e.jsxs("div",{className:"workflow-configured-name",children:[E.name,gr(E.phase,E.id,"workflow-configured-phase")]}),e.jsx("p",{className:"workflow-configured-description",children:E.description})]},E.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."}),Y()]}):e.jsxs(e.Fragment,{children:[G&&e.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[e.jsx("h4",{children:"Workflow Steps"}),D]}),L(),Y()]}),g&&(()=>{const E=n.find(z=>z.workflowStepId===g);if(!E)return null;const J=u[E.workflowStepId]??"markdown",ue=E.phase||"pre-merge";return e.jsx("div",{className:"workflow-output-modal-overlay",onClick:z=>{z.target===z.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:E.workflowStepName}),gr(ue,E.workflowStepId,"workflow-output-modal-phase")]}),e.jsxs("div",{className:"workflow-output-modal-controls",children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>k(E.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:J==="markdown"?"Switch to plain text":"Switch to markdown",children:J==="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(Dt,{size:16})})]})]}),e.jsx("div",{className:"workflow-output-modal-body",children:e.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${J==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:J==="markdown"?e.jsx("div",{className:"markdown-body",children:e.jsx(ni,{remarkPlugins:[si],components:Bu,children:E.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:E.output})})})]})})})()]})}const oM=/^[a-zA-Z0-9_-]{1,64}$/,cM=200;function Uu(t){return t?new Date(t).toLocaleString():""}function dM(t,n=cM){return t.length<=n?t:t.substring(0,n)+"…"}function uM({taskId:t,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[l,o]=a.useState([]),[d,m]=a.useState(!0),[c,u]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[b,x]=a.useState(""),[y,v]=a.useState(null),[M,N]=a.useState([]),[A,w]=a.useState(!1),[S,k]=a.useState(!1),[P,C]=a.useState(""),[R,O]=a.useState(""),[Z,I]=a.useState(!1),[_,j]=a.useState(null),[Q,Y]=a.useState(null),[L,D]=a.useState(!1),U=a.useCallback(async()=>{try{const V=await Dx(t,i);o(V)}catch(V){n(xe(V)||"Failed to load documents","error")}finally{m(!1)}},[t,i,n]);a.useEffect(()=>{U()},[U]);async function G(V){c===V.key?(u(null),g(""),f(null),x(""),v(null),N([]),D(!1)):(u(V.key),g(V.content),f(null),x(""),v(null),N([]),D(!1))}async function E(V){if(y===V)v(null),N([]);else{v(V),w(!0);try{const K=await Fx(t,V,i);N(K)}catch(K){n(xe(K)||"Failed to load revisions","error")}finally{w(!1)}}}function J(){c&&(f(c),x(h))}function ue(){f(null),x("")}async function z(){if(!(!p||!b.trim())){I(!0);try{await Hc(t,p,b,{},i),f(null),x(""),await U();const V=l.find(K=>K.key===p);V&&g(V.content),n("Document saved","success")}catch(V){n(xe(V)||"Failed to save document","error")}finally{I(!1)}}}async function te(){const V=P.trim(),K=R.trim();if(!V){n("Document key is required","error");return}if(!oM.test(V)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!K){n("Content is required","error");return}I(!0);try{await Hc(t,V,K,{},i),k(!1),C(""),O(""),await U(),n("Document created","success")}catch(de){n(xe(de)||"Failed to create document","error")}finally{I(!1)}}async function F(V){j(V);try{await Lx(t,V,i),Y(null),j(null),c===V&&(u(null),g("")),y===V&&(v(null),N([])),await U(),n("Document deleted","success")}catch(K){n(xe(K)||"Failed to delete document","error")}finally{j(null)}}function fe(V){g(V.content),f(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"}),S&&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:P,onChange:V=>C(V.target.value),placeholder:"e.g., plan, notes, research",disabled:Z}),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:R,onChange:V=>O(V.target.value),rows:6,placeholder:"Enter document content…",disabled:Z})]}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{k(!1),C(""),O("")},disabled:Z,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void te(),disabled:Z||!P.trim()||!R.trim(),children:Z?"Creating…":"Create"})]})]}),l.length===0&&!S?e.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):e.jsx("div",{className:"task-documents-list",children:l.map(V=>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:V.key}),e.jsxs("span",{className:"task-document-revision-badge",children:["v",V.revision]})]}),e.jsxs("div",{className:"task-document-meta",children:[e.jsx("span",{className:"task-document-author",children:V.author}),e.jsx("span",{className:"task-document-timestamp",children:Uu(V.updatedAt||V.createdAt)})]})]}),c===V.key&&p!==V.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:()=>D(K=>!K),"aria-label":L?"Switch to plain text":"Switch to markdown","aria-pressed":L,title:L?"Switch to plain text":"Switch to markdown",children:L?"Markdown":"Plain"})}),e.jsx("div",{className:"task-document-content",children:L?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})}),y===V.key&&e.jsxs("div",{className:"task-document-revisions",children:[e.jsx("h5",{children:"Revision History"}),A?e.jsx("div",{className:"detail-log-empty",children:"Loading…"}):M.length<=1?e.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):e.jsx("div",{className:"task-document-revision-list",children:M.filter(K=>K.revision<V.revision).sort((K,de)=>de.revision-K.revision).map(K=>e.jsxs("div",{className:"task-document-revision-item",onClick:()=>fe(K),children:[e.jsxs("div",{className:"revision-header",children:[e.jsxs("span",{className:"revision-badge",children:["v",K.revision]}),e.jsx("span",{className:"revision-author",children:K.author}),e.jsx("span",{className:"revision-timestamp",children:Uu(K.createdAt)})]}),e.jsx("div",{className:"revision-preview",children:dM(K.content,100)})]},K.id))})]})]}),p===V.key&&e.jsxs("div",{className:"task-document-edit-form",children:[e.jsx("textarea",{value:b,onChange:K=>x(K.target.value),rows:10,disabled:Z}),e.jsxs("div",{className:"form-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:ue,disabled:Z,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void z(),disabled:Z||!b.trim(),children:Z?"Saving…":"Save"})]})]}),e.jsxs("div",{className:"task-document-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>void G(V),children:c===V.key?e.jsxs(e.Fragment,{children:[e.jsx(Ds,{size:14})," Collapse"]}):e.jsxs(e.Fragment,{children:[e.jsx(zt,{size:14})," Expand"]})}),c===V.key&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void E(V.key),children:[e.jsx(_a,{size:14})," History"]}),r&&p!==V.key&&e.jsx("button",{className:"btn btn-sm",onClick:J,children:"Edit"}),r&&(Q===V.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 F(V.key),disabled:_===V.key,children:_===V.key?"…":"Yes"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Y(null),disabled:_===V.key,children:"No"})]}):e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Y(V.key),children:e.jsx(Ht,{size:14})}))]})]})]},V.key))}),r&&!S&&e.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>k(!0),children:[e.jsx(Vt,{size:14})," New Document"]})]})}function mM(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function hM(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 pM(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 fM(t,n,s){if(t.planningModelProvider&&t.planningModelId)return{provider:t.planningModelProvider,modelId:t.planningModelId};const i=pM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function gM(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 bM(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 xM(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function vM(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 Hu(t,n){return t.length>n?t.slice(0,n)+"…":t}function qu(t=[],n=[]){return t.length===n.length&&t.every((s,i)=>s===n[i])}function Vl(t){const n=t.indexOf("/");return!t||n===-1?null:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function ba(t){return typeof t=="string"&&Vo.includes(t)?t:cs}const Wl=200,yM=new Set(["triage","todo"]);function kM({task:t,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:l,onDeleteTask:o,onMergeTask:d,onRetryTask:m,onDuplicateTask:c,onTaskUpdated:u,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,b]=a.useState(p),[x,y]=a.useState(()=>"prompt"in t?t:null),[v,M]=a.useState(()=>!("prompt"in t));a.useEffect(()=>{if("prompt"in t){y(t),M(!1);return}let ae=!1;return M(!0),y(null),Mr(t.id,n).then(Qe=>{ae||(y(Qe),M(!1))}).catch(()=>{ae||M(!1)}),()=>{ae=!0}},[t.id,n]);const N=x??{...t,prompt:""},A=t.status==="failed"||t.status==="stuck-killed"||t.status==="specifying"||t.status==="needs-respecify"||(t.stuckKillCount??0)>0||(t.recoveryRetryCount??0)>0||!!t.nextRecoveryAt;a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{P(!1)},[t.id]);const[w,S]=a.useState("activity"),[k,P]=a.useState(!1),[C,R]=a.useState(t.attachments||[]),[O,Z]=a.useState(!1),[I,_]=a.useState(t.dependencies||[]),[j,Q]=a.useState(!1),[Y,L]=a.useState(""),[D,U]=a.useState(null),[G,E]=a.useState([]),[J,ue]=a.useState(!1),[z,te]=a.useState(!1),[F,fe]=a.useState(!1),[V,K]=a.useState(!1),[de,we]=a.useState(!1),[ve,Se]=a.useState(N.prompt||""),[Pe,Oe]=a.useState(""),[Ie,rt]=a.useState(!1),[Ee,_e]=a.useState(""),[Be,et]=a.useState(!1),[De,Xe]=a.useState(!1),[re,ne]=a.useState(t.title||""),[ge,le]=a.useState(t.description||""),[Te,ye]=a.useState(t.dependencies||[]),[He,nt]=a.useState(""),[mt,he]=a.useState(""),[ie,be]=a.useState(""),[Me,Ze]=a.useState(""),[je,tt]=a.useState("default"),[Ce,qe]=a.useState(void 0),[ce,Ue]=a.useState(cs),[Ve,Ae]=a.useState(""),[We,xt]=a.useState(t.enabledWorkflowSteps||[]),[yt,Ct]=a.useState([]),[Tt,Et]=a.useState(!1),Mt=a.useRef(!1),[vt,Ft]=a.useState(!1),[Je,pt]=a.useState(!1),ze=a.useRef(null),at=a.useRef(null),{getSlotsForId:q}=fh(n),$=q("task-detail-tab");a.useEffect(()=>(Mt.current=!0,()=>{Mt.current=!1}),[]);const[pe,ct]=a.useState(void 0),[bt,Nt]=a.useState([]),[Bt,Lt]=a.useState(!1),[wn,hn]=a.useState(t.enabledWorkflowSteps||[]);a.useEffect(()=>{ne(t.title||""),le(t.description||""),Xe(!1)},[t.id,t.title,t.description]),a.useEffect(()=>{hn(t.enabledWorkflowSteps||[])},[t.id,t.enabledWorkflowSteps]),a.useEffect(()=>{let ae=!1;return Ki(n).then(Qe=>{ae||ct(Qe)}).catch(()=>{}),()=>{ae=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let ae=!1;return Lt(!0),ty(t.id,n).then(Qe=>{ae||Nt(Qe)}).catch(Qe=>{ae||h(`Failed to load workflow results: ${xe(Qe)}`,"error")}).finally(()=>{ae||Lt(!1)}),()=>{ae=!0}},[f,t.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const ae=n?`?projectId=${encodeURIComponent(n)}`:"",Qe=ut=>{try{const It=JSON.parse(ut.data);It.id===t.id&&Array.isArray(It.workflowStepResults)&&Nt(It.workflowStepResults)}catch{}};return Os(`/api/events${ae}`,{events:{"task:updated":Qe}})},[f,t.id,n]),a.useEffect(()=>{j||L("")},[j]),a.useEffect(()=>{if(!t.assignedAgentId){U(null);return}const ae=G.find(ut=>ut.id===t.assignedAgentId);if(ae){U(ae);return}let Qe=!1;return oh(t.assignedAgentId,n).then(ut=>{Qe||U(ut)}).catch(()=>{Qe||U(null)}),()=>{Qe=!0}},[t.assignedAgentId,n,G]),a.useEffect(()=>{ue(!1)},[t.id]),a.useEffect(()=>{if(!(vt||Je))return;const Qe=ut=>{const It=ut.target,Ss=ze.current?.contains(It),gs=at.current?.contains(It);!Ss&&vt&&Ft(!1),!gs&&Je&&pt(!1)};return document.addEventListener("mousedown",Qe),()=>document.removeEventListener("mousedown",Qe)},[vt,Je]),a.useEffect(()=>{if(!(vt||Je))return;const Qe=ut=>{ut.key==="Escape"&&(ut.stopPropagation(),vt&&Ft(!1),Je&&pt(!1))};return document.addEventListener("keydown",Qe),()=>document.removeEventListener("keydown",Qe)},[vt,Je]),a.useEffect(()=>{we(!1),Se(N.prompt||""),Oe("")},[t.id,N.prompt]);const nn=yM.has(t.column)&&!Tt,Pn=a.useCallback(()=>{if(!nn)return;Xe(!0),ne(t.title||""),le(t.description||""),ye(t.dependencies||[]);const ae=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"",Qe=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"",ut=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";nt(ae),he(Qe),be(ut),Ze(t.thinkingLevel??""),tt(ae||Qe||ut?"custom":"default"),Ae(""),xt(t.enabledWorkflowSteps||[]),Ct([]),qe(t.reviewLevel),Ue(ba(t.priority))},[nn,t]),on=a.useCallback(()=>{Xe(!1),ne(t.title||""),le(t.description||""),ye(t.dependencies||[]),Ue(ba(t.priority)),yt.forEach(ae=>URL.revokeObjectURL(ae.previewUrl)),Ct([])},[t.title,t.description,t.dependencies,t.priority,yt]),Un=a.useCallback(async()=>{Et(!0);try{const ae={},Qe=re.trim(),ut=ge.trim();Qe&&Qe!==(t.title??"")&&(ae.title=Qe),ut&&ut!==(t.description??"")&&(ae.description=ut),qu(Te,t.dependencies??[])||(ae.dependencies=Te),qu(We,t.enabledWorkflowSteps??[])||(ae.enabledWorkflowSteps=We);const It=Vl(He),Ss=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"";He!==Ss&&(ae.modelProvider=It?.provider??null,ae.modelId=It?.modelId??null);const gs=Vl(mt),sl=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"";mt!==sl&&(ae.validatorModelProvider=gs?.provider??null,ae.validatorModelId=gs?.modelId??null);const Xa=Vl(ie),il=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";ie!==il&&(ae.planningModelProvider=Xa?.provider??null,ae.planningModelId=Xa?.modelId??null);const al=t.thinkingLevel??"";Me!==al&&(ae.thinkingLevel=Me!==""?Me:null);const ri=t.reviewLevel;Ce!==ri&&(ae.reviewLevel=Ce);const Js=ba(t.priority);if(ce!==Js&&(ae.priority=ce),Object.keys(ae).length>0){const Us=await Ws(t.id,ae,n);u?.(Us)}if(yt.length>0){const Us=[];for(const li of yt)try{const rl=await $a(t.id,li.file,n);R(Ts=>[...Ts,rl])}catch{Us.push(li.file.name)}Us.length>0&&h(`Failed to upload: ${Us.join(", ")}`,"error")}yt.forEach(Us=>URL.revokeObjectURL(Us.previewUrl)),Ct([]),h(`Updated ${t.id}`,"success"),Xe(!1)}catch(ae){h(`Failed to update ${t.id}: ${xe(ae)}`,"error")}finally{Mt.current&&Et(!1)}},[t,re,ge,Te,He,mt,ie,Me,Ce,ce,We,yt,h,n,u]),gn=a.useCallback(async ae=>{try{await Ws(t.id,{description:ae},n),h("Description saved","success")}catch(Qe){h(`Failed to save: ${xe(Qe)}`,"error")}},[t.id,h,n]),Zt=a.useCallback(ae=>{De&&(ae.key==="Escape"?(ae.preventDefault(),on()):ae.key==="Enter"&&(ae.ctrlKey||ae.metaKey)&&(ae.preventDefault(),Un()))},[De,on,Un]);a.useEffect(()=>{if(De)return document.addEventListener("keydown",Zt),()=>document.removeEventListener("keydown",Zt)},[De,Zt]);const Wt=a.useRef(null),{entries:Tn,loading:bn,loadMore:sn,hasMore:Hn,total:xn,loadingMore:qt}=Fp(t.id,f==="logs"&&w==="agent-log",n);a.useEffect(()=>{const ae=Qe=>{Qe.key==="Escape"&&!De&&i()};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[i,De]);const $n=a.useCallback(ae=>{ae.target===ae.currentTarget&&i()},[i]),qn=a.useCallback(async ae=>{try{await l(t.id,ae),i(),h(`Moved to ${ds[ae]}`,"success")}catch(Qe){h(xe(Qe),"error")}},[t.id,l,i,h]),Nn=a.useCallback(async()=>{if(confirm(`Delete ${t.id}?`))try{await o(t.id),i(),h(`Deleted ${t.id}`,"info")}catch(ae){const Qe=vM(ae);if(!Qe||Qe.dependentIds.length===0){h(xe(ae),"error");return}const ut=Qe.dependentIds.join(", ");if(!confirm(`${t.id} is a dependency of ${ut}.
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(Ss){h(xe(Ss),"error")}}},[t.id,o,i,h]),Dn=a.useCallback(()=>{confirm(`Merge ${t.id} into the current branch?`)&&(i(),h(`Merging ${t.id}...`,"info"),d(t.id).then(ae=>{const Qe=ae.merged?`Merged ${t.id} (branch: ${ae.branch})`:`Closed ${t.id} (${ae.error||"no branch to merge"})`;h(Qe,"success")}).catch(ae=>{h(xe(ae),"error")}))},[t.id,d,i,h]),se=a.useCallback(()=>{m&&(i(),m(t.id).then(()=>{h(`Retried ${t.id}`,"success")}).catch(ae=>{h(xe(ae),"error")}))},[t.id,m,i,h]),Fe=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 ae=await c(t.id);i(),h(`Duplicated ${t.id} → ${ae.id}`,"success")}catch(ae){h(xe(ae),"error")}},[t.id,c,i,h]),st=a.useCallback(async()=>{try{t.paused?(await xx(t.id,n),h(`Unpaused ${t.id}`,"success")):(await bx(t.id,n),h(`Paused ${t.id}`,"success")),i()}catch(ae){h(xe(ae),"error")}},[t.id,t.paused,i,h]),T=a.useCallback(async()=>{try{await jx(t.id,n),h(`Plan approved — ${t.id} moved to Todo`,"success"),i()}catch(ae){h(xe(ae),"error")}},[t.id,i,h]),W=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await wx(t.id,n),h(`Plan rejected — ${t.id} returned to Triage for re-specification`,"info"),i()}catch(ae){h(xe(ae),"error")}},[t.id,i,h]),ee=a.useCallback(async()=>{if(confirm("Rebuild the specification for this task? The task will move to triage for re-specification."))try{await Bx(t.id,n),i(),h(`Respecifying ${t.id}...`,"info")}catch(ae){h(xe(ae),"error")}},[t.id,n,i,h]),me=a.useCallback(()=>{rt(!0),_e("")},[]),ke=a.useCallback(()=>{Ft(!1),pt(!1)},[]),Re=a.useCallback(ae=>{ke(),qn(ae)},[ke]),dt=a.useCallback(ae=>{ke(),ae()},[ke]),Rt=a.useCallback(()=>{ke(),Dn()},[ke]),pn=a.useCallback(()=>{rt(!1),_e(""),et(!1)},[]),kt=a.useCallback(async()=>{if(!Ee.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Ee.length>2e3){h("Feedback must be 2000 characters or less","error");return}et(!0);try{const ae=await Ux(t.id,Ee.trim(),n);h(`Refinement task created: ${ae.id}`,"success"),i()}catch(ae){h(xe(ae),"error")}finally{et(!1)}},[t.id,Ee,h,i]),ht=a.useCallback(async ae=>{Z(!0);try{const Qe=await $a(t.id,ae,n);R(ut=>[...ut,Qe]),h("Screenshot attached","success")}catch(Qe){h(xe(Qe),"error")}finally{Z(!1)}},[t.id,h]),Ps=a.useCallback(async ae=>{const Qe=ae.target.files?.[0];Qe&&(await ht(Qe),Wt.current&&(Wt.current.value=""))},[ht]);a.useEffect(()=>{const ae=Qe=>{const ut=Qe.clipboardData?.items;if(ut)for(let It=0;It<ut.length;It++){const Ss=ut[It];if(Ss.type.startsWith("image/")){const gs=Ss.getAsFile();if(gs){Qe.preventDefault(),ht(gs);return}}}};return document.addEventListener("paste",ae),()=>document.removeEventListener("paste",ae)},[ht]);const oe=a.useCallback(ae=>{ae.preventDefault()},[]),$e=a.useCallback(ae=>{ae.preventDefault();const Qe=ae.dataTransfer.files;for(let ut=0;ut<Qe.length;ut++){const It=Qe[ut];if(It.type.startsWith("image/")){ht(It);return}}},[ht]),ot=a.useCallback(async ae=>{try{await _x(t.id,ae,n),R(Qe=>Qe.filter(ut=>ut.filename!==ae)),h("Attachment deleted","info")}catch(Qe){h(xe(Qe),"error")}},[t.id,h]),jt=a.useCallback(async ae=>{const Qe=wn;hn(ae);try{const ut=await Ws(t.id,{enabledWorkflowSteps:ae},n);h("Workflow steps updated","success"),u?.(ut)}catch(ut){hn(Qe),h(`Failed to update workflow steps: ${xe(ut)}`,"error")}},[t.id,n,wn,u,h]),St=a.useCallback(async()=>{te(!0);try{const ae=await aa(void 0,n);E(ae),ue(!0)}catch(ae){h(`Failed to load agents: ${xe(ae)}`,"error"),ue(!1)}finally{te(!1)}},[n,h]),cn=a.useCallback(async ae=>{try{const Qe=await ed(t.id,ae,n),ut=G.find(It=>It.id===ae)??null;U(ut||(It=>It?.id===ae?It:null)),ue(!1),u?.(Qe),h("Assigned agent updated","success")}catch(Qe){h(`Failed to assign agent: ${xe(Qe)}`,"error")}},[t.id,n,G,u,h]),dn=a.useCallback(async()=>{try{const ae=await ed(t.id,null,n);U(null),ue(!1),u?.(ae),h("Agent unassigned","success")}catch(ae){h(`Failed to unassign agent: ${xe(ae)}`,"error")}},[t.id,n,u,h]),mn=a.useCallback(async ae=>{const Qe=[...I,ae];_(Qe);try{await Ws(t.id,{dependencies:Qe},n)}catch(ut){_(I),h(xe(ut),"error")}},[t.id,I,h]),fn=a.useCallback(async(ae,Qe)=>{ae.stopPropagation();const ut=I.filter(It=>It!==Qe);_(ut);try{await Ws(t.id,{dependencies:ut},n)}catch(It){_(I),h(xe(It),"error")}},[t.id,I,h]),vn=a.useCallback(async ae=>{try{const Qe=await Mr(ae,n);r(Qe)}catch{h(`Failed to load dependency ${ae}`,"error")}},[r,h]),Sn=a.useCallback(async ae=>{fe(!0);try{await Ws(N.id,{prompt:ae},n),h("Spec updated","success"),x&&(x.prompt=ae)}catch(Qe){throw h(xe(Qe),"error"),Qe}finally{fe(!1)}},[N,x,h]),rs=a.useCallback(async ae=>{K(!0);try{await Ox(t.id,ae,n),h("AI revision requested. Task moved to triage.","success"),i()}catch(Qe){const ut=xe(Qe);ut.includes("in-review")||ut.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(ut,"error")}finally{K(!1)}},[t.id,h,i]),Vn=a.useCallback(()=>{we(!0),Se(N.prompt||""),Oe("")},[N.prompt]),Cn=a.useCallback(()=>{we(!1),Se(N.prompt||""),Oe("")},[N.prompt]),Rn=a.useCallback(async()=>{if(ve===(N.prompt||"")){Cn();return}await Sn(ve),we(!1)},[ve,N.prompt,Sn,Cn]),Qn=a.useCallback(async()=>{Pe.trim()&&await rs(Pe.trim())},[Pe,rs]),yn=a.useCallback(ae=>{ae.key==="Escape"?(ae.preventDefault(),Cn()):ae.key==="Enter"&&(ae.ctrlKey||ae.metaKey)&&(ae.preventDefault(),Rn())},[Cn,Rn]),Wn=s.filter(ae=>ae.id!==t.id&&!I.includes(ae.id)).sort((ae,Qe)=>{const ut=Qe.createdAt.localeCompare(ae.createdAt);if(ut!==0)return ut;const It=parseInt(ae.id.slice(ae.id.lastIndexOf("-")+1),10)||0;return(parseInt(Qe.id.slice(Qe.id.lastIndexOf("-")+1),10)||0)-It}),ps=D?.name??t.assignedAgentId??null,Xn=go[t.column]||[],fs={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},Fn=t.status?fs[t.status]:void 0;return e.jsx("div",{className:"modal-overlay open",onClick:$n,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg",onDragOver:oe,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:ds[t.column]})]}),e.jsxs("div",{className:"modal-header-actions",children:[!De&&nn&&e.jsx("button",{className:"modal-edit-btn",onClick:Pn,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${f==="logs"&&w==="agent-log"&&!De?" detail-body--agent-log":""}`,children:[De?e.jsx("div",{className:"modal-edit-form",children:e.jsx(Op,{mode:"edit",title:re,onTitleChange:ne,description:ge,onDescriptionChange:le,dependencies:Te,onDependenciesChange:ye,executorModel:He,onExecutorModelChange:nt,validatorModel:mt,onValidatorModelChange:he,planningModel:ie,onPlanningModelChange:be,thinkingLevel:Me,onThinkingLevelChange:Ze,presetMode:je,onPresetModeChange:tt,selectedPresetId:Ve,onSelectedPresetIdChange:Ae,selectedWorkflowSteps:We,onWorkflowStepsChange:xt,pendingImages:yt,onImagesChange:Ct,tasks:s.filter(ae=>ae.id!==t.id),projectId:n,disabled:Tt,addToast:h,isActive:De,onAutoSaveDescription:gn,reviewLevel:Ce,onReviewLevelChange:qe,priority:ce,onPriorityChange:Ue})}):e.jsxs(e.Fragment,{children:[(()=>{const ae=t.title||t.description||t.id,Qe=!k&&ae.length>Wl;return e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"detail-title",children:Qe?ae.slice(0,Wl)+"…":ae}),ae.length>Wl&&e.jsx("button",{className:"detail-description-toggle",onClick:()=>P(!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--${ba(t.priority)}`,children:["Priority: ",ba(t.priority)]})]})]}),t.status==="failed"&&t.error&&e.jsxs("div",{className:"detail-error-alert",children:[e.jsx("span",{className:"detail-error-icon",children:"⚠"}),e.jsxs("div",{className:"detail-error-content",children:[e.jsx("div",{className:"detail-error-title",children:"Task Failed"}),e.jsx("div",{className:"detail-error-message",children:t.error})]})]}),!De&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"detail-tabs",children:[e.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>b("definition"),children:"Definition"}),e.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>b("logs"),children:"Logs"}),(t.column==="in-progress"||t.column==="in-review"||t.column==="done")&&e.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>b("changes"),children:"Changes"}),e.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>b("comments"),children:"Comments"}),e.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>b("documents"),children:"Documents"}),e.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>b("model"),children:"Model"}),e.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>b("workflow"),children:"Workflow"}),$.map((ae,Qe)=>{const ut=`plugin-${Qe}`;return e.jsx("button",{className:`detail-tab${f===ut?" detail-tab-active":""}`,onClick:()=>b(ut),children:ae.slot.label},`plugin-tab-${ae.pluginId}`)})]}),f==="workflow"?e.jsx("div",{className:"detail-section",children:e.jsx(lM,{taskId:t.id,results:bt,loading:Bt,enabledWorkflowSteps:wn,canEdit:nn,projectId:n,isTaskInProgress:t.column==="in-progress"&&t.status!=="paused",onWorkflowStepsChange:jt})}):f==="model"?e.jsx("div",{className:"detail-section",children:e.jsx(U2,{task:t,addToast:h,onTaskUpdated:u,settings:pe})}):f==="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:()=>S("activity"),children:"Activity"}),e.jsx("button",{className:`log-subview-btn${w==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>S("agent-log"),children:"Agent Log"})]}),w==="agent-log"?e.jsx(F2,{entries:Tn,loading:bn,executorModel:mM(t,pe),validatorModel:hM(t,pe),planningModel:fM(t,Tn,pe),hasMore:Hn,onLoadMore:sn,loadingMore:qt,totalCount:xn}):e.jsxs("div",{className:"detail-activity",children:[e.jsx("h4",{children:"Activity"}),N.activityLogTruncatedCount?e.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",N.log.length," activity entries."]}):null,N.log&&N.log.length>0?e.jsx("div",{className:"detail-activity-list",children:[...N.log].reverse().map((ae,Qe)=>e.jsxs("div",{className:"detail-log-entry",children:[e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-timestamp",children:bM(ae.timestamp)}),e.jsx("span",{className:"detail-log-action",children:ae.action})]}),ae.outcome&&e.jsx("div",{className:"detail-log-outcome",children:ae.outcome})]},Qe))}):e.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?e.jsx(X2,{taskId:t.id,worktree:t.worktree,projectId:n,column:t.column,mergeDetails:t.mergeDetails,modifiedFiles:t.modifiedFiles}):f==="comments"?e.jsx(K2,{task:t,addToast:h,projectId:n,onTaskUpdated:u}):f==="documents"?e.jsx(uM,{taskId:t.id,addToast:h,projectId:n,onTaskUpdated:u,canEdit:nn}):typeof f=="string"&&f.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(J2,{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:[ps?e.jsxs("span",{className:"detail-agent-chip",children:[e.jsx(an,{size:14}),ps,e.jsx("button",{className:"detail-agent-clear",onClick:()=>void dn(),title:"Unassign agent",children:e.jsx(Dt,{size:12})})]}):e.jsx("button",{className:"btn btn-sm",onClick:()=>{J?ue(!1):St()},children:"Assign Agent"}),J&&e.jsxs("div",{className:"agent-picker-dropdown",children:[z&&e.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!z&&G.filter(ae=>ae.state!=="terminated").map(ae=>e.jsxs("button",{className:`agent-picker-item${t.assignedAgentId===ae.id?" selected":""}`,onClick:()=>void cn(ae.id),children:[e.jsx(an,{size:14}),e.jsx("span",{className:"agent-picker-name",children:ae.name}),e.jsx("span",{className:"agent-picker-role",children:ae.role})]},ae.id)),!z&&G.filter(ae=>ae.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"}),N.steps&&N.steps.length>0?e.jsxs("div",{className:"step-progress-wrapper",children:[e.jsx("div",{className:"step-progress-bar",children:N.steps.map((ae,Qe)=>e.jsx("div",{className:`step-progress-segment step-progress-segment--${ae.status}`,"data-tooltip":`${ae.name} (${ae.status})`,style:{backgroundColor:gM(ae.status)}},Qe))}),e.jsxs("span",{className:"step-progress-label",children:[N.steps.filter(ae=>ae.status==="done").length,"/",N.steps.length," step",N.steps.length===1?"":"s"]})]}):e.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),e.jsxs("div",{className:"detail-section",children:[!de&&e.jsx("div",{className:"detail-spec-edit-trigger",children:e.jsx("button",{className:"btn btn-sm",onClick:Vn,children:"Edit"})}),de?e.jsxs("div",{className:"spec-editor-edit-mode",children:[e.jsx("textarea",{className:"spec-editor-textarea",value:ve,onChange:ae=>Se(ae.target.value),onKeyDown:yn,disabled:F,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:Cn,disabled:F,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Rn(),disabled:ve===(N.prompt||"")||F,children:F?"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:Pe,onChange:ae=>Oe(ae.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:V,rows:4,maxLength:2e3}),e.jsxs("div",{className:"spec-editor-revision-actions",children:[e.jsxs("span",{className:"spec-editor-char-count",children:[Pe.length,"/2000"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Qn(),disabled:!Pe.trim()||V,children:V?"Requesting…":"Request AI Revision"})]})]})]}):v?e.jsx("div",{className:"spec-loading",children:"Loading specification…"}):N.prompt?e.jsx("div",{className:"markdown-body",children:e.jsx(ni,{remarkPlugins:[si],children:N.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(ae=>{const Qe=As(`/api/tasks/${t.id}/attachments/${ae.filename}`);return e.jsxs("div",{className:"detail-attachment-card",children:[e.jsx("a",{className:"detail-attachment-link",href:Qe,target:"_blank",rel:"noopener noreferrer",children:e.jsx("img",{src:Qe,alt:ae.originalName,className:"detail-attachment-image"})}),e.jsxs("div",{className:"detail-attachment-meta",children:[ae.originalName," (",xM(ae.size),")"]}),e.jsx("button",{className:"detail-attachment-delete",onClick:()=>ot(ae.filename),title:"Delete attachment",children:"×"})]},ae.filename)})}):e.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),e.jsx("input",{className:"detail-hidden-file-input",ref:Wt,type:"file",accept:"image/*",onChange:Ps}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Wt.current?.click(),disabled:O,children:O?"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(ae=>{const Qe=s.find(It=>It.id===ae),ut=Qe?.title||Qe?.description||ae;return e.jsxs("li",{className:"detail-dep-item",children:[e.jsxs("span",{className:"detail-dep-link",onClick:()=>vn(ae),onKeyDown:It=>{(It.key==="Enter"||It.key===" ")&&(It.preventDefault(),vn(ae))},role:"link",tabIndex:0,title:`Click to view ${ae}`,children:[e.jsx("span",{className:"detail-dep-id",children:ae}),e.jsx("span",{className:"detail-dep-label",children:Hu(ut,40)})]}),e.jsx("button",{className:"dep-remove-btn",onClick:It=>fn(It,ae),title:`Remove dependency ${ae}`,children:"×"})]},ae)})}):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:()=>{j&&L(""),Q(ae=>!ae)},children:"Add Dependency"}),j&&(()=>{const ae=Y.toLowerCase(),Qe=ae?Wn.filter(ut=>ut.id.toLowerCase().includes(ae)||ut.title&&ut.title.toLowerCase().includes(ae)||ut.description&&ut.description.toLowerCase().includes(ae)):Wn;return e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Y,onChange:ut=>L(ut.target.value),onClick:ut=>ut.stopPropagation()}),Qe.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Qe.map(ut=>e.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{mn(ut.id),Q(!1)},children:[e.jsx("span",{className:"dep-dropdown-id",children:ut.id}),e.jsx("span",{className:"dep-dropdown-title",children:Hu(ut.title||ut.description||ut.id,30)})]},ut.id))]})})()]})]}),t.column==="in-review"&&e.jsx(q2,{taskId:t.id,projectId:n,prInfo:t.prInfo,automationStatus:t.status??null,autoMerge:pe?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:ae=>{t.prInfo=ae,h(`PR #${ae.number} created`,"success")},onPrUpdated:ae=>{t.prInfo=ae},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:on,disabled:Tt,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:Un,disabled:Tt,children:Tt?"Saving…":"Save"})]}):e.jsxs(e.Fragment,{children:[t.column==="triage"&&t.status==="awaiting-approval"&&N.prompt&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-primary btn-sm",onClick:T,children:"Approve Plan"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:W,children:"Reject Plan"})]}),t.column==="triage"&&t.status!=="awaiting-approval"&&!A&&e.jsx("button",{className:"btn btn-sm btn-danger",onClick:Nn,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(t.column!=="triage"||t.status==="awaiting-approval"||A)&&e.jsxs("div",{className:"detail-actions-dropdown",ref:at,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>{pt(ae=>!ae),Ft(!1)},"aria-haspopup":"menu","aria-expanded":Je,children:["Actions",e.jsx(zt,{size:12})]}),Je&&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:()=>dt(Nn),children:"Delete"}),c&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>dt(Fe),children:"Duplicate"}),(t.column==="done"||t.column==="in-review")&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>dt(me),children:"Refine"}),e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>dt(ee),children:"Respecify"}),A&&m&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>dt(se),children:"Retry"}),t.column!=="done"&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>dt(st),children:t.paused?"Unpause":"Pause"})]})]}),e.jsx("div",{className:"modal-actions-spacer"}),e.jsx("div",{className:"detail-move-dropdown",ref:ze,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:()=>{Ft(ae=>!ae),pt(!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:Rt,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:()=>Re("todo"),children:"Move to Todo"}),e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Re("in-progress"),children:"Back to In Progress"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Re(Xn[0]),disabled:Xn.length===0,children:["Move to ",Xn.length>0?ds[Xn[0]]:""]}),Xn.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{Ft(ae=>!ae),pt(!1)},"aria-haspopup":"menu","aria-expanded":vt,children:e.jsx(zt,{size:12})}),vt&&e.jsx("div",{className:"detail-move-menu",role:"menu",children:Xn.map(ae=>e.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Re(ae),children:["Move to ",ds[ae]]},ae))})]})]})})]})}),Ie&&e.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:pn,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal detail-refine-modal",onClick:ae=>ae.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:pn,"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:Ee,onChange:ae=>_e(ae.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:[Ee.length,"/2000 characters"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:kt,disabled:!Ee.trim()||Be,children:Be?"Creating...":"Create Refinement Task"})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:pn,disabled:Be,children:"Cancel"})})]})})]})})}function jM(t={}){const{projectId:n,pollInterval:s=6e4,autoRefresh:i=!1}=t,[r,l]=a.useState(null),[o,d]=a.useState(!0),[m,c]=a.useState(null),[u,h]=a.useState(null),g=a.useRef(null),p=a.useRef(null),f=a.useRef(!0),b=a.useCallback(async(S=!1)=>{g.current&&g.current.abort(),g.current=new AbortController,S&&(d(!0),c(null));try{const k=await Mx(n);if(!f.current)return;l(k),c(null),h(new Date),d(!1)}catch(k){if(k instanceof Error&&k.name==="AbortError"||!f.current)return;const P=k instanceof Error?k.message:"Failed to fetch memory backend status";c(P),d(!1)}},[n]);a.useEffect(()=>(f.current=!0,b(!1),()=>{f.current=!1}),[b]),a.useEffect(()=>{if(i)return p.current=setInterval(()=>{b(!1)},s),()=>{p.current&&(clearInterval(p.current),p.current=null)}},[i,s,b]),a.useEffect(()=>()=>{f.current=!1,g.current&&g.current.abort(),p.current&&(clearInterval(p.current),p.current=null)},[]);const x=a.useCallback(()=>b(!0),[b]),y=r?.currentBackend??null,v=r?.capabilities??null,M=r?.availableBackends??[],N=v?.readable??!1,A=v?.writable??!1,w=v?.supportsAtomicWrite??!1;return{status:r,currentBackend:y,capabilities:v,availableBackends:M,isReadable:N,isWritable:A,supportsAtomicWrite:w,loading:o,error:m,lastUpdated:u,refresh:x}}const wM=[{value:"light",label:"Light",icon:Gm},{value:"dark",label:"Dark",icon:Vm},{value:"system",label:"System",icon:Vr}],Vu=[{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 NM({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:wM.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(Gm,{size:20}):t==="dark"?e.jsx(Vm,{size:20}):e.jsx(Vr,{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)}`," / ",Vu.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:Vu.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 SM(t){if(!t)return!1;const n=t.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function Bp({content:t,onChange:n,readOnly:s,filePath:i}){const[r,l]=a.useState(!1),[o,d]=a.useState(!0),m=SM(i),c=m&&(s?!0:r),u=a.useCallback(()=>{l(!1)},[]),h=a.useCallback(()=>{l(!0)},[]),g=a.useCallback(()=>{d(p=>!p)},[]);return e.jsxs("div",{className:"file-editor-container",children:[m?e.jsxs("div",{className:"file-editor-toolbar",children:[e.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&e.jsxs("button",{className:`btn btn-sm ${c?"":"btn-primary"}`,onClick:u,disabled:!c,"aria-label":"Edit mode",children:[e.jsx(Om,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:h,disabled:c,"aria-label":"Preview mode",children:[e.jsx(Oo,{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:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function Up({authenticated:t,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[l,o]=a.useState(null),[d,m]=a.useState(null),c=a.useRef(!0);a.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const u=a.useCallback(async()=>{try{const y=await qx();return c.current&&r(y),y}catch(y){return c.current&&m({kind:"error",message:y instanceof Error?y.message:String(y)}),null}},[]);a.useEffect(()=>{u()},[u]);const h=a.useCallback(async()=>{o("testing"),m(null),await u(),c.current&&o(null)},[u]),g=a.useCallback(async y=>{o(y?"enabling":"disabling"),m(null);try{const v=await Vx(y);c.current&&m({kind:v.enabled?"enabled":"disabled",restartRequired:v.restartRequired}),n?.(v.enabled),await u()}catch(v){c.current&&m({kind:"error",message:v instanceof Error?v.message:String(v)})}finally{c.current&&o(null)}},[n,u]),p=i?.binary.available??!1,f=i?.enabled??t,b=e.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",e.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),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(lt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:l!==null,children:l==="disabling"?"Disabling…":"Disable"}):e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:l!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:l==="enabling"?"Enabling…":"Enable"})]});return s?e.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${t?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[e.jsxs("div",{className:"auth-provider-header",children:[e.jsxs("div",{className:"auth-provider-info",children:[e.jsx(ss,{provider:"claude-cli",size:"sm"}),e.jsx("strong",{children:"Anthropic — via Claude CLI"}),e.jsx(CM,{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(Wu,{status:i,authenticated:t}),d&&e.jsx(Ku,{action:d})]})]})]}):e.jsxs("div",{className:`onboarding-provider-card${t?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ss,{provider:"claude-cli",size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,e.jsx(Wu,{status:i,authenticated:t})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:x}),d&&e.jsx(Ku,{action:d})]})}function CM({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 Wu({status:t,authenticated:n}){if(!t)return e.jsxs("small",{className:"settings-muted",children:[e.jsx(lt,{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 Ku({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}],EM={"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..."}},Gu=["executor","triage","reviewer","merger"],xa={executor:"Executor Agent",triage:"Triage Agent",reviewer:"Reviewer Agent",merger:"Merger Agent",scheduler:"Scheduler Agent",engineer:"Engineer Agent",custom:"Custom Agent"},qs={executor:"#3b82f6",triage:"#f59e0b",reviewer:"#8b5cf6",merger:"#10b981",scheduler:"#06b6d4",engineer:"#ec4899",custom:"#6b7280"},Kl={name:"",description:"",role:"executor",prompt:""};function MM(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 AM({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(Kl),[g,p]=a.useState(null),[f,b]=a.useState(null),[x,y]=a.useState(new Set),[v,M]=a.useState(null),[N,A]=a.useState(!1),[w,S]=a.useState(null),k=a.useRef(null),P=t?.templates??[],C=t?.roleAssignments??{},R=w===null?null:w.source==="builtin"?Li.find(z=>z.id===w.id):P.find(z=>z.id===w.id),O=a.useCallback(z=>{const te=Li.filter(fe=>fe.role===z),F=P.filter(fe=>fe.role===z);return[...te,...F]},[P]);a.useEffect(()=>{w!==null&&k.current?.focus()},[w]);const Z=a.useCallback(()=>{c(!0),d(null),h(Kl),p(null),S(null)},[]),I=a.useCallback(z=>{d(z.id),c(!1),h({name:z.name,description:z.description,role:z.role,prompt:z.prompt}),p(null),S(null)},[]),_=a.useCallback(()=>{d(null),c(!1),h(Kl),p(null),S(null),A(!1)},[]),j=a.useCallback(()=>{const z=u.name.trim();if(!z){p("Template name is required");return}let te;if(m){if(te=MM(z,P),new Set(Li.map(de=>de.id)).has(te)){p(`Template ID "${te}" conflicts with a built-in template. Please use a different name.`);return}}else te=o;const F={id:te,name:z,description:u.description.trim(),role:u.role,prompt:u.prompt,builtIn:!1};let fe;m?fe=[...P,F]:fe=P.map(K=>K.id===te?F:K);const V={...C};for(const[K,de]of Object.entries(V))de===te&&u.role!==K&&delete V[K];n({...t,templates:fe,roleAssignments:Object.keys(V).length>0?V:void 0}),_()},[u,m,o,P,C,t,n,_]),Q=a.useCallback(z=>{const te=P.filter(V=>V.id!==z),F={...C};let fe=!1;for(const[V,K]of Object.entries(F))K===z&&(delete F[V],fe=!0);n({...t,templates:te.length>0?te:void 0,roleAssignments:Object.keys(F).length>0||fe?Object.keys(F).length>0?F:void 0:C}),b(null),o===z&&_()},[P,C,t,n,o,_]),Y=a.useCallback((z,te)=>{const F={...C};te===""?delete F[z]:F[z]=te,n({...t,roleAssignments:Object.keys(F).length>0?F:void 0})},[C,t,n]),L=a.useCallback((z,te)=>{const F={...s};F[z]=te||null,i(F)},[s,i]),D=a.useCallback(z=>{const te={...s};te[z]=null,i(te)},[s,i]),U=a.useCallback(z=>{y(te=>{const F=new Set(te);return F.has(z)?F.delete(z):F.add(z),F})},[]),G=a.useCallback(z=>{M(te=>te===z?null:z)},[]),E=a.useCallback((z,te)=>{A(!1),S({source:z,id:te})},[]),J=a.useCallback(()=>{S(null),A(z=>!z)},[]),ue=z=>Li.some(te=>te.id===z);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(Dm,{size:14}),"Templates"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="assignments"?"active":""}`,onClick:()=>l("assignments"),"data-testid":"tab-assignments",children:[e.jsx(Vb,{size:14}),"Assignments"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="overrides"?"active":""}`,onClick:()=>l("overrides"),"data-testid":"tab-overrides",children:[e.jsx(Mb,{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:z=>h(te=>({...te,name:z.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:z=>h(te=>({...te,description:z.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:z=>h(te=>({...te,role:z.target.value})),"data-testid":"template-role-select",children:Gu.map(z=>e.jsx("option",{value:z,children:xa[z]},z))})]}),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:J,"aria-label":"Expand prompt to fullscreen","data-testid":"template-prompt-fullscreen",children:e.jsx(Xs,{size:14})})]}),N?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:z=>{z.key==="Escape"&&(z.preventDefault(),A(!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:()=>A(!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:z=>h(te=>({...te,prompt:z.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:z=>h(te=>({...te,prompt:z.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:j,"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(z=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${z.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:z.name}),e.jsx("span",{className:"prompt-template-badge-built-in",style:{borderColor:qs[z.role]},children:"Built-in"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:qs[z.role]+"20",color:qs[z.role]},children:xa[z.role]})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>E("builtin",z.id),title:"View full prompt","aria-label":`View full prompt for ${z.name}`,"data-testid":`expand-view-${z.id}`,children:e.jsx(Xs,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:z.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:z.prompt})})]},z.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."}),P.length===0&&!m&&e.jsx("div",{className:"prompt-template-empty",children:"No custom templates yet. Create one to get started."}),P.length>0&&e.jsx("div",{className:"prompt-template-list",children:P.map(z=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${z.id}`,children:f===z.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsxs("p",{children:['Delete "',z.name,'"?']}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>Q(z.id),"data-testid":`confirm-delete-${z.id}`,children:"Delete"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>b(null),"data-testid":`cancel-delete-${z.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:z.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:"Custom"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:qs[z.role]+"20",color:qs[z.role]},children:xa[z.role]}),ue(z.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:()=>E("custom",z.id),title:"View full prompt","aria-label":`View full prompt for ${z.name}`,"data-testid":`expand-view-${z.id}`,children:e.jsx(Xs,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>I(z),title:"Edit","aria-label":`Edit ${z.name}`,"data-testid":`edit-${z.id}`,children:e.jsx(Ln,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>b(z.id),title:"Delete","aria-label":`Delete ${z.name}`,"data-testid":`delete-${z.id}`,children:e.jsx(Ht,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:z.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:z.prompt})})]})},z.id))}),!m&&o===null&&e.jsxs("button",{className:"btn btn-primary prompt-template-add-btn",onClick:Z,"data-testid":"add-template-btn",children:[e.jsx(Vt,{size:14}),"Add Custom Template"]})]}),R&&e.jsxs("div",{ref:k,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:z=>{z.key==="Escape"&&(z.preventDefault(),S(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[R.name,e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:qs[R.role]+"20",color:qs[R.role]},children:xa[R.role]})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>S(null),"data-testid":`collapse-view-${R.id}`,children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:R.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:Gu.map(z=>{const te=O(z),F=C[z]??"",fe=te.find(K=>K.id===F),V=!!F;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${z}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:"prompt-role-badge",style:{backgroundColor:qs[z]+"20",color:qs[z]},children:xa[z]}),V&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[fe?.name??"Custom"," (overrides default)"]})]}),e.jsxs("select",{className:"prompt-role-select",value:F,onChange:K=>Y(z,K.target.value),"data-testid":`select-${z}`,children:[e.jsx("option",{value:"",children:"Use default"}),te.map(K=>e.jsxs("option",{value:K.id,children:[K.name,ue(K.id)?" (built-in)":" (custom)"]},K.id))]})]},z)})}),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(EM).map(z=>{const te=z.key,F=s?.[te]??"",fe=F!=="",V=x.has(te);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${te}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("div",{className:"prompt-override-info",onClick:()=>U(te),role:"button",tabIndex:0,onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&U(te)},children:[e.jsx("span",{className:"prompt-override-name",children:z.name}),e.jsx("code",{className:"prompt-override-key",children:te}),fe&&e.jsx("span",{className:"prompt-override-badge",children:"customized"})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[V&&e.jsx("button",{className:"prompt-override-fullscreen-btn",onClick:K=>{K.stopPropagation(),G(te)},"aria-label":"Expand to fullscreen","data-testid":`fullscreen-${te}`,children:e.jsx(Xs,{size:14})}),e.jsx("button",{className:"prompt-override-expand-btn","aria-label":V?"Collapse":"Expand","data-testid":`expand-${te}`,onClick:K=>{K.stopPropagation(),U(te)},children:V?e.jsx(Ds,{size:16}):e.jsx(zt,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:z.description}),V&&(v===te?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:K=>{K.key==="Escape"&&(K.preventDefault(),M(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[z.name,e.jsx("code",{className:"prompt-override-key",children:te})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>M(null),"data-testid":`collapse-fullscreen-${te}`,children:[e.jsx(Ks,{size:14}),"Collapse"]})]}),e.jsx("textarea",{id:`prompt-${te}-fullscreen`,"aria-label":`${z.name} prompt override (${te}) - fullscreen`,className:"prompt-override-textarea",value:F,onChange:K=>{L(te,K.target.value)},placeholder:`Default: ${z.defaultContent.slice(0,100)}${z.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${te}`}),e.jsxs("div",{className:"prompt-override-footer",children:[fe&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>D(te),"data-testid":`reset-fullscreen-${te}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:fe?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${z.defaultContent.length} chars).`})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${te}`,"aria-label":`${z.name} prompt override (${te})`,className:"prompt-override-textarea",value:F,onChange:K=>{L(te,K.target.value)},placeholder:`Default: ${z.defaultContent.slice(0,100)}${z.defaultContent.length>100?"...":""}`,rows:4,"data-testid":`override-input-${te}`}),e.jsxs("div",{className:"prompt-override-footer",children:[fe&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:K=>{K.stopPropagation(),D(te)},"data-testid":`reset-${te}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:fe?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${z.defaultContent.length} chars).`})]})]}))]},te)})})]})]})]})}const PM=a.lazy(()=>en(()=>import("./PluginManager-CXUWZBOc.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.PluginManager}))),TM=a.lazy(()=>en(()=>import("./PiExtensionsManager-COxkYM2m.js"),__vite__mapDeps([7,1,4,5,8])).then(t=>({default:t.PiExtensionsManager}))),Ju="(max-width: 768px)",Gl=".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"}],Yu=1440*60*1e3,RM=2,Di=["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],Qu={insights:"Insights",roadmap:"Roadmaps",memoryView:"Memory Editor",skillsView:"Skills View",nodesView:"Nodes View",devServer:"Dev Server",devServerView:"Dev Server View"};function _M({onClose:t,addToast:n,projectId:s,initialSection:i,themeMode:r="dark",colorTheme:l="default",onThemeModeChange:o,onColorThemeChange:d,onReopenOnboarding:m}){const[c,u]=a.useState({maxConcurrent:2,maxTriageConcurrent:2,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,autoMerge:!0,mergeStrategy:"direct",recycleWorktrees:!1,worktreeNaming:"random",includeTaskIdInCommit:!0,worktreeInitCommand:"",ntfyEnabled:!1,ntfyTopic:void 0}),[h,g]=a.useState(!0),[p,f]=a.useState(null),[b,x]=a.useState(null),[y,v]=a.useState(null),M=br.find(T=>!T.isGroupHeader),[N,A]=a.useState(i??M?.id??"authentication"),[w,S]=a.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(Ju)?.matches===!0:!1),[k,P]=a.useState(null),C=br.find(T=>T.id===N)?.scope,[R,O]=a.useState([]),[Z,I]=a.useState(!1),[_,j]=a.useState(null),[Q,Y]=a.useState({}),[L,D]=a.useState({}),[U,G]=a.useState({}),E=a.useRef(null),[J,ue]=a.useState([]),[z,te]=a.useState(!1),[F,fe]=a.useState([]),[V,K]=a.useState([]),[de,we]=a.useState(!1),[ve,Se]=a.useState(null),[Pe,Oe]=a.useState(null),[Ie,rt]=a.useState(null),[Ee,_e]=a.useState(!1),[Be,et]=a.useState(""),[De,Xe]=a.useState(!1),[re,ne]=a.useState(!1),[ge,le]=a.useState([]),[Te,ye]=a.useState([]),[He,nt]=a.useState(Gl),[mt,he]=a.useState(""),[ie,be]=a.useState(!1),[Me,Ze]=a.useState(null),[je,tt]=a.useState(!1),[Ce,qe]=a.useState(!1),ce=a.useRef(!1),[Ue,Ve]=a.useState(4),Ae=a.useRef(4),[We,xt]=a.useState(!1),[,yt]=a.useState(null),[Ct,Tt]=a.useState(null),[Et,Mt]=a.useState(!1),[vt,Ft]=a.useState("both"),[Je,pt]=a.useState(!0),ze=a.useRef(null),{status:at,capabilities:q,loading:$,error:pe,refresh:ct}=jM({projectId:s});a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const T=window.matchMedia(Ju);if(!T)return;const W=ee=>{S(ee?ee.matches:T.matches)};return W(),typeof T.addEventListener=="function"?(T.addEventListener("change",W),()=>T.removeEventListener("change",W)):(T.addListener(W),()=>T.removeListener(W))},[]),a.useEffect(()=>{Promise.all([Ki(s),Tx(s)]).then(([T,W])=>{u(T),f(T),x(W),v(W),g(!1)}).catch(T=>{n(xe(T),"error"),g(!1)})},[n,s]),a.useEffect(()=>{My().then(T=>{Ve(T.globalMaxConcurrent),Ae.current=T.globalMaxConcurrent}).catch(()=>{})},[]);const bt=a.useCallback(async()=>{try{const{providers:T}=await ji();O(T),Y(W=>{const ee={};for(const[me,ke]of Object.entries(W)){const Re=T.find(dt=>dt.id===me);Re&&!Re.authenticated&&(ee[me]=ke)}return Object.keys(ee).length===Object.keys(W).length?W:ee})}catch{}},[]);a.useEffect(()=>{(N==="global-models"||N==="project-models")&&(te(!0),Jn().then(T=>{ue(T.models),fe(T.favoriteProviders),K(T.favoriteModels)}).catch(()=>ue([])).finally(()=>te(!1)))},[N]),a.useEffect(()=>{N==="backups"&&(_e(!0),td(s).then(T=>rt(T)).catch(()=>rt(null)).finally(()=>_e(!1)))},[N,s]),a.useEffect(()=>{N==="worktrees"&&nh(s).then(T=>le(T)).catch(()=>le([]))},[N,s]),a.useEffect(()=>{if(N!=="memory"||re)return;if(ce.current){ce.current=!1;return}let T=!1;return Xe(!0),Bc(s).then(async({files:W})=>{if(T)return;ye(W);const ee=W.some(ke=>ke.path===He)?He:W.find(ke=>ke.path===Gl)?.path??W.find(ke=>ke.layer==="dreams")?.path??W[0]?.path??Gl;nt(ee);const{content:me}=await Sx(ee,s);T||(et(me),ne(!1))}).catch(W=>{T||(n(xe(W)||"Failed to load project memory","error"),et(""))}).finally(()=>{T||Xe(!1)}),()=>{T=!0}},[N,re,He,s,n]),a.useEffect(()=>(N==="authentication"&&(I(!0),bt().finally(()=>I(!1))),()=>{E.current&&(clearInterval(E.current),E.current=null)}),[N,bt]);const Nt=a.useCallback(async T=>{j(T),Y(W=>{if(!(T in W))return W;const ee={...W};return delete ee[T],ee});try{const{url:W,instructions:ee}=await Xm(T);ee?.trim()&&Y(me=>({...me,[T]:ee})),window.open(As(W),"_blank"),E.current=setInterval(async()=>{try{const{providers:me}=await ji();O(me),me.find(Re=>Re.id===T)?.authenticated&&(E.current&&(clearInterval(E.current),E.current=null),j(null),Y(Re=>{if(!(T in Re))return Re;const dt={...Re};return delete dt[T],dt}),n("Login successful","success"))}catch{}},2e3)}catch(W){n(xe(W)||"Login failed","error"),j(null),Y(ee=>{if(!(T in ee))return ee;const me={...ee};return delete me[T],me})}},[n]),Bt=a.useCallback(async T=>{j(T);try{await Zm(T),await bt(),n("Logged out","success")}catch(W){n(xe(W)||"Logout failed","error")}finally{j(null)}},[n,bt]),Lt=a.useCallback(async T=>{const W=L[T]?.trim();if(!W){G(ee=>({...ee,[T]:"API key is required"}));return}j(T),G(ee=>{const me={...ee};return delete me[T],me});try{await eh(T,W),D(ee=>{const me={...ee};return delete me[T],me}),await bt(),n("API key saved","success")}catch(ee){G(me=>({...me,[T]:xe(ee)||"Failed to save API key"}))}finally{j(null)}},[L,n,bt]),wn=a.useCallback(async T=>{j(T);try{await th(T),D(W=>{const ee={...W};return delete ee[T],ee}),G(W=>{const ee={...W};return delete ee[T],ee}),await bt(),n("API key cleared","success")}catch(W){n(xe(W)||"Failed to clear API key","error")}finally{j(null)}},[n,bt]),hn=a.useCallback(async()=>{if(!(!c.ntfyEnabled||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic))){we(!0);try{const T=c.ntfyBaseUrl?.trim();(await Rx({ntfyEnabled:c.ntfyEnabled,ntfyTopic:c.ntfyTopic,...T?{ntfyBaseUrl:T}:{}},s)).success?n("Test notification sent — check your ntfy app!","success"):n("Failed to send test notification","error")}catch(T){n(xe(T)||"Failed to send test notification","error")}finally{we(!1)}}},[n,c.ntfyBaseUrl,c.ntfyEnabled,c.ntfyTopic,s]),nn=a.useCallback(async()=>{_e(!0);try{const T=await by(s);if(T.success){n("Backup created successfully","success");const W=await td(s);rt(W)}else n(T.error||"Failed to create backup","error")}catch(T){n(xe(T)||"Failed to create backup","error")}finally{_e(!1)}},[n,s]),Pn=a.useCallback(async()=>{try{const T=C==="global"?"global":C==="project"?"project":"both",W=await xy(T,s),ee=new Blob([JSON.stringify(W,null,2)],{type:"application/json"}),me=URL.createObjectURL(ee),ke=document.createElement("a"),Re=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;ke.href=me,ke.download=Re,document.body.appendChild(ke),ke.click(),document.body.removeChild(ke),URL.revokeObjectURL(me),n(`Settings exported (${T==="global"?"global":T==="project"?"project":"all"} scope)`,"success")}catch(T){n(xe(T)||"Failed to export settings","error")}},[n,C,s]),on=a.useCallback(async T=>{const W=T.target.files?.[0];if(W){yt(W),Mt(!0);try{const ee=await W.text(),me=JSON.parse(ee);Tt(me),xt(!0)}catch(ee){n(`Invalid JSON file: ${xe(ee)}`,"error"),yt(null)}finally{Mt(!1)}}},[n]),Un=a.useCallback(async()=>{if(Ct){Mt(!0);try{const T=await vy(Ct,{scope:vt,merge:Je},s);if(T.success){const W=[];T.globalCount>0&&W.push(`${T.globalCount} global`),T.projectCount>0&&W.push(`${T.projectCount} project`),n(`Imported ${W.join(", ")} setting(s)`,"success"),xt(!1),Tt(null),yt(null);const ee=await Ki(s);u(ee)}else n(T.error||"Import failed","error")}catch(T){n(xe(T)||"Failed to import settings","error")}finally{Mt(!1)}}},[n,Ct,vt,Je,s]),gn=a.useCallback(async T=>{const W=F,me=W.includes(T)?W.filter(ke=>ke!==T):[T,...W];fe(me);try{await Kt({favoriteProviders:me,favoriteModels:V})}catch{fe(W)}},[F,V]),Zt=a.useCallback(async T=>{const W=V,me=W.includes(T)?W.filter(ke=>ke!==T):[T,...W];K(me);try{await Kt({favoriteProviders:F,favoriteModels:me})}catch{K(W)}},[V,F]);a.useEffect(()=>{const T=W=>{W.key==="Escape"&&t()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[t]);const Wt=a.useCallback(T=>{T.target===T.currentTarget&&t()},[t]),Tn=[{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 bn(T){if(!b?.project)return"inherited";const W=b.project[T.projectProviderKey],ee=b.project[T.projectModelKey];return W!==void 0||ee!==void 0?"overridden":"inherited"}function sn(T){const W=c[T.projectProviderKey],ee=c[T.projectModelKey];return W&&ee?`${W}/${ee}`:""}function Hn(T,W){if(W){const ee=W.indexOf("/");u(me=>({...me,[T.projectProviderKey]:W.slice(0,ee),[T.projectModelKey]:W.slice(ee+1)}))}else{if(bn(T)==="inherited")return;u(me=>({...me,[T.projectProviderKey]:void 0,[T.projectModelKey]:void 0}))}}function xn(T){bn(T)!=="inherited"&&u(ee=>({...ee,[T.projectProviderKey]:void 0,[T.projectModelKey]:void 0}))}const qt=a.useCallback(async()=>{if(!(k||Pe))try{const T={...c,worktreeInitCommand:c.worktreeInitCommand?.trim()||void 0,taskPrefix:c.taskPrefix?.trim()||void 0},W={};for(const[me,ke]of Object.entries(T))if(ej(me)){const Re=p?.[me];ke===void 0&&Re!==void 0?W[me]=null:W[me]=ke}const ee={};for(const[me,ke]of Object.entries(T)){if(me==="githubTokenConfigured"||me==="prAuthAvailable"||!tj(me))continue;const Re=y?.project?.[me];["planningProvider","planningModelId","validatorProvider","validatorModelId","executionProvider","executionModelId","titleSummarizerProvider","titleSummarizerModelId","defaultProviderOverride","defaultModelIdOverride","planningFallbackProvider","planningFallbackModelId","validatorFallbackProvider","validatorFallbackModelId","titleSummarizerFallbackProvider","titleSummarizerFallbackModelId"].includes(me)?ke!==Re&&(ke==null&&Re!==void 0&&Re!==null?ee[me]=null:ke!==void 0&&(ee[me]=ke)):ee[me]=ke}await Promise.all([Object.keys(W).length>0?Kt(W):Promise.resolve(),Object.keys(ee).length>0?Ca(ee,s):Promise.resolve(),Ue!==Ae.current?Ay({globalMaxConcurrent:Ue??4}):Promise.resolve()]),n("Settings saved","success"),t()}catch(T){n(xe(T),"error")}},[c,Ue,k,Pe,p,y,t,n,s]),$n=a.useCallback(async()=>{try{await Cx(He,Be,s),ne(!1),n("Memory saved","success")}catch(T){n(xe(T)||"Failed to save memory","error")}},[He,Be,s,n]),qn=a.useCallback(async()=>{tt(!0);try{const{path:T,content:W}=await Ex(He,s),ee=T??He;He!==ee&&(ce.current=!0),nt(ee),et(W),ne(!1);const{files:me}=await Bc(s);ye(me),n("Memory file compacted","success")}catch(T){n(xe(T)||"Failed to compact memory","error")}finally{tt(!1)}},[He,s,n]),Nn=a.useCallback(async()=>{be(!0),Ze(null);try{const T=await Px(mt,s);Ze(T),n(T.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",T.qmdAvailable?"success":"warning")}catch(T){n(xe(T)||"Failed to test memory retrieval","error")}finally{be(!1)}},[mt,s,n]),Dn=a.useCallback(async()=>{qe(!0);try{const T=await Ax(s);await ct(),n(T.qmdAvailable?"qmd installed successfully":"qmd install finished, but qmd is still unavailable",T.qmdAvailable?"success":"warning")}catch(T){n(xe(T)||"Failed to install qmd","error")}finally{qe(!1)}},[s,ct,n]),se=()=>{if(!Pe)return;const T=Pe.name.trim();if(!T){n("Preset name is required","error");return}const W=c.modelPresets||[];let ee;ve?ee=ve:ee=eM(T,W);const me={id:ee,name:T,executorProvider:Pe.executorProvider,executorModelId:Pe.executorModelId,validatorProvider:Pe.validatorProvider,validatorModelId:Pe.validatorModelId};u(ke=>{const Re=ke.modelPresets||[],dt=ve?Re.map(Rt=>Rt.id===ve?me:Rt):[...Re,me];return{...ke,modelPresets:dt}}),Se(null),Oe(null)},Fe=()=>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(An,{size:14})}),e.jsx("span",{children:"These settings only affect this project."})]}):null,st=()=>{switch(N){case"general":return e.jsxs(e.Fragment,{children:[Fe(),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:T=>{const W=T.target.value;u(ee=>({...ee,taskPrefix:W||void 0})),W&&!/^[A-Z]{1,10}$/.test(W)?P("Prefix must be 1–10 uppercase letters"):P(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:T=>u(W=>({...W,requirePlanApproval:T.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:T=>u(W=>({...W,showQuickChatFAB:T.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 T=c.defaultProvider&&c.defaultModelId?`${c.defaultProvider}/${c.defaultModelId}`:"",W=Tn.filter(ee=>ee.laneId!=="default");return e.jsxs(e.Fragment,{children:[Fe(),e.jsx("h4",{className:"settings-section-heading",children:"Default Model"}),z?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):J.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(Gt,{id:"defaultModel",label:"Default Model",models:J,value:T,onChange:ee=>{if(!ee)u(me=>({...me,defaultProvider:void 0,defaultModelId:void 0}));else{const me=ee.indexOf("/");u(ke=>({...ke,defaultProvider:ee.slice(0,me),defaultModelId:ee.slice(me+1)}))}},placeholder:"Use default",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt}),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(Gt,{id:"fallbackModel",label:"Fallback Model",models:J,value:c.fallbackProvider&&c.fallbackModelId?`${c.fallbackProvider}/${c.fallbackModelId}`:"",onChange:ee=>{if(!ee)u(me=>({...me,fallbackProvider:void 0,fallbackModelId:void 0}));else{const me=ee.indexOf("/");u(ke=>({...ke,fallbackProvider:ee.slice(0,me),fallbackModelId:ee.slice(me+1)}))}},placeholder:"No fallback",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt}),e.jsx("small",{children:"Used automatically if the primary default model hits a retryable provider error like rate limiting or overload."})]})]}),(()=>{const ee=J.find(me=>me.provider===c.defaultProvider&&me.id===c.defaultModelId);return ee&&!ee.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:me=>{const ke=me.target.value;u(Re=>({...Re,defaultThinkingLevel:ke||void 0}))},children:[e.jsx("option",{value:"",children:"Default"}),nj.map(me=>e.jsx("option",{value:me,children:me.charAt(0).toUpperCase()+me.slice(1)},me))]}),e.jsx("small",{children:"Controls how much reasoning effort the AI model uses. Higher levels produce better results but cost more."})]})})(),J.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."}),W.map(ee=>{const me=c[ee.globalProviderKey],ke=c[ee.globalModelKey],Re=me&&ke?`${me}/${ke}`:"";return e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`global-${ee.laneId}-model`,children:ee.label}),e.jsx(Gt,{id:`global-${ee.laneId}-model`,label:ee.label,models:J,value:Re,onChange:dt=>{if(!dt){u(pn=>({...pn,[ee.globalProviderKey]:void 0,[ee.globalModelKey]:void 0}));return}const Rt=dt.indexOf("/");u(pn=>({...pn,[ee.globalProviderKey]:dt.slice(0,Rt),[ee.globalModelKey]:dt.slice(Rt+1)}))},placeholder:"Use default",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt}),e.jsx("small",{children:ee.helperText})]},`global-${ee.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:ee=>u(me=>({...me,openrouterModelSync:ee.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 T=c.modelPresets||[],W=T.map(ke=>({id:ke.id,name:ke.name})),ee=new Set(Object.values(c.defaultPresetBySize||{}).filter(Boolean)),me=Tn.filter(ke=>ke.laneId==="execution"||ke.laneId==="planning"||ke.laneId==="validator"||ke.laneId==="summarization");return e.jsxs(e.Fragment,{children:[Fe(),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:ke=>{const Re=ke.target.value;u(dt=>({...dt,tokenCap:Re?parseInt(Re,10):null}))}}),c.tokenCap!=null&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to default (no cap)",onClick:()=>u(ke=>({...ke,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."}),z?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):J.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No models available. Configure authentication first."}):e.jsx(e.Fragment,{children:me.map(ke=>{const Re=bn(ke),dt=sn(ke),Rt=Re==="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:`${ke.laneId}Model`,children:ke.label}),e.jsx("span",{className:`settings-lane-badge ${Rt?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:Rt?"Explicitly set for this project":"Inherited from global settings",children:Rt?"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(Gt,{id:`${ke.laneId}Model`,label:ke.label,models:J,value:dt,onChange:pn=>Hn(ke,pn),placeholder:"Use global",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt})}),Rt&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to inherit from global",onClick:()=>xn(ke),style:{whiteSpace:"nowrap"},children:"Reset"})]}),e.jsxs("small",{children:[ke.helperText," Falls back to: ",ke.fallbackOrder,"."]})]},ke.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Fallback Models"}),z?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):J.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(Gt,{id:"planningFallbackModel",label:"Planning Fallback Model",models:J,value:c.planningFallbackProvider&&c.planningFallbackModelId?`${c.planningFallbackProvider}/${c.planningFallbackModelId}`:"",onChange:ke=>{if(!ke)u(Re=>({...Re,planningFallbackProvider:void 0,planningFallbackModelId:void 0}));else{const Re=ke.indexOf("/");u(dt=>({...dt,planningFallbackProvider:ke.slice(0,Re),planningFallbackModelId:ke.slice(Re+1)}))}},placeholder:"Use global fallback",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt}),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(Gt,{id:"validatorFallbackModel",label:"Validator Fallback Model",models:J,value:c.validatorFallbackProvider&&c.validatorFallbackModelId?`${c.validatorFallbackProvider}/${c.validatorFallbackModelId}`:"",onChange:ke=>{if(!ke)u(Re=>({...Re,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0}));else{const Re=ke.indexOf("/");u(dt=>({...dt,validatorFallbackProvider:ke.slice(0,Re),validatorFallbackModelId:ke.slice(Re+1)}))}},placeholder:"Use global fallback",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt}),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"}),T.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No presets configured yet."}):e.jsx("div",{className:"settings-preset-list",children:T.map(ke=>{const Re=Ro(ke),dt=`${Re.executorValue||"default"} / ${Re.validatorValue||"default"}`;return e.jsxs("div",{className:"settings-preset-item",children:[e.jsxs("div",{className:"settings-preset-item-meta",children:[e.jsx("strong",{children:ke.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:dt})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Se(ke.id),Oe({...ke})},children:"Edit"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{ee.has(ke.id)&&!confirm(`Preset "${ke.name}" is used in auto-selection. Delete it anyway?`)||(u(Rt=>({...Rt,modelPresets:(Rt.modelPresets||[]).filter(pn=>pn.id!==ke.id),defaultPresetBySize:Object.fromEntries(Object.entries(Rt.defaultPresetBySize||{}).filter(([,pn])=>pn!==ke.id))})),ve===ke.id&&(Se(null),Oe(null)))},children:"Delete"})]})]},ke.id)})}),Pe?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Se(null),Oe({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:"Add Preset"})})]}),Pe?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:Pe.name,onChange:ke=>{const Re=ke.target.value;Oe(dt=>dt&&{...dt,name:Re})}})]}),J.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(Gt,{id:"preset-executor-model",label:"Preset executor model",models:J,value:Pe.executorProvider&&Pe.executorModelId?`${Pe.executorProvider}/${Pe.executorModelId}`:"",onChange:ke=>{if(!ke){Oe(dt=>dt&&{...dt,executorProvider:void 0,executorModelId:void 0});return}const Re=ke.indexOf("/");Oe(dt=>dt&&{...dt,executorProvider:ke.slice(0,Re),executorModelId:ke.slice(Re+1)})},placeholder:"Use default",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:"Validator model"}),e.jsx(Gt,{id:"preset-validator-model",label:"Preset validator model",models:J,value:Pe.validatorProvider&&Pe.validatorModelId?`${Pe.validatorProvider}/${Pe.validatorModelId}`:"",onChange:ke=>{if(!ke){Oe(dt=>dt&&{...dt,validatorProvider:void 0,validatorModelId:void 0});return}const Re=ke.indexOf("/");Oe(dt=>dt&&{...dt,validatorProvider:ke.slice(0,Re),validatorModelId:ke.slice(Re+1)})},placeholder:"Use default",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:se,children:"Save preset"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Se(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:ke=>u(Re=>({...Re,autoSelectModelPreset:ke.target.checked}))}),"Auto-select preset based on task size"]})}),c.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(ke=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${ke}`,children:ke==="S"?"Small tasks (S):":ke==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${ke}`,value:c.defaultPresetBySize?.[ke]||"",onChange:Re=>{const dt=Re.target.value||void 0;u(Rt=>({...Rt,defaultPresetBySize:{...Rt.defaultPresetBySize||{},[ke]:dt}}))},children:[e.jsx("option",{value:"",children:"No preset"}),W.map(Re=>e.jsx("option",{value:Re.id,children:Re.name},Re.id))]})]},ke))}):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:ke=>u(Re=>({...Re,autoSummarizeTitles:ke.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"}),z?e.jsx("small",{children:"Loading available models..."}):J.length===0?e.jsx("small",{children:"No models available. Configure authentication first."}):e.jsx(Gt,{id:"titleSummarizerModel",label:"Title summarization model",models:J,value:c.titleSummarizerProvider&&c.titleSummarizerModelId?`${c.titleSummarizerProvider}/${c.titleSummarizerModelId}`:"",onChange:ke=>{if(!ke){u(dt=>({...dt,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0}));return}const Re=ke.indexOf("/");u(dt=>({...dt,titleSummarizerProvider:ke.slice(0,Re),titleSummarizerModelId:ke.slice(Re+1)}))},placeholder:"Use fallback model",favoriteProviders:F,onToggleFavorite:gn,favoriteModels:V,onToggleModelFavorite:Zt}),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(ke=>({...ke,titleSummarizerProvider:ke.planningProvider,titleSummarizerModelId:ke.planningModelId})),disabled:!c.planningProvider||!c.planningModelId,children:"Use planning model"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>u(ke=>({...ke,titleSummarizerProvider:ke.defaultProvider,titleSummarizerModelId:ke.defaultModelId})),disabled:!c.defaultProvider||!c.defaultModelId,children:"Use default model"})]})})]})]})}case"appearance":return e.jsxs(e.Fragment,{children:[Fe(),e.jsx("h4",{className:"settings-section-heading",children:"Appearance"}),e.jsx(NM,{themeMode:r,colorTheme:l,onThemeModeChange:T=>{u(W=>({...W,themeMode:T})),o?.(T)},onColorThemeChange:T=>{u(W=>({...W,colorTheme:T})),d?.(T)}})]});case"scheduling":return e.jsxs(e.Fragment,{children:[Fe(),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:Ue??"",onChange:T=>{const W=T.target.value;Ve(W===""?void 0:Number(W))}}),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:T=>{const W=T.target.value;u(ee=>({...ee,maxConcurrent:W===""?void 0:Number(W)}))}})]}),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:T=>{const W=T.target.value;u(ee=>({...ee,maxTriageConcurrent:W===""?void 0:Number(W)}))}}),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:T=>{const W=T.target.value;u(ee=>({...ee,pollIntervalMs:W===""?void 0:Number(W)}))}})]}),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:T=>{const W=T.target.value,ee=Number(W);u(me=>({...me,taskStuckTimeoutMs:W&&ee>0?ee*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:T=>u(W=>({...W,specStalenessEnabled:T.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:T=>{const W=T.target.value,ee=Number(W);u(me=>({...me,specStalenessMaxAgeMs:W!==""?ee*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:T=>u(W=>({...W,autoArchiveDoneTasksEnabled:T.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/Yu):RM,onChange:T=>{const W=T.target.value,ee=Number(W);u(me=>({...me,autoArchiveDoneAfterMs:W===""?void 0:ee*Yu}))},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:T=>u(W=>({...W,archiveAgentLogMode:T.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:T=>{const W=T.target.value,ee=Number(W);u(me=>({...me,maxStuckKills:W&&ee>0?ee: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:T=>u(W=>({...W,groupOverlappingFiles:T.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:T=>u(W=>({...W,runStepsInNewSessions:T.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:T=>{const W=T.target.value;u(ee=>({...ee,maxParallelSteps:W===""?void 0:Number(W)}))},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:[Fe(),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:T=>{const W=T.target.value;u(ee=>({...ee,maxWorktrees:W===""?void 0:Number(W)}))}}),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:T=>u(W=>({...W,worktreeInitCommand:T.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:T=>u(W=>({...W,recycleWorktrees:T.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:T=>u(W=>({...W,worktreeNaming:T.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:T=>u(W=>({...W,worktreeRebaseBeforeMerge:T.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:T=>u(W=>({...W,worktreeRebaseRemote:T.target.value||void 0})),children:[e.jsx("option",{value:"",children:"Use git default"}),ge.map(T=>e.jsxs("option",{value:T.name,children:[T.name," (",T.fetchUrl,")"]},T.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:[Fe(),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:T=>u(W=>({...W,testCommand:T.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:T=>u(W=>({...W,buildCommand:T.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:[Fe(),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:T=>u(W=>({...W,autoMerge:T.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:T=>u(W=>({...W,mergeStrategy:T.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:T=>u(W=>({...W,includeTaskIdInCommit:T.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:T=>u(W=>({...W,commitAuthorEnabled:T.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:T=>u(W=>({...W,commitAuthorName:T.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:T=>u(W=>({...W,commitAuthorEmail:T.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:T=>u(W=>({...W,autoResolveConflicts:T.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:T=>u(W=>({...W,smartConflictResolution:T.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:T=>u(W=>({...W,pushAfterMerge:T.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:T=>u(W=>({...W,pushRemote:T.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:T,status:W,loading:ee,error:me}={capabilities:q,status:at,loading:$,error:pe},ke=c.memoryEnabled!==!1,Re=T?.writable??!0,dt=ke&&Re,Rt=Te.find(kt=>kt.path===He),pn={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[Fe(),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:kt=>u(ht=>({...ht,memoryEnabled:kt.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."})]}),ee?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:"Checking memory write access..."})}):me?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Failed to load backend status: ",me]})}):null,W?.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:W.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dn,disabled:Ce,children:Ce?"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:kt=>u(ht=>({...ht,memoryAutoSummarizeEnabled:kt.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:kt=>u(ht=>({...ht,memoryAutoSummarizeThresholdChars:parseInt(kt.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:kt=>u(ht=>({...ht,memoryAutoSummarizeSchedule:kt.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:kt=>u(ht=>({...ht,memoryDreamsEnabled:kt.target.checked})),disabled:!ke}),"Process dreams from daily memory"]}),e.jsx("small",{children:"Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md."})]}),ke&&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:kt=>u(ht=>({...ht,memoryDreamsSchedule:kt.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:mt,onChange:kt=>he(kt.target.value),placeholder:"Search memory with qmd"}),e.jsx("small",{children:"Runs the same qmd-backed memory_search path agents use."})]}),e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Nn,disabled:ie,children:ie?"Testing…":"Test Retrieval"})}),Me&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[Me.results.length," result",Me.results.length===1?"":"s"," ",'for "',Me.query,'"']}),e.jsxs("small",{children:["qmd ",Me.qmdAvailable?"available":"missing"," · ",Me.usedFallback?"local fallback used":"qmd path used"]}),Me.results.length>0?e.jsx("ul",{children:Me.results.map((kt,ht)=>e.jsxs("li",{children:[e.jsxs("span",{children:[kt.path,":",kt.lineStart]}),e.jsx("p",{children:kt.snippet})]},`${kt.path}-${kt.lineStart}-${ht}`))}):e.jsx("small",{children:"No matching memory found."})]})]}),!ke&&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."}),ke&&!Re&&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:kt=>{nt(kt.target.value),ne(!1)},disabled:re,children:Te.map(kt=>e.jsxs("option",{value:kt.path,children:[kt.label," - ",kt.path]},kt.path))}),e.jsx("small",{children:re?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),Rt&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:pn[Rt.layer]}),e.jsx("strong",{children:Rt.path}),e.jsxs("small",{children:[Rt.size.toLocaleString()," bytes · updated ",new Date(Rt.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:Rt?.label||"Memory Editor"}),e.jsxs("small",{children:[Rt?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",Rt?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",Rt?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!Rt&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(Bp,{content:Be,onChange:kt=>{et(kt),ne(!0)},readOnly:!dt,filePath:He})})]})]}),!De&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qn,disabled:!dt||re||je,children:je?"Compacting…":"Compact Selected File"}),e.jsx("small",{children:re?"Save or discard edits before compacting this file.":`Compacts ${He} and writes the result back to the same file.`})]}),re&&dt&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:$n,children:"Save Memory"})}),re&&!dt&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Cannot save: ",ke?"Backend is read-only":"Memory is disabled"]})})]})}case"experimental":{const T=c.experimentalFeatures??{},ee=Array.from(new Set([...Object.keys(Qu),...Object.keys(T)])).sort((me,ke)=>me.localeCompare(ke)).map(me=>[me,T[me]===!0]);return e.jsxs(e.Fragment,{children:[Fe(),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:ee.map(([me,ke])=>e.jsxs("label",{htmlFor:`experimental-${me}`,className:"checkbox-label",children:[e.jsx("input",{id:`experimental-${me}`,type:"checkbox",checked:ke,onChange:Re=>{u(dt=>({...dt,experimentalFeatures:{...dt.experimentalFeatures??{},[me]:Re.target.checked}}))}}),e.jsx("span",{children:Qu[me]??me})]},me))})]})]})}case"backups":return e.jsxs(e.Fragment,{children:[Fe(),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:T=>u(W=>({...W,autoBackupEnabled:T.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:T=>u(W=>({...W,autoBackupSchedule:T.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:T=>{const W=T.target.value;u(ee=>({...ee,autoBackupRetention:W===""?void 0:Number(W)}))},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:T=>u(W=>({...W,autoBackupDir:T.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 (..)"})]}),Ee?e.jsx("div",{className:"settings-empty-state",children:"Loading backup info…"}):Ie?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:Ie.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:Ie.totalSize>1024*1024?`${(Ie.totalSize/(1024*1024)).toFixed(1)} MB`:`${(Ie.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:"total size"})]})]}),Ie.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:["View ",Ie.backups.length," backup(s)"]}),e.jsxs("ul",{children:[Ie.backups.slice(0,10).map(T=>e.jsxs("li",{children:[e.jsx("code",{children:T.filename}),e.jsx("span",{className:"backup-size",children:T.size>1024*1024?`${(T.size/(1024*1024)).toFixed(1)} MB`:`${(T.size/1024).toFixed(1)} KB`})]},T.filename)),Ie.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:["...and ",Ie.backups.length-10," more"]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:nn,disabled:Ee,children:Ee?"Creating…":"Backup Now"})})]});case"notifications":return e.jsxs(e.Fragment,{children:[Fe(),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:T=>u(W=>({...W,ntfyEnabled:T.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:T=>{const W=T.target.value;u(ee=>({...ee,ntfyTopic:W||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:T=>{const W=T.target.value;u(ee=>({...ee,ntfyBaseUrl:W||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:hn,disabled:de||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic),children:de?"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:T=>{const W=c.ntfyEvents??[...Di],ee=T.target.checked?W.includes("in-review")?W:[...W,"in-review"]:W.filter(me=>me!=="in-review");u(me=>({...me,ntfyEvents:ee.length>0?ee: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:T=>{const W=c.ntfyEvents??[...Di],ee=T.target.checked?W.includes("merged")?W:[...W,"merged"]:W.filter(me=>me!=="merged");u(me=>({...me,ntfyEvents:ee.length>0?ee: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:T=>{const W=c.ntfyEvents??[...Di],ee=T.target.checked?W.includes("failed")?W:[...W,"failed"]:W.filter(me=>me!=="failed");u(me=>({...me,ntfyEvents:ee.length>0?ee: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:T=>{const W=c.ntfyEvents??[...Di],ee=T.target.checked?W.includes("awaiting-approval")?W:[...W,"awaiting-approval"]:W.filter(me=>me!=="awaiting-approval");u(me=>({...me,ntfyEvents:ee.length>0?ee: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:T=>{const W=c.ntfyEvents??[...Di],ee=T.target.checked?W.includes("awaiting-user-review")?W:[...W,"awaiting-user-review"]:W.filter(me=>me!=="awaiting-user-review");u(me=>({...me,ntfyEvents:ee.length>0?ee: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:T=>{const W=c.ntfyEvents??[...Di],ee=T.target.checked?W.includes("planning-awaiting-input")?W:[...W,"planning-awaiting-input"]:W.filter(me=>me!=="planning-awaiting-input");u(me=>({...me,ntfyEvents:ee.length>0?ee: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:T=>{const W=T.target.value;u(ee=>({...ee,ntfyDashboardHost:W||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:[Fe(),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:T=>u(W=>({...W,settingsSyncEnabled:T.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:T=>u(W=>({...W,settingsSyncAuth:T.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:T=>u(W=>({...W,settingsSyncInterval:parseInt(T.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:T=>u(W=>({...W,settingsSyncConflictResolution:T.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:[Fe(),e.jsx("h4",{className:"settings-section-heading",children:"Prompts"}),e.jsx(AM,{value:c.agentPrompts,onChange:T=>{u(W=>({...W,agentPrompts:T}))},promptOverrides:c.promptOverrides,onPromptOverridesChange:T=>{u(W=>({...W,promptOverrides:T}))}})]});case"plugins":return e.jsxs(e.Fragment,{children:[Fe(),e.jsx("h4",{className:"settings-section-heading",children:"Plugins"}),e.jsx(a.Suspense,{fallback:null,children:e.jsx(PM,{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(TM,{addToast:n,projectId:s})});case"authentication":{const T=R.filter(Re=>Re.type==="cli"),ee=[...R.filter(Re=>Re.type!=="cli")].sort((Re,dt)=>Re.authenticated!==dt.authenticated?Re.authenticated?-1:1:Re.name.localeCompare(dt.name)),me=ee.filter(Re=>Re.authenticated),ke=ee.filter(Re=>!Re.authenticated);return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:"Authentication"}),Z?e.jsx("div",{className:"settings-empty-state",children:"Loading authentication status…"}):R.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No providers available"}):e.jsxs(e.Fragment,{children:[T.some(Re=>Re.id==="claude-cli")&&e.jsx(Up,{compact:!0,authenticated:T.find(Re=>Re.id==="claude-cli")?.authenticated??!1,onToggled:()=>{bt()}}),me.length===0&&e.jsx("div",{className:"auth-section-hint",children:"Sign in to at least one provider to get started with AI models."}),me.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Authenticated"}),me.map(Re=>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:Re.name}),e.jsx("span",{"data-testid":`auth-status-${Re.id}`,className:`auth-status-badge ${Re.authenticated?"authenticated":"not-authenticated"}`,children:"✓ Active"}),Re.authenticated&&Re.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",Re.keyHint]})]}),Re.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:L[Re.id]??"",onChange:dt=>D(Rt=>({...Rt,[Re.id]:dt.target.value})),disabled:_===Re.id}),Re.authenticated&&!L[Re.id]?e.jsx("button",{className:"btn btn-sm",onClick:()=>wn(Re.id),disabled:_===Re.id,children:"Clear"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt(Re.id),disabled:_===Re.id,children:"Save"})]}),_===Re.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),U[Re.id]&&e.jsx("small",{className:"auth-apikey-error",children:U[Re.id]})]}):e.jsx("div",{children:_===Re.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>Bt(Re.id),children:"Logout"})})]})},Re.id))]}),ke.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Available"}),ke.map(Re=>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:Re.name}),e.jsx("span",{"data-testid":`auth-status-${Re.id}`,className:`auth-status-badge ${Re.authenticated?"authenticated":"not-authenticated"}`,children:"✗ Not connected"})]}),Re.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:L[Re.id]??"",onChange:dt=>D(Rt=>({...Rt,[Re.id]:dt.target.value})),disabled:_===Re.id}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt(Re.id),disabled:_===Re.id,children:"Save"})]}),_===Re.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),U[Re.id]&&e.jsx("small",{className:"auth-apikey-error",children:U[Re.id]})]}):e.jsxs("div",{children:[_===Re.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt(Re.id),children:"Login"}),Q[Re.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`auth-login-instructions-${Re.id}`,children:Q[Re.id]})]})]})},Re.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:Wt,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:N,onChange:T=>A(T.target.value),children:br.filter(T=>!T.isGroupHeader).map(T=>e.jsx("option",{value:T.id,children:T.label},T.id))})]}),e.jsx("nav",{className:"settings-sidebar",children:br.map(T=>T.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:T.label},T.id):e.jsxs("button",{className:`settings-nav-item${N===T.id?" active":""}`,onClick:()=>A(T.id),title:T.scope==="global"?"Shared across all projects":T.scope==="project"?"Specific to this project":void 0,children:[T.scope==="global"&&e.jsx(vi,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),T.scope==="project"&&e.jsx(An,{className:"settings-scope-icon","aria-label":"Project setting",size:16}),T.icon&&!T.scope&&e.jsx(T.icon,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),T.label]},T.id))}),e.jsx("div",{className:"settings-content",children:st()})]}),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:Pn,title:"Export settings to JSON file",children:"Export"}),e.jsx("input",{type:"file",ref:ze,accept:".json,application/json",style:{display:"none"},onChange:on}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ze.current?.click(),disabled:Et,title:"Import settings from JSON file",children:Et?"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:qt,disabled:h,children:"Save"})]})]})]}),We&&Ct&&e.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.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:"}),Ct.global&&Object.keys(Ct.global).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:"Global Settings:"}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(Ct.global).filter(([,T])=>T!==void 0).map(([T])=>e.jsx("li",{children:T},T))})]}),Ct.project&&Object.keys(Ct.project).length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("strong",{children:"Project Settings:"}),e.jsx("ul",{className:"import-preview-list",children:Object.entries(Ct.project).filter(([,T])=>T!==void 0).map(([T])=>e.jsx("li",{children:T},T))})]}),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:T=>Ft(T.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:Je,onChange:T=>pt(T.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:Un,disabled:Et,children:Et?"Importing…":"Confirm Import"})]})]})})]})}const IM=640;function $M({isOpen:t,onClose:n,onImport:s,tasks:i,projectId:r}){const[l,o]=a.useState(""),[d,m]=a.useState(""),[c,u]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[b,x]=a.useState([]),[y,v]=a.useState(null),[M,N]=a.useState([]),[A,w]=a.useState(null),[S,k]=a.useState(null),[P,C]=a.useState(!1),[R,O]=a.useState([]),[Z,I]=a.useState(!1),[_,j]=a.useState(""),Q=a.useRef(!1),[Y,L]=a.useState(!1),[D,U]=a.useState("list"),G=a.useRef(null),E=new Set;for(const le of i){const Te=le.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Te&&E.add(Te[1]);const ye=le.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);ye&&E.add(ye[1])}a.useEffect(()=>{if(t)return o(""),m(""),u(""),x([]),v(null),N([]),w(null),f("issues"),k(null),C(!1),O([]),I(!0),j(""),G.current=null,Q.current=!0,Yx().then(le=>{if(Q.current)if(O(le),I(!1),le.length===1){const Te=le[0];o(Te.owner),m(Te.repo),j(Te.name)}else le.length>1&&(o(""),m(""),j(""))}).catch(()=>{Q.current&&I(!1)}),()=>{Q.current=!1}},[t]);const J=a.useCallback(le=>{if(j(le),le==="")o(""),m("");else{const Te=R.find(ye=>ye.name===le);Te&&(o(Te.owner),m(Te.repo))}},[R]),ue=a.useCallback(async()=>{if(!l.trim()||!d.trim()){k("Repository must be selected");return}g(!0),k(null),x([]),v(null);try{const le=c.split(",").map(ye=>ye.trim()).filter(Boolean),Te=await Wx(l.trim(),d.trim(),30,le.length>0?le:void 0);x(Te),Te.length===0&&k("No open issues found")}catch(le){k(xe(le)||"Failed to fetch issues")}finally{g(!1)}},[l,d,c]),z=a.useCallback(async()=>{if(!l.trim()||!d.trim()){k("Repository must be selected");return}g(!0),k(null),N([]),w(null);try{const le=await Gx(l.trim(),d.trim(),30);N(le),le.length===0&&k("No open pull requests found")}catch(le){k(xe(le)||"Failed to fetch pull requests")}finally{g(!1)}},[l,d]);a.useEffect(()=>{if(!t||!l.trim()||!d.trim()||h||P)return;const le={owner:l.trim(),repo:d.trim(),labels:c.trim(),tab:p};G.current?.owner===le.owner&&G.current?.repo===le.repo&&G.current?.labels===le.labels&&G.current?.tab===le.tab||(G.current=le,p==="issues"?ue():z())},[l,d,c,p,t,h,P,ue,z]),a.useEffect(()=>{if(!t)return;const le=Te=>{Te.key==="Escape"&&n()};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[t,n]),a.useEffect(()=>{if(!t)return;const le=()=>{L(window.innerWidth<=IM)};return le(),window.addEventListener("resize",le),()=>window.removeEventListener("resize",le)},[t]);const te=a.useCallback(le=>{v(le),Y&&U("preview")},[Y]),F=a.useCallback(le=>{w(le),Y&&U("preview")},[Y]),fe=a.useCallback(()=>{U("list")},[]),V=a.useCallback(async()=>{if(p==="issues"){if(y===null)return;C(!0),k(null);try{const le=await Kx(l.trim(),d.trim(),y,r);s(le),n()}catch(le){const Te=xe(le);Te?.includes("already imported")?k(Te):k(Te||"Failed to import issue")}finally{C(!1)}}else{if(A===null)return;C(!0),k(null);try{const le=await Jx(l.trim(),d.trim(),A,r);s(le),n()}catch(le){const Te=xe(le);Te?.includes("already imported")?k(Te):k(Te||"Failed to import pull request")}finally{C(!1)}}},[p,y,A,l,d,s,n]),K=b.find(le=>le.number===y),de=M.find(le=>le.number===A);if(!t)return null;const we=R.length>0,ve=R.length===1,Se=b.filter(le=>E.has(le.html_url)).length,Pe=M.filter(le=>E.has(le.html_url)).length,Oe=S==="No open issues found",Ie=S==="No open pull requests found",rt=p==="issues"?Oe:Ie,Ee=!!S&&!Oe&&b.length===0&&!h,_e=!!S&&!Ie&&M.length===0&&!h,Be=p==="issues"?Ee:_e,et=h||b.length>0||Oe||Ee,De=h||M.length>0||Ie||_e,Xe=p==="issues"?et:De,re=!!S&&b.length>0&&!Oe,ne=!!S&&M.length>0&&!Ie,ge=p==="issues"?re:ne;return e.jsx("div",{className:"modal-overlay open",onClick:le=>le.target===le.currentTarget&&n(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg github-import-modal",children:[e.jsxs("div",{className:"modal-header github-import-modal__header",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"Import from GitHub"}),e.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),e.jsxs("div",{className:"modal-body github-import-modal__body",children:[e.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[e.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{f("issues"),w(null)},disabled:h||P,children:[e.jsx(Ur,{size:16}),e.jsx("span",{children:"Issues"})]}),e.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),v(null)},disabled:h||P,children:[e.jsx(ts,{size:16}),e.jsx("span",{children:"Pull Requests"})]})]}),e.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[e.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:Z?e.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[e.jsx(lt,{size:16,className:"spin"}),e.jsx("span",{children:"Detecting…"})]}):we?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:R[0].name}),e.jsxs("span",{className:"github-import-remote-pill__repo",children:[R[0].owner,"/",R[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:le=>J(le.target.value),disabled:h||P,"aria-label":"Select Git remote",children:[e.jsx("option",{value:"",children:"Select remote…"}),R.map(le=>e.jsxs("option",{value:le.name,children:[le.name," (",le.owner,"/",le.repo,")"]},le.name))]})]}):e.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),e.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?e.jsxs(e.Fragment,{children:[e.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),e.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:c,onChange:le=>u(le.target.value),onKeyDown:le=>le.key==="Enter"&&ue(),disabled:h||P||!we,"aria-label":"Filter issues by labels"})]}):e.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",l||"selected remote"]})}),e.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:e.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?ue:z,disabled:h||P||!l.trim()||!d.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?e.jsx(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14}),e.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!Z&&!we&&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"})]}),ge&&e.jsx("div",{className:"form-error github-import-banner",role:"alert",children:S}),e.jsxs("div",{className:"github-import-workspace",children:[e.jsxs("section",{className:`github-import-list-pane ${Y?"mobile":""} ${D==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[e.jsxs("div",{className:"github-import-pane-header",children:[e.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&e.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[e.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),e.jsxs("span",{children:[Se," imported"]})]}),p==="pulls"&&M.length>0&&e.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[e.jsxs("span",{children:[M.length," pull request",M.length===1?"":"s"]}),e.jsxs("span",{children:[Pe," imported"]})]})]}),e.jsxs("div",{className:"github-import-pane-content",children:[!Xe&&e.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:e.jsxs("div",{children:[e.jsx("strong",{children:"Nothing loaded yet"}),e.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&e.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[e.jsx(lt,{size:16,className:"spin"}),e.jsxs("div",{children:[e.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),e.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),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 ",p==="issues"?"issues":"pull requests"]}),e.jsx("span",{children:S})]})}),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 ",p==="issues"?"issues":"pull requests"," found"]}),e.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(le=>{const Te=E.has(le.html_url);return e.jsxs("div",{className:`issue-item ${y===le.number?"selected":""} ${Te?"imported":""}`,onClick:()=>!Te&&te(le.number),children:[e.jsx("input",{type:"radio",name:"issue",checked:y===le.number,onChange:()=>te(le.number),disabled:Te,"aria-label":`Select issue #${le.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",le.number]}),e.jsx("span",{className:"issue-title",children:le.title})]}),le.labels.length>0&&e.jsx("span",{className:"issue-labels",children:le.labels.map(ye=>e.jsx("span",{className:"label-chip",children:ye.name},ye.name))})]}),Te&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},le.number)})}),p==="pulls"&&M.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:M.map(le=>{const Te=E.has(le.html_url);return e.jsxs("div",{className:`issue-item ${A===le.number?"selected":""} ${Te?"imported":""}`,onClick:()=>!Te&&F(le.number),children:[e.jsx("input",{type:"radio",name:"pull",checked:A===le.number,onChange:()=>F(le.number),disabled:Te,"aria-label":`Select pull request #${le.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",le.number]}),e.jsx("span",{className:"issue-title",children:le.title})]}),e.jsxs("span",{className:"pull-branch-info",children:[le.headBranch," → ",le.baseBranch]})]}),Te&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},le.number)})})]})]}),e.jsxs("section",{className:`github-import-preview-pane ${Y?"mobile":""} ${D==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[e.jsxs("div",{className:"github-import-pane-header",children:[Y&&e.jsxs("button",{className:"github-import-back-button",onClick:fe,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[e.jsx(sa,{size:16}),e.jsx("span",{children:"Back"})]}),e.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),e.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&K?e.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[e.jsxs("div",{className:"preview-meta",children:["Issue #",K.number]}),e.jsx("div",{className:"preview-title",children:K.title}),e.jsx("div",{className:"preview-body",children:K.body?K.body.slice(0,200)+(K.body.length>200?"…":""):"(no description)"})]}):p==="issues"?e.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:e.jsxs("div",{children:[e.jsx("strong",{children:"No issue selected"}),e.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&de?e.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[e.jsxs("div",{className:"preview-meta",children:["Pull Request #",de.number]}),e.jsx("div",{className:"preview-title",children:de.title}),e.jsxs("div",{className:"preview-branch",children:[e.jsx("strong",{children:"Branch:"})," ",de.headBranch," → ",de.baseBranch]}),e.jsx("div",{className:"preview-body",children:de.body?de.body.slice(0,200)+(de.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?e.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:e.jsxs("div",{children:[e.jsx("strong",{children:"No pull request selected"}),e.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),e.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[e.jsx("button",{className:"btn",onClick:n,disabled:P,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:V,disabled:(p==="issues"?y===null:A===null)||P,children:P?e.jsx(lt,{size:14,className:"spin"}):"Import"})]})]})})}const DM=["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 FM(t,n){return t&&n?`${t}/${n}`:""}function LM(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 zM({isOpen:t,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:l,projectId:o,resumeSessionId:d}){const[m,c]=a.useState(""),[u,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,b]=a.useState([]),[x,y]=a.useState([]),[v,M]=a.useState(null),N=a.useRef(!1),[A,w]=a.useState(""),[S,k]=a.useState(!0),[P,C]=a.useState(!1),[R,O]=a.useState(!1),Z=a.useRef(null),I=a.useRef(null),_=a.useRef(null),[j,Q]=a.useState(d??null),Y=a.useMemo(()=>Si(),[]),{isLockedByOther:L,takeControl:D,isLoading:U}=Qr(t?j:null),{activeTabMap:G,broadcastUpdate:E,broadcastCompleted:J,broadcastLock:ue,broadcastUnlock:z,broadcastHeartbeat:te}=ra(),[F,fe]=a.useState(void 0),[V,K]=a.useState(void 0),[de,we]=a.useState([]),[ve,Se]=a.useState(!1),[Pe,Oe]=a.useState(null),[Ie,rt]=a.useState([]),[Ee,_e]=a.useState([]),Be=a.useRef(null),et=FM(F,V),De=a.useCallback((ce,Ue)=>{if(!ce||!Ue)return"Using default";const Ve=de.find(Ae=>Ae.provider===ce&&Ae.id===Ue);return Ve?`${Ve.provider}/${Ve.id}`:`${ce}/${Ue}`},[de]),Xe=a.useCallback(async()=>{Se(!0),Oe(null);try{const ce=await Jn();we(ce.models),rt(ce.favoriteProviders),_e(ce.favoriteModels)}catch(ce){Oe(xe(ce)||"Failed to load models")}finally{Se(!1)}},[]),re=a.useCallback(ce=>{rt(Ue=>{const Ve=Ue,We=Ve.includes(ce)?Ve.filter(xt=>xt!==ce):[ce,...Ve];return Kt({favoriteProviders:We,favoriteModels:Ee}).catch(()=>{rt(Ve)}),We})},[Ee]),ne=a.useCallback(ce=>{_e(Ue=>{const Ve=Ue,We=Ve.includes(ce)?Ve.filter(xt=>xt!==ce):[ce,...Ve];return Kt({favoriteProviders:Ie,favoriteModels:We}).catch(()=>{_e(Ve)}),We})},[Ie]),ge=a.useCallback(ce=>{I.current?.close();const Ue=Kv(ce,o,{onThinking:Ve=>{w(Ae=>Ae+Ve),E({sessionId:ce,status:"generating",needsInput:!1,owningTabId:Y,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onQuestion:Ve=>{C(!1),O(!1),Ri(o),h({type:"question",session:{sessionId:ce,currentQuestion:Ve,summary:null}}),w(""),E({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:Y,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onSummary:Ve=>{C(!1),O(!1),Ri(o),h({type:"summary",session:{sessionId:ce,currentQuestion:null,summary:Ve},summary:Ve}),M(Ve),w(""),E({sessionId:ce,status:"complete",needsInput:!1,owningTabId:Y,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onError:Ve=>{const Ae=Ve||"Session failed while contacting the AI.";C(!1),O(!1),p(null),h(We=>We.type==="question"||We.type==="summary"||We.type==="error"?{type:"error",session:We.session,errorMessage:Ae}:{type:"error",session:{sessionId:ce,currentQuestion:null,summary:null},errorMessage:Ae}),w(""),_.current=ce,E({sessionId:ce,status:"error",needsInput:!1,owningTabId:Y,type:"planning",title:m.trim()||"Planning session",projectId:o??null}),J({sessionId:ce,status:"error"})},onComplete:()=>{C(!1),O(!1),_.current=null,J({sessionId:ce,status:"complete"})},onConnectionStateChange:Ve=>{C(Ve==="reconnecting")}});I.current=Ue},[J,E,m,o,Y]),le=a.useCallback(async ce=>{const Ue=ce??m;if(Ue.trim()){p(null),w(""),y([]),b([]),C(!1),h({type:"loading"});try{const Ve=F&&V?{planningModelProvider:F,planningModelId:V}:void 0,{sessionId:Ae}=await Tv(Ue.trim(),o,Ve);_.current=Ae,Q(Ae),ge(Ae),b([])}catch(Ve){C(!1),p(xe(Ve)||"Failed to start planning session"),h({type:"initial"}),_.current=null,Q(null)}}},[ge,m,V,F,o]);a.useEffect(()=>{t&&u.type==="initial"&&Z.current?.focus()},[t,u.type]),a.useEffect(()=>{t&&Xe()},[t,Xe]),a.useEffect(()=>{if(t&&l&&!N.current&&u.type==="initial"){c(l);const ce=setTimeout(()=>{N.current=!0,le(l)},0);return()=>clearTimeout(ce)}else if(t&&!l&&!N.current&&u.type==="initial"){const ce=Mw(o);ce&&c(ce)}},[t,l,u.type,le]),a.useEffect(()=>{if(!t||!d||u.type!=="initial")return;let ce=!1;return(async()=>{try{const Ue=await ti(d);if(ce||!Ue)return;_.current=d,Q(d);const Ve=Ji(Ue.conversationHistory);if(y(Ve),b(Ve.map(Ae=>Ae.response).filter(Ae=>!!(Ae&&typeof Ae=="object"&&!Array.isArray(Ae)))),Ue.status==="awaiting_input"&&Ue.currentQuestion){Ri(o);const Ae=JSON.parse(Ue.currentQuestion);h({type:"question",session:{sessionId:d,currentQuestion:Ae,summary:null}}),Ue.thinkingOutput&&w(Ue.thinkingOutput),ge(d)}else if(Ue.status==="complete"&&Ue.result){Ri(o);const Ae=JSON.parse(Ue.result);h({type:"summary",session:{sessionId:d,currentQuestion:null,summary:Ae},summary:Ae}),M(Ae)}else Ue.status==="generating"?(h({type:"loading"}),Ue.thinkingOutput&&w(Ue.thinkingOutput),ge(d)):Ue.status==="error"&&(p(null),h({type:"error",session:{sessionId:d,currentQuestion:null,summary:null},errorMessage:Ue.error||"Session failed"}))}catch{p("Failed to resume session")}})(),()=>{ce=!0}},[ge,t,d,u.type,o]),a.useEffect(()=>{t||(N.current=!1,C(!1),O(!1),Q(null))},[t]),a.useEffect(()=>{if(!t){Be.current&&(z(Be.current,Y),Be.current=null);return}if(j&&Be.current!==j){Be.current&&z(Be.current,Y),ue(j,Y),Be.current=j;return}!j&&Be.current&&(z(Be.current,Y),Be.current=null)},[ue,z,t,j,Y]),a.useEffect(()=>{if(!t||!j||Be.current!==j)return;te(Y);const ce=setInterval(()=>{te(Y)},3e4);return()=>{clearInterval(ce)}},[te,t,j,Y]),a.useEffect(()=>()=>{I.current?.close(),I.current=null,Be.current&&(z(Be.current,Y),Be.current=null)},[z,Y]),a.useEffect(()=>{if(!t)return;const ce=()=>{I.current?.close(),I.current=null};return window.addEventListener("beforeunload",ce),()=>window.removeEventListener("beforeunload",ce)},[t]);const Te=a.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),ye=a.useCallback(()=>{let ce=null;u.type==="question"||u.type==="summary"||u.type==="error"?ce=u.session.sessionId:u.type==="breakdown"?ce=u.sessionId:u.type==="loading"&&(ce=_.current),m&&Ew(m,o),I.current?.close(),I.current=null,ce&&ih(ce,o,Y).catch(()=>{}),c(""),h({type:"initial"}),p(null),b([]),y([]),M(null),w(""),C(!1),O(!1),fe(void 0),K(void 0),_.current=null,Q(null),n()},[m,n,o,Y,u]);a.useEffect(()=>{if(!t)return;const ce=Ue=>{Ue.key==="Escape"&&ye()};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[t,ye]);const He=a.useCallback(async ce=>{if(u.type!=="question")return;const{session:Ue}=u,Ve=Ue.sessionId,Ae=Ue.currentQuestion;if(!Ae){p("No active question in session");return}p(null),b(We=>[...We,ce]),y(We=>[...We,{question:Ae,response:ce}]),h({type:"loading"}),w("");try{await Rv(Ve,ce,o,Y)}catch(We){p(xe(We)||"Failed to submit response"),h({type:"question",session:Ue})}},[o,Y,u]),nt=a.useCallback(async()=>{if(u.type!=="error")return;const ce=u.session;p(null),O(!0),w(""),h({type:"loading"}),ge(ce.sessionId);try{_.current=ce.sessionId,Q(ce.sessionId),await _v(ce.sessionId,o,Y)}catch(Ue){let Ve=Ue;if((xe(Ue)||"").includes("not in an error state"))try{const We=await ti(ce.sessionId);if(!We)throw new Error("Failed to refresh planning session.");if(_.current=We.id,Q(We.id),We.status==="generating")w(We.thinkingOutput??""),h({type:"loading"});else if(We.status==="awaiting_input"){if(!We.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const xt=JSON.parse(We.currentQuestion);Ri(o),h({type:"question",session:{sessionId:We.id,currentQuestion:xt,summary:null}}),I.current?.isConnected()||ge(We.id)}else if(We.status==="complete"){if(!We.result)throw new Error("Planning session is complete but has no result.");const xt=JSON.parse(We.result);Ri(o),h({type:"summary",session:{sessionId:We.id,currentQuestion:null,summary:xt},summary:xt}),M(xt)}else We.status==="error"&&h({type:"error",session:{sessionId:We.id,currentQuestion:null,summary:null},errorMessage:We.error||"Retry failed. Please try again."});C(!1);return}catch(We){Ve=We}I.current?.close(),I.current=null,h({type:"error",session:ce,errorMessage:xe(Ve)||"Retry failed. Please try again."}),C(!1)}finally{O(!1)}},[ge,o,Y,u]),mt=a.useCallback(async()=>{if(u.type==="summary"){p(null),h({type:"loading"});try{const ce=await Iv(u.session.sessionId,v??void 0,o);s(ce),ye()}catch(ce){p(xe(ce)||"Failed to create task"),h({type:"summary",session:u.session,summary:u.summary})}}},[v,u,o,s,ye]),he=a.useCallback(async()=>{if(u.type==="summary"){p(null),h({type:"loading"});try{const ce=await $v(u.session.sessionId,v??void 0,o);Q(ce.sessionId),h({type:"breakdown",sessionId:ce.sessionId,subtasks:ce.subtasks,dirty:!1})}catch(ce){p(xe(ce)||"Failed to start breakdown"),h({type:"summary",session:u.session,summary:u.summary})}}},[v,u,o]),ie=a.useCallback(async()=>{if(u.type==="breakdown"){p(null),h({type:"creating"});try{const ce=await Dv(u.sessionId,u.subtasks,o);i(ce.tasks),c(""),h({type:"initial"}),p(null),b([]),y([]),M(null),w(""),fe(void 0),K(void 0),_.current=null,Q(null),n()}catch(ce){p(xe(ce)||"Failed to create tasks"),h({type:"breakdown",sessionId:u.sessionId,subtasks:u.subtasks,dirty:u.dirty})}}},[u,i,n,o]),be=a.useCallback(()=>{if(u.type==="question"&&f.length>0){const ce=f.slice(0,-1);b(ce),h({type:"question",session:u.session})}},[u,f]),Me=()=>u.type==="question"?Math.min(f.length+1,3):3,Ze=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",je=j?G.get(j):null,tt=je&&je.tabId!==Y,Ce=!!(tt&&!je.stale),qe=L&&(!tt||je.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&ye(),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:[Ze&&e.jsx("button",{className:"modal-send-to-background",onClick:Te,title:"Send to background","aria-label":"Send to background",children:e.jsx(Ks,{size:16})}),e.jsx("button",{className:"modal-close",onClick:ye,"aria-label":"Close",children:e.jsx(Dt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[g&&e.jsx("div",{className:"form-error planning-error",children:g}),P&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ce&&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:Z,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:m,onChange:ce=>c(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"&&!ce.shiftKey&&m.trim()&&(ce.preventDefault(),le())}})]}),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:DM.map((ce,Ue)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>c(ce),children:ce.length>40?ce.slice(0,40)+"...":ce},Ue))})]}),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(Gt,{id:"planning-modal-model",label:"Planning Model",value:et,onChange:ce=>{const{provider:Ue,modelId:Ve}=LM(ce);fe(Ue),K(Ve)},models:de,disabled:ve,favoriteProviders:Ie,onToggleFavorite:re,favoriteModels:Ee,onToggleModelFavorite:ne}),Pe&&e.jsxs("div",{className:"form-hint form-hint-error",children:[Pe," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{Xe()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${F&&V?"model-badge-custom":"model-badge-default"}`,children:De(F,V)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>le(),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(lt,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:A?"AI is thinking...":"Generating next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>k(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&A&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:A})})]})]}),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(Ns,{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 nt(),disabled:R,children:[R?e.jsx(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:ye,disabled:R,children:"Dismiss"})]})]})]})}),u.type==="creating"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(lt,{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(OM,{question:u.session.currentQuestion,progress:Me(),historyEntries:x,onSubmit:He,onBack:f.length>0?be:void 0})}),u.type==="summary"&&v&&e.jsx(BM,{summary:v,historyEntries:x,onSummaryChange:M,tasks:r,onCreateTask:mt,onBreakIntoTasks:he,onRefine:()=>{h({type:"question",session:u.session})},isLoading:!1}),u.type==="breakdown"&&e.jsx(HM,{subtasks:u.subtasks,dirty:u.dirty,isLoading:!1,onUpdateSubtasks:ce=>h({...u,subtasks:ce,dirty:!0}),onCreateTasks:ie,onBack:()=>{const Ue={sessionId:u.sessionId,currentQuestion:null,summary:v??null};v&&h({type:"summary",session:Ue,summary:v})}}),L&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(qr,{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:()=>{D()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function OM({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(Ns,{entries:s}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-question-panel",children:[e.jsxs("div",{className:"planning-progress",children:[e.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>e.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),e.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),e.jsxs("div",{className:"planning-question-content",children:[e.jsx("h4",{className:"planning-question-text",children:t.question}),t.description&&e.jsx("p",{className:"planning-question-desc",children:t.description}),e.jsxs("div",{className:"planning-options",children:[t.type==="text"&&e.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:d,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&d.trim()&&(h.preventDefault(),c())}}),t.type==="single_select"&&t.options&&e.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:t.options.map(h=>e.jsxs("label",{className:"planning-option planning-option--radio",children:[e.jsx("input",{type:"radio",name:t.id,value:h.id,checked:l[t.id]===h.id,onChange:()=>o({[t.id]:h.id})}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&e.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),t.type==="multi_select"&&t.options&&e.jsx("div",{className:"planning-checkbox-group",children:t.options.map(h=>{const g=l[t.id]||[];return e.jsxs("label",{className:"planning-option planning-option--checkbox",children:[e.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(b=>b!==h.id);o({[t.id]:f})}}),e.jsxs("div",{className:"planning-option-content",children:[e.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&e.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),t.type==="confirm"&&e.jsxs("div",{className:"planning-confirm-group",children:[e.jsxs("button",{className:`planning-confirm-btn ${l[t.id]===!0?"selected":""}`,onClick:()=>o({[t.id]:!0}),children:[e.jsx(tn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${l[t.id]===!1?"selected":""}`,onClick:()=>o({[t.id]:!1}),children:[e.jsx(Dt,{size:18}),"No"]})]})]})]})]})]}),e.jsxs("div",{className:"planning-actions",children:[r&&e.jsxs("button",{className:"btn",onClick:r,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Back"]}),e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:c,disabled:!u(),children:["Continue",e.jsx(Oa,{size:16,className:"icon-ml-4"})]})]})]})}function BM({summary:t,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:l,onRefine:o,isLoading:d}){const[m,c]=a.useState(!1),[u,h]=a.useState(t.suggestedDependencies),g=p=>{const f=u.includes(p)?u.filter(b=>b!==p):[...u,p];h(f),s({...t,suggestedDependencies:f})};return e.jsxs("div",{className:"planning-summary",children:[e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(tn,{size:24,className:"icon-success"}),e.jsx("h4",{children:"Planning Complete!"}),e.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),e.jsxs("div",{className:"planning-summary-form",children:[e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{children:["Description",e.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>c(!m),children:m?"Collapse":"Expand"})]}),e.jsx("textarea",{className:`planning-textarea ${m?"expanded":""}`,rows:m?10:4,value:t.description,onChange:p=>s({...t,description:p.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Suggested Size"}),e.jsxs("select",{className:"planning-size-select",value:t.suggestedSize,onChange:p=>s({...t,suggestedSize:p.target.value}),disabled:d,children:[e.jsx("option",{value:"S",children:"S (Small)"}),e.jsx("option",{value:"M",children:"M (Medium)"}),e.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Suggested Dependencies"}),e.jsx("div",{className:"planning-deps-list",children:i.map(p=>e.jsxs("label",{className:`planning-dep-chip ${u.includes(p.id)?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:u.includes(p.id),onChange:()=>g(p.id)}),e.jsx("span",{className:"planning-dep-id",children:p.id}),e.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Key Deliverables"}),e.jsx("ul",{className:"planning-deliverables",children:t.keyDeliverables.map((p,f)=>e.jsx("li",{children:p},f))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:o,disabled:d,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Refine Further"]}),e.jsxs("div",{className:"planning-summary-actions-right",children:[e.jsx("button",{className:"btn",onClick:l,disabled:d,title:"Break the plan into multiple tasks with dependencies",children:d?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Hr,{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(lt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(tn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function Xu(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 UM(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function HM({subtasks:t,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:l}){const[o,d]=a.useState(null),[m,c]=a.useState(null),[u,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>t.length===0||t.some(S=>!S.title.trim())?!0:Xu(t),[t]),f=a.useCallback((S,k)=>{i(t.map(P=>P.id===S?{...P,...k}:P))},[t,i]),b=a.useCallback(()=>{i([...t,UM(t.length+1)])},[t,i]),x=a.useCallback(S=>{i(t.filter(k=>k.id!==S).map(k=>({...k,dependsOn:k.dependsOn.filter(P=>P!==S)})))},[t,i]),y=a.useCallback((S,k)=>{if(k<0||k>=t.length)return;const P=[...t],[C]=P.splice(S,1);P.splice(k,0,C),i(P)},[t,i]),v=a.useCallback(S=>k=>{d(S),k.dataTransfer.setData("text/plain",S),k.dataTransfer.effectAllowed="move"},[]),M=a.useCallback(()=>{d(null),c(null),h(null)},[]),N=a.useCallback(S=>k=>{if(k.preventDefault(),S===o)return;const P=k.currentTarget.getBoundingClientRect(),C=P.top+P.height/2,R=k.clientY<C?"before":"after";c(S),h(R)},[o]),A=a.useCallback(S=>k=>{k.preventDefault();const P=k.dataTransfer.getData("text/plain");if(!P||P===S){M();return}const C=t.findIndex(_=>_.id===P),R=t.findIndex(_=>_.id===S);if(C===-1||R===-1){M();return}const O=[...t],[Z]=O.splice(C,1);let I=R;u==="after"&&C<R&&I--,u==="after"&&I++,O.splice(I,0,Z),i(O),M()},[t,u,i,M]),w=a.useCallback(S=>{const k=S.currentTarget.getBoundingClientRect(),P=S.clientX,C=S.clientY;(P<k.left||P>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(Hr,{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((S,k)=>{const P=o===S.id,C=m===S.id,R=["task-detail-section","subtask-item",P?"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:R,"data-testid":`subtask-item-${k}`,draggable:!s,onDragStart:v(S.id),onDragEnd:M,onDragOver:N(S.id),onDrop:A(S.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(Bo,{size:16}),e.jsx("strong",{children:S.id})]}),e.jsxs("div",{className:"subtask-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>y(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:()=>y(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(S.id),disabled:s,children:[e.jsx(Ht,{size:14})," Remove"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title"}),e.jsx("input",{ref:O=>{g.current[k]=O},value:S.title,onChange:O=>f(S.id,{title:O.target.value}),onKeyDown:O=>{O.key==="Enter"&&(O.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:S.description,onChange:O=>f(S.id,{description:O.target.value}),disabled:s})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Size"}),e.jsxs("select",{className:"planning-size-select",value:S.suggestedSize,onChange:O=>f(S.id,{suggestedSize:O.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(O=>O.id!==S.id).map(O=>{const Z=S.dependsOn.includes(O.id);return e.jsxs("label",{className:`planning-dep-chip ${Z?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:Z,onChange:()=>{const I=Z?S.dependsOn.filter(_=>_!==O.id):[...S.dependsOn,O.id];f(S.id,{dependsOn:I})},disabled:s}),e.jsx("span",{className:"planning-dep-id",children:O.id}),e.jsx("span",{className:"planning-dep-title",children:O.title||"Untitled"})]},O.id)}),k===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),k>0&&t.slice(0,k).filter(O=>O.id!==S.id).length===0&&e.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},S.id)}),e.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[e.jsx(Vt,{size:16,className:"icon-mr-6"})," Add subtask"]}),Xu(t)&&e.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:l,disabled:s,children:[e.jsx(sa,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),e.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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 Zu(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 VM({isOpen:t,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:l,resumeSessionId:o}){const[d,m]=a.useState({type:"initial"}),[c,u]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[b,x]=a.useState(!0),[y,v]=a.useState(!1),[M,N]=a.useState(!1),[A,w]=a.useState(s),[S,k]=a.useState(null),[P,C]=a.useState(!1),[R,O]=a.useState(null),[Z,I]=a.useState(null),[_,j]=a.useState(null),Q=a.useRef(null),Y=a.useRef([]),L=a.useRef(!1),D=a.useRef(null),U=d.type==="generating"||d.type==="editing"||d.type==="creating"||d.type==="error"?d.sessionId:null,G=a.useMemo(()=>Si(),[]),{isLockedByOther:E,takeControl:J,isLoading:ue}=Qr(t?U:null),{activeTabMap:z,broadcastUpdate:te,broadcastCompleted:F,broadcastLock:fe,broadcastUnlock:V,broadcastHeartbeat:K}=ra(),de=a.useMemo(()=>c.length===0||c.some(he=>!he.title.trim())?!0:Zu(c),[c]),we=d.type==="generating"||d.type==="editing"||d.type==="error",ve=U?z.get(U):null,Se=ve&&ve.tabId!==G,Pe=!!(Se&&!ve.stale),Oe=E&&(!Se||ve.stale),Ie=a.useCallback(()=>{A&&Aw(A,l),Q.current?.close(),Q.current=null,m({type:"initial"}),u([]),g([]),f(""),x(!0),v(!1),N(!1),k(null),C(!1),L.current=!1},[A,l]),rt=a.useCallback(()=>{Q.current?.close(),Q.current=null,n()},[n]),Ee=a.useCallback(async()=>{if(!((P||d.type==="editing"||d.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(U)try{await lh(U,l,G)}catch{}Ie(),n()}},[P,n,Ie,U,G,d.type,l]),_e=a.useCallback(he=>{Q.current?.close(),Q.current=cy(he,l,{onThinking:ie=>{f(be=>be+ie),te({sessionId:he,status:"generating",needsInput:!1,owningTabId:G,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:l??null})},onSubtasks:ie=>{v(!1),N(!1),bl(l),u(ie),m({type:"editing",sessionId:he}),C(!1),te({sessionId:he,status:"awaiting_input",needsInput:!0,owningTabId:G,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:l??null})},onError:ie=>{const be=ie||"Session failed while contacting the AI.";v(!1),N(!1),k(null),m({type:"error",sessionId:he,errorMessage:be}),te({sessionId:he,status:"error",needsInput:!1,owningTabId:G,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:l??null}),F({sessionId:he,status:"error"})},onComplete:()=>{F({sessionId:he,status:"complete"})},onConnectionStateChange:ie=>{v(ie==="reconnecting")}})},[F,te,A,l,G]),Be=a.useCallback(async()=>{if(A.trim()){k(null),g([]),f(""),v(!1);try{const{sessionId:he}=await ry(A.trim(),l);m({type:"generating",sessionId:he}),_e(he)}catch(he){k(xe(he)||"Failed to start subtask breakdown"),m({type:"initial"})}}},[_e,A,l]);a.useEffect(()=>{if(!t){Ie();return}if(t&&s&&!L.current)w(s),L.current=!0,Be();else if(t&&!s&&!L.current){const he=Pw(l);he&&w(he)}},[t,s,Be,Ie]),a.useEffect(()=>{!t||!o||d.type!=="initial"||(async()=>{try{const he=await ti(o);if(!he)return;const ie=Ji(he.conversationHistory);if(g(ie),he.status==="generating"||he.status==="awaiting_input")f(he.thinkingOutput??""),m({type:"generating",sessionId:o}),_e(o);else if(he.status==="complete"&&he.result){bl(l);const be=JSON.parse(he.result);u(be),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(xe(he)||"Failed to resume session")}})()},[_e,t,o,d.type,l]),a.useEffect(()=>{if(!t){D.current&&(V(D.current,G),D.current=null);return}if(U&&D.current!==U){D.current&&V(D.current,G),fe(U,G),D.current=U;return}!U&&D.current&&(V(D.current,G),D.current=null)},[fe,V,t,U,G]),a.useEffect(()=>{if(!t||!U||D.current!==U)return;K(G);const he=setInterval(()=>{K(G)},3e4);return()=>{clearInterval(he)}},[K,t,U,G]),a.useEffect(()=>()=>{Q.current?.close(),D.current&&(V(D.current,G),D.current=null)},[V,G]),a.useEffect(()=>{if(!t)return;const he=ie=>{ie.key==="Escape"&&(ie.preventDefault(),Ee())};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[t,Ee]);const et=a.useCallback((he,ie)=>{u(be=>be.map(Me=>Me.id===he?{...Me,...ie}:Me)),C(!0)},[]),De=a.useCallback(()=>{u(he=>[...he,qM(he.length+1)]),C(!0)},[]),Xe=a.useCallback(he=>{u(ie=>ie.filter(be=>be.id!==he).map(be=>({...be,dependsOn:be.dependsOn.filter(Me=>Me!==he)}))),C(!0)},[]),re=a.useCallback(he=>ie=>{O(he),ie.dataTransfer.setData("text/plain",he),ie.dataTransfer.effectAllowed="move"},[]),ne=a.useCallback(()=>{O(null),I(null),j(null)},[]),ge=a.useCallback(he=>ie=>{if(ie.preventDefault(),he===R)return;const be=ie.currentTarget.getBoundingClientRect(),Me=be.top+be.height/2,Ze=ie.clientY<Me?"before":"after";I(he),j(Ze)},[R]),le=a.useCallback(he=>ie=>{ie.preventDefault();const be=ie.dataTransfer.getData("text/plain");if(!be||be===he){O(null),I(null),j(null);return}u(Me=>{const Ze=Me.findIndex(ce=>ce.id===be),je=Me.findIndex(ce=>ce.id===he);if(Ze===-1||je===-1)return Me;const tt=[...Me],[Ce]=tt.splice(Ze,1);let qe=je;return _==="after"&&Ze<je&&qe--,_==="after"&&qe++,tt.splice(qe,0,Ce),tt}),C(!0),O(null),I(null),j(null)},[_]),Te=a.useCallback(he=>{const ie=he.currentTarget.getBoundingClientRect(),be=he.clientX,Me=he.clientY;(be<ie.left||be>ie.right||Me<ie.top||Me>ie.bottom)&&(I(null),j(null))},[]),ye=a.useCallback((he,ie)=>{ie<0||ie>=c.length||(u(be=>{const Me=[...be],[Ze]=Me.splice(he,1);return Me.splice(ie,0,Ze),Me}),C(!0))},[c.length]),He=a.useCallback(he=>{Y.current[he+1]?.focus()},[]),nt=a.useCallback(async()=>{if(!(!U||de)){k(null),m({type:"creating",sessionId:U});try{const he=await dy(U,c,r,l);i(he.tasks),Ie(),n()}catch(he){k(xe(he)||"Failed to create tasks"),m({type:"editing",sessionId:U})}}},[de,n,i,r,l,Ie,U,c]),mt=a.useCallback(async()=>{if(d.type!=="error")return;const he=d.sessionId;k(null),N(!0),f(""),m({type:"generating",sessionId:he}),_e(he);try{await ly(he,l,G)}catch(ie){let be=ie;if((xe(ie)||"").includes("not in an error state"))try{const Ze=await ti(he);if(!Ze)throw new Error("Failed to refresh subtask session.");if(g(Ji(Ze.conversationHistory)),Ze.status==="generating"||Ze.status==="awaiting_input")f(Ze.thinkingOutput??""),m({type:"generating",sessionId:Ze.id}),Q.current?.isConnected()||_e(Ze.id);else if(Ze.status==="complete"){if(!Ze.result)throw new Error("Subtask session is complete but has no result.");bl(l);const je=JSON.parse(Ze.result);u(je),m({type:"editing",sessionId:Ze.id}),C(!1)}else Ze.status==="error"&&m({type:"error",sessionId:Ze.id,errorMessage:Ze.error??"Retry failed. Please try again."});v(!1);return}catch(Ze){be=Ze}Q.current?.close(),Q.current=null,m({type:"error",sessionId:he,errorMessage:xe(be)||"Retry failed. Please try again."}),v(!1)}finally{N(!1)}},[_e,l,G,d]);return t?e.jsx("div",{className:"modal-overlay open",onClick:he=>he.target===he.currentTarget&&void Ee(),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(Hr,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Subtask Breakdown"})]}),e.jsxs("div",{className:"modal-header-actions",children:[we&&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 Ee(),"aria-label":"Close",children:e.jsx(Dt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[S&&e.jsx("div",{className:"form-error planning-error",children:S}),y&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Pe&&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:A})]})}),d.type==="generating"&&e.jsxs("div",{className:"planning-loading",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{entries:h,defaultShowThinking:!0}),e.jsx("div",{className:"conversation-separator"})]}),e.jsx(lt,{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&&p&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:p})})]})]}),d.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ns,{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 mt(),disabled:M,children:[M?e.jsx(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:M?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:()=>void Ee(),disabled:M,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(Ns,{entries:h}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(tn,{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,ie)=>{const be=R===he.id,Me=Z===he.id,Ze=["task-detail-section","subtask-item",be?"subtask-item-dragging":"",Me?"subtask-item-drop-target":"",Me&&_==="before"?"subtask-item-drop-before":"",Me&&_==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:Ze,"data-testid":`subtask-item-${ie}`,draggable:d.type!=="creating",onDragStart:re(he.id),onDragEnd:ne,onDragOver:ge(he.id),onDrop:le(he.id),onDragLeave:Te,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(Bo,{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:()=>ye(ie,ie-1),disabled:d.type==="creating"||ie===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:()=>ye(ie,ie+1),disabled:d.type==="creating"||ie===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:()=>Xe(he.id),disabled:d.type==="creating",children:[e.jsx(Ht,{size:14})," Remove"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title"}),e.jsx("input",{ref:je=>{Y.current[ie]=je},value:he.title,onChange:je=>et(he.id,{title:je.target.value}),onKeyDown:je=>{je.key==="Enter"&&(je.preventDefault(),He(ie))},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:je=>et(he.id,{description:je.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:je=>et(he.id,{suggestedSize:je.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,ie).filter(je=>je.id!==he.id).map(je=>{const tt=he.dependsOn.includes(je.id);return e.jsxs("label",{className:`planning-dep-chip ${tt?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:tt,onChange:()=>{const Ce=tt?he.dependsOn.filter(qe=>qe!==je.id):[...he.dependsOn,je.id];et(he.id,{dependsOn:Ce})},disabled:d.type==="creating"}),e.jsx("span",{className:"planning-dep-id",children:je.id}),e.jsx("span",{className:"planning-dep-title",children:je.title||"Untitled"})]},je.id)}),ie===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),ie>0&&c.slice(0,ie).filter(je=>je.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(Vt,{size:16,className:"icon-mr-6"})," Add subtask"]}),Zu(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 Ee(),disabled:d.type==="creating",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void nt(),disabled:d.type==="creating"||de,children:d.type==="creating"?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):e.jsx(e.Fragment,{children:"Create Tasks"})})]})]}),E&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(qr,{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:()=>{J()},disabled:ue,className:"btn btn-primary session-lock-take-control",children:ue?"Taking control...":"Take Control"})]})})]})]})}):null}const WM=5,KM=1e3,GM=45e3;function xr(){return{scrollback:null,connected:null,data:[]}}function JM(t,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),l=a.useRef(t),o=a.useRef(n),d=l.current!==t||o.current!==n;d&&(l.current=t,o.current=n,r.current++);const m=a.useRef(null),c=a.useRef(0),u=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),b=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(new Set),v=a.useRef(xr()),M=a.useCallback(I=>{p.current.add(I);const _=v.current;return _.data.length>0&&(_.data.forEach(j=>I(j)),_.data=[]),()=>p.current.delete(I)},[]),N=a.useCallback(I=>(f.current.add(I),()=>f.current.delete(I)),[]),A=a.useCallback(I=>{b.current.add(I);const _=v.current;return _.connected&&(I(_.connected),_.connected=null),()=>b.current.delete(I)},[]),w=a.useCallback(I=>{x.current.add(I);const _=v.current;return _.scrollback&&(I(_.scrollback),_.scrollback=null),()=>x.current.delete(I)},[]),S=a.useCallback(I=>(y.current.add(I),()=>y.current.delete(I)),[]),k=a.useCallback(I=>{const _=m.current;_?.readyState===WebSocket.OPEN&&_.send(JSON.stringify({type:"input",data:I}))},[]),P=a.useCallback((I,_)=>{const j=m.current;j?.readyState===WebSocket.OPEN&&j.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),v.current=xr()},[]),R=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),v.current=xr()},[]),O=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 j=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(t)}`;n&&(j+=`&projectId=${encodeURIComponent(n)}`);const Q=new WebSocket(As(j));m.current=Q,Q.onopen=()=>{if(r.current!==I){Q.close();return}v.current=xr(),i("connected"),c.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===I&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify({type:"ping"}))},GM)},Q.onmessage=Y=>{if(r.current===I)try{const L=JSON.parse(Y.data),D=v.current;switch(L.type){case"data":L.data&&(p.current.size===0&&D.data.push(L.data),p.current.forEach(U=>U(L.data)));break;case"scrollback":L.data&&(D.scrollback=L.data,x.current.forEach(U=>U(L.data)));break;case"connected":L.shell&&L.cwd&&(D.connected={shell:L.shell,cwd:L.cwd},b.current.forEach(U=>U({shell:L.shell,cwd:L.cwd})));break;case"exit":L.exitCode!==void 0&&f.current.forEach(U=>U(L.exitCode));break;case"ping":Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Q.onclose=Y=>{if(r.current!==I)return;if(m.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(Y.code===4e3||Y.code===4004){i("disconnected"),Y.code===4004&&y.current.forEach(U=>U());return}if(c.current++,c.current>WM){i("disconnected");return}const L=KM*Math.pow(2,c.current-1);i("reconnecting");const D=r.current;u.current=setTimeout(()=>{r.current===D&&(g.current||O())},Math.min(L,16e3))},Q.onerror=()=>{}},[t,n]),Z=a.useCallback(()=>{c.current=0,R(),O()},[R,O]);return a.useEffect(()=>(d&&(C(),c.current=0,i("disconnected")),t?O():i("disconnected"),R),[t,n,d,O,R,C]),{connectionStatus:s,sendInput:k,resize:P,onData:M,onExit:N,onConnect:A,onScrollback:w,reconnect:Z,onSessionInvalid:S}}const Hp="kb-terminal-tabs",YM=15e3,QM=15e3;function em(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function tm(t){if(typeof window>"u")return[];try{const n=In(Hp,t);if(n)return JSON.parse(n)}catch{}return[]}function Jl(t){const n=t instanceof Error?t.message:typeof t=="string"?t:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function nm(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 XM(t){const[n,s]=a.useState(()=>tm(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(tm(t)),r(!1),o(!0),m(null)},[t]),a.useEffect(()=>{try{us(Hp,JSON.stringify(n),t)}catch{}},[t,n]),a.useEffect(()=>{let A=!1;const w=h.current;return(async()=>{if(!A)try{const k=await nm(iv(t),YM,"listTerminalSessions");if(A||w!==h.current)return;const P=new Set(k.map(C=>C.id));o(!0),s(C=>{if(A||w!==h.current)return C;const O=C.map(_=>({..._,_verified:P.has(_.sessionId)})).filter(_=>_._verified);if(O.length===0)return[];const Z=O.map(({_verified:_,...j})=>j);return Z.find(_=>_.isActive)?Z:Z.map((_,j)=>({..._,isActive:j===0}))}),r(!0)}catch(k){if(A||w!==h.current)return;const P=Jl(k);P||console.warn("Failed to validate terminal sessions with server:",k),o(!P),r(!0)}})(),()=>{A=!0}},[t]),a.useEffect(()=>{if(n.length===0&&i&&l){const A=h.current,w=setTimeout(()=>{nm(tr(void 0,void 0,void 0,t),QM,"createTerminalSession").then(S=>{if(A!==h.current)return;const k={id:em(),sessionId:S.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(P=>P.length>0?P:[...P.map(R=>({...R,isActive:!1})),k]),m(null)}).catch(S=>{if(A!==h.current)return;Jl(S)||console.error(S);const k=S instanceof Error?S.message:typeof S=="string"?S:"Failed to create terminal session";m(k)})},0);return()=>clearTimeout(w)}},[i,l,n.length,c]);const g=a.useCallback(async()=>{const A=await tr(void 0,void 0,void 0,t),w={id:em(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(S=>[...S.map(P=>({...P,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(A=>{s(w=>{const S=w.find(R=>R.id===A);if(!S)return w;qc(S.sessionId,t).catch(R=>{console.warn(`Failed to kill terminal session ${S.sessionId}:`,R)});const k=w.findIndex(R=>R.id===A),P=S.isActive,C=w.filter(R=>R.id!==A);if(C.length===0)return[];if(P){const R=Math.min(k,C.length-1);return C.map((O,Z)=>({...O,isActive:Z===R}))}return C})},[]),b=a.useCallback(A=>{s(w=>{let S=!1;const k=w.map(P=>P.id===A?(S=!0,{...P,isActive:!0}):{...P,isActive:!1});return S?k:w})},[]),x=a.useCallback((A,w)=>{s(S=>S.map(k=>k.id===A?{...k,title:w}:k))},[]),y=a.useCallback(async()=>{s(S=>{const k=S.find(P=>P.isActive);return k&&qc(k.sessionId,t).catch(P=>{console.warn(`Failed to kill old session ${k.sessionId}:`,P)}),S});const A=n.find(S=>S.isActive);if(!A)return;const w=await tr(void 0,void 0,void 0,t);s(S=>S.map(k=>k.id===A.id?{...k,sessionId:w.sessionId}:k))},[n]),v=a.useCallback(async()=>{const A=n.find(w=>w.isActive);if(A)try{const w=await tr(void 0,void 0,void 0,t);s(S=>S.map(k=>k.id===A.id?{...k,sessionId:w.sessionId}:k)),m(null)}catch(w){Jl(w)||console.error(w);const S=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";m(S)}},[n]),M=n.find(A=>A.isActive)??null,N=a.useCallback(()=>{m(null),h.current+=1,u(A=>A+1)},[]);return{tabs:n,activeTab:M,isReady:i,bootstrapError:d,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:x,restartActiveTab:y,retryBootstrap:N,replaceActiveTabSession:v}}const ZM=1e4,eA=[500,1500,3e3];function tA(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 nA(t){return new Promise(n=>setTimeout(n,t))}async function sA(t,n=eA){let s;for(let i=0;i<=n.length;i+=1)try{return await t()}catch(r){if(!tA(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 nA(l)}throw s??new Error("Dynamic import failed")}function sm(){if(typeof window>"u")return!1;const t="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return t&&n}function iA(){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=aA()-t.offsetTop-t.height;return i>=30&&i>80?i:0}let Yl=null;function aA(){return Yl===null&&(Yl=window.innerHeight),Yl}function rA({isOpen:t,onClose:n,initialCommand:s,projectId:i}){const[r,l]=a.useState(null),[o,d]=a.useState(null),[m,c]=a.useState(!1),[u,h]=a.useState(null),[g,p]=a.useState(0),[f,b]=a.useState(0),[x,y]=a.useState(null),v=a.useRef(null),M=a.useRef(null),N=a.useRef(null),A=a.useRef(null),w=a.useRef(!1),S=a.useRef(!1),k=a.useRef(null),P=a.useRef(0),C=a.useRef(null),R=a.useRef(i);P.current=f;const O=a.useCallback(Ee=>{if(Ee&&S.current!==Ee)return;const _e=A.current,Be=N.current,et=k.current;if(!(!_e||!Be)&&!(Ee&&S.current!==Ee))try{_e.fit(),et&&et(Be.cols,Be.rows)}catch{}},[]);a.useEffect(()=>{t&&p(Ee=>Ee+1)},[t]),a.useEffect(()=>{if(!t||!sm())return;const Ee=window.visualViewport;if(!Ee)return;const _e=()=>{const Be=iA();b(Be),y(Ee.height),Be>0&&M.current?.scrollIntoView&&M.current.scrollIntoView({block:"end",behavior:"smooth"}),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const et=typeof S.current=="string"?S.current:void 0;C.current=requestAnimationFrame(()=>{C.current=null,O(et)})};return _e(),Ee.addEventListener("resize",_e),Ee.addEventListener("scroll",_e),()=>{Ee.removeEventListener("resize",_e),Ee.removeEventListener("scroll",_e),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),b(0),y(null)}},[O,t]);const{tabs:Z,activeTab:I,isReady:_,bootstrapError:j,createTab:Q,closeTab:Y,setActiveTab:L,updateTabTitle:D,restartActiveTab:U,retryBootstrap:G,replaceActiveTabSession:E}=XM(i),{connectionStatus:J,sendInput:ue,resize:z,onData:te,onConnect:F,onExit:fe,onScrollback:V,reconnect:K,onSessionInvalid:de}=JM(I?.sessionId??null,i);k.current=z,a.useEffect(()=>{if(!t||!_||!I)return;const Ee=I.sessionId,_e=R.current!==i;if(_e&&(R.current=i),S.current===Ee&&N.current&&!_e)return;N.current&&(S.current!==Ee||_e)&&(N.current.dispose(),N.current=null,A.current=null,S.current=!1,c(!1),h(null));let Be=!0,et;const Xe=(async()=>{const re=sA(()=>Promise.all([en(()=>import("./vendor-xterm-DzcZoU0P.js").then(Te=>Te.x),__vite__mapDeps([4,1,5])),en(()=>import("./addon-fit-C7jRorKK.js").then(Te=>Te.a),__vite__mapDeps([9,1])),en(()=>import("./addon-web-links-CkJwd4cQ.js").then(Te=>Te.a),__vite__mapDeps([10,1]))])),ne=new Promise((Te,ye)=>{et=setTimeout(()=>{ye(new Error("xterm initialization timed out"))},ZM)});let ge,le;try{const[{Terminal:Te},{FitAddon:ye},{WebLinksAddon:He}]=await Promise.race([re,ne]);if(!Be||!v.current||N.current)return;ge=new Te({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}),le=new ye,ge.loadAddon(le);const nt=new He;if(ge.loadAddon(nt),!sm())try{const{WebglAddon:be}=await en(async()=>{const{WebglAddon:Ze}=await import("./addon-webgl-BjvOw43o.js").then(je=>je.a);return{WebglAddon:Ze}},__vite__mapDeps([11,1])),Me=new be;Me.onContextLoss(()=>{Me.dispose()}),ge.loadAddon(Me)}catch{}ge.open(v.current),clearTimeout(et);const mt=v.current?.querySelector(".xterm-helper-textarea");if(mt&&mt.focus(),v.current)try{v.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{le.fit();const be=v.current?.querySelector(".xterm-helper-textarea");be&&be.focus()},50),N.current=ge,A.current=le,S.current=Ee,P.current>0&&(C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),C.current=requestAnimationFrame(()=>{C.current=null,O(Ee)})),c(!0),h(null);const he=ge.onData(be=>{ue(be)}),ie=()=>{if(A.current&&N.current)try{A.current.fit();const{cols:be,rows:Me}=N.current;z(be,Me)}catch{}};return window.addEventListener("resize",ie),()=>{he.dispose(),window.removeEventListener("resize",ie)}}catch(Te){if(clearTimeout(et),!Be)return;const ye=Te instanceof Error?Te.message:"xterm initialization failed";h(ye)}})();return()=>{Be=!1,clearTimeout(et),Xe.then(re=>re?.())}},[O,t,_,I,I?.sessionId,ue,z]),a.useEffect(()=>{t||(N.current&&(N.current.dispose(),N.current=null),A.current=null,S.current=!1,c(!1),h(null),w.current=!1,l(null),d(null))},[t]),a.useEffect(()=>{if(!m||!N.current||!I)return;const Ee=I.sessionId,_e=re=>{S.current===Ee&&N.current?.write(re)},Be=te(re=>{_e(re)}),et=V(re=>{_e(re)}),De=F(re=>{D(I.id,re.shell.split("/").pop()||re.shell)}),Xe=fe(re=>{S.current===Ee&&(d(re),N.current?.write(`\r
641
- \x1B[33m[Process exited with code ${re}]\x1B[0m\r
642
- `))});return()=>{Be(),et(),De(),Xe()}},[m,I?.sessionId,I?.id,I,J,te,V,F,fe,D]),a.useEffect(()=>{J==="connected"&&s&&w.current!==s&&I&&(w.current=s,setTimeout(()=>{ue(s+`
643
- `)},500))},[J,s,ue,I,g]),a.useEffect(()=>{if(!t)return;const Ee=_e=>{if(!(!_e.ctrlKey&&!_e.metaKey)){if(_e.code==="Equal"||_e.code==="NumpadAdd"){if(_e.preventDefault(),N.current){const Be=N.current.options.fontSize||14;N.current.options.fontSize=Math.min(Be+1,32),A.current?.fit()}return}if(_e.code==="Minus"||_e.code==="NumpadSubtract"){if(_e.preventDefault(),N.current){const Be=N.current.options.fontSize||14;N.current.options.fontSize=Math.max(Be-1,8),A.current?.fit()}return}if(_e.code==="Digit0"||_e.code==="Numpad0"){_e.preventDefault(),N.current&&(N.current.options.fontSize=14,A.current?.fit());return}}};return window.addEventListener("keydown",Ee),()=>window.removeEventListener("keydown",Ee)},[t]),a.useEffect(()=>{if(!t)return;const Ee=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[t,n]),a.useEffect(()=>{J==="connected"&&N.current&&setTimeout(()=>{if(!N.current||!v.current)return;const Ee=v.current.querySelector(".xterm-helper-textarea");Ee&&Ee.focus();try{v.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[J]);const we=a.useCallback(()=>{if(!v.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;N.current?.focus();const _e=v.current.querySelector(".xterm-helper-textarea");if(!_e)return;_e.autocapitalize="off",_e.autocomplete="off",_e.autocorrect="off",_e.spellcheck=!1,_e.setAttribute("inputmode","text");try{_e.focus({preventScroll:!0})}catch{_e.focus()}const Be=_e.value.length;_e.setSelectionRange(Be,Be)},[]);a.useEffect(()=>de(()=>{N.current?.clear(),d(null),w.current=!1,N.current&&(N.current.dispose(),N.current=null),A.current=null,S.current=!1,c(!1),h(null),E().catch(_e=>{console.error("Failed to replace invalid terminal session:",_e)})}),[de,E]);const ve=a.useCallback(Ee=>{Ee.target===Ee.currentTarget&&n()},[n]),Se=a.useCallback(()=>{N.current?.clear()},[]),Pe=a.useCallback(async()=>{N.current?.clear(),d(null),w.current=!1;try{await U()}catch(Ee){l(xe(Ee)||"Failed to restart terminal session")}},[U]),Oe=a.useCallback(()=>{N.current&&(N.current.dispose(),N.current=null),A.current=null,S.current=!1,h(null),c(!1)},[]);if(!t)return null;const Ie=()=>{switch(J){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&&!j||!m&&!u;return e.jsx("div",{className:"modal-overlay open",onClick:ve,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:e.jsxs("div",{ref:M,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}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:[Z.map(Ee=>e.jsxs("div",{className:`terminal-tab ${Ee.isActive?"terminal-tab--active":""}`,onClick:()=>L(Ee.id),title:Ee.title,role:"tab","aria-selected":Ee.isActive,children:[e.jsx("span",{className:"terminal-tab-label",children:Ee.title}),Z.length>1&&e.jsx("button",{className:"terminal-tab-close",onClick:_e=>{_e.stopPropagation(),Y(Ee.id)},title:"Close tab",children:"×"})]},Ee.id)),e.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:Q,title:"New terminal",children:"+"})]}),e.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[e.jsx(zs,{size:16}),Ie()]}),e.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[J==="disconnected"&&I&&e.jsxs("button",{className:"terminal-reconnect-btn",onClick:K,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[e.jsx(Mn,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),o!==null&&e.jsxs("button",{className:"terminal-restart-btn",onClick:Pe,title:"New Session","data-testid":"terminal-restart-btn",children:[e.jsx(Mn,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),e.jsxs("button",{className:"terminal-clear-btn",onClick:Se,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[e.jsx(Ht,{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(Dt,{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&&!j&&e.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[e.jsx("div",{className:"terminal-spinner"}),e.jsx("span",{children:"Starting terminal..."})]}),j&&!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: ",j]}),e.jsxs("button",{className:"terminal-retry-btn",onClick:G,"data-testid":"terminal-retry-btn",children:[e.jsx(Mn,{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(Mn,{size:14}),"Reinitialize"]})]})}),e.jsx("div",{ref:v,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:we,onTouchStart:we},I?.sessionId)]}),e.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[e.jsxs("span",{className:`terminal-connection-status ${J}`,children:[J==="connected"&&"Connected",J==="connecting"&&"Connecting...",J==="reconnecting"&&"Reconnecting...",J==="disconnected"&&"Disconnected"]}),o!==null&&e.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",o]}),e.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • Ctrl+L clear • Esc close"})]})]})})}const va={name:"",command:""};function im(t){return/^[a-zA-Z0-9_-]+$/.test(t)}function lA(t,n=60){return t.length<=n?t:t.slice(0,n-3)+"..."}function oA({isOpen:t,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[l,o]=a.useState({}),[d,m]=a.useState(!0),[c,u]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(va),[b,x]=a.useState(!1),[y,v]=a.useState(null),[M,N]=a.useState(null),A=a.useCallback(async()=>{try{m(!0);const _=await Va(i);o(_)}catch(_){s(xe(_)||"Failed to load scripts","error")}finally{m(!1)}},[s,i]);a.useEffect(()=>{t&&A()},[t,A]);const w=a.useCallback(()=>{u(!0),g(null),f(va),N(null)},[]),S=a.useCallback((_,j)=>{g(_),u(!1),f({name:_,command:j}),N(null)},[]),k=a.useCallback(()=>{g(null),u(!1),f(va),N(null)},[]),P=a.useCallback(_=>{f(j=>({...j,name:_})),_&&!im(_)?N("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):N(null)},[]),C=a.useCallback(async()=>{const _=p.name.trim(),j=p.command.trim();if(!_){s("Script name is required","error");return}if(!im(_)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!j){s("Script command is required","error");return}x(!0);try{await iy(_,j,i),s(h?"Script updated":"Script created","success"),g(null),u(!1),f(va),N(null),await A()}catch(Q){const Y=xe(Q);Y?.includes("already exists")?s("A script with this name already exists","error"):s(Y||"Failed to save script","error")}finally{x(!1)}},[p,h,s,A,i]),R=a.useCallback(async _=>{try{await ay(_,i),s("Script deleted","success"),v(null),h===_&&(g(null),f(va)),await A()}catch(j){s(xe(j)||"Failed to delete script","error")}},[h,s,A,i]),O=a.useCallback((_,j)=>{r&&r(_,j)},[r]);if(!t)return null;const Z=c||h!==null,I=Object.entries(l).map(([_,j])=>({name:_,command:j}));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(lt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):Z?e.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),e.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:_=>P(_.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:M?"var(--color-error)":void 0}}),M&&e.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:M}),e.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),e.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:_=>f(j=>({...j,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||!!M,"data-testid":"script-save-btn",children:b?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(Vt,{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:lA(_.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:()=>O(_.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:()=>S(_.name,_.command),title:"Edit","aria-label":`Edit ${_.name}`,"data-testid":`edit-script-${_.name}`,children:e.jsx(Vt,{size:14,style:{transform:"rotate(45deg)"}})}),y===_.name?e.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[e.jsx("button",{className:"btn-icon",onClick:()=>R(_.name),title:"Confirm delete","aria-label":`Confirm delete ${_.name}`,"data-testid":`confirm-delete-script-${_.name}`,style:{color:"var(--color-error)"},children:e.jsx(Ht,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>v(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${_.name}`,children:e.jsx(Dt,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>v(_.name),title:"Delete","aria-label":`Delete ${_.name}`,"data-testid":`delete-script-${_.name}`,children:e.jsx(Ht,{size:14})})]})]})},_.name))})]})})]})})}function cA(t,n,s){const[i,r]=a.useState([]),[l,o]=a.useState("."),[d,m]=a.useState(!1),[c,u]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(b=>b+1)},[]),f=a.useCallback(b=>{o(b),u(null)},[]);return a.useEffect(()=>{o("."),u(null),r([])},[t]),a.useEffect(()=>{if(!t)return;let b=!1;async function x(){m(!0),u(null);try{const y=await jv(t,l==="."?void 0:l,s);b||r(y.entries)}catch(y){b||(u(xe(y)||"Failed to load files"),r([]))}finally{b||m(!1)}}return x(),()=>{b=!0}},[t,l,n,h,s]),{entries:i,currentPath:l,setPath:f,loading:d,error:c,refresh:p}}function dA(t,n,s,i){const[r,l]=a.useState(""),[o,d]=a.useState(""),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,p]=a.useState(!1),[f,b]=a.useState(null),x=a.useCallback(M=>{l(M),b(null)},[]);a.useEffect(()=>{if(!t||!n){l(""),d(""),c(null),b(null);return}let M=!1;async function N(){h(!0),b(null);try{const A=await wv(t,n,i);M||(l(A.content),d(A.content),c(A.mtime))}catch(A){M||(b(xe(A)||"Failed to load file"),l(""),d(""),c(null))}finally{M||h(!1)}}return N(),()=>{M=!0}},[t,n,s,i]);const y=r!==o,v=a.useCallback(async()=>{if(!(!t||!n||!y)){p(!0),b(null);try{const M=await Nv(t,n,r,i);d(r),c(M.mtime)}catch(M){throw b(xe(M)||"Failed to save file"),M}finally{p(!1)}}},[t,n,r,y,i]);return{content:r,setContent:x,originalContent:o,loading:u,saving:g,error:f,save:v,hasChanges:y,mtime:m}}const uA=1e4;function mA(t){const s=t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||t||"Project Root"}function hA(t){return{id:t.id,label:t.id,title:t.title,worktree:t.worktree,kind:"task"}}function pA(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 kv(t);if(c)return;s(mA(g.project)),r(g.tasks.map(hA)),m(null)}catch(g){c||m(xe(g)||"Failed to load workspaces")}finally{c||o(!1)}}u();const h=window.setInterval(()=>{u()},uA);return()=>{c=!0,window.clearInterval(h)}},[t]),{projectName:n,workspaces:i,loading:l,error:d}}function fA(t){return t===void 0?"":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function gA(t){return t?new Date(t).toLocaleDateString():""}function am(t,n){return t==="."?n:`${t}/${n}`}const ya={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Ql={type:null,entry:null,entryFullPath:""},bA=200,xA=500,rm=10;function vA({x:t,y:n,entry:s,onAction:i,onClose:r}){const l=a.useRef(null),[o,d]=a.useState({x:t,y:n});a.useEffect(()=>{const u=l.current;if(!u)return;const h=u.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,x=g?.offsetTop??0,y=8;let v=t-b,M=n-x;v+h.width>p-y&&(v=p-y-h.width),M+h.height>f-y&&(M=f-y-h.height),v<y&&(v=y),M<y&&(M=y),d({x:v+b,y:M+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:qi,disabled:!1},{id:"move",label:"Move",icon:cb,disabled:!1},{id:"rename",label:"Rename",icon:Ln,disabled:!1},...m?[{id:"download-zip",label:"Download as ZIP",icon:Br,disabled:!1}]:[{id:"download",label:"Download",icon:lg,disabled:!1}],{id:"divider",label:"",icon:qi,disabled:!0},{id:"delete",label:"Delete",icon:Ht,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 yA({type:t,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:l,error:o}){const d=a.useRef(null),m=t==="rename"?n.name:"",[c,u]=a.useState(m);a.useEffect(()=>{setTimeout(()=>d.current?.focus(),50)},[]),a.useEffect(()=>{if(t==="rename"&&d.current){const f=n.name.lastIndexOf(".");f>0?d.current.setSelectionRange(0,f):d.current.select()}},[t,n.name]);const h=f=>{f.key==="Enter"&&c.trim()&&i(c.trim()),f.key==="Escape"&&r()};if(t==="delete")return e.jsx("div",{className:"context-menu-overlay",onClick:r,children:e.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),e.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",e.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),o&&e.jsx("div",{className:"file-browser-dialog-error",children:o}),e.jsxs("div",{className:"file-browser-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:r,disabled:l,children:"Cancel"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:l,children:l?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[t];return e.jsx("div",{className:"context-menu-overlay",onClick:r,children:e.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[e.jsx("div",{className:"file-browser-dialog-title",children:p.title}),e.jsx("div",{className:"file-browser-dialog-info",children:t==="rename"?n.name:s}),e.jsx("input",{ref:d,className:"file-browser-dialog-input",type:"text",value:c,onChange:f=>u(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:l}),o&&e.jsx("div",{className:"file-browser-dialog-error",children:o}),e.jsxs("div",{className:"file-browser-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:r,disabled:l,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(c.trim()),disabled:l||!c.trim(),children:l?`${p.confirm}ing...`:p.confirm})]})]})})}function kA({entries:t,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:l,onRetry:o,workspace:d,onRefresh:m,projectId:c}){const[u,h]=a.useState(ya),[g,p]=a.useState(Ql),[f,b]=a.useState(!1),[x,y]=a.useState(null),[v,M]=a.useState(!1),[N,A]=a.useState(null),w=a.useRef(null),S=a.useRef(null),k=a.useRef(null),P=a.useRef(!1),C=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]),R=a.useCallback(()=>{C(),k.current=null,M(!1),A(null)},[C]);a.useEffect(()=>()=>{C()},[C]);const O=a.useCallback((U,G,E,J)=>{h({visible:!0,x:U,y:G,entry:E,entryFullPath:J})},[]),Z=a.useCallback((U,G,E)=>{if(U.touches.length!==1)return;const J=U.touches[0];J&&(R(),k.current={x:J.clientX,y:J.clientY},S.current=window.setTimeout(()=>{M(!0),A(E)},bA),w.current=window.setTimeout(()=>{const ue=k.current;ue&&(P.current=!0,M(!1),A(null),C(),O(ue.x,ue.y,G,E))},xA))},[R,C,O]),I=a.useCallback(U=>{const G=k.current,E=U.touches[0];!G||!E||(Math.abs(E.clientX-G.x)>rm||Math.abs(E.clientY-G.y)>rm)&&R()},[R]),_=a.useCallback(()=>{R()},[R]);a.useEffect(()=>{if(!u.visible)return;const U=document.querySelector(".file-browser-list"),G=()=>{P.current=!1,R(),h(ya)};return U?.addEventListener("scroll",G),()=>U?.removeEventListener("scroll",G)},[R,u.visible]),a.useEffect(()=>{if(!u.visible)return;const U=G=>{G.key==="Escape"&&(P.current=!1,h(ya))};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[u.visible]);const j=a.useCallback((U,G)=>{U.preventDefault(),U.stopPropagation(),R(),P.current=!1,O(U.clientX,U.clientY,G,am(n,G.name))},[R,n,O]),Q=a.useCallback(U=>{if(!u.entry)return;P.current=!1;const G=u.entry,E=u.entryFullPath;if(h(ya),U==="download"){if(!d)return;const J=sh(d,E,c);window.open(As(J),"_blank");return}if(U==="download-zip"){if(!d)return;const J=Pv(d,E,c);window.open(As(J),"_blank");return}p({type:U,entry:G,entryFullPath:E}),y(null)},[u,d,c]),Y=a.useCallback(async U=>{if(!(!g.type||!g.entry||!d)){b(!0),y(null);try{switch(g.type){case"copy":await Cv(d,g.entryFullPath,U,c);break;case"move":await Ev(d,g.entryFullPath,U,c);break;case"rename":await Av(d,g.entryFullPath,U,c);break;case"delete":await Mv(d,g.entryFullPath,c);break}p(Ql),m?.()}catch(G){y(xe(G)||"Operation failed")}finally{b(!1)}}},[g,d,m,c]),L=a.useCallback(()=>{p(Ql),y(null)},[]),D=a.useCallback((U,G)=>{if(P.current){P.current=!1;return}u.visible||(U.type==="directory"?i(G):s(G))},[u.visible,i,s]);return r?e.jsxs("div",{className:"file-browser-loading",children:[e.jsx(lt,{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 U=n.split("/").filter(Boolean);U.pop(),i(U.length===0?".":U.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(U=>{const G=am(n,U.name),E=v&&N===G;return e.jsxs("div",{className:`file-node file-node--${U.type} ${E?"file-node--long-pressing":""}`,onClick:()=>D(U,G),onContextMenu:J=>j(J,U),onTouchStart:J=>Z(J,U,G),onTouchMove:I,onTouchEnd:_,onTouchCancel:_,children:[e.jsx("div",{className:"file-node-icon",children:U.type==="directory"?e.jsx(An,{size:16}):e.jsx(Bm,{size:16})}),e.jsx("div",{className:"file-node-name",children:U.name}),U.type==="file"&&U.size!==void 0&&e.jsx("div",{className:"file-node-size",children:fA(U.size)}),U.mtime&&e.jsx("div",{className:"file-node-time",children:gA(U.mtime)})]},U.name)})}),u.visible&&u.entry&&e.jsx(vA,{x:u.x,y:u.y,entry:u.entry,onAction:Q,onClose:()=>{P.current=!1,h(ya)}}),g.type&&g.entry&&e.jsx(yA,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:Y,onCancel:L,loading:f,error:x})]})}function jA(t,n=44){if(t)return t.length<=n?t:`${t.slice(0,n-1)}…`}function wA({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($c,{size:14}):e.jsx(co,{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($c,{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(co,{size:14}),e.jsx("span",{children:d.id})]}),d.title&&e.jsx("span",{className:"workspace-selector-option-meta",title:d.title,children:jA(d.title)})]},d.id))]})]})]})}const NA=768,qp=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),SA=new Set([...qp,".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 lm(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return SA.has(n)}function CA(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return qp.has(n)}function EA({initialWorkspace:t="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:l}=pA(i),[o,d]=a.useState(t),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,p]=a.useState("list"),{entries:f,currentPath:b,setPath:x,loading:y,error:v,refresh:M}=cA(o,!0,i),{content:N,setContent:A,originalContent:w,loading:S,saving:k,error:P,save:C,hasChanges:R,mtime:O}=dA(o,m,!0,i);a.useEffect(()=>{d(t)},[t]),a.useEffect(()=>{const U=()=>{h(window.innerWidth<=NA)};return U(),window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[]),a.useEffect(()=>{m||p("list")},[m]),a.useEffect(()=>{const U=G=>{G.key==="Escape"&&n(),(G.metaKey||G.ctrlKey)&&G.key==="s"&&(G.preventDefault(),R&&!k&&C())};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[n,R,k,C]);const Z=a.useCallback(U=>{c(U),u&&p("editor")},[u]),I=a.useCallback(()=>{p("list")},[]),_=a.useCallback(()=>{A(w)},[w,A]),j=a.useCallback(U=>{d(U),c(null),p("list"),s?.(U)},[s]),Y=`Files — ${a.useMemo(()=>o==="project"?"Project":l.find(U=>U.id===o)?.id??o,[o,l])}`,L=a.useMemo(()=>!m||!CA(m)?null:sh(o,m,i),[m,o,i]),D=U=>{const G=new Blob([U]).size;return G<1024?`${G} B`:`${(G/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:U=>U.stopPropagation(),children:[e.jsxs("div",{className:"modal-header file-browser-modal-header",children:[e.jsxs("div",{className:"file-browser-header-title",children:[e.jsx(An,{size:18}),e.jsx("span",{children:Y}),m&&e.jsx("span",{className:"file-browser-header-path",children:m})]}),e.jsxs("div",{className:"file-browser-header-actions",children:[e.jsx(wA,{currentWorkspace:o,projectName:r,workspaces:l,onSelect:j}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Dt,{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(kA,{entries:f,currentPath:b,onSelectFile:Z,onNavigate:x,loading:y,error:v,onRetry:M,workspace:o,onRefresh:M,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(sa,{size:16}),e.jsx("span",{children:"Back"})]}),m,lm(m)&&e.jsxs("span",{className:"file-browser-binary-indicator",children:[e.jsx(Sg,{size:12}),"Binary file — read only"]}),O&&e.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(O).toLocaleString()]}),S&&e.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),e.jsx("div",{className:"file-browser-actions",children:!L&&R&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:_,disabled:k,children:[e.jsx(jb,{size:14}),"Discard"]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void C(),disabled:k,children:[e.jsx(Km,{size:14}),k?"Saving...":"Save"]})]})})]}),P&&!L&&e.jsx("div",{className:"file-browser-error-banner",children:P}),L?e.jsx("div",{className:"file-browser-image-preview",children:e.jsx("img",{src:L,alt:m??"",className:"file-browser-image"})}):e.jsx("div",{className:"file-editor-wrapper",children:e.jsx(Bp,{content:N,onChange:A,filePath:m,readOnly:lm(m)})}),!L&&e.jsxs("div",{className:"file-browser-footer",children:[e.jsx("span",{children:D(N)}),R&&e.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):e.jsxs("div",{className:"file-browser-placeholder",children:[e.jsx(An,{size:48,opacity:.3}),e.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function MA(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 Hx();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:xe(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 AA(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 PA(t){return t>90?"usage-progress-fill--high":t>70?"usage-progress-fill--medium":"usage-progress-fill--low"}function TA({window:t,viewMode:n,providerName:s}){const i=PA(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),y=Math.floor(x/24),v=x%24;y>0&&v>0?m=`resets in ${y}d ${v}h`:y>0?m=`resets in ${y}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",p=c?.status==="behind",f=c?.status==="on-track";return e.jsxs("div",{className:"usage-window",children:[e.jsxs("div",{className:"usage-window-header",children:[e.jsx("span",{className:"usage-window-label",children:t.label}),e.jsx("span",{className:"usage-window-percentage",children:o})]}),e.jsxs("div",{className:"usage-progress-wrapper",children:[e.jsx("div",{className:"usage-progress-bar",children:e.jsx("div",{className:`usage-progress-fill ${i}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${t.label}: ${o}`})}),u&&e.jsx("div",{className:"usage-pace-marker",style:{left:`${h}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),e.jsxs("div",{className:"usage-window-footer",children:[e.jsx("span",{className:"usage-window-left",children:d}),e.jsxs("span",{className:"usage-window-reset-group",children:[m&&e.jsx("span",{className:"usage-window-reset",children:m}),t.resetAt&&e.jsx("span",{className:"usage-window-reset-at",children:AA(t.resetAt)})]})]}),u&&e.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(Uo,{size:14,className:"pace-icon pace-ahead"}),e.jsx("span",{className:"pace-text pace-ahead",children:c.message})]}),p&&e.jsxs(e.Fragment,{children:[e.jsx(Ob,{size:14,className:"pace-icon pace-behind"}),e.jsx("span",{className:"pace-text pace-behind",children:c.message})]}),f&&e.jsxs(e.Fragment,{children:[e.jsx(tn,{size:14,className:"pace-icon pace-ontrack"}),e.jsx("span",{className:"pace-text pace-ontrack",children:c.message})]})]})]})}function RA(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 _A({provider:t,viewMode:n}){const s=()=>{switch(t.status){case"ok":return e.jsx("span",{className:"usage-status-badge usage-status-badge--connected",children:"Connected"});case"error":return e.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return e.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return e.jsxs("div",{className:"usage-provider","data-provider":t.name,"data-status":t.status,children:[e.jsxs("div",{className:"usage-provider-header",children:[e.jsxs("div",{className:"usage-provider-info",children:[e.jsx(ss,{provider:RA(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(TA,{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 IA(){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 $A({isOpen:t,onClose:n,projectId:s}){const{providers:i,loading:r,error:l,lastUpdated:o,refresh:d}=MA({autoRefresh:t}),[m,c]=a.useState(!1),[u,h]=a.useState("used"),g=a.useRef(null),p=a.useRef(t),f=a.useRef(!1);a.useEffect(()=>{t||(f.current=!1)},[t]),a.useEffect(()=>{i.length>0&&(f.current=!0)},[i.length]),a.useEffect(()=>{!p.current&&t&&(!o||Date.now()-o.getTime()>5e3)&&d(),p.current=t},[t,o,d]),a.useEffect(()=>{const v=In("kb-usage-view-mode",s);if(v==="used"||v==="remaining"){h(v);return}h("used")},[s]);const b=a.useCallback(v=>{h(v),us("kb-usage-view-mode",v,s)},[s]),x=a.useCallback(async()=>{c(!0),await d(),c(!1)},[d]);a.useEffect(()=>{if(!t)return;const v=M=>{M.key==="Escape"&&n()};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[t,n]);const y=a.useCallback(v=>{v.target===v.currentTarget&&n()},[n]);return t?e.jsx("div",{className:"modal-overlay open",onClick:y,"data-testid":"usage-modal-overlay",children:e.jsxs("div",{className:"modal usage-modal","data-testid":"usage-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"usage-header",children:[e.jsx(ws,{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(Dt,{size:20})})]})]}),e.jsx("div",{className:"usage-content",ref:g,children:(r||!f.current&&!l)&&i.length===0?e.jsx(IA,{}):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(v=>e.jsx(_A,{provider:v,viewMode:u},v.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(Mn,{size:14,className:m?"spin":"",style:{marginRight:6}}),"Refresh"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function Vp(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 Lr(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 DA={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Wp={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},FA={cron:Fm,webhook:Jm,api:Lm,manual:jn},LA={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},zA={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function OA({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(tn,{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:Vp(n)})]})}function BA({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"} ${Lr(t.startedAt)}`,children:[e.jsx("span",{className:`schedule-history-status ${t.success?"success":"failure"}`,children:t.success?e.jsx(tn,{size:12}):e.jsx(Ba,{size:12})}),e.jsx("span",{className:"schedule-history-time",children:Lr(t.startedAt)}),t.triggerType&&e.jsx("span",{className:"routine-history-trigger-type",children:Wp[t.triggerType]}),e.jsx("span",{className:"schedule-history-duration",children:Vp(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 UA({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=DA[t.trigger.type],u=FA[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}),Wp[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(An,{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(Ht,{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(Hi,{size:12}),e.jsx("code",{className:"routine-cron",children:h})]}),e.jsx("div",{className:"routine-meta-item",children:e.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${t.executionPolicy}`,children:LA[t.executionPolicy]})}),e.jsx("div",{className:"routine-meta-item",children:e.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${t.catchUpPolicy}`,children:zA[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:Lr(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:Lr(t.lastRunAt)})]}),t.lastRunResult&&e.jsx(OA,{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,p)=>e.jsx(BA,{result:g,index:p},`${g.startedAt}-${p}`)),t.runHistory.length>10&&e.jsxs("div",{className:"schedule-history-more",children:["…and ",t.runHistory.length-10," more"]})]})]})]})}function HA({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(Yg,{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 Xl(){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:Xl(),type:t,name:"New Command Step",command:"",continueOnFailure:!1}:t==="ai-prompt"?{id:Xl(),type:t,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Xl(),type:t,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function VA({step:t,onSave:n,onCancel:s}){const[i,r]=a.useState(t.name),[l,o]=a.useState(t.type),[d,m]=a.useState(t.command??""),[c,u]=a.useState(t.prompt??""),[h,g]=a.useState(t.modelProvider??""),[p,f]=a.useState(t.modelId??""),[b,x]=a.useState(t.taskTitle??""),[y,v]=a.useState(t.taskDescription??""),[M,N]=a.useState(t.taskColumn??"triage"),[A,w]=a.useState(t.timeoutMs),[S,k]=a.useState(t.continueOnFailure??!1),[P,C]=a.useState({}),[R,O]=a.useState([]),[Z,I]=a.useState(!1),[_,j]=a.useState(null);a.useEffect(()=>{let U=!1;return I(!0),j(null),Jn().then(G=>{U||O(G.models)}).catch(G=>{U||j(G instanceof Error?G.message:"Failed to load models")}).finally(()=>{U||I(!1)}),()=>{U=!0}},[]);const Q=a.useCallback(()=>{const U={};return i.trim()||(U.name="Step name is required"),l==="command"&&!d.trim()&&(U.command="Command is required"),l==="ai-prompt"&&!c.trim()&&(U.prompt="Prompt is required"),l==="create-task"&&!y.trim()&&(U.taskDescription="Task description is required"),(l==="ai-prompt"||l==="create-task")&&(h||p)&&(!h||!p)&&(U.modelProvider="Both model provider and model ID must be set together"),A!==void 0&&A<1e3&&(U.timeoutMs="Timeout must be at least 1 second (1000ms)"),C(U),Object.keys(U).length===0},[i,l,d,c,y,h,p,A]),Y=h&&p?`${h}/${p}`:"",L=a.useCallback(U=>{if(!U)g(""),f("");else{const G=U.indexOf("/");G!==-1&&(g(U.slice(0,G)),f(U.slice(G+1)))}},[]),D=a.useCallback(()=>{if(!Q())return;const U={...t,name:i.trim(),type:l,command:l==="command"?d.trim():void 0,prompt:l==="ai-prompt"?c.trim():void 0,taskTitle:l==="create-task"&&b.trim()?b.trim():void 0,taskDescription:l==="create-task"&&y.trim()?y.trim():void 0,taskColumn:l==="create-task"?M:void 0,modelProvider:(l==="ai-prompt"||l==="create-task")&&h.trim()?h.trim():void 0,modelId:(l==="ai-prompt"||l==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:A||void 0,continueOnFailure:S};l!=="ai-prompt"&&delete U.prompt,l!=="create-task"&&(delete U.taskTitle,delete U.taskDescription,delete U.taskColumn),n(U)},[Q,n,t,i,l,d,c,b,y,M,h,p,A,S]);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:U=>r(U.target.value),"aria-invalid":!!P.name}),P.name&&e.jsx("small",{className:"field-error",children:P.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:U=>o(U.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:U=>m(U.target.value),rows:2,"aria-invalid":!!P.command}),P.command&&e.jsx("small",{className:"field-error",children:P.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:U=>u(U.target.value),rows:3,"aria-invalid":!!P.prompt}),P.prompt&&e.jsx("small",{className:"field-error",children:P.prompt})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-model-${t.id}`,children:"Model (optional)"}),e.jsx(Gt,{id:`step-model-${t.id}`,label:"Model",models:R,value:Y,onChange:L,placeholder:"Use default",disabled:Z}),_&&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:U=>x(U.target.value)}),e.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-task-description-${t.id}`,children:"Task Description *"}),e.jsx("textarea",{id:`step-task-description-${t.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:y,onChange:U=>v(U.target.value),rows:4,"aria-invalid":!!P.taskDescription}),P.taskDescription&&e.jsx("small",{className:"field-error",children:P.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:M,onChange:U=>N(U.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(Gt,{id:`step-task-model-${t.id}`,label:"Model",models:R,value:Y,onChange:L,placeholder:"Use default",disabled:Z}),_&&e.jsx("small",{className:"field-error",children:_}),P.modelProvider&&e.jsx("small",{className:"field-error",children:P.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:A??"",onChange:U=>w(U.target.value?Number(U.target.value):void 0),"aria-invalid":!!P.timeoutMs}),P.timeoutMs&&e.jsx("small",{className:"field-error",children:P.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:S,onChange:U=>k(U.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:D,children:"Save Step"})]})]})}function WA({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(f=>f.id===c);if(h<0)return;const g=u==="up"?h-1:h+1;if(g<0||g>=t.length)return;const p=[...t];[p[h],p[g]]=[p[g],p[h]],n(p)},[t,n]),m=a.useCallback(c=>{n(t.map(u=>u.id===c.id?c:u)),r(null)},[t,n]);return e.jsxs("div",{className:"steps-editor",children:[e.jsx("div",{className:"steps-editor-header",children:e.jsxs("span",{className:"steps-editor-title",children:["Steps (",t.length,")"]})}),t.length===0&&e.jsx("div",{className:"steps-empty-state",children:e.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),e.jsx("div",{className:"steps-list",children:t.map((c,u)=>e.jsx("div",{className:"step-card",children:i===c.id?e.jsx(VA,{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(Bo,{size:14})}),e.jsx("span",{className:"step-card-index",children:u+1}),e.jsx(HA,{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(Ht,{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(Vt,{size:14}),"Add Command Step"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("ai-prompt"),children:[e.jsx(Vt,{size:14}),"Add AI Prompt Step"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("create-task"),children:[e.jsx(Vt,{size:14}),"Add Create Task Step"]})]})]})}const Kp={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},KA={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function GA(t){const n=t.trim();for(const[s,i]of Object.entries(Kp))if(i===n)return s;return"custom"}function JA(t){const n=t.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function YA(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 QA(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 XA=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],ZA=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function om(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function cm({routine:t,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:l}){const o=!!t,d=t?QA(t):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[m,c]=a.useState(t?.name??""),[u,h]=a.useState(t?.description??""),[g,p]=a.useState(d.triggerType),[f,b]=a.useState(d.cronExpression),[x,y]=a.useState(()=>d.triggerType!=="cron"?"custom":GA(d.cronExpression)),[v,M]=a.useState(d.webhookPath),[N,A]=a.useState(d.webhookSecret),[w,S]=a.useState(d.endpoint),[k,P]=a.useState(t?.executionPolicy??"queue"),[C,R]=a.useState(t?.catchUpPolicy??"run_one"),[O,Z]=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,[j,Q]=a.useState(t?.steps&&t.steps.length>0&&!I&&!_?"advanced":"simple"),[Y,L]=a.useState(()=>I?"ai-prompt":_?"create-task":"command"),[D,U]=a.useState(t?.command??""),[G,E]=a.useState(t?.steps??[]),[J,ue]=a.useState(!1),[z,te]=a.useState(t?.timeoutMs??3e5),[F,fe]=a.useState(I?t.steps?.[0]?.prompt??"":""),[V,K]=a.useState(_?t.steps?.[0]?.taskTitle??"":""),[de,we]=a.useState(_?t.steps?.[0]?.taskDescription??"":""),[ve,Se]=a.useState(_?t.steps?.[0]?.taskColumn??"triage":"triage"),[Pe,Oe]=a.useState(I||_?t.steps?.[0]?.modelProvider??"":""),[Ie,rt]=a.useState(I||_?t.steps?.[0]?.modelId??"":""),[Ee,_e]=a.useState([]),[Be,et]=a.useState(!1),[De,Xe]=a.useState(null),[re,ne]=a.useState(i??"global"),[ge,le]=a.useState({}),[Te,ye]=a.useState(!1),He=a.useRef(!0);a.useEffect(()=>()=>{He.current=!1},[]),a.useEffect(()=>{i&&ne(i)},[i]),a.useEffect(()=>{let Ae=!1;return et(!0),Xe(null),Jn().then(We=>{Ae||_e(We.models)}).catch(We=>{Ae||Xe(We instanceof Error?We.message:"Failed to load models")}).finally(()=>{Ae||et(!1)}),()=>{Ae=!0}},[]);const nt=Pe&&Ie?`${Pe}/${Ie}`:"",mt=a.useCallback(Ae=>{if(!Ae){Oe(""),rt("");return}const We=Ae.indexOf("/");We!==-1&&(Oe(Ae.slice(0,We)),rt(Ae.slice(We+1)))},[]),he=a.useCallback(()=>{const Ae={};if(m.trim()||(Ae.name="Name is required"),re==="project"&&!r&&(Ae.scope="Project-specific entries require an active project."),g==="cron"&&x==="custom"&&(f.trim()?JA(f)||(Ae.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Ae.cronExpression="Cron expression is required"),g==="webhook"&&!v.trim()&&(Ae.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(Ae.endpoint="API endpoint is required"),j==="simple")Y==="command"&&!D.trim()&&(Ae.command="Command is required"),Y==="ai-prompt"&&!F.trim()&&(Ae.prompt="Prompt is required"),Y==="create-task"&&!de.trim()&&(Ae.taskDescription="Task description is required"),(Pe.trim()&&!Ie.trim()||!Pe.trim()&&Ie.trim())&&(Ae.model="Both model provider and model ID must be set, or both must be empty");else{G.length===0&&(Ae.steps="At least one step is required"),J&&(Ae.stepsEditing="Please save or cancel all step edits before saving the routine");const We=[];G.forEach((xt,yt)=>{xt.name?.trim()||We.push(`Step ${yt+1}: Name is required`),xt.type==="command"&&!xt.command?.trim()&&We.push(`Step ${yt+1}: Command is required`),xt.type==="ai-prompt"&&!xt.prompt?.trim()&&We.push(`Step ${yt+1}: Prompt is required`),xt.type==="create-task"&&!xt.taskDescription?.trim()&&We.push(`Step ${yt+1}: Task description is required`)}),We.length>0&&(Ae.steps=We.join("; "))}return z<1e3&&(Ae.timeoutMs="Timeout must be at least 1 second (1000ms)"),le(Ae),Object.keys(Ae).length===0},[m,g,f,x,v,w,re,r,j,Y,D,F,de,Pe,Ie,G,J,z]),ie=a.useCallback(async Ae=>{if(Ae.preventDefault(),!!he()){ye(!0);try{let We=t?.scope??re??(r?"project":"global");We==="project"&&!r&&(We="global");const xt=YA(g,f,v,N,w);let yt,Ct;j==="simple"?Y==="command"?yt=D.trim()||void 0:Y==="ai-prompt"?Ct=[{id:om(),type:"ai-prompt",name:m.trim(),prompt:F.trim(),modelProvider:Pe.trim()||void 0,modelId:Ie.trim()||void 0}]:Ct=[{id:om(),type:"create-task",name:m.trim(),taskTitle:V.trim()||void 0,taskDescription:de.trim(),taskColumn:ve,modelProvider:Pe.trim()||void 0,modelId:Ie.trim()||void 0}]:Ct=G;const Tt={name:m.trim(),agentId:t?.agentId??"",description:u.trim()||void 0,trigger:xt,command:yt,steps:Ct,timeoutMs:z,executionPolicy:k,catchUpPolicy:C,enabled:O,scope:We};await n(Tt)}finally{He.current&&ye(!1)}}},[he,n,m,u,g,f,v,N,w,j,Y,D,F,Pe,Ie,V,de,ve,G,z,k,C,O,re,r,t?.scope,t?.agentId]),be="routine-name-error",Me="routine-cron-error",Ze="routine-webhook-error",je="routine-endpoint-error",tt="routine-command-error",Ce="routine-prompt-error",qe="routine-task-description-error",ce="routine-model-error",Ue="routine-timeout-error",Ve=a.useCallback(Ae=>{y(Ae),Ae!=="custom"&&b(Kp[Ae])},[]);return e.jsxs("form",{className:"routine-form",onSubmit:ie,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:Ae=>c(Ae.target.value),"aria-invalid":!!ge.name,"aria-describedby":ge.name?be:void 0}),ge.name&&e.jsx("small",{id:be,className:"field-error",children:ge.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:Ae=>h(Ae.target.value),rows:2})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Scope"}),e.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[e.jsxs("button",{type:"button",className:`routine-scope-btn${re==="global"?" active":""}`,onClick:()=>{ne("global"),l?.("global")},role:"radio","aria-checked":re==="global"?"true":"false",disabled:!!t?.scope,title:t?.scope?`Scope is locked to ${t.scope} for existing routines`:"Global scope",children:[e.jsx(vi,{size:12}),"Global"]}),e.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{ne("project"),l?.("project")},role:"radio","aria-checked":re==="project"?"true":"false",disabled:!!t?.scope||!r,title:t?.scope?`Scope is locked to ${t.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[e.jsx(An,{size:12}),"Project"]})]}),e.jsx("small",{children:!r&&!t?.scope?"No active project. Routines will be created at global scope.":re==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ge.scope&&e.jsx("small",{className:"field-error",children:ge.scope})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Trigger Type"}),e.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[e.jsx(Fm,{size:14}),"Cron"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[e.jsx(Jm,{size:14}),"Webhook"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[e.jsx(Lm,{size:14}),"API"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[e.jsx(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:Ae=>Ve(Ae.target.value),children:Object.entries(KA).map(([Ae,We])=>e.jsx("option",{value:Ae,children:We},Ae))}),e.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),e.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:Ae=>b(Ae.target.value),disabled:x!=="custom","aria-invalid":!!ge.cronExpression,"aria-describedby":ge.cronExpression?Me:void 0}),ge.cronExpression?e.jsx("small",{id:Me,className:"field-error",children:ge.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: ${f}`})]}),g==="webhook"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),e.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:v,onChange:Ae=>M(Ae.target.value),"aria-invalid":!!ge.webhookPath,"aria-describedby":ge.webhookPath?Ze:void 0}),ge.webhookPath?e.jsx("small",{id:Ze,className:"field-error",children:ge.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:N,onChange:Ae=>A(Ae.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:Ae=>S(Ae.target.value),"aria-invalid":!!ge.endpoint,"aria-describedby":ge.endpoint?je:void 0}),ge.endpoint?e.jsx("small",{id:je,className:"field-error",children:ge.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${j==="simple"?" active":""}`,onClick:()=>Q("simple"),role:"radio","aria-checked":j==="simple",children:"Simple"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${j==="advanced"?" active":""}`,onClick:()=>Q("advanced"),role:"radio","aria-checked":j==="advanced",children:"Multi-Step"})]}),e.jsx("small",{children:j==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),j==="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${Y==="command"?" active":""}`,onClick:()=>L("command"),role:"radio","aria-checked":Y==="command",children:"Command"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="ai-prompt"?" active":""}`,onClick:()=>L("ai-prompt"),role:"radio","aria-checked":Y==="ai-prompt",children:"AI Prompt"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="create-task"?" active":""}`,onClick:()=>L("create-task"),role:"radio","aria-checked":Y==="create-task",children:"Create Task"})]})]}),Y==="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:D,onChange:Ae=>U(Ae.target.value),"aria-invalid":!!ge.command,"aria-describedby":ge.command?tt:void 0}),ge.command?e.jsx("small",{id:tt,className:"field-error",children:ge.command}):e.jsx("small",{children:"Shell command to execute."})]}):Y==="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:F,onChange:Ae=>fe(Ae.target.value),rows:3,"aria-invalid":!!ge.prompt,"aria-describedby":ge.prompt?Ce:void 0}),ge.prompt?e.jsx("small",{id:Ce,className:"field-error",children:ge.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(Gt,{id:"routine-model",label:"Model",models:Ee,value:nt,onChange:mt,placeholder:"Use default",disabled:Be}),De&&e.jsx("small",{className:"field-error",children:De}),ge.model&&e.jsx("small",{id:ce,className:"field-error",children:ge.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:V,onChange:Ae=>K(Ae.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:de,onChange:Ae=>we(Ae.target.value),rows:4,"aria-invalid":!!ge.taskDescription,"aria-describedby":ge.taskDescription?qe:void 0}),ge.taskDescription?e.jsx("small",{id:qe,className:"field-error",children:ge.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:Ae=>Se(Ae.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(Gt,{id:"routine-task-model",label:"Executor Model",models:Ee,value:nt,onChange:mt,placeholder:"Use default",disabled:Be}),De&&e.jsx("small",{className:"field-error",children:De}),ge.model&&e.jsx("small",{id:ce,className:"field-error",children:ge.model})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(WA,{steps:G,onChange:E,onEditingChange:ue}),ge.steps&&e.jsx("small",{className:"field-error",children:ge.steps}),ge.stepsEditing&&e.jsx("small",{className:"field-error",children:ge.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:z,onChange:Ae=>te(Number(Ae.target.value)),"aria-invalid":!!ge.timeoutMs,"aria-describedby":ge.timeoutMs?Ue:void 0}),ge.timeoutMs?e.jsx("small",{id:Ue,className:"field-error",children:ge.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:Ae=>P(Ae.target.value),children:XA.map(Ae=>e.jsx("option",{value:Ae.value,children:Ae.label},Ae.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:Ae=>R(Ae.target.value),children:ZA.map(Ae=>e.jsx("option",{value:Ae.value,children:Ae.label},Ae.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:O,onChange:Ae=>Z(Ae.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:Te,children:"Cancel"}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Te,children:Te?"Saving…":o?"Save Changes":"Create Routine"})]})]})}const eP=3e4;function tP({onClose:t,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[l,o]=a.useState([]),[d,m]=a.useState("list"),[c,u]=a.useState(),[h,g]=a.useState(null),p=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),f=a.useCallback(async()=>{try{const R=await Gv(p);o(R)}catch(R){n(xe(R)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const R=setInterval(()=>{f()},eP);return()=>clearInterval(R)},[f]),a.useEffect(()=>{const R=O=>{O.key==="Escape"&&(d!=="list"?(m("list"),u(void 0)):t())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[t,d]);const b=a.useCallback(R=>{R.target===R.currentTarget&&t()},[t]),x=a.useCallback(async R=>{try{await Jv(R,p),n("Routine created","success"),m("list"),await f()}catch(O){n(xe(O)||"Failed to create routine","error")}},[n,f,p]),y=a.useCallback(R=>{u(R),m("edit")},[]),v=a.useCallback(async R=>{if(c)try{await Yc(c.id,R,p),n("Routine updated","success"),m("list"),u(void 0),await f()}catch(O){n(xe(O)||"Failed to update routine","error")}},[c,n,f,p]),M=a.useCallback(async R=>{try{await Yv(R.id,p),n(`Deleted "${R.name}"`,"success"),await f()}catch(O){n(xe(O)||"Failed to delete routine","error")}},[n,f,p]),N=a.useCallback(async R=>{g(R.id);try{const{result:O}=await Qv(R.id,p);O.success?n(`"${R.name}" completed successfully`,"success"):n(`"${R.name}" failed: ${O.error||"Unknown error"}`,"error"),await f()}catch(O){n(xe(O)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),A=a.useCallback(async R=>{try{await Yc(R.id,{enabled:!R.enabled},p),n(`"${R.name}" ${R.enabled?"disabled":"enabled"}`,"success"),await f()}catch(O){n(xe(O)||"Failed to toggle routine","error")}},[n,f,p]),w=a.useCallback(()=>{m("list"),u(void 0)},[]),S=a.useCallback(R=>{r(R),m("list"),u(void 0)},[]),k=()=>d==="create"?e.jsx(cm,{onSubmit:x,onCancel:w,scope:i,projectId:s}):d==="edit"&&c?e.jsx(cm,{routine:c,onSubmit:v,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(Vt,{size:14}),"Create your first automation"]})]}):e.jsx("div",{className:"routine-list",children:l.map(R=>e.jsx(UA,{routine:R,onEdit:y,onDelete:M,onRun:N,onToggle:A,running:h===R.id},R.id))}),P=()=>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(Vt,{size:14}),"New Automation"]}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:e.jsx(Dt,{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:()=>S("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:()=>S("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[e.jsx(An,{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:P()})]})})}const nP=3e4,_o=new Map,Zl=new Map;function dm(t){return t??"default"}function um(t){const n=_o.get(t);return n?Date.now()>=n.expiresAt?(_o.delete(t),null):n:null}function sP(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 iP(t){const n=Zl.get(t);if(n)return n;const s=ji().then(({providers:i,ghCli:r})=>{const o={...sP(i,r),ghCli:r,expiresAt:Date.now()+nP};return _o.set(t,o),o}).finally(()=>{Zl.delete(t)});return Zl.set(t,s),s}function Gp(t){const n=dm(t),s=um(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=dm(t),p=um(g);if(p)return r(p.hasAiProvider),o(p.hasGithub),d(p.ghCli),c(!1),u.current=!0,()=>{h=!0};u.current=!1;async function f(){!u.current&&c(!0);try{const x=await iP(g);if(h)return;r(x.hasAiProvider),o(x.hasGithub),d(x.ghCli)}catch{}finally{h||(u.current=!0,c(!1))}}return f(),()=>{h=!0}},[t]),a.useMemo(()=>({hasAiProvider:i,hasGithub:l,loading:m,hasWarnings:!i||!l}),[i,l,m])}function Jp({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(Dt,{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 aP({isOpen:t,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:l,onPlanningMode:o,onSubtaskBreakdown:d}){const[m,c]=a.useState(""),[u,h]=a.useState([]),[g,p]=a.useState([]),[f,b]=a.useState(!1),[x,y]=a.useState(""),[v,M]=a.useState(""),[N,A]=a.useState(""),[w,S]=a.useState(""),[k,P]=a.useState(""),[C,R]=a.useState("default"),[O,Z]=a.useState(!1),[I,_]=a.useState([]),[j,Q]=a.useState(!1),[Y,L]=a.useState(void 0),[D,U]=a.useState(cs),[G,E]=a.useState(null),[J,ue]=a.useState([]),[z,te]=a.useState(!1),[F,fe]=a.useState(!1),V=a.useRef(null),[K,de]=a.useState(!1),[we,ve]=a.useState(""),Se=a.useRef(null),{hasAiProvider:Pe,hasGithub:Oe,loading:Ie}=Gp(s),rt=a.useCallback(ye=>{Q(!0),_(ye)},[]),Ee=a.useCallback(()=>{Q(!1)},[]),_e=a.useCallback(async()=>{if(J.length>0){te(!0);return}fe(!0);try{const ye=await aa(void 0,s);ue(ye),te(!0)}catch(ye){const He=xe(ye);l(He?`Failed to load agents: ${He}`:"Failed to load agents","error"),te(!1)}finally{fe(!1)}},[J.length,s,l]);a.useEffect(()=>{if(!z)return;const ye=He=>{V.current&&!V.current.contains(He.target)&&te(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[z]),a.useEffect(()=>{if(!K)return;const ye=He=>{Se.current&&!Se.current.contains(He.target)&&(de(!1),ve(""))};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[K]);const Be=i.filter(ye=>!u.includes(ye.id)).sort((ye,He)=>{const nt=He.createdAt.localeCompare(ye.createdAt);if(nt!==0)return nt;const mt=parseInt(ye.id.slice(ye.id.lastIndexOf("-")+1),10)||0;return(parseInt(He.id.slice(He.id.lastIndexOf("-")+1),10)||0)-mt}),et=we?Be.filter(ye=>ye.id.toLowerCase().includes(we.toLowerCase())||ye.title&&ye.title.toLowerCase().includes(we.toLowerCase())||ye.description&&ye.description.toLowerCase().includes(we.toLowerCase())):Be,De=(ye,He)=>ye.length>He?ye.slice(0,He)+"…":ye;a.useEffect(()=>{const ye=m.trim()!==""||u.length>0||g.length>0||x!==""||v!==""||N!==""||w!==""||I.length>0||G!==null||Y!==void 0||D!==cs;Z(ye)},[m,u,g,x,v,N,w,I,G,Y,D]);const Xe=a.useCallback(()=>{O&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(ye=>URL.revokeObjectURL(ye.previewUrl)),p([]),c(""),h([]),y(""),M(""),A(""),S(""),P(""),R("default"),_([]),Q(!1),E(null),te(!1),L(void 0),U(cs),Z(!1),n())},[O,n,g]),re=a.useCallback(async()=>{const ye=m.trim();if(!(!ye||f)){b(!0);try{const He=x.indexOf("/"),nt=v.indexOf("/"),mt=N.indexOf("/"),he=await r({title:void 0,description:ye,column:"triage",dependencies:u.length?u:void 0,enabledWorkflowSteps:j?I.length>0?I:[]:void 0,...G?{assignedAgentId:G}:{},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:v&&nt!==-1?v.slice(0,nt):void 0,validatorModelId:v&&nt!==-1?v.slice(nt+1):void 0,planningModelProvider:N&&mt!==-1?N.slice(0,mt):void 0,planningModelId:N&&mt!==-1?N.slice(mt+1):void 0,thinkingLevel:w!==""?w:void 0,reviewLevel:Y,priority:D});if(g.length>0){const ie=[];for(const be of g)try{await $a(he.id,be.file,s)}catch{ie.push(be.file.name)}ie.length>0&&l(`Failed to upload: ${ie.join(", ")}`,"error")}g.forEach(ie=>URL.revokeObjectURL(ie.previewUrl)),p([]),c(""),h([]),y(""),M(""),A(""),S(""),P(""),R("default"),_([]),Q(!1),E(null),te(!1),L(void 0),U(cs),l(`Created ${he.id}`,"success"),n()}catch(He){l(xe(He)||"Failed to create task","error")}finally{b(!1)}}},[m,u,g,x,v,N,w,f,r,l,n,s,C,k,I,j,G,Y,D]),ne=a.useCallback(ye=>{ye.key==="Escape"&&(ye.preventDefault(),Xe())},[Xe]),le=(G?J.find(ye=>ye.id===G):void 0)?.name??G,Te=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:Se,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(ye=>!ye),disabled:f,"data-testid":"dep-trigger",children:u.length>0?`${u.length} selected`:"Add dependencies"}),K&&e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:we,onChange:ye=>ve(ye.target.value),onClick:ye=>ye.stopPropagation()}),et.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):et.map(ye=>e.jsxs("div",{className:`dep-dropdown-item${u.includes(ye.id)?" selected":""}`,onClick:()=>{h(u.includes(ye.id)?u.filter(He=>He!==ye.id):[...u,ye.id]),de(!1),ve("")},onMouseDown:He=>He.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:ye.id}),e.jsx("span",{className:"dep-dropdown-title",children:De(ye.title||ye.description||ye.id,30)})]},ye.id))]})]}),u.length>0&&e.jsx("div",{className:"selected-deps",children:u.map(ye=>e.jsxs("span",{className:"dep-chip",children:[ye,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(u.filter(He=>He!==ye)),disabled:f,children:"×"})]},ye))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Assign Agent"}),e.jsxs("div",{className:"agent-trigger-wrap",ref:V,children:[e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{z?te(!1):_e()},disabled:f,"data-testid":"new-task-agent-button",children:[e.jsx(an,{size:12,style:{verticalAlign:"middle"}}),le?` ${le}`:" Assign agent"]}),z&&e.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ye=>ye.preventDefault(),children:[e.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),F&&e.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!F&&J.filter(ye=>ye.state!=="terminated").map(ye=>e.jsxs("div",{className:`dep-dropdown-item${G===ye.id?" selected":""}`,onMouseDown:He=>He.preventDefault(),onClick:()=>{E(ye.id===G?null:ye.id),te(!1)},"data-testid":`agent-option-${ye.id}`,children:[e.jsx(an,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:ye.role}),e.jsx("span",{className:"dep-dropdown-title",children:ye.name})]},ye.id)),!F&&J.filter(ye=>ye.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),G&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:ye=>ye.preventDefault(),onClick:()=>{E(null),te(!1)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return t?e.jsx("div",{className:"modal-overlay open",onClick:Xe,onKeyDown:ne,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ye=>ye.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"New Task"}),e.jsx("button",{className:"modal-close",onClick:Xe,disabled:f,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[!Ie&&e.jsx(Jp,{hasAiProvider:Pe,hasGithub:Oe}),e.jsx(Op,{mode:"create",description:m,onDescriptionChange:c,dependencies:u,onDependenciesChange:h,executorModel:x,onExecutorModelChange:y,validatorModel:v,onValidatorModelChange:M,presetMode:C,onPresetModeChange:R,selectedPresetId:k,onSelectedPresetIdChange:P,selectedWorkflowSteps:I,onWorkflowStepsChange:rt,onDefaultOnApplied:Ee,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:l,isActive:t,onPlanningMode:o,onSubtaskBreakdown:d,onClose:Xe,planningModel:N,onPlanningModelChange:A,thinkingLevel:w,onThinkingLevelChange:S,reviewLevel:Y,onReviewLevelChange:L,priority:D,onPriorityChange:U,renderBelowPrimary:Te,hideDependencies:!0})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:Xe,disabled:f,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:re,disabled:!m.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const rP=5e3;function lP(t={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:l=!1}=t,[o,d]=a.useState([]),[m,c]=a.useState(!1),[u,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),b=a.useRef(void 0),x=a.useCallback(async()=>{try{c(!0),h(null);let M;l?M=await ad({limit:i,projectId:n,type:s}):M=(await Qc({limit:i,type:s,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),d(M),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load activity log")}finally{c(!1)}},[i,n,s,l]),y=a.useCallback(async()=>{if(b.current)try{c(!0);let M;l?M=await ad({limit:i,projectId:n,type:s,since:b.current}):M=(await Qc({limit:i,type:s,since:b.current,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),d(N=>[...N,...M]),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load more entries")}finally{c(!1)}},[i,n,s,l]),v=a.useCallback(()=>{d([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{x()},[x]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{x()},rP),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,x]),{entries:o,loading:m,error:u,refresh:x,clear:v,hasMore:g,loadMore:y}}const eo={"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"},oP={"task:created":e.jsx(Vt,{size:14,className:"activity-icon created"}),"task:moved":e.jsx(Oa,{size:14,className:"activity-icon moved"}),"task:updated":e.jsx(Mn,{size:14,className:"activity-icon updated"}),"task:deleted":e.jsx(Dt,{size:14,className:"activity-icon deleted"}),"task:merged":e.jsx(tn,{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 cP(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 dP({isOpen:t,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:l=[],onProjectFilterChange:o,currentProject:d}){const[m,c]=a.useState("all"),[u,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=m==="all"?void 0:m,b=u==="all"?void 0:u,x=!d&&l.length>0,{entries:y,loading:v,error:M,refresh:N,hasMore:A}=lP({projectId:b,type:f,limit:100,autoRefresh:t,useCentralFeed:x}),w=y.map(R=>({id:R.id,timestamp:R.timestamp,type:R.type,taskId:R.taskId,taskTitle:R.taskTitle,details:R.details,metadata:R.metadata,projectId:R.projectId,projectName:R.projectName})),S=async()=>{try{await Xv(),N(),p(!1)}catch{p(!1)}},k=R=>{i&&i(R)},P=R=>{h(R),o?.(R==="all"?void 0:R)};a.useEffect(()=>{if(!t)return;const R=O=>{O.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[t,n,g]);const C=m!=="all"||u!=="all";return t?e.jsx("div",{className:"modal-overlay open",onClick:R=>{R.target===R.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(_a,{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(An,{size:14}),e.jsxs("select",{value:u,onChange:R=>P(R.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[e.jsx("option",{value:"all",children:"All Projects"}),l.map(R=>e.jsx("option",{value:R.id,children:R.name},R.id))]})]}),e.jsxs("div",{className:"activity-log-filter",children:[e.jsx(Sr,{size:14}),e.jsxs("select",{value:m,onChange:R=>c(R.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[e.jsx("option",{value:"all",children:"All Events"}),Object.entries(eo).map(([R,O])=>e.jsx("option",{value:R,children:O},R))]})]}),e.jsx("button",{className:"activity-log-refresh",onClick:()=>N(),title:"Refresh","data-testid":"activity-refresh",children:v?e.jsx(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14})}),w.length>0&&e.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:e.jsx(Ht,{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(R=>R.id===u)?.name||u]}),m!=="all"&&e.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",eo[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:[M&&e.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[e.jsx(is,{size:16}),e.jsx("span",{children:M})]}),w.length===0&&!v&&!M&&e.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[e.jsx(_a,{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(R=>e.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[e.jsx("div",{className:"activity-log-entry-icon",children:oP[R.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:eo[R.type]}),e.jsx("span",{className:"activity-log-entry-time",children:cP(R.timestamp)})]}),e.jsxs("div",{className:"activity-log-entry-details",children:[R.taskId&&e.jsx("button",{className:"activity-log-task-link",onClick:()=>k(R.taskId),"data-testid":"activity-task-link",children:R.taskId}),R.taskTitle&&e.jsx("span",{className:"activity-log-task-title",children:R.taskTitle}),e.jsx("span",{className:"activity-log-entry-text",children:R.details})]}),R.metadata&&Object.keys(R.metadata).length>0&&e.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof R.metadata.from=="string"&&typeof R.metadata.to=="string"&&e.jsxs("span",{className:"activity-log-metadata-item",children:[R.metadata.from," → ",R.metadata.to]}),typeof R.metadata.merged=="boolean"&&e.jsx("span",{className:`activity-log-metadata-item ${R.metadata.merged?"success":"error"}`,children:R.metadata.merged?"Merged":"Not merged"})]})]})]},R.id))}),A&&!v&&e.jsx("button",{className:"activity-log-load-more",onClick:N,"data-testid":"activity-load-more",children:"Load More"}),v&&w.length>0&&e.jsx("div",{className:"activity-log-loading",children:e.jsx(lt,{size:20,className:"spin"})})]}),g&&e.jsx("div",{className:"activity-log-confirm-overlay",children:e.jsxs("div",{className:"activity-log-confirm-dialog",children:[e.jsx("h3",{children:"Clear Activity Log?"}),e.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),e.jsxs("div",{className:"activity-log-confirm-actions",children:[e.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),e.jsx("button",{className:"activity-log-confirm-clear",onClick:S,children:"Clear Log"})]})]})})]})}):null}const ka=[{id:"status",label:"Status",icon:Wm},{id:"changes",label:"Changes",icon:zm},{id:"commits",label:"Commits",icon:Ra},{id:"branches",label:"Branches",icon:Fs},{id:"worktrees",label:"Worktrees",icon:zg},{id:"stashes",label:"Stashes",icon:Br},{id:"remotes",label:"Remotes",icon:Um}];function mm({status:t}){switch(t){case"added":case"untracked":return e.jsx(yg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return e.jsx(Om,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return e.jsx(bg,{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(jg,{size:14,className:"gm-file-icon"})}}function hm({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 uP(t){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),t(`Copied ${s||"to clipboard"}`,"success")}catch{t("Failed to copy","error")}},[t])}function Xi(t){if(!t)return"—";const n=new Date(t);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const l=Math.floor(r/60);if(l<24)return`${l}h ago`;const o=Math.floor(l/24);return o<30?`${o}d ago`:n.toLocaleDateString()}function mP({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=uP(i),[p,f]=a.useState(null),[b,x]=a.useState([]),[y,v]=a.useState(new Set),[M,N]=a.useState(""),[A,w]=a.useState(!1),[S,k]=a.useState(null),[P,C]=a.useState(!1),[R,O]=a.useState([]),[Z,I]=a.useState(null),[_,j]=a.useState(null),[Q,Y]=a.useState(!1),[L,D]=a.useState(20),[U,G]=a.useState(""),[E,J]=a.useState([]),[ue,z]=a.useState(""),[te,F]=a.useState(""),[fe,V]=a.useState(""),[K,de]=a.useState(null),[we,ve]=a.useState([]),[Se,Pe]=a.useState(!1),[Oe,Ie]=a.useState(null),[rt,Ee]=a.useState(null),[_e,Be]=a.useState(!1),[et,De]=a.useState([]),[Xe,re]=a.useState([]),[ne,ge]=a.useState(""),[le,Te]=a.useState(null),[ye,He]=a.useState(null),[nt,mt]=a.useState(null),he=a.useCallback(async()=>{if(t){m(!0),u(null);try{switch(l){case"status":{const q=await Cs(r);f(q);break}case"changes":{const[q,$]=await Promise.all([Cs(r),Pi(r)]);f(q),x($),v(new Set);break}case"commits":{const q=await av(L,r);O(q);break}case"branches":{const[q,$]=await Promise.all([ca(r),Cs(r)]);J(q),f($);break}case"worktrees":{const q=await cv(r);De(q);break}case"stashes":{const q=await nr(r);re(q);break}case"remotes":{const q=await Cs(r);f(q);break}}}catch(q){u(xe(q)||"Failed to fetch git data"),i(xe(q)||"Failed to fetch git data","error")}finally{m(!1)}}},[l,t,L,i,r]);a.useEffect(()=>{t&&he()},[he,t]),a.useEffect(()=>{if(!t)return;const q=$=>{if($.key==="Escape"){n();return}if(($.key==="ArrowUp"||$.key==="ArrowDown")&&$.altKey){$.preventDefault();const pe=ka.findIndex(ct=>ct.id===l);$.key==="ArrowUp"&&pe>0?o(ka[pe-1].id):$.key==="ArrowDown"&&pe<ka.length-1&&o(ka[pe+1].id)}};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[t,n,l]);const ie=a.useCallback(async q=>{try{await Wc(q,r),i(`Staged ${q.length} file(s)`,"success");const $=await Pi(r);x($),v(new Set)}catch($){i(xe($)||"Failed to stage files","error")}},[i,r]),be=a.useCallback(async q=>{try{await vv(q,r),i(`Unstaged ${q.length} file(s)`,"success");const $=await Pi(r);x($),v(new Set)}catch($){i(xe($)||"Failed to unstage files","error")}},[i,r]),Me=a.useCallback(async q=>{if(confirm(`Discard changes to ${q.length} file(s)? This cannot be undone.`))try{await yv(q,r),i(`Discarded changes to ${q.length} file(s)`,"success");const[$,pe]=await Promise.all([Pi(r),Cs(r)]);x($),f(pe),v(new Set)}catch($){i(xe($)||"Failed to discard changes","error")}},[i,r]),Ze=a.useCallback(async q=>{if(q.preventDefault(),!!M.trim()){w(!0);try{const $=await Kc(M.trim(),r);i(`Committed: ${$.hash}`,"success"),N("");const[pe,ct]=await Promise.all([Pi(r),Cs(r)]);x(pe),f(ct)}catch($){i(xe($)||"Failed to commit","error")}finally{w(!1)}}},[M,i,r]),je=a.useCallback(async()=>{if(M.trim()){w(!0);try{const q=b.filter(bt=>!bt.staged).map(bt=>bt.file);q.length>0&&await Wc(q,r);const $=await Kc(M.trim(),r);i(`Committed: ${$.hash}`,"success"),N("");const[pe,ct]=await Promise.all([Pi(r),Cs(r)]);x(pe),f(ct)}catch(q){i(xe(q)||"Failed to commit","error")}finally{w(!1)}}},[M,b,i,r]),tt=a.useCallback(async()=>{C(!0);try{const q=await xv(r);k(q)}catch(q){i(xe(q)||"Failed to load diff","error")}finally{C(!1)}},[i,r]),Ce=a.useCallback(q=>{v($=>{const pe=new Set($);return pe.has(q)?pe.delete(q):pe.add(q),pe})},[]),qe=a.useCallback(async q=>{if(Z===q){I(null),j(null);return}I(q),Y(!0);try{const $=await Ar(q,r);j($)}catch($){i(xe($)||"Failed to load diff","error"),j(null)}finally{Y(!1)}},[Z,i,r]),ce=a.useCallback(()=>{D(q=>Math.min(q+20,100))},[]),Ue=a.useMemo(()=>{if(!U.trim())return R;const q=U.toLowerCase();return R.filter($=>$.message.toLowerCase().includes(q)||$.author.toLowerCase().includes(q)||$.shortHash.toLowerCase().includes(q))},[R,U]),Ve=a.useCallback(async q=>{if(q.preventDefault(),!!ue.trim()){m(!0);try{await dv(ue.trim(),te.trim()||void 0,r),i(`Created branch ${ue}`,"success"),z(""),F("");const $=await ca(r);J($)}catch($){i(xe($)||"Failed to create branch","error")}finally{m(!1)}}},[ue,te,i,r]),Ae=a.useCallback(async q=>{m(!0);try{await uv(q,r),i(`Switched to ${q}`,"success");const[$,pe]=await Promise.all([Cs(r),ca(r)]);f($),J(pe)}catch($){i(xe($)||"Failed to checkout branch","error")}finally{m(!1)}},[i,r]),We=a.useCallback(async q=>{if(confirm(`Delete branch "${q}"?`)){m(!0);try{await Vc(q,void 0,r),i(`Deleted branch ${q}`,"success");const $=await ca(r);J($)}catch($){if(xe($).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await Vc(q,!0,r),i(`Force deleted branch ${q}`,"success");const pe=await ca(r);J(pe)}catch(pe){i(xe(pe)||"Failed to delete branch","error")}}else i(xe($)||"Failed to delete branch","error")}finally{m(!1)}}},[i,r]),xt=a.useMemo(()=>{if(!fe.trim())return E;const q=fe.toLowerCase();return E.filter($=>$.name.toLowerCase().includes(q))},[E,fe]),yt=a.useCallback(async q=>{if(K===q){de(null),ve([]),Ie(null),Ee(null);return}de(q),ve([]),Ie(null),Ee(null),Pe(!0);try{const $=await ov(q,10,r);ve($)}catch{ve([])}finally{Pe(!1)}},[K,r]),Ct=a.useCallback(async q=>{if(Oe===q){Ie(null),Ee(null);return}Ie(q),Ee(null),Be(!0);try{const $=await Ar(q,r);Ee($)}catch{Ee(null)}finally{Be(!1)}},[Oe,r]),Tt=a.useCallback(()=>{de(null),ve([]),Ie(null),Ee(null)},[]),Et=a.useCallback(async q=>{q.preventDefault(),Te("create");try{await fv(ne.trim()||void 0,r),i("Changes stashed","success"),ge("");const $=await nr(r);re($)}catch($){i(xe($)||"Failed to stash changes","error")}finally{Te(null)}},[ne,i,r]),Mt=a.useCallback(async(q,$=!1)=>{Te(`apply-${q}`);try{await gv(q,$,r),i($?"Stash popped":"Stash applied","success");const pe=await nr(r);re(pe)}catch(pe){i(xe(pe)||"Failed to apply stash","error")}finally{Te(null)}},[i,r]),vt=a.useCallback(async q=>{if(confirm(`Drop stash@{${q}}? This cannot be undone.`)){Te(`drop-${q}`);try{await bv(q,r),i("Stash dropped","success");const $=await nr(r);re($)}catch($){i(xe($)||"Failed to drop stash","error")}finally{Te(null)}}},[i,r]),Ft=a.useCallback(async()=>{He("fetch");try{const q=await mv(void 0,r);mt(q),i(q.message||"Fetch completed",q.fetched?"success":"info");const $=await Cs(r);f($)}catch(q){i(xe(q)||"Fetch failed","error")}finally{He(null)}},[i,r]),Je=a.useCallback(async()=>{He("pull");try{const q=await hv(r);mt(q),q.conflict?i("Merge conflict detected. Resolve manually.","error"):i(q.message||"Pull completed","success");const $=await Cs(r);f($)}catch(q){i(xe(q)||"Pull failed","error")}finally{He(null)}},[i,r]),pt=a.useCallback(async()=>{He("push");try{const q=await pv(r);mt(q),i(q.message||"Push completed","success");const $=await Cs(r);f($)}catch(q){i(xe(q)||"Push failed","error")}finally{He(null)}},[i,r]),ze=a.useMemo(()=>b.filter(q=>q.staged),[b]),at=a.useMemo(()=>b.filter(q=>!q.staged),[b]);return t?e.jsx("div",{className:"modal-overlay open",onClick:q=>q.target===q.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(co,{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:he,disabled:d,title:"Refresh",children:e.jsx(Mn,{size:14,className:d?"spin":""})}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Dt,{size:18})})]})]}),e.jsxs("div",{className:"gm-layout",children:[e.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ka.map(q=>{const $=q.icon;return e.jsxs("button",{role:"tab","aria-selected":l===q.id,className:`gm-nav-item${l===q.id?" active":""}`,onClick:()=>o(q.id),children:[e.jsx($,{size:16}),e.jsx("span",{className:"gm-nav-label",children:q.label})]},q.id)})}),e.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&e.jsxs("div",{className:"gm-loading",children:[e.jsx(lt,{size:24,className:"spin"}),e.jsx("span",{children:"Loading..."})]}),c&&!d&&e.jsxs("div",{className:"gm-error",children:[e.jsx(is,{size:18}),e.jsx("span",{children:c}),e.jsx("button",{className:"btn btn-sm",onClick:he,children:"Retry"})]}),l==="status"&&!d&&p&&e.jsx(hP,{status:p,copyToClipboard:g}),l==="changes"&&!d&&e.jsx(pP,{status:p,stagedFiles:ze,unstagedFiles:at,selectedFiles:y,toggleFileSelection:Ce,onStageFiles:ie,onUnstageFiles:be,onDiscardChanges:Me,onViewDiff:tt,changeDiff:S,loadingChangeDiff:P,commitMessage:M,setCommitMessage:N,onCommit:Ze,onStageAllAndCommit:je,committing:A}),l==="commits"&&!d&&e.jsx(fP,{commits:Ue,commitSearch:U,setCommitSearch:G,selectedCommit:Z,commitDiff:_,loadingDiff:Q,onCommitClick:qe,onLoadMore:ce,canLoadMore:R.length>=L&&L<100,copyToClipboard:g}),l==="branches"&&!d&&e.jsx(gP,{branches:xt,branchSearch:fe,setBranchSearch:V,newBranchName:ue,setNewBranchName:z,branchBase:te,setBranchBase:F,onCreateBranch:Ve,onCheckoutBranch:Ae,onDeleteBranch:We,loading:d,allBranches:E,selectedBranch:K,branchCommits:we,loadingBranchCommits:Se,expandedBranchCommit:Oe,branchCommitDiff:rt,loadingBranchCommitDiff:_e,onSelectBranch:yt,onBranchCommitClick:Ct,onCloseBranchDetails:Tt}),l==="worktrees"&&!d&&e.jsx(bP,{worktrees:et}),l==="stashes"&&!d&&e.jsx(xP,{stashes:Xe,stashMessage:ne,setStashMessage:ge,onCreateStash:Et,onApplyStash:Mt,onDropStash:vt,stashLoading:le}),l==="remotes"&&!d&&e.jsx(vP,{status:p,remoteLoading:ye,lastRemoteResult:nt,onFetch:Ft,onPull:Je,onPush:pt,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function hP({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(qi,{size:12})})]})]}),e.jsxs("div",{className:"gm-status-card",children:[e.jsx("span",{className:"gm-status-label",children:"Working Tree"}),e.jsx("span",{className:`gm-status-badge ${t.isDirty?"dirty":"clean"}`,children:t.isDirty?e.jsxs(e.Fragment,{children:[e.jsx(is,{size:12}),"Modified"]}):e.jsxs(e.Fragment,{children:[e.jsx(tn,{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(tn,{size:12}),"Up to date"]})]})]})]})]})}function pP({status:t,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:l,onUnstageFiles:o,onDiscardChanges:d,onViewDiff:m,changeDiff:c,loadingChangeDiff:u,commitMessage:h,setCommitMessage:g,onCommit:p,onStageAllAndCommit:f,committing:b}){const x=s.filter(v=>i.has(`unstaged:${v.file}`)),y=n.filter(v=>i.has(`staged:${v.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:[x.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>l(x.map(v=>v.file)),title:"Stage selected",children:[e.jsx(Vt,{size:12})," Stage (",x.length,")"]}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>d(x.map(v=>v.file)),title:"Discard selected",children:e.jsx(Ba,{size:12})})]}),s.length>0&&e.jsx("button",{className:"btn btn-sm",onClick:()=>l(s.map(v=>v.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(v=>e.jsxs("div",{className:"gm-file-item",children:[e.jsx("label",{className:"gm-file-checkbox",children:e.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${v.file}`),onChange:()=>r(`unstaged:${v.file}`)})}),e.jsx(mm,{status:v.status}),e.jsx("span",{className:"gm-file-name",title:v.file,children:v.file}),e.jsx(hm,{status:v.status}),e.jsx("button",{className:"gm-icon-btn",onClick:()=>l([v.file]),title:"Stage file",children:e.jsx(Vt,{size:12})})]},`unstaged:${v.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:[y.length>0&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>o(y.map(v=>v.file)),title:"Unstage selected",children:["Unstage (",y.length,")"]}),n.length>0&&e.jsx("button",{className:"btn btn-sm",onClick:()=>o(n.map(v=>v.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(v=>e.jsxs("div",{className:"gm-file-item staged",children:[e.jsx("label",{className:"gm-file-checkbox",children:e.jsx("input",{type:"checkbox",checked:i.has(`staged:${v.file}`),onChange:()=>r(`staged:${v.file}`)})}),e.jsx(mm,{status:v.status}),e.jsx("span",{className:"gm-file-name",title:v.file,children:v.file}),e.jsx(hm,{status:v.status}),e.jsx("button",{className:"gm-icon-btn",onClick:()=>o([v.file]),title:"Unstage file",children:e.jsx(Dt,{size:12})})]},`staged:${v.file}`))})]}),s.length>0&&e.jsxs("div",{className:"gm-diff-section",children:[e.jsxs("button",{className:"btn btn-sm",onClick:m,disabled:u,children:[u?e.jsx(lt,{size:14,className:"spin"}):e.jsx(zm,{size:14}),"View Diff"]}),c&&e.jsxs("div",{className:"gm-diff-viewer",children:[c.stat&&e.jsx("pre",{className:"gm-diff-stat",children:c.stat}),e.jsx("pre",{className:"gm-diff-patch",children:c.patch})]})]}),e.jsxs("form",{className:"gm-commit-form",onSubmit:p,children:[e.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:h,onChange:v=>g(v.target.value),rows:3,disabled:b}),e.jsxs("div",{className:"gm-commit-actions",children:[e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!h.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?e.jsx(lt,{size:14,className:"spin"}):e.jsx(fi,{size:14}),"Commit"]}),s.length>0&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:f,disabled:b||!h.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function fP({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:Xi(u.date)}),u.parents.length>1&&e.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),e.jsx("div",{className:"gm-commit-actions-row",children:e.jsx("button",{className:"gm-icon-btn",onClick:()=>c(u.hash,"commit hash"),title:"Copy full hash",children:e.jsx(qi,{size:12})})}),i===u.hash&&e.jsx("div",{className:"gm-commit-diff",children:l?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(lt,{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 gP({branches:t,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:l,setBranchBase:o,onCreateBranch:d,onCheckoutBranch:m,onDeleteBranch:c,loading:u,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:b,branchCommitDiff:x,loadingBranchCommitDiff:y,onSelectBranch:v,onBranchCommitClick:M,onCloseBranchDetails:N}){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:A=>s(A.target.value)})]})]}),e.jsxs("form",{className:"gm-create-form",onSubmit:d,children:[e.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:A=>r(A.target.value),disabled:u}),e.jsxs("select",{value:l,onChange:A=>o(A.target.value),disabled:u,className:"gm-branch-select",children:[e.jsx("option",{value:"",children:"Base: HEAD"}),h.map(A=>e.jsx("option",{value:A.name,children:A.name},A.name))]}),e.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:u||!i.trim(),children:[e.jsx(Vt,{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(A=>e.jsxs("div",{children:[e.jsxs("div",{className:`gm-branch-item${A.isCurrent?" current":""}${g===A.name?" selected":""}`,onClick:()=>v(A.name),children:[e.jsxs("div",{className:"gm-branch-info",children:[e.jsxs("span",{className:"gm-branch-name",children:[A.isCurrent&&e.jsx(En,{size:14,className:"gm-current-icon"}),A.name]}),A.remote&&e.jsxs("span",{className:"gm-branch-remote",children:["→ ",A.remote]}),A.lastCommitDate&&e.jsx("span",{className:"gm-branch-date",children:Xi(A.lastCommitDate)})]}),e.jsx("div",{className:"gm-branch-actions",children:!A.isCurrent&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),m(A.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(A.name)},disabled:u,title:"Delete",children:e.jsx(Ht,{size:14})})]})})]}),g===A.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 ",A.name]}),e.jsx("button",{className:"gm-icon-btn",onClick:N,title:"Close","data-testid":"close-branch-details",children:e.jsx(Dt,{size:14})})]}),f?e.jsxs("div",{className:"gm-branch-details-loading",children:[e.jsx(lt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?e.jsx("div",{className:"gm-empty",children:"No commits found"}):e.jsx("div",{className:"gm-branch-commits-list",children:p.map(w=>e.jsxs("div",{className:"gm-branch-commit",children:[e.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>M(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:Xi(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:y?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(lt,{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))})]})]},A.name))})]})}function bP({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 xP({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(lt,{size:14,className:"spin"}):e.jsx(Br,{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:Xi(d.date)})]})]}),e.jsxs("div",{className:"gm-stash-actions",children:[e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(d.index,!1),disabled:o!==null,title:"Apply stash (keep)",children:o===`apply-${d.index}`?e.jsx(lt,{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(lt,{size:14,className:"spin"}):e.jsx(Ht,{size:14})})]})]},d.index))})]})}function vP({status:t,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:l,addToast:o,projectId:d,copyToClipboard:m}){const c=ne=>{try{return new URL(ne).hostname}catch{return ne.replace(/^git@/,"").split(":")[0]||ne}},[u,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[x,y]=a.useState(""),[v,M]=a.useState(""),[N,A]=a.useState(null),[w,S]=a.useState(""),[k,P]=a.useState(""),[C,R]=a.useState(!1),[O,Z]=a.useState([]),[I,_]=a.useState(!1),[j,Q]=a.useState(null),[Y,L]=a.useState([]),[D,U]=a.useState(!1),[G,E]=a.useState(null),J=u.find(ne=>ne.name===j),[ue,z]=a.useState(null),[te,F]=a.useState(null),[fe,V]=a.useState(!1),[K,de]=a.useState(null),[we,ve]=a.useState(null),[Se,Pe]=a.useState(!1);a.useEffect(()=>{Oe()},[]),a.useEffect(()=>{t&&t.ahead>0?Ie():t&&t.ahead===0&&Z([])},[t?.ahead]),a.useEffect(()=>{u.length>0&&!j&&Q(u[0].name)},[u]),a.useEffect(()=>{j?rt(j):(L([]),E(null))},[j]),a.useEffect(()=>{j&&!u.find(ne=>ne.name===j)&&Q(u.length>0?u[0].name:null)},[u,j]);const Oe=async()=>{p(!0);try{const ne=await nh(d);h(ne)}catch(ne){o(xe(ne)||"Failed to load remotes","error")}finally{p(!1)}},Ie=async()=>{_(!0);try{const ne=await rv(d);Z(ne)}catch{Z([])}finally{_(!1)}},rt=async ne=>{U(!0),E(null);try{const ge=await lv(ne,void 0,10,d);L(ge)}catch(ge){E(xe(ge)||"Failed to load remote commits"),L([])}finally{U(!1)}},Ee=async ne=>{if(ne.preventDefault(),!(!x.trim()||!v.trim())){b("add");try{await Qx(x.trim(),v.trim(),d),o(`Remote '${x}' added successfully`,"success"),y(""),M(""),R(!1),await Oe()}catch(ge){o(xe(ge)||"Failed to add remote","error")}finally{b(null)}}},_e=async ne=>{if(confirm(`Are you sure you want to remove remote '${ne}'?`)){b(`remove-${ne}`);try{await Xx(ne,d),o(`Remote '${ne}' removed`,"success"),await Oe()}catch(ge){o(xe(ge)||"Failed to remove remote","error")}finally{b(null)}}},Be=async ne=>{if(k.trim()){b(`rename-${ne}`);try{await Zx(ne,k.trim(),d),o(`Remote renamed to '${k.trim()}'`,"success"),A(null),P(""),await Oe()}catch(ge){o(xe(ge)||"Failed to rename remote","error")}finally{b(null)}}},et=async ne=>{if(w.trim()){b(`url-${ne}`);try{await ev(ne,w.trim(),d),o("Remote URL updated","success"),A(null),S(""),await Oe()}catch(ge){o(xe(ge)||"Failed to update remote URL","error")}finally{b(null)}}},De=a.useCallback(async(ne,ge)=>{if(ge==="ahead"){if(ue===ne){z(null),F(null);return}z(ne),F(null),V(!0);try{const le=await Ar(ne);F(le)}catch{F(null)}finally{V(!1)}}else{if(K===ne){de(null),ve(null);return}de(ne),ve(null),Pe(!0);try{const le=await Ar(ne);ve(le)}catch{ve(null)}finally{Pe(!1)}}},[ue,K]),Xe=ne=>{A(`url-${ne.name}`),S(ne.pushUrl||ne.fetchUrl)},re=ne=>{A(`name-${ne.name}`),P(ne.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:()=>R(!C),disabled:f!==null,title:C?"Cancel":"Add Remote",children:C?e.jsx(Dt,{size:14}):e.jsx(Vt,{size:14})})]}),C&&e.jsxs("form",{className:"gm-remote-form",onSubmit:Ee,children:[e.jsx("input",{type:"text",placeholder:"Remote name",value:x,onChange:ne=>y(ne.target.value),disabled:f==="add",className:"gm-input"}),e.jsx("input",{type:"text",placeholder:"Repository URL",value:v,onChange:ne=>M(ne.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!x.trim()||!v.trim()||f==="add",children:[f==="add"?e.jsx(lt,{size:12,className:"spin"}):e.jsx(Vt,{size:12}),"Add"]})]}),g?e.jsxs("div",{className:"gm-loading",children:[e.jsx(lt,{size:16,className:"spin"}),"Loading..."]}):u.length===0?e.jsx("div",{className:"gm-empty",children:"No remotes"}):u.map(ne=>e.jsxs("div",{className:`gm-remote-selector-item${j===ne.name?" selected":""}`,onClick:()=>Q(ne.name),role:"button",tabIndex:0,children:[e.jsxs("div",{className:"gm-remote-selector-info",children:[e.jsxs("span",{className:"gm-remote-selector-name",children:[ne.name,ne.name==="origin"&&e.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),e.jsx("span",{className:"gm-remote-selector-host",children:c(ne.fetchUrl)})]}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:ge=>{ge.stopPropagation(),_e(ne.name)},disabled:f!==null,title:"Remove remote",children:e.jsx(Ht,{size:14})})]},ne.name))]}),e.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[j&&J?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:j}),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(lt,{size:14,className:"spin"}):e.jsx(Mn,{size:14}),"Fetch"]}),e.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?e.jsx(lt,{size:14,className:"spin"}):e.jsx(ts,{size:14}),"Pull"]}),e.jsxs("button",{className:"btn btn-primary",onClick:l,disabled:n!==null||g,children:[n==="push"?e.jsx(lt,{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:"}),N===`url-${j}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:w,onChange:ne=>S(ne.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>et(j),disabled:f===`url-${j}`,children:f===`url-${j}`?e.jsx(lt,{size:12,className:"spin"}):e.jsx(En,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),S("")},title:"Cancel",children:e.jsx(Dt,{size:12})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"gm-url-value",title:J.fetchUrl,children:J.fetchUrl}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>m(J.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:e.jsx(qi,{size:14})}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Xe(J),disabled:f!==null,title:"Edit remote URL",children:e.jsx(Ln,{size:14})})]})]}),J.pushUrl&&J.pushUrl!==J.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:J.pushUrl,children:J.pushUrl}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>m(J.pushUrl,"push URL"),title:"Copy push URL",children:e.jsx(qi,{size:14})})]})]}),e.jsx("div",{className:"gm-remote-detail-name-row",children:N===`name-${j}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:k,onChange:ne=>P(ne.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Be(j),disabled:f===`rename-${j}`,children:f===`rename-${j}`?e.jsx(lt,{size:12,className:"spin"}):e.jsx(En,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),P("")},title:"Cancel",children:e.jsx(Dt,{size:12})})]}):e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(J),disabled:f!==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(lt,{size:14,className:"spin"}),"Loading..."]}):O.length>0?e.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:O.map(ne=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>De(ne.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:ne.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:ne.message,children:ne.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:ne.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Xi(ne.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:ue===ne.hash?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})})]}),ue===ne.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:fe?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):te?e.jsxs(e.Fragment,{children:[ne.message&&e.jsx("div",{className:"gm-commit-message-full",children:ne.message}),te.stat&&e.jsx("pre",{className:"gm-diff-stat",children:te.stat}),e.jsx("pre",{className:"gm-diff-patch",children:te.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ne.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(Wm,{size:14}),"Recent commits on ",j]})}),D?e.jsxs("div",{className:"gm-loading",children:[e.jsx(lt,{size:14,className:"spin"}),"Loading commits..."]}):G?e.jsxs("div",{className:"gm-error",children:[e.jsx(is,{size:14}),G]}):Y.length===0?e.jsxs("div",{className:"gm-empty",children:["No commits found on ",j,". Try fetching first."]}):e.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:Y.map(ne=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>De(ne.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:ne.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:ne.message,children:ne.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:ne.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Xi(ne.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:K===ne.hash?e.jsx(zt,{size:14}):e.jsx(ln,{size:14})})]}),K===ne.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Se?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(lt,{size:16,className:"spin"}),"Loading diff..."]}):we?e.jsxs(e.Fragment,{children:[ne.message&&e.jsx("div",{className:"gm-commit-message-full",children:ne.message}),we.stat&&e.jsx("pre",{className:"gm-diff-stat",children:we.stat}),e.jsx("pre",{className:"gm-diff-patch",children:we.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ne.hash))})]})]}):e.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&e.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const ja={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function yP(t,n){return t&&n?`${t}/${n}`:""}function kP(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 jP(t){switch(t){case"file-text":return xi;case"check-circle":return tn;case"shield":return Tb;case"zap":return jn;case"eye":return Oo;case"globe":return vi;case"layout-grid":return ki;default:return tn}}function wP(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 NP({isOpen:t,onClose:n,addToast:s,projectId:i}){const[r,l]=a.useState([]),[o,d]=a.useState([]),[m,c]=a.useState(!0),[u,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,b]=a.useState(null),[x,y]=a.useState(!1),[v,M]=a.useState(ja),[N,A]=a.useState(!1),[w,S]=a.useState(!1),[k,P]=a.useState(null),[C,R]=a.useState(null),[O,Z]=a.useState({}),[I,_]=a.useState([]),j=a.useCallback(async()=>{try{c(!0);const F=await Kr(i);l(F)}catch(F){s(xe(F)||"Failed to load workflow steps","error")}finally{c(!1)}},[s,i]),Q=a.useCallback(async()=>{try{const F=await Va(i);Z(F||{})}catch{}},[i]),Y=a.useCallback(async()=>{try{const F=await Jn();_(F.models||[])}catch{}},[]),L=a.useCallback(async()=>{try{h(!0);const F=await ny();d(F.templates)}catch(F){s(xe(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{t&&(j(),L(),Q(),Y())},[t,j,L,Q,Y]);const D=a.useCallback(()=>{y(!0),b(null),M(ja)},[]),U=a.useCallback(F=>{b(F.id),y(!1),M({name:F.name,description:F.description,mode:F.mode||"prompt",phase:F.phase||"pre-merge",prompt:F.prompt,scriptName:F.scriptName||"",enabled:F.enabled,defaultOn:F.defaultOn||!1,modelProvider:F.modelProvider||"",modelId:F.modelId||""})},[]),G=a.useCallback(()=>{b(null),y(!1),M(ja)},[]),E=a.useCallback(async()=>{if(!v.name.trim()||!v.description.trim()){s("Name and description are required","error");return}A(!0);try{const F=v.mode==="prompt"&&v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:v.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(x){const fe={name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"&&v.prompt.trim()||void 0,scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...F};await Xc(fe,i),s("Workflow step created","success")}else f&&(await Zv(f,{name:v.name.trim(),description:v.description.trim(),mode:v.mode,phase:v.phase,prompt:v.mode==="prompt"?v.prompt:"",scriptName:v.mode==="script"?v.scriptName.trim():void 0,enabled:v.enabled,defaultOn:v.defaultOn,...F},i),s("Workflow step updated","success"));y(!1),b(null),M(ja),await j()}catch(F){s(xe(F)||"Failed to save workflow step","error")}finally{A(!1)}},[v,x,f,s,j]),J=a.useCallback(async F=>{try{await ey(F,i),s("Workflow step deleted","success"),P(null),f===F&&(b(null),M(ja)),await j()}catch(fe){s(xe(fe)||"Failed to delete workflow step","error")}},[f,s,j]),ue=a.useCallback(async()=>{if(!(!f&&!x)&&v.mode==="prompt"){if(x){if(!v.name.trim()||!v.description.trim()){s("Name and description are required before refining","error");return}A(!0);try{const F=v.modelProvider&&v.modelId?{modelProvider:v.modelProvider,modelId:v.modelId}:{},fe={name:v.name.trim(),description:v.description.trim(),mode:"prompt",prompt:v.prompt.trim()||void 0,enabled:v.enabled,defaultOn:v.defaultOn||void 0,...F},V=await Xc(fe,i);y(!1),b(V.id),S(!0);const K=await Zc(V.id,i);M(de=>({...de,prompt:K.prompt})),s("Prompt refined with AI","success"),await j()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{A(!1),S(!1)}return}if(f){S(!0);try{const F=await Zc(f,i);M(fe=>({...fe,prompt:F.prompt})),s("Prompt refined with AI","success"),await j()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{S(!1)}}}},[f,x,v,s,j]),z=a.useCallback(async F=>{R(F.id);try{await sy(F.id,i),s(`Added ${F.name} workflow step`,"success"),await j(),p("my-steps")}catch(fe){const V=xe(fe);V?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(V||"Failed to add workflow step from template","error")}finally{R(null)}},[s,j]);if(!t)return null;const te=x||f!==null;return e.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"workflow-step-manager",children:e.jsxs("div",{className:"modal workflow-step-manager-modal",onClick:F=>F.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:[!te&&e.jsxs("div",{className:"wfm-tab-row",children:[e.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[e.jsx(Dm,{size:14}),"My Workflow Steps (",r.length,")"]}),e.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[e.jsx(ki,{size:14}),"Templates (",o.length,")"]})]}),g==="my-steps"&&!te&&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(F=>e.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${F.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:F.name}),e.jsx("span",{className:`wfm-badge ${F.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:F.enabled?"Enabled":"Disabled"}),e.jsx("span",{className:`wfm-badge ${(F.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(F.mode||"prompt")==="script"?"Script":"AI Prompt"}),e.jsx("span",{className:`wfm-badge ${(F.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(F.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),F.defaultOn&&e.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),e.jsx("div",{className:"wfm-step-card-desc",children:F.description})]}),e.jsxs("div",{className:"wfm-step-card-actions",children:[e.jsx("button",{className:"btn-icon",onClick:()=>U(F),title:"Edit","aria-label":`Edit ${F.name}`,children:e.jsx(Ln,{size:14})}),k===F.id?e.jsxs("div",{className:"wfm-delete-confirm",children:[e.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>J(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:e.jsx(En,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>P(null),title:"Cancel delete","aria-label":"Cancel delete",children:e.jsx(Dt,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>P(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:e.jsx(Ht,{size:14})})]})]})},F.id))})]}),g==="templates"&&!te&&e.jsx(e.Fragment,{children:u?e.jsxs("div",{className:"wfm-loading",children:[e.jsx(lt,{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(F=>{const fe=jP(F.icon),V=wP(F.category),K=C===F.id;return e.jsx("div",{className:"wfm-template-card","data-testid":`template-${F.id}`,children:e.jsxs("div",{className:"wfm-template-inner",children:[e.jsx("div",{className:"wfm-template-icon",children:e.jsx(fe,{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:F.name}),e.jsx("span",{className:V,children:F.category})]}),e.jsx("div",{className:"wfm-template-desc",children:F.description}),e.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>z(F),disabled:K,"data-testid":`add-template-${F.id}`,children:K?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:12,className:"spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vt,{size:12}),"Add"]})})]})]})},F.id)})})}),te&&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:v.name,onChange:F=>M(fe=>({...fe,name:F.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:v.description,onChange:F=>M(fe=>({...fe,description:F.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 ${v.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[e.jsx(Zs,{size:14}),"AI Prompt"]}),e.jsxs("button",{className:`btn ${v.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,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 ${v.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),e.jsx("button",{className:`btn ${v.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),e.jsx("div",{className:"wfm-field-hint",children:v.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),v.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:ue,disabled:!v.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?e.jsx(lt,{size:12,className:"spin"}):e.jsx(On,{size:12}),e.jsx("span",{children:"Refine with AI"})]})]}),e.jsx("textarea",{value:v.prompt,onChange:F=>M(fe=>({...fe,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),v.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"}),v.modelProvider&&v.modelId&&e.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>M(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[e.jsx(Dt,{size:12}),e.jsx("span",{children:"Use default"})]})]}),e.jsx("span",{className:"wfm-model-hint",children:v.modelProvider&&v.modelId?`Using ${v.modelProvider}/${v.modelId}`:"Using global default model"}),e.jsx("div",{"data-testid":"workflow-step-model-select",children:e.jsx(Gt,{models:I,value:yP(v.modelProvider,v.modelId),onChange:F=>{const fe=kP(F);M(V=>({...V,modelProvider:fe.provider,modelId:fe.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),v.mode==="script"&&e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Script"}),Object.keys(O).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:v.scriptName,onChange:F=>M(fe=>({...fe,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[e.jsx("option",{value:"",children:"Select a script…"}),Object.entries(O).map(([F,fe])=>e.jsxs("option",{value:F,children:[F," (",fe,")"]},F))]})]}),e.jsxs("label",{className:"wfm-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:v.enabled,onChange:F=>M(fe=>({...fe,enabled:F.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:v.defaultOn,onChange:F=>M(fe=>({...fe,defaultOn:F.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:G,disabled:N,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:E,disabled:N||!v.name.trim()||!v.description.trim()||v.mode==="script"&&!v.scriptName.trim(),"data-testid":"save-workflow-step",children:N?"Saving...":x?"Create":"Save"})]})]})]})]})}),!te&&e.jsx("div",{className:"wfm-footer",children:e.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:D,"data-testid":"add-workflow-step",children:[e.jsx(Vt,{size:14}),"Add Workflow Step"]})})]})})}const SP=36e5,CP=3e5,to=[{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 EP(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 MP(t){return typeof t!="number"||!Number.isFinite(t)?SP:Math.max(CP,Math.round(t))}function TI(t){if(to.some(s=>s.value===t))return[...to];const n={value:t,label:`${EP(t)} (custom)`};return[...to,n].sort((s,i)=>s.value-i.value)}const AP=2,PP=6e4;function TP(t){const n=MP(t?.heartbeatIntervalMs);return Math.max(n*AP,PP)}function RP(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 _P(t){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:l}=t,o=RP(t);if(n==="terminated")return{label:"Terminated",icon:e.jsx(os,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:e.jsx(ws,{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(ws,{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=TP(l);return m>c?{label:"Unresponsive",icon:e.jsx(ws,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:e.jsx(Bg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const wa=[{value:"triage",label:"Triage",icon:"⊕"},{value:"executor",label:"Executor",icon:"▶"},{value:"reviewer",label:"Reviewer",icon:"⊙"},{value:"merger",label:"Merger",icon:"⊞"},{value:"scheduler",label:"Scheduler",icon:"◷"},{value:"engineer",label:"Engineer",icon:"⎔"},{value:"custom",label:"Custom",icon:"✦"}];function IP({isOpen:t,onClose:n,addToast:s,projectId:i}){const[r,l]=a.useState([]),[o,d]=a.useState(!1),[m,c]=a.useState(!1),[u,h]=a.useState(""),[g,p]=a.useState("custom"),[f,b]=a.useState("all"),[x,y]=a.useState(()=>{if(typeof window>"u")return"list";const j=In("fn-agent-view",i);return j==="board"||j==="list"?j:"list"});a.useEffect(()=>{const j=In("fn-agent-view",i);if(j==="board"||j==="list"){y(j);return}y("list")},[i]),a.useEffect(()=>{us("fn-agent-view",x,i)},[i,x]);const[v,M]=a.useState(null),N=a.useRef(null),A=a.useMemo(()=>f==="all"?r.filter(j=>j.state!=="terminated"):r,[r,f]),w=a.useCallback(async()=>{d(!0);try{const Q=await aa(f!=="all"?{state:f}:void 0,i);l(Q)}catch(j){s(`Failed to load agents: ${xe(j)}`,"error")}finally{d(!1)}},[f,s,i]);a.useEffect(()=>{t&&w()},[t,w]),a.useEffect(()=>{if(!t)return;const j=setInterval(()=>{w()},3e4);return()=>{clearInterval(j)}},[t,w]);const S=async()=>{if(u.trim())try{await my({name:u.trim(),role:g},i),s(`Agent "${u}" created`,"success"),h(""),c(!1),w()}catch(j){s(`Failed to create agent: ${xe(j)}`,"error")}},k=async(j,Q)=>{try{await py(j,Q,i),s(`Agent state updated to ${Q}`,"success"),w()}catch(Y){s(`Failed to update state: ${xe(Y)}`,"error")}},P=async(j,Q)=>{if(confirm(`Delete agent "${Q}"? This cannot be undone.`))try{await fy(j,i),s(`Agent "${Q}" deleted`,"success"),w()}catch(Y){s(`Failed to delete agent: ${xe(Y)}`,"error")}},C=async(j,Q)=>{const Y=r.find(L=>L.id===j);if(Y){if(Y.role===Q){M(null);return}try{await hy(j,{role:Q},i),s(`Agent role updated to ${wa.find(L=>L.value===Q)?.label??Q}`,"success"),M(null),w()}catch(L){s(`Failed to update role: ${xe(L)}`,"error")}}},R=(j,Q)=>{j.key==="Escape"&&M(null)},O=j=>wa.find(Q=>Q.value===j)?.label??j,Z=j=>wa.find(Q=>Q.value===j)?.icon??"◆",I=j=>_P(j),_=j=>j.color==="var(--state-active-text)"?"active":j.color==="var(--state-paused-text)"?"paused":j.color==="var(--state-error-text)"?"error":"muted";return t?e.jsx("div",{className:"modal-overlay open",onClick:j=>j.target===j.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:()=>y("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:()=>y("list"),title:"List view","aria-label":"List view","aria-pressed":x==="list",children:e.jsx(uo,{size:16})})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void w(),title:"Refresh",disabled:o,children:e.jsx(Mn,{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:f,onChange:j=>b(j.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(Vt,{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:j=>h(j.target.value),onKeyDown:j=>j.key==="Enter"&&S(),className:"input",autoFocus:!0}),e.jsx("select",{className:"select",value:g,onChange:j=>p(j.target.value),children:wa.map(j=>e.jsxs("option",{value:j.value,children:[j.icon," ",j.label]},j.value))}),e.jsx("button",{className:"btn btn--primary",onClick:()=>void S(),children:"Create"})]}),e.jsx("div",{className:x==="board"?"agent-board":"agent-list",children:A.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"?A.map(j=>{const Q=I(j),Y=_(Q);return e.jsxs("div",{className:"agent-board-card","data-state":j.state,children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:Z(j.role)}),e.jsx("span",{className:"agent-board-badge","data-state":j.state,children:j.state}),e.jsx("span",{className:"agent-board-health","data-health":Y,title:Q.label,children:Q.icon})]}),e.jsx("div",{className:"agent-board-name",title:j.name,children:j.name}),e.jsx("div",{className:"agent-board-id",children:j.id}),e.jsxs("div",{className:"agent-board-actions",children:[j.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"active"),title:"Activate",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:e.jsx(Ht,{size:14})})]}),j.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"paused"),title:"Pause",children:e.jsx($s,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),j.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"active"),title:"Resume",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),j.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"paused"),title:"Pause",children:e.jsx($s,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),j.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"active"),title:"Retry",children:e.jsx(rn,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),j.state==="terminated"&&e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:e.jsx(Ht,{size:14})})]})]},j.id)}):A.map(j=>{const Q=I(j),Y=_(Q);return e.jsxs("div",{className:"agent-card","data-state":j.state,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[v===j.id?e.jsx("select",{ref:N,className:"select agent-role-select",value:j.role,onChange:L=>void C(j.id,L.target.value),onKeyDown:L=>R(L,j.id),onBlur:()=>M(null),autoFocus:!0,children:wa.map(L=>e.jsxs("option",{value:L.value,children:[L.icon," ",L.label]},L.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>M(j.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:L=>{(L.key==="Enter"||L.key===" ")&&M(j.id)},children:Z(j.role)}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:j.name}),e.jsx("span",{className:"agent-id text-secondary",children:j.id})]})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:"badge agent-list-state-badge","data-state":j.state,children:j.state}),e.jsxs("span",{className:"badge agent-list-health-badge","data-health":Y,title:Q.label,children:[Q.icon,!Q.stateDerived&&` ${Q.label}`]}),e.jsx("span",{className:"badge text-secondary",children:O(j.role)})]})]}),e.jsxs("div",{className:"agent-card-body",children:[j.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:j.taskId})]}),j.lastHeartbeatAt&&e.jsxs("div",{className:"agent-heartbeat",children:[e.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),e.jsx("span",{children:new Date(j.lastHeartbeatAt).toLocaleString()})]})]}),e.jsxs("div",{className:"agent-card-actions",children:[j.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"active"),title:"Activate",children:[e.jsx(rn,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:[e.jsx(Ht,{size:14})," Delete"]})]}),j.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"paused"),title:"Pause",children:[e.jsx($s,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),j.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"active"),title:"Resume",children:[e.jsx(rn,{size:14})," Resume"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),j.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"paused"),title:"Pause",children:[e.jsx($s,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),j.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(j.id,"active"),title:"Retry",children:[e.jsx(rn,{size:14})," Retry"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(j.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),j.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void k(j.id,"active"),title:"Start",children:[e.jsx(rn,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:[e.jsx(Ht,{size:14})," Delete"]})]})]})]},j.id)})})]})]})}):null}const Ni="fusion_model_onboarding_state",Zi=[],ea=[],zr=!1,Or=!1,ta={},$P=void 0,DP={"ai-setup":"AI Setup",github:"GitHub","first-task":"First Task",complete:"Complete"};function hs(){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"?FP(n):null}catch{return null}}function FP(t){const n=t.postOnboardingDismissedAt??$P;return{...t,completedSteps:t.completedSteps??Zi,skippedSteps:t.skippedSteps??ea,dismissed:t.dismissed??zr,completed:t.completed??Or,stepData:t.stepData??ta,...n?{postOnboardingDismissedAt:n}:{}}}function vr(t,n){if(!(typeof window>"u")){if(!n){const s={currentStep:t,updatedAt:new Date().toISOString(),completedSteps:Zi,skippedSteps:ea,dismissed:zr,completed:Or,stepData:ta};try{localStorage.setItem(Ni,JSON.stringify(s))}catch{}return}try{const s=hs(),i=new Date().toISOString(),r=n.completed??Or;let l=n.dismissed??zr;r&&(l=!1);const o=n.completedSteps??s?.completedSteps??Zi,d=n.skippedSteps??s?.skippedSteps??ea,m={...s?.stepData??ta};if(n.stepData)for(const[u,h]of Object.entries(n.stepData))h!==void 0&&(m[u]={...m[u]??{},...h});const c={currentStep:t,updatedAt:i,completedSteps:o,skippedSteps:d,dismissed:l,completed:r,stepData:m};localStorage.setItem(Ni,JSON.stringify(c))}catch{}}}function LP(t){if(!(typeof window>"u"))try{const n=hs(),s=new Date().toISOString();if(!n){const l={currentStep:t,updatedAt:s,completedSteps:Zi,skippedSteps:[t],dismissed:zr,completed:Or,stepData:ta};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 pm(){if(!(typeof window>"u"))try{const t=hs(),n=new Date().toISOString(),s=t?{...t,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Zi,skippedSteps:ea,dismissed:!1,completed:!0,stepData:ta};localStorage.setItem(Ni,JSON.stringify(s))}catch{}}function na(){const t=hs();return t?t.completed===!0?!0:typeof t.completedAt=="string"&&t.completedAt.length>0:!1}function zP(){if(!(typeof window>"u"))try{const t=hs(),n=new Date().toISOString(),s=t?{...t,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Zi,skippedSteps:ea,dismissed:!1,completed:!1,stepData:ta,postOnboardingDismissedAt:n};localStorage.setItem(Ni,JSON.stringify(s))}catch{}}function Yp(){const t=hs();return t?typeof t.postOnboardingDismissedAt=="string"&&t.postOnboardingDismissedAt.length>0:!1}function OP(){const t=hs();return!t||na()?!1:t.currentStep!=="complete"}function BP(){const t=hs();if(!t||na()||t.currentStep==="complete")return null;const n=t.currentStep,s=DP[n]??qP(t.currentStep);return{currentStep:t.currentStep,label:s,completedSteps:t.completedSteps}}function UP(){const t=hs();return t?t.skippedSteps:ea}function HP(t){const n=hs();return!n||!n.stepData?null:n.stepData[t]??null}function qP(t){return t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Qp="fusion_onboarding_events",fm="fusion_onboarding_session_id",VP=200,WP=50;function ys(t,n={}){if(!(typeof window>"u"))try{const s=GP(),i=QP(n.step),r={type:t,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:KP()},l=YP([...s,r]);JP(l)}catch{}}function KP(){if(typeof window>"u")return"server-session";try{const t=sessionStorage.getItem(fm);if(t)return t;const n=gm();return sessionStorage.setItem(fm,n),n}catch{return gm()}}function gm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function GP(){try{const t=localStorage.getItem(Qp);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(XP):[]}catch{return[]}}function JP(t){try{localStorage.setItem(Qp,JSON.stringify(t))}catch{}}function YP(t){const n=[...t];for(;n.length>VP;)n.splice(0,WP);return n}function QP(t){if(t==="ai-setup"||t==="github"||t==="first-task"||t==="complete")return t}function XP(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 ZP=1e4,eT=1e3;function tT(){const[t,n]=a.useState([]),[s,i]=a.useState(!0),[r,l]=a.useState(null),o=a.useRef(null),d=a.useRef(0),m=a.useCallback(async()=>{try{l(null);const p=await sd();n(p)}catch(p){l(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const x=await sd();p||(n(x),l(null))}catch(x){p||l(x instanceof Error?x.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const b=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-d.current<eT||(d.current=x,m())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[m]),a.useEffect(()=>{if(!s)return o.current=setInterval(()=>{m()},ZP),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async p=>{const f=await yy(p);return n(b=>[...b,f]),f},[]),u=a.useCallback(async(p,f)=>{const b=await ky(p,f);return n(x=>x.map(y=>y.id===p?b:y)),b},[]),h=a.useCallback(async p=>{await jy(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await wy(p);n(b=>b.map(x=>x.id===p?{...x,status:f.status,updatedAt:f.checkedAt}:x))},[]);return{nodes:t,loading:s,error:r,refresh:m,register:c,update:u,unregister:h,healthCheck:g}}function Xp({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 nT={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"}}},Zp={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:"..."}},sT={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},bm={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 Io(t){if(bm[t])return bm[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 no=["anthropic","openai","google","gemini","ollama"],iT=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],aT={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"},rT={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function $o(t){return aT[t]??t}function xm(t){const n=$o(t),s=iT.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function vm(t,n){if(t.authenticated!==n.authenticated)return t.authenticated?-1:1;const s=xm(t.id),i=xm(n.id);if(s!==i)return s-i;const r=$o(t.id),l=$o(n.id);if(r!==l)return r.localeCompare(l);const o=rT[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 lT(t,n){const s=n.trim();if(!s)return"API key is required";const i=Zp[t]??sT;return i.pattern.test(s)?null:`${Io(t)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const ef={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"},oT={description:"AI provider — connect to start using AI models",apiKeyInfo:ef};function Do(t){return nT[t]??oT}function cT(t){return Do(t.id).apiKeyInfo??ef}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 dT({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 uT({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=Zp[t.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${l?" onboarding-apikey-input--success":""}`,f=e.jsxs(e.Fragment,{children:[g&&e.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),e.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&e.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),e.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return o?e.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${t.id}`,children:[e.jsxs("div",{className:"onboarding-apikey-connected-header",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),e.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),e.jsx("button",{className:"btn btn-sm",onClick:()=>c(t.id),disabled:i,children:i?"Removing…":"Remove Key"}),e.jsx(Vs,{summary:"Advanced setup details",children:f}),r&&e.jsx("small",{className:"field-error",children:r})]}):e.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${t.id}`,children:[e.jsx("label",{htmlFor:u,className:"onboarding-apikey-field-label",children:n.fieldLabel}),e.jsxs("div",{className:"onboarding-apikey-input-row",children:[e.jsx("input",{id:u,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>d(t.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&m(t.id,s)},"data-testid":u}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>m(t.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${t.id}`,children:i?"Saving…":"Save"})]}),r&&e.jsx("small",{className:"field-error",children:r}),l&&!r&&e.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${t.id}`,children:l}),e.jsx(Vs,{summary:"Advanced setup details",children:f})]})}const mT=150;function hT({onComplete:t,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:l,firstCreatedTask:o,onViewTask:d}){const m=hs(),c=m&&m.currentStep!=="complete"?m.currentStep:"ai-setup",u=m?.completedSteps??[],h=m?.skippedSteps??UP(),[g,p]=a.useState(!0),[f,b]=a.useState(c),[x,y]=a.useState(u),[v,M]=a.useState(h),[N,A]=a.useState(!1),[w,S]=a.useState(""),[k,P]=a.useState(!1),[C,R]=a.useState(null),[O,Z]=a.useState(null),[I,_]=a.useState([]),[j,Q]=a.useState(void 0),[Y,L]=a.useState(!0),[D,U]=a.useState(null),[G,E]=a.useState({}),[J,ue]=a.useState([]),[z,te]=a.useState(""),[F,fe]=a.useState(!1),[V,K]=a.useState({}),[de,we]=a.useState({}),[ve,Se]=a.useState({}),Pe=a.useRef({}),Oe=a.useRef(null),Ie=a.useRef(null),[rt,Ee]=a.useState({}),[_e,Be]=a.useState(()=>hs()?.stepData?.github?.skipped===!0),et=a.useRef(0),De=a.useRef(o),Xe=a.useRef(!1),re=m?.currentStep,ne=!!m&&m.currentStep!=="complete",[ge,le]=a.useState(()=>hs()?.stepData?.["ai-setup"]?.skippedProviders??{}),Te=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"first-task",label:"First Task"}],ye=Te.findIndex(se=>se.key===f);a.useEffect(()=>{f!=="complete"&&vr(f,{completedSteps:x,skippedSteps:v})},[f,x,v]),a.useEffect(()=>{Xe.current||(Xe.current=!0,ys("onboarding:wizard-opened",{source:ne?"resume":"initial",resumedFromStep:re}))},[ne,re]),a.useEffect(()=>{const se=De.current!=null,Fe=o!=null;!se&&Fe&&A(!0),Fe||A(!1),De.current=o},[o]);const He=a.useRef(c);a.useEffect(()=>{if(He.current==="ai-setup"&&f!=="ai-setup"&&!I.some(Fe=>Fe.id!=="github"&&Fe.authenticated)){const Fe={};for(const st of I)st.id!=="github"&&!st.authenticated&&!ge[st.id]&&(Fe[st.id]=!0);if(Object.keys(Fe).length>0){const st={...ge,...Fe};le(st),vr(f,{stepData:{"ai-setup":{skippedProviders:st}}})}}He.current=f},[f,I,ge]);const nt=a.useCallback(async()=>{try{const{providers:se,ghCli:Fe}=await ji();_(se),Q(Fe),E(st=>{const T={};for(const[W,ee]of Object.entries(st)){const me=se.find(ke=>ke.id===W);me&&!me.authenticated&&(T[W]=ee)}return Object.keys(T).length===Object.keys(st).length?st:T}),le(st=>{const T={...st};for(const W of se)W.authenticated&&T[W.id]&&delete T[W.id];return Object.keys(T).length===Object.keys(st).length?st:T})}catch{}},[]),mt=a.useRef(!1);a.useEffect(()=>{mt.current&&nt(),mt.current=f!=="ai-setup"},[f,nt]);const he=I.find(se=>se.id==="github"),ie=!!he,be=he?.authenticated??!1,Me=j?.authenticated??!1,Ze=be||Me,je=!be&&Me,tt=a.useCallback(se=>{if(se.authenticated)return"connected";const Fe=rt?.[se.id];return Fe==="timeout"||Fe==="failed"?"retry":ge[se.id]?"skipped":"not-connected"},[rt,ge]);function Ce({status:se}){const Fe={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:st,className:T}=Fe[se];return e.jsx("span",{"data-testid":"provider-status-badge",className:T,"data-status":se,children:st})}const qe=a.useCallback(()=>{if(Ze)return"connected";const se=rt.github;return se==="pending"?"pending":se==="failed"||se==="timeout"?"failed":_e?"skipped":"not-connected"},[Ze,rt,_e]);function ce({status:se}){const Fe={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:st,className:T}=Fe[se];return e.jsx("span",{"data-testid":"github-status-badge",className:T,"data-status":se,children:st})}const Ue=a.useCallback(async()=>{try{const se=await Jn();ue(se.models)}catch{}},[]),Ve=a.useCallback(async()=>{try{const se=await ia();if(se.defaultProvider&&se.defaultModelId){const Fe=`${se.defaultProvider}/${se.defaultModelId}`;te(Fe)}}catch{}},[]);a.useEffect(()=>{Promise.all([nt(),Ue(),Ve()]).finally(()=>L(!1))},[nt,Ue,Ve]),a.useEffect(()=>{const se=HP("ai-setup");if(se?.loginOutcomes){const Fe=se.loginOutcomes,st={};for(const[T,W]of Object.entries(Fe))W!=="pending"&&(st[T]=W);Object.keys(st).length>0&&Ee(st)}},[]);const Ae=a.useCallback((se,Fe)=>{vr(f,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[se]:Fe}}}})},[f,x]);a.useEffect(()=>{const se=Object.entries(rt).filter(([Fe,st])=>st!=="pending");for(const[Fe,st]of se)Ae(Fe,st)},[rt,Ae]),a.useEffect(()=>()=>{Ie.current&&clearInterval(Ie.current),Object.values(Pe.current).forEach(clearTimeout),Pe.current={}},[]);const We=a.useCallback(se=>{Be(se),vr(f,{completedSteps:x,stepData:{github:{skipped:se}}})},[f,x]),xt=a.useCallback(()=>{y(se=>[...new Set([...se,f])]),M(se=>se.filter(Fe=>Fe!==f)),ys("onboarding:step-completed",{step:f}),f==="github"&&!be&&We(!1),f==="ai-setup"?b("github"):f==="github"&&b("first-task")},[f,be,We]),yt=a.useCallback(()=>{M(se=>[...new Set([...se,f])]),LP(f),ys("onboarding:step-skipped",{step:f}),f==="github"&&!be&&We(!0),f==="ai-setup"?b("github"):f==="github"&&b("first-task")},[f,be,We]),Ct=a.useCallback(()=>{const se=f;y(Fe=>Fe.filter(st=>st!==se)),M(Fe=>Fe.filter(st=>st!==se)),se==="github"&&!be&&We(!1),f==="github"?b("ai-setup"):f==="first-task"&&b("github")},[f,be,We]),Tt=a.useCallback(()=>{yt()},[yt]),Et=a.useCallback(async se=>{Ee(Fe=>{const st=Fe[se];if(st&&st!=="pending"){const{[se]:T,...W}=Fe;return W}return Fe}),E(Fe=>{if(!(se in Fe))return Fe;const st={...Fe};return delete st[se],st}),Ee(Fe=>({...Fe,[se]:"pending"})),U(se),et.current=0;try{const{url:Fe,instructions:st}=await Xm(se);st?.trim()&&E(T=>({...T,[se]:st})),window.open(As(Fe),"_blank"),Ie.current=setInterval(async()=>{if(et.current++,et.current>=mT){Ie.current&&(clearInterval(Ie.current),Ie.current=null),U(null),Ee(T=>({...T,[se]:"timeout"})),E(T=>{if(!(se in T))return T;const W={...T};return delete W[se],W}),n("Login timed out. Please try again.","warning");return}try{const{providers:T,ghCli:W}=await ji();_(T),Q(W),T.find(me=>me.id===se)?.authenticated&&(Ie.current&&(clearInterval(Ie.current),Ie.current=null),U(null),Ee(me=>({...me,[se]:"success"})),E(me=>{if(!(se in me))return me;const ke={...me};return delete ke[se],ke}),se==="github"&&We(!1),n("Login successful","success"))}catch{}},2e3)}catch(Fe){Fe instanceof Error&&Fe.message.includes("already in progress")||Fe&&typeof Fe=="object"&&"status"in Fe&&Fe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ee(T=>({...T,[se]:"failed"}))):(n(Fe instanceof Error?Fe.message:"Login failed","error"),Ee(T=>({...T,[se]:"failed"}))),U(null),E(T=>{if(!(se in T))return T;const W={...T};return delete W[se],W})}},[n,We]),Mt=a.useCallback(se=>{Ie.current&&(clearInterval(Ie.current),Ie.current=null),U(null),et.current=0,Ee(Fe=>({...Fe,[se]:"cancelled"})),E(Fe=>{if(!(se in Fe))return Fe;const st={...Fe};return delete st[se],st})},[]),vt=a.useCallback((se,Fe)=>{K(T=>({...T,[se]:Fe}));const st=Pe.current[se];st&&(clearTimeout(st),delete Pe.current[se]),we(T=>{if(!T[se])return T;const W={...T};return delete W[se],W}),Se(T=>{if(!T[se])return T;const W={...T};return delete W[se],W})},[]),Ft=a.useCallback(()=>{const se=Oe.current;if(!se)return;const Fe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof se.scrollTo=="function"){se.scrollTo({top:0,behavior:Fe?"auto":"smooth"});return}}catch{}se.scrollTop=0},[]),Je=a.useCallback(async(se,Fe)=>{const st=(Fe??V[se]??"").trim(),T=lT(se,st);if(T){we(ee=>({...ee,[se]:T}));return}const W=Pe.current[se];W&&(clearTimeout(W),delete Pe.current[se]),U(se),we(ee=>{const me={...ee};return delete me[se],me}),Se(ee=>{if(!ee[se])return ee;const me={...ee};return delete me[se],me});try{await eh(se,st),await nt(),Ft(),K(ee=>{const me={...ee};return delete me[se],me}),we(ee=>{if(!ee[se])return ee;const me={...ee};return delete me[se],me}),Se(ee=>({...ee,[se]:"✓ Key saved"})),Pe.current[se]=setTimeout(()=>{Se(ee=>{if(!ee[se])return ee;const me={...ee};return delete me[se],me}),delete Pe.current[se]},3e3),n("API key saved","success")}catch(ee){const me=ee instanceof TypeError&&ee.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":ee instanceof Error?ee.message:"Failed to save API key";we(ke=>({...ke,[se]:me})),Se(ke=>{if(!ke[se])return ke;const Re={...ke};return delete Re[se],Re}),n(me,"error")}finally{U(null)}},[V,n,nt,Ft]),pt=a.useCallback(async se=>{U(se);try{await th(se),await nt(),n("API key removed","success")}catch(Fe){n(Fe instanceof Error?Fe.message:"Failed to clear API key","error")}finally{U(null)}},[n,nt]),ze=a.useCallback(async se=>{U(se);try{await Zm(se),await nt(),n("Logged out","success")}catch(Fe){n(Fe instanceof Error?Fe.message:"Logout failed","error")}finally{U(null)}},[n,nt]),at=a.useCallback(se=>{te(se)},[]),q=a.useCallback(async()=>{try{const se={modelOnboardingComplete:!0};if(z){const Fe=z.indexOf("/"),st=Fe!==-1?z.slice(0,Fe):void 0,T=Fe!==-1?z.slice(Fe+1):z,W=J.find(ee=>ee.id===T);W?(se.defaultProvider=W.provider,se.defaultModelId=W.id):st&&T&&(se.defaultProvider=st,se.defaultModelId=T)}await Kt(se),pm()}catch{}},[z,J,Kt,pm]),$=a.useCallback(async()=>{fe(!0);try{await q(),ys("onboarding:completed",{completedSteps:x,skippedSteps:v}),b("complete")}finally{fe(!1)}},[q,x,v]),pe=a.useCallback(async()=>{if(!s)return;const se=w.trim();if(!se){R("Please enter a task description.");return}R(null),P(!0);let Fe=!1;try{const st=await Qm({description:se},s);Z(st),A(!0),ys("onboarding:first-task-created",{taskId:st?.id}),n("Task created","success"),Fe=!0}catch(st){const T=st instanceof Error?st.message:"Something went wrong creating your task. Please try again.";R(T),n(T,"error")}finally{P(!1)}Fe&&q()},[s,w,n,q]),ct=a.useCallback(async()=>{fe(!0);try{await q()}finally{fe(!1)}ys("onboarding:open-new-task",{}),r?.()},[q,r]),bt=a.useCallback(async()=>{if(Ze){fe(!0);try{await q()}finally{fe(!1)}p(!1),t(),ys("onboarding:open-github-import",{}),l?.()}},[q,Ze,t,l]),Nt=a.useCallback(async()=>{ys("onboarding:dismissed",{currentStep:f,completedSteps:x,skippedSteps:v}),fe(!0);try{await Kt({modelOnboardingComplete:!0})}catch{}p(!1),t()},[f,x,v,t]),Bt=a.useCallback(()=>{ys("onboarding:finished",{}),p(!1),t()},[t]),Lt=a.useCallback(()=>{const se=o??O;se&&(q(),d?.(se),t())},[o,O,q,d,t]),wn=a.useCallback(()=>{q(),t()},[q,t]);if(!g)return null;const hn=qe(),nn=I.filter(se=>se.id!=="github"),Pn=[...nn].sort(vm),on=Pn.some(se=>!se.type||se.type==="oauth"),Un=Pn.some(se=>se.type==="api_key"),gn=nn.filter(se=>se.authenticated),Zt=gn.length>0,Wt=!!s,Tn=f==="github"&&!Zt,bn=(()=>{if(!z)return"";const se=z.indexOf("/"),Fe=se===-1?void 0:z.slice(0,se),st=se===-1?z:z.slice(se+1),T=J.find(W=>W.id===st&&(!Fe||W.provider===Fe));return T?.name?T.name:Fe?`${Io(Fe)} ${st}`:z})(),sn=[];if(Wt?sn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):sn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Zt){const se=Io(gn[0]?.id??"");sn.push({label:"AI Provider",status:"connected",detail:`${se} connected — AI agents can work on tasks`})}else nn.length>0&&nn.some(se=>ge[se.id])?sn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):sn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Ze?sn.push({label:"GitHub",status:"connected",detail:je?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ie||_e?sn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):sn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),bn&&sn.push({label:"Default Model",status:"connected",detail:bn});const Hn=o??O,xn=Hn?.description?.split(`
644
- `)[0]?.trim()||Hn?.title||"",qt=new Set(no),$n=Pn.filter(se=>qt.has(se.id)).sort((se,Fe)=>{const st=no.indexOf(se.id),T=no.indexOf(Fe.id);return st!==T?st-T:vm(se,Fe)}),qn=Pn.filter(se=>se.authenticated&&!qt.has(se.id)),Nn=Pn.filter(se=>!se.authenticated&&!qt.has(se.id)),Dn=se=>{if(se.id==="claude-cli"&&se.type==="cli")return e.jsx(Up,{authenticated:se.authenticated,onToggled:()=>{nt()}},se.id);if(se.type==="api_key"){const Fe=Do(se.id),st=cT(se);return e.jsxs("div",{"data-testid":`onboarding-provider-card-${se.id}`,className:`onboarding-provider-card${se.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ss,{provider:se.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsxs("strong",{className:"onboarding-provider-card__name",children:[e.jsx(qm,{size:14,className:"onboarding-provider-key-icon"}),se.name]}),e.jsx("span",{className:"onboarding-provider-card__description",children:Fe.description}),e.jsx(Ce,{status:tt(se)}),se.authenticated&&se.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",se.keyHint]})]}),e.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:e.jsx(uT,{provider:se,apiKeyInfo:st,inputValue:V[se.id]??"",isSaving:D===se.id,error:de[se.id],success:ve[se.id],isConnected:se.authenticated,onInputChange:vt,onSave:Je,onClear:pt})})]},se.id)}return e.jsxs("div",{"data-testid":`onboarding-provider-card-${se.id}`,className:`onboarding-provider-card${se.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ss,{provider:se.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:se.name}),e.jsx("span",{className:"onboarding-provider-card__description",children:Do(se.id).description}),e.jsx(Ce,{status:tt(se)})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:D===se.id?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:se.authenticated?"Logging out…":"Waiting for login…"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Mt(se.id),children:"Cancel"})]}):se.authenticated?e.jsx("button",{className:"btn btn-sm",onClick:()=>ze(se.id),children:"Logout"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Et(se.id),children:"Login"})}),D===se.id&&G[se.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`onboarding-login-instructions-${se.id}`,children:G[se.id]}),rt[se.id]==="timeout"&&D!==se.id&&e.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),rt[se.id]==="failed"&&D!==se.id&&e.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},se.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:[f==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx(jn,{size:24})," Set Up AI ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),f==="github"&&e.jsxs(e.Fragment,{children:[e.jsx(ts,{size:24})," Connect GitHub ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),f==="first-task"&&e.jsxs(e.Fragment,{children:[e.jsx(yb,{size:24})," Create Your First Task"]}),f==="complete"&&e.jsxs(e.Fragment,{children:[e.jsx(tn,{size:24})," All Set!"]})]}),f!=="complete"&&e.jsx("button",{className:"modal-close",onClick:Nt,"aria-label":"Skip onboarding",title:"Skip for now",children:e.jsx(Dt,{size:20})})]}),e.jsx("div",{className:"model-onboarding-steps",children:Te.map((se,Fe)=>{const st=x.includes(se.key)&&ye>Fe,T=v.includes(se.key)&&!x.includes(se.key)&&ye>Fe,W=st||T;return e.jsxs("div",{className:"onboarding-step-wrapper",children:[Fe>0&&e.jsx("div",{className:`model-onboarding-step-connector ${Fe<=ye?"done":""}`}),W?e.jsxs("button",{className:`model-onboarding-step-indicator ${f===se.key?"active":""} ${st?"done":""} ${T?"skipped":""}`,onClick:()=>b(se.key),"aria-label":`Go back to ${se.label}`,title:`Review ${se.label}`,children:[e.jsx("span",{className:"step-number",children:st?e.jsx(tn,{size:14}):T?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Fe+1}),e.jsx("span",{className:"step-label",children:se.label})]}):e.jsxs("div",{className:`model-onboarding-step-indicator ${f===se.key?"active":""} ${st?"done":""} ${T?"skipped":""}`,children:[e.jsx("span",{className:"step-number",children:st?e.jsx(tn,{size:14}):T?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Fe+1}),e.jsx("span",{className:"step-label",children:se.label})]})]},se.key)})}),e.jsxs("div",{className:"model-onboarding-content",ref:Oe,children:[f==="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."}),!Y&&I.length>0&&(()=>{const se=I.filter(ee=>ee.id!=="github"&&ee.authenticated).length,Fe=I.filter(ee=>ee.id!=="github").length,st=Object.keys(ge).filter(ee=>!I.find(me=>me.id===ee)?.authenticated).length;if(Fe===0)return null;let T="onboarding-provider-summary",W="";return se>0?(T+=" onboarding-provider-summary--connected",W=`✓ ${se} of ${Fe} provider${Fe!==1?"s":""} connected`):st>0?(T+=" onboarding-provider-summary--skipped",W=`${st} provider${st!==1?"s":""} skipped`):(T+=" onboarding-provider-summary--none",W="No providers connected yet"),e.jsx("div",{className:T,"data-testid":"provider-summary",children:W})})(),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(se=>se.authenticated)&&e.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),Y?e.jsxs("div",{className:"model-onboarding-loading",children:[e.jsx(lt,{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"}),$n.length>0?e.jsx("div",{className:"model-onboarding-providers",children:$n.map(se=>Dn(se))}):e.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),qn.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:qn.map(se=>Dn(se))})]}),e.jsx(Vs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:e.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Nn.length>0?e.jsx("div",{className:"model-onboarding-providers",children:Nn.map(se=>Dn(se))}):e.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),on&&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."})}),Un&&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."})}),J.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(Gt,{models:J,value:z,onChange:at,placeholder:"Select a default model…",label:"Default model"})}),z&&e.jsx("div",{className:"onboarding-model-preview",children:e.jsxs("small",{className:"settings-muted",children:["Selected:"," ",J.find(se=>se.id===z)?.name??z]})})]})]}),f==="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"})]})}),Tn&&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."})}),ie?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"onboarding-provider-row",children:[e.jsxs("div",{className:"onboarding-provider-info",children:[e.jsxs("strong",{children:[e.jsx(ts,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),e.jsx("span",{"data-testid":"onboarding-auth-status-github",children:e.jsx(ce,{status:hn})})]}),be&&(D==="github"?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>ze("github"),children:"Disconnect"}))]}),(hn==="not-connected"||hn==="pending")&&e.jsx("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:D==="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:()=>Mt("github"),children:"Cancel"})]}):e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Et("github"),children:[e.jsx(ts,{size:16}),"Connect"]})}),hn==="connected"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:je?"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."}),hn==="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:()=>Et("github"),children:"Retry"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Tt,children:"Skip for now"})]})]}),hn==="pending"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),hn==="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:()=>Et("github"),children:"Connect anyway"})})]}),hn==="not-connected"&&e.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):e.jsxs("div",{className:"model-onboarding-github-optional",children:[e.jsx(ts,{size:48,className:"optional-icon"}),je?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 →"})]})]}),f==="first-task"&&e.jsxs("div",{className:"model-onboarding-first-task",children:[e.jsx("p",{className:"model-onboarding-description",children:Wt?"Your workspace is ready. Here's how to get started:":"Before creating your first task, register a project directory."}),N&&Hn?e.jsxs("div",{className:"onboarding-task-created",children:[e.jsx(tn,{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:Hn.id}),xn&&e.jsx("p",{className:"onboarding-task-created__description",children:xn}),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:Lt,children:"View Task"}),e.jsx("button",{type:"button",className:"btn",onClick:wn,children:"Go to Dashboard"})]})]}):e.jsxs(e.Fragment,{children:[Wt?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:se=>{S(se.target.value),R(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:pe,disabled:k,"data-testid":"onboarding-first-task-submit",children:k?e.jsxs(e.Fragment,{children:[e.jsx(lt,{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(dT,{items:sn}),Wt&&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:ct,disabled:F,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(Vt,{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${Ze?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:bt,disabled:F||!Ze,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(ts,{size:24})}),e.jsxs("div",{className:"cta-content",children:[e.jsx("strong",{children:"Import from GitHub"}),e.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Ze&&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."]})]})]})]}),f==="complete"&&e.jsxs("div",{className:"model-onboarding-complete",children:[e.jsx(tn,{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:[f==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Nt,disabled:F,children:"Skip for now"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:yt,children:"Skip setup →"}),e.jsx("button",{className:"btn btn-primary",onClick:xt,children:"Next →"})]}),f==="github"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Ct,children:"← Back"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:yt,children:"Skip GitHub →"}),e.jsx("button",{className:"btn btn-primary",onClick:xt,children:"Next →"})]}),f==="first-task"&&!N&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Ct,children:"← Back"}),e.jsx("button",{className:"btn btn-primary",onClick:$,disabled:F,children:F?e.jsxs(e.Fragment,{children:[e.jsx(lt,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),f==="complete"&&e.jsxs("button",{className:"btn btn-primary",onClick:Bt,children:[e.jsx(tn,{size:16}),e.jsx("span",{children:"Get Started"})]})]})]})})}const pT=a.lazy(()=>en(()=>import("./SetupWizardModal-Cakxqkad.js"),__vite__mapDeps([12,1,2,3,4,5])).then(t=>({default:t.SetupWizardModal})));function fT({projectId:t,tasks:n,projects:s,currentProject:i,addToast:r,toasts:l,removeToast:o,modalManager:d,projectActions:m,taskHandlers:c,taskOperations:u,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[b,x]=a.useState(null),y=p??d.closeSettings,v=a.useCallback(()=>{d.openNewTask()},[d]),M=a.useCallback(()=>{d.openGitHubImport()},[d]),N=a.useCallback(w=>{x(null),d.closeModelOnboarding(),d.openDetailTask(w)},[d]),A=a.useCallback(async w=>{const S=await c.handleModalCreate(w);return d.modelOnboardingOpen&&x(S),S},[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(kM,{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(_M,{onClose:y,addToast:r,initialSection:d.settingsInitialSection,projectId:t,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})}),e.jsx($M,{isOpen:d.githubImportOpen,onClose:d.closeGitHubImport,onImport:c.handleGitHubImport,tasks:n,projectId:t}),e.jsx(ui,{children:e.jsx(zM,{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(VM,{isOpen:d.isSubtaskOpen,onClose:d.closeSubtask,initialDescription:d.subtaskInitialDescription??"",onTasksCreated:c.handleSubtaskTasksCreated,projectId:t,resumeSessionId:d.subtaskResumeSessionId})}),e.jsx(rA,{isOpen:d.terminalOpen,onClose:d.closeTerminal,initialCommand:d.terminalInitialCommand,projectId:t}),e.jsx(oA,{isOpen:d.scriptsOpen,onClose:d.closeScripts,addToast:r,onRunScript:d.runScript,projectId:t}),d.filesOpen&&e.jsx(EA,{initialWorkspace:d.fileBrowserWorkspace,isOpen:!0,onClose:d.closeFiles,onWorkspaceChange:d.setFileWorkspace,projectId:t}),e.jsx($A,{isOpen:d.usageOpen,onClose:d.closeUsage,projectId:t}),d.schedulesOpen&&e.jsx(tP,{onClose:d.closeSchedules,addToast:r,projectId:t}),e.jsx(ui,{children:e.jsx(aP,{isOpen:d.newTaskModalOpen,onClose:d.closeNewTask,tasks:n,onCreateTask:A,addToast:r,projectId:t,onPlanningMode:d.openPlanningWithInitialPlan,onSubtaskBreakdown:d.openSubtaskBreakdown})}),e.jsx(dP,{isOpen:d.activityLogOpen,onClose:d.closeActivityLog,tasks:n,projectId:t,projects:s,currentProject:i,onOpenTaskDetail:w=>{const S=n.find(k=>k.id===w);S&&d.openDetailTask(S)}}),e.jsx(ui,{children:e.jsx(mP,{isOpen:d.gitManagerOpen,onClose:d.closeGitManager,tasks:n,addToast:r,projectId:t})}),e.jsx(ui,{children:e.jsx(NP,{isOpen:d.workflowStepsOpen,onClose:d.closeWorkflowSteps,addToast:r,projectId:t})}),e.jsx(IP,{isOpen:d.agentsOpen,onClose:d.closeAgents,addToast:r,projectId:t}),d.setupWizardOpen&&e.jsx(a.Suspense,{fallback:null,children:e.jsx(pT,{onProjectRegistered:m.handleSetupComplete,onClose:d.closeSetupWizard})}),d.modelOnboardingOpen&&e.jsx(hT,{onComplete:m.handleModelOnboardingComplete,addToast:r,projectId:t??"",onOpenSetupWizard:m.handleAddProject,onOpenNewTask:v,onOpenGitHubImport:M,firstCreatedTask:b,onViewTask:N}),e.jsx(Xp,{toasts:l,onRemove:o})]})}const Fo=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function gT(t,n){if(n==="ready")return"done";const s=Fo.findIndex(r=>r.id===n),i=Fo.findIndex(r=>r.id===t);return i<s?"done":i===s?"active":"pending"}function bT({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:Fo.map(n=>{const s=gT(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(lt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),e.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const xT=5e3;function vT(t,n,s){return t||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function yT(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 kT(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 Sy(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()},xT),()=>{u.current&&(clearInterval(u.current),u.current=null)}),[g]);const p=yT(t,s,i),f=vT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:o,error:m,refresh:g}}const jT={planning:Ls,subtask:yi,mission_interview:ns,milestone_interview:ns,slice_interview:ns},wT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function NT({sessions:t,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const[l,o]=a.useState(!1),[d,m]=a.useState(new Set),c=a.useRef(null),u=a.useRef(new Map),h=a.useRef(null),{activeTabMap:g}=ra(),p=a.useMemo(()=>Si(),[]);if(a.useEffect(()=>{if(!l)return;const x=y=>{c.current&&!c.current.contains(y.target)&&o(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,y=new Map;for(const v of t){const M=g.get(v.id),N=[v.status,v.updatedAt,M?.tabId??v.lockedByTab??"",M?.stale?"stale":"fresh"].join("|"),A=u.current.get(v.id);A&&A!==N&&x.add(v.id),y.set(v.id,N)}if(u.current=y,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 f=t.length,b=s>0;return e.jsxs("div",{ref:c,className:"background-tasks-indicator",children:[e.jsxs("button",{className:`background-tasks-indicator__pill${b?" background-tasks-indicator__pill--attention":""}`,onClick:()=>o(x=>!x),title:`${f} background AI task${f!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&e.jsx(lt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&e.jsx(Ic,{size:12}),e.jsxs("span",{children:["AI ",f]})]}),l&&e.jsxs("div",{className:"background-tasks-indicator__popover",children:[e.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),e.jsx("div",{className:"background-tasks-indicator__popover-list",children:t.map(x=>{const y=jT[x.type],v=x.status==="generating",M=x.status==="awaiting_input",N=x.status==="error",A=g.get(x.id),w=A?.tabId??x.lockedByTab??null,S=!!(w&&w!==p&&!A?.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:()=>{S&&!window.confirm("This session is active in another tab. Open anyway?")||(i(x),o(!1))},children:[N?e.jsx(is,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):e.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),e.jsxs("div",{className:"background-tasks-indicator__session-content",children:[e.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),e.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[N?"Failed":wT[x.type],v&&" — generating...",M&&!S&&" — needs input",M&&S&&" — active in another tab"]})]}),v&&e.jsx(lt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),M&&!S&&e.jsx(Ic,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),M&&S&&e.jsx(qr,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),e.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:P=>{P.stopPropagation(),r(x.id)},title:"Dismiss",children:e.jsx(Dt,{size:12})})]},x.id)})})]})]})}function ST(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 CT(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 ET({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}=kT(t,n,s,m),g=a.useMemo(()=>CT(c.executorState),[c.executorState]),p=a.useMemo(()=>ST(c.lastActivityAt),[c.lastActivityAt]),f=g.icon;return h?e.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:e.jsxs("span",{className:"executor-status-bar__error",children:[e.jsx(Uo,{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(NT,{sessions:i,generating:r??0,needsInput:l??0,onOpenSession:o,onDismissSession:d}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),e.jsx("span",{className:"executor-status-bar__count",children:c.queuedTaskCount})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${c.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Running"}),e.jsx("span",{className:"executor-status-bar__count",children:c.runningTaskCount}),e.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),e.jsx("span",{className:"executor-status-bar__max",children:c.maxConcurrent})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),c.stuckTaskCount>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[e.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),e.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:c.stuckTaskCount})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${c.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),e.jsx("span",{className:`executor-status-bar__count ${c.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:c.blockedTaskCount})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),e.jsx("span",{className:"executor-status-bar__count",children:c.inReviewCount})]}),e.jsx("div",{className:"executor-status-bar__spacer"}),e.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[e.jsx(Hi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__time",children:p})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx(f,{size:12,style:{color:g.color},"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__state",style:{color:g.color},children:g.label})]})]})}const MT={planning:Ls,subtask:yi,mission_interview:ns,milestone_interview:ns,slice_interview:ns},AT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},pi=new Set;function PT({sessions:t,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,l]=a.useState(0),o=()=>l(f=>f+1);a.useEffect(()=>{if(pi.size===0)return;const f=new Map(t.map(x=>[x.id,x]));let b=!1;for(const x of pi){const y=f.get(x);y&&y.status!=="awaiting_input"&&y.status!=="error"&&(pi.delete(x),b=!0)}b&&o()},[t]);const d=a.useMemo(()=>t.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!pi.has(f.id)),[t,r]);if(d.length===0)return null;const m=d.filter(f=>f.status==="awaiting_input").length,c=d.filter(f=>f.status==="error").length;let u="";m>0&&c>0?u=`${m} AI session${m===1?"":"s"} need${m===1?"s":""} your input, ${c} failed`:m>0?u=`${m} AI session${m===1?"":"s"} need${m===1?"s":""} your input`:c>0&&(u=`${c} AI session${c===1?"":"s"} failed`);const h=f=>{pi.add(f),o()},g=f=>{pi.delete(f.id),o(),n(f)},p=()=>{for(const f of d)pi.add(f.id);o(),i()};return e.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[e.jsxs("div",{className:"session-notification-banner__header",children:[e.jsxs("div",{className:"session-notification-banner__headline",children:[e.jsx(is,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:u})]}),e.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[e.jsx(Dt,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Dismiss all"})]})]}),e.jsx("div",{className:"session-notification-banner__list",children:d.map(f=>{const b=MT[f.type],x=f.status==="error";return e.jsxs("article",{className:`session-notification-banner__item${x?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[e.jsxs("div",{className:"session-notification-banner__item-main",children:[x?e.jsx(is,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):e.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),e.jsxs("div",{className:"session-notification-banner__text",children:[e.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),e.jsx("p",{className:"session-notification-banner__meta",children:x?"Failed":AT[f.type]})]})]}),e.jsxs("div",{className:"session-notification-banner__actions",children:[e.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:x?"Retry":"Resume"}),e.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:e.jsx(Dt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function TT({onResume:t}){const n=BP();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",onClick:()=>{ys("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 RT({onOpenSettings:t,onOpenModelOnboarding:n}){const s=na(),i=Yp(),[r,l]=a.useState(!0),[o,d]=a.useState(!1),[m,c]=a.useState(!1),[u,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){l(!1);return}let y=!1;return(async()=>{try{l(!0),d(!1);const[M,N]=await Promise.all([ji(),ia()]);if(y)return;const A=M.providers??[],w=A.find(R=>R.id==="github"),k=!A.some(R=>R.id!=="github"&&R.authenticated),P=!N.defaultProvider&&!N.defaultModelId,C=w?!w.authenticated:!1;h({needsAiProvider:k,needsDefaultModel:P,needsGitHub:C})}catch{y||d(!0)}finally{y||l(!1)}})(),()=>{y=!0}},[s,i]);const g=a.useCallback(()=>{zP(),c(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{t("global-models")},[t]),b=a.useCallback(()=>{t("authentication")},[t]),x=a.useMemo(()=>{const y=[];return u.needsAiProvider&&y.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:jn}),u.needsDefaultModel&&y.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:qm}),u.needsGitHub&&y.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:ts}),y},[u.needsAiProvider,u.needsDefaultModel,u.needsGitHub,b,f,p]);return!s||i||m||r||o||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(y=>{const v=y.icon;return e.jsxs("li",{className:"post-onboarding-recommendations__item",children:[e.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[e.jsx(is,{size:14,"aria-hidden":!0}),e.jsx(v,{size:14,"aria-hidden":!0})]}),e.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[e.jsx("strong",{children:y.title}),e.jsx("span",{children:y.description})]}),e.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:y.onAction,children:y.actionLabel})]},y.id)})})]})]}),e.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:e.jsx(Dt,{size:16,"aria-hidden":!0})})]})}function _T({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 so(t){return t>99?"99+":String(t)}function IT({view:t,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:l,onOpenMailbox:o,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:c,onOpenSchedules:u,onOpenScripts:h,onToggleTerminal:g,onOpenFiles:p,onOpenGitHubImport:f,onOpenPlanning:b,onResumePlanning:x,activePlanningSessionCount:y=0,onOpenUsage:v,onRunScript:M,projectId:N,onViewAllProjects:A,showSkillsTab:w,experimentalFeatures:S}){const k=Jr(),[P,C]=a.useState(!1),[R,O]=a.useState(!1),[Z,I]=a.useState({}),[_,j]=a.useState(!1),Q=a.useMemo(()=>Object.entries(Z).sort(([te],[F])=>te.localeCompare(F)),[Z]);a.useEffect(()=>{if(!R)return;let te=!1;return j(!0),Va(N).then(F=>{te||I(F)}).catch(()=>{te||I({})}).finally(()=>{te||j(!1)}),()=>{te=!0}},[R,N]);const Y=a.useCallback(()=>C(!1),[]),L=a.useCallback(te=>{Y(),te?.()},[Y]);if(a.useEffect(()=>{if(!P)return;const te=F=>{F.key==="Escape"&&C(!1)};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[P]),k!=="mobile"||i)return null;const D=y>0&&x?x:b,U=!!S?.roadmap,G=!!w,E=U&&(!G||t==="roadmaps"),J=G&&(!U||t!=="roadmaps"),ue=G&&!J,z=t==="documents"||t==="insights"||t==="memory"||t==="devserver"||t==="dev-server"||t==="roadmaps"&&!E||t==="skills"&&!J;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(ns,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":t==="chat",onClick:()=>n("chat"),children:[e.jsx(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(Bi,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-nav-tab-badge",children:so(d)})]}),J&&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"})]}),E&&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(mo,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${z?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>C(te=>!te),children:[e.jsx(oo,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:Y}),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:()=>L(o),children:[e.jsx(Bi,{}),e.jsx("span",{children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:so(d)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>L(l),children:[e.jsx(ws,{}),e.jsx("span",{children:"Activity Log"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>L(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:()=>L(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:()=>O(te=>!te),"aria-expanded":R,"aria-haspopup":"menu","aria-label":"Show scripts",children:e.jsx(ln,{size:14,className:`mobile-more-chevron${R?" mobile-more-chevron--open":""}`})})]}),R&&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(lt,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts…"})]}):Q.length>0?e.jsxs(e.Fragment,{children:[Q.map(([te,F])=>e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${te}`,onClick:()=>{M&&M(te,F),Y(),O(!1)},children:[e.jsx(rn,{size:14}),e.jsx("span",{children:te})]},te)),h&&e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{Y(),O(!1),h()},children:[e.jsx(Es,{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:()=>{Y(),O(!1),h()},children:[e.jsx(Es,{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:()=>L(p),children:[e.jsx(An,{}),e.jsx("span",{children:"Files"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>L(D),children:[e.jsx(Ls,{}),e.jsx("span",{children:"Planning"}),y>0&&e.jsx("span",{className:"mobile-more-item-badge",children:so(y)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>L(c),children:[e.jsx(po,{}),e.jsx("span",{children:"Workflow Steps"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>L(u),children:[e.jsx(Hi,{}),e.jsx("span",{children:"Automation"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>L(f),children:[e.jsx(_T,{}),e.jsx("span",{children:"Import from GitHub"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>L(v),children:[e.jsx(ws,{}),e.jsx("span",{children:"Usage"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>L(A),children:[e.jsx(Hm,{}),e.jsx("span",{children:"Projects"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>L(()=>n("documents")),children:[e.jsx(xi,{}),e.jsx("span",{children:"Documents"})]}),ue&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>L(()=>n("skills")),children:[e.jsx(jn,{}),e.jsx("span",{children:"Skills"})]}),U&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>L(()=>n("roadmaps")),children:[e.jsx(mo,{}),e.jsx("span",{children:"Roadmaps"})]}),S?.insights&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>L(()=>n("insights")),children:[e.jsx(On,{}),e.jsx("span",{children:"Insights"})]}),S?.memoryView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>L(()=>n("memory")),children:[e.jsx(Nr,{}),e.jsx("span",{children:"Memory"})]}),S?.devServerView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{L(()=>n("dev-server"))},children:[e.jsx(Vr,{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:()=>L(r),children:[e.jsx(Ia,{}),e.jsx("span",{children:"Settings"})]})]})]})]})}function $T({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 gc="__fn_agent__";function tf(t,n){const s=typeof t=="string"?t.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function ym(t,n,s){const i=typeof t=="string"?t.trim():"",r=tf(n,s),l=i||(r.modelProvider&&r.modelId?gc:"");return l?{agentId:l,...r}:null}function io(t,n,s){const i=tf(n,s),r=i.modelProvider??"",l=i.modelId??"";return`${t}::${r}/${l}`}function DT(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 km(t){return{id:t.id,sessionId:t.sessionId,role:t.role,content:t.content,thinkingOutput:t.thinkingOutput,toolCalls:DT(t.metadata),createdAt:t.createdAt}}function FT(t,n){const[s,i]=a.useState(null),[r,l]=a.useState(!1),[o,d]=a.useState([]),[m,c]=a.useState(!1),[u,h]=a.useState(!1),[g,p]=a.useState(""),[f,b]=a.useState(""),[x,y]=a.useState([]),[v,M]=a.useState(""),N=a.useRef(null),A=a.useRef(!1),w=a.useRef(""),S=a.useRef(""),k=a.useRef(null);a.useEffect(()=>{w.current=v},[v]);const P=a.useCallback(async L=>{const D={agentId:L.agentId};return L.modelProvider&&L.modelId&&(D.modelProvider=L.modelProvider,D.modelId=L.modelId),(await Ok(D,t)).session},[t]),C=a.useCallback(async(L,D,U)=>{const G=ym(L,D,U);if(!G)return;const E=io(G.agentId,G.modelProvider,G.modelId);l(!0);try{const{session:J}=await zk({agentId:G.agentId,modelProvider:G.modelProvider,modelId:G.modelId},t);if(J)i(J),S.current=E;else{const ue=await P(G);i(ue),S.current=E}}catch(J){console.error("[useQuickChat] Failed to initialize session:",J),n?.("Failed to initialize chat","error")}finally{l(!1)}},[t,n,P]),R=a.useCallback(async()=>{if(s){c(!0);try{const L=await od(s.id,{limit:50},t);d(L.messages.map(km))}catch(L){console.error("[useQuickChat] Failed to load messages:",L)}finally{c(!1)}}},[s,t]);a.useEffect(()=>{s?R():d([])},[s,R]);const O=a.useCallback(async()=>{if(s){c(!0);try{const L=await od(s.id,{limit:50},t);d(L.messages.map(km))}catch(L){console.error("[useQuickChat] Failed to reload messages:",L)}finally{c(!1)}}},[s,t]),Z=a.useCallback(async(L,D,U)=>{const G=ym(L,D,U);if(!G)return;const E=io(G.agentId,G.modelProvider,G.modelId);if(k.current=G,N.current&&(N.current.close(),N.current=null),p(""),b(""),y([]),h(!1),E===S.current&&s){await O();return}d([]),S.current=E,await C(G.agentId,G.modelProvider,G.modelId)},[C,O,s]),I=a.useCallback(async(L,D)=>{await Z(gc,L,D)},[Z]),_=a.useCallback(async()=>{const L=k.current;if(!L)return;const D=io(L.agentId,L.modelProvider,L.modelId);N.current&&(N.current.close(),N.current=null),p(""),b(""),y([]),h(!1),d([]),l(!0);try{const U=await P(L);i(U),S.current=D}catch(U){console.error("[useQuickChat] Failed to start a fresh session:",U),n?.("Failed to start a new chat","error")}finally{l(!1)}},[n,P]),j=a.useCallback(()=>{s&&(A.current=!0,N.current?.close(),N.current=null,Bk(s.id,t).catch(()=>{}),h(!1),p(""),b(""),y([]))},[s,t]),Q=a.useCallback(()=>{w.current="",M("")},[]),Y=a.useCallback(L=>{if(!s||!L.trim())return;if(u){w.current=L,M(L);return}A.current=!1,N.current&&(N.current.close(),N.current=null);const U={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:L,createdAt:new Date().toISOString()};d(z=>[...z,U]),p(""),b(""),y([]),h(!0);let G="",E="",J=[];const ue={onThinking:z=>{E+=z,b(E)},onText:z=>{G+=z,p(G)},onToolStart:z=>{J=[...J,{toolName:z.toolName,args:z.args,isError:!1,status:"running"}],y(J)},onToolEnd:z=>{const te=[...J];for(let F=te.length-1;F>=0;F--){const fe=te[F];if(fe?.toolName===z.toolName&&fe.status==="running"){te[F]={...fe,status:"completed",isError:z.isError,result:z.result},J=te,y(te);return}}J=[...te,{toolName:z.toolName,isError:z.isError,result:z.result,status:"completed"}],y(J)},onDone:z=>{const te={id:z.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:G,thinkingOutput:E||void 0,toolCalls:J.length>0?J:void 0,createdAt:new Date().toISOString()};d(fe=>[...fe,te]),p(""),b(""),y([]),h(!1),N.current=null;const F=w.current.trim();F&&(w.current="",M(""),Y(F))},onError:z=>{if(p(""),b(""),y([]),h(!1),N.current=null,console.error("[useQuickChat] Stream error:",z),n?.("Failed to get response","error"),!A.current){const te=w.current.trim();te&&(w.current="",M(""),Y(te))}O()}};N.current=Uk(s.id,L,ue,t)},[s,u,t,n,O]);return a.useEffect(()=>()=>{N.current&&(N.current.close(),N.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:o,messagesLoading:m,isStreaming:u,streamingText:g,streamingThinking:f,streamingToolCalls:x,pendingMessage:v,sendMessage:Y,stopStreaming:j,clearPendingMessage:Q,switchSession:Z,startModelChat:I,startFreshSession:_,loadMessages:R,reloadMessages:O}),[s,r,o,m,u,g,f,x,v,Y,j,Q,Z,I,_,R,O])}function LT(t,n){const[s,i]=a.useState([]),[r,l]=a.useState(null),[o,d]=a.useState(!1),m=a.useCallback(async g=>{d(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,x=await aa({...f,...g,includeEphemeral:g?.includeEphemeral??b},t);i(x)}catch(p){console.error("Failed to load agents:",p)}finally{d(!1)}},[t,n?.filterState,n?.showSystemAgents]),c=a.useCallback(async()=>{try{const g=await gy(t);l(g)}catch(g){console.error("Failed to load agent stats:",g)}},[t]);a.useEffect(()=>{m(),c()},[m,c]),a.useEffect(()=>{const g=t?`?projectId=${encodeURIComponent(t)}`:"",p=()=>{m(),c()};return Os(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[t,m,c]);const u=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:u||!aj(g));return{agents:s,activeAgents:h,stats:r,isLoading:o,loadAgents:m,loadStats:c}}function zT({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(Bm,{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 OT=200;function BT(t={}){const{projectId:n,workspace:s="project"}=t,[i,r]=a.useState(!1),[l,o]=a.useState(""),[d,m]=a.useState(-1),[c,u]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),b=a.useRef(null),x=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),x.current?.abort()},[]);const y=a.useCallback((w,S)=>{if(S<0||S>w.length){r(!1);return}const k=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=S-1;P>=0;P--){if(w[P]==="#")if(P===0){const C=w.slice(P+1,S);m(P),o(C),f(0),r(!0);return}else{const C=w[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(C)){const R=w.slice(P+1,S);m(P),o(R),f(0),r(!0);return}r(!1);return}if(!k(w[P])){r(!1);return}}r(!1)},[]),v=a.useCallback(()=>{r(!1),o(""),m(-1),u([]),f(0),g(!1)},[]),M=a.useCallback(async w=>{if(!w.trim()){u([]),g(!1);return}x.current?.abort(),x.current=new AbortController;try{g(!0);const S=await Sv(w,s,n);u(S.files),f(0)}catch(S){S.name!=="AbortError"&&u([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M(l)},OT),()=>{b.current&&clearTimeout(b.current)}},[l,i,M]);const N=a.useCallback((w,S)=>{if(!i||d<0)return S;const k=S.slice(0,d),P=S.slice(d+1),C=P.match(/[\s]|$/),R=C?C.index:P.length,O=P.slice(R);return`${k}#${w.path}${O}`},[i,d]),A=a.useCallback((w,S)=>{if(!i||c.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),f(k=>Math.min(k+1,c.length-1)),!0;case"ArrowUp":return w.preventDefault(),f(k=>Math.max(k-1,0)),!0;case"Enter":case"Tab":return c[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),v(),!0;default:return!1}},[i,c,p,v]);return{mentionActive:i,files:c,loading:h,mentionQuery:l,selectedIndex:p,setSelectedIndex:f,detectMention:y,selectFile:N,dismissMention:v,handleKeyDown:A}}const UT={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"},HT={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function qT(t){return`${t.name?.trim()||t.id} (${t.role})`}function VT(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 WT(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 KT(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 GT(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 jm(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(Jb,{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=KT(s.args),d=GT(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 JT(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 YT(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 y=JSON.parse(x);if(typeof y.x=="number"&&typeof y.y=="number"&&!isNaN(y.x)&&!isNaN(y.y))return y}}catch{}return i()}),[o,d]=a.useState(!1),m=a.useRef(null),c=n??a.useRef(!1),u=a.useCallback(b=>{if(typeof window>"u")return b;const x=48,y=window.innerWidth<=768?4:8,v=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,N=window.innerWidth-x-y,A=window.innerHeight-x-y-v-M;return{x:Math.max(y,Math.min(N,b.x)),y:Math.max(y,Math.min(A,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 y=b.target.closest(".quick-chat-fab");y&&(b.preventDefault(),typeof y.setPointerCapture=="function"&&y.setPointerCapture(b.pointerId),m.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},c.current=!1,d(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!m.current||!o)return;const x=b.clientX-m.current.pointerX,y=b.clientY-m.current.pointerY;if((Math.abs(x)>=5||Math.abs(y)>=5)&&(c.current=!0),c.current){const v=m.current.x-x,M=m.current.y-y,N=u({x:v,y:M});l(N)}},[o,u]),f=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:p,handlePointerUp:f}}function QT({projectId:t,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:l=[],favoriteModels:o=[],onToggleFavorite:d,onToggleModelFavorite:m}){const{agents:c}=LT(t),[u,h]=a.useState(!1),g=i!==void 0,p=g?i:u,f=g?ze=>{r?.(typeof ze=="function"?ze(p):ze)}:h,[b,x]=a.useState("agent"),[y,v]=a.useState(""),[M,N]=a.useState([]),[A,w]=a.useState(!1),[S,k]=a.useState(""),[P,C]=a.useState(""),[R,O]=a.useState(""),[Z,I]=a.useState(!1),[_,j]=a.useState(0),[Q,Y]=a.useState(-1),[,L]=a.useState(!1),[D,U]=a.useState({top:0,left:0}),G=BT({projectId:t}),E=a.useCallback(ze=>{if(!ze||!G.mentionActive)return;const at=ze.getBoundingClientRect();U({top:at.top-260,left:at.left+8})},[G.mentionActive]),J=a.useRef(!1),ue=a.useRef(!1),z=a.useRef(""),te=a.useRef(0),F=a.useRef(null),{position:fe,isDragging:V,handlePointerDown:K,handlePointerMove:de,handlePointerUp:we}=YT(t,J),{activeSession:ve,messages:Se,isStreaming:Pe,streamingText:Oe,streamingThinking:Ie,streamingToolCalls:rt,sessionsLoading:Ee,messagesLoading:_e,sendMessage:Be,stopStreaming:et,pendingMessage:De,clearPendingMessage:Xe,switchSession:re,startModelChat:ne,startFreshSession:ge}=FT(t,n),le=a.useRef(null),Te=a.useRef(null),ye=a.useRef(null),He=a.useRef(null),nt=a.useMemo(()=>VT(S),[S]),mt=a.useMemo(()=>M.find(ze=>`${ze.provider}/${ze.id}`===S)??null,[M,S]),he=a.useMemo(()=>WT(mt,nt),[mt,nt]),ie=a.useMemo(()=>b==="model"?nt?`${gc}::${nt.modelProvider}/${nt.modelId}`:"":y?`${y}::`:"",[b,nt,y]),be=b==="agent"?!!y:!!nt;a.useEffect(()=>{if(c.length===0){v(""),x("model");return}c.some(at=>at.id===y)||v(c[0]?.id??"")},[c,y]),a.useEffect(()=>{!p||ue.current||(ue.current=!0,w(!0),Jn().then(ze=>{const at=ze.models??[];if(N(at),c.length===0&&at.length>0&&!S){const q=at[0];q&&k(`${q.provider}/${q.id}`)}}).catch(ze=>{console.error("[QuickChatFAB] Failed to load models:",ze),N([])}).finally(()=>{w(!1)}))},[p,c.length,S]),a.useEffect(()=>{if(!p){z.current="";return}if(!ie){z.current="";return}if(ie!==z.current){if(z.current=ie,b==="model"&&nt){ne(nt.modelProvider,nt.modelId);return}b==="agent"&&y&&re(y)}},[p,b,nt,y,ie,ne,re]),a.useEffect(()=>{p||(I(!1),O(""),Y(-1))},[p]);const Me=a.useCallback(ze=>{v(ze)},[]),Ze=a.useCallback(ze=>{k(ze)},[]),je=a.useCallback(()=>{!be||Ee||ge()},[be,Ee,ge]),tt=a.useMemo(()=>c.find(ze=>ze.id===y)??null,[c,y]),Ce=a.useMemo(()=>{const ze=R.trim().toLowerCase();return ze?c.filter(at=>at.name.toLowerCase().includes(ze)):c},[c,R]),qe=a.useMemo(()=>{const ze=new Map;for(const at of c)ze.set(at.name.toLowerCase(),at);return ze},[c]);a.useEffect(()=>{j(0)},[R,Z]),a.useEffect(()=>()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),a.useEffect(()=>{if(!p)return;const ze=q=>{const $=q.target;le.current?.contains($)||Te.current?.contains($)||$.closest(".model-combobox-dropdown--portal")||f(!1)},at=q=>{q.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",ze),document.addEventListener("keydown",at),()=>{document.removeEventListener("mousedown",ze),document.removeEventListener("keydown",at)}},[p,f]),a.useEffect(()=>{if(!p)return;const ze=ye.current;ze&&(ze.scrollTop=ze.scrollHeight)},[Se,Oe,Ie,p]);const ce=a.useMemo(()=>b==="agent"?tt?`Message ${tt.name||tt.id}`:"Select an agent to start chatting":he?`Message ${he}`:"Select a model to start chatting",[b,tt,he]),Ue=!be||!ve||Ee,Ve=De.length>50?`${De.slice(0,50)}…`:De,Ae=a.useCallback(()=>{const ze=P.trim();!ze||Ue||(C(""),I(!1),O(""),Y(-1),Be(ze))},[Be,Ue,P]),We=a.useCallback((ze,at)=>{const q=JT(ze,at);if(q){I(!0),O(q.filter),Y(q.start);return}I(!1),O(""),Y(-1)},[]),xt=a.useCallback(ze=>{const at=He.current;if(!at||Q<0)return;const q=at.selectionStart??te.current,$=at.selectionEnd??q,pe=Math.max(q,$),ct=Math.min(Q,pe),Nt=`${`@${ze.name.replace(/\s+/g,"_")}`} `,Bt=P.slice(0,ct)+Nt+P.slice(pe),Lt=ct+Nt.length;C(Bt),I(!1),O(""),j(0),Y(-1),window.requestAnimationFrame(()=>{He.current&&(He.current.focus(),He.current.setSelectionRange(Lt,Lt))})},[Q,P]),yt=a.useCallback(ze=>{const at=ze.target.value,q=ze.target.selectionStart??at.length;te.current=q,C(at),We(at,q),G.detectMention(at,q),L(G.mentionActive),G.mentionActive&&E(ze.target)},[We,G,E]),Ct=a.useCallback(()=>{F.current!==null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{I(!1),O(""),Y(-1),L(!1),G.dismissMention(),F.current=null},120)},[G]),Tt=a.useCallback(()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),Et=a.useCallback(ze=>{const at=ze.currentTarget,q=at.selectionStart??at.value.length;te.current=q,We(at.value,q),G.detectMention(at.value,q),L(G.mentionActive),G.mentionActive&&E(at)},[We,G,E]),Mt=a.useCallback(ze=>{ze.key!=="Escape"&&Et(ze)},[Et]),vt=a.useCallback(ze=>{const at=/@([\w-]+)/g,q=[];let $=0,pe=at.exec(ze);for(;pe;){const[ct,bt=""]=pe,Nt=pe.index;Nt>$&&q.push(ze.slice($,Nt));const Bt=bt.replace(/_/g," ").toLowerCase(),Lt=qe.get(Bt);Lt?q.push(e.jsxs("span",{className:"chat-mention-chip",children:["@",Lt.name.replace(/\s+/g,"_")]},`${Lt.id}-${Nt}`)):q.push(ct),$=Nt+ct.length,pe=at.exec(ze)}return $<ze.length&&q.push(ze.slice($)),q.length===0?ze:q},[qe]),Ft=a.useCallback(ze=>{if(te.current=ze.currentTarget.selectionStart??te.current,G.mentionActive&&G.files.length>0){if(G.handleKeyDown(ze,P),ze.key==="Enter"||ze.key==="Tab"){const at=G.files[G.selectedIndex];if(at){const q=G.selectFile(at,P);C(q),G.dismissMention(),L(!1)}}return}if(Z&&ze.key==="ArrowDown"){ze.preventDefault(),Ce.length>0&&j(at=>(at+1)%Ce.length);return}if(Z&&ze.key==="ArrowUp"){ze.preventDefault(),Ce.length>0&&j(at=>at===0?Ce.length-1:at-1);return}if(Z&&ze.key==="Enter"){ze.preventDefault();const at=Ce[_]??Ce[0];at&&xt(at);return}if(Z&&ze.key==="Escape"){ze.preventDefault(),ze.stopPropagation(),I(!1),O(""),Y(-1);return}ze.key!=="Enter"||ze.shiftKey||(ze.preventDefault(),Ae())},[Z,Ce,_,xt,Ae,G,P]),Je=a.useCallback(()=>{if(J.current){J.current=!1;return}f(ze=>!ze)},[f]),pt=fe.y+60;return e.jsxs(e.Fragment,{children:[s&&e.jsx("button",{ref:Te,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":V?"true":"false",style:{right:fe.x,bottom:fe.y},onPointerDown:K,onPointerMove:de,onPointerUp:we,onClick:Je,children:e.jsx(Zs,{size:24})}),p&&e.jsxs("div",{className:"quick-chat-panel",ref:le,"data-testid":"quick-chat-panel",style:{right:fe.x,bottom:pt},children:[e.jsxs("div",{className:"quick-chat-panel-header",children:[e.jsxs("div",{style:HT,children:[e.jsx("h3",{children:"Quick Chat"}),he&&e.jsx("span",{style:UT,"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:je,disabled:!be||Ee,children:"New chat"}),e.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:e.jsx(Dt,{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"),v("")},children:"Model"})]}),b==="agent"&&c.length>0&&e.jsxs("div",{className:"quick-chat-panel-agent-select",children:[e.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),e.jsx("select",{id:"quick-chat-agent-select",value:y,onChange:ze=>Me(ze.target.value),"data-testid":"quick-chat-agent-select",children:c.map(ze=>e.jsx("option",{value:ze.id,children:qT(ze)},ze.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(Gt,{id:"quick-chat-model-override",models:M,value:S,onChange:Ze,label:"Select model override",placeholder:A?"Loading models…":"Select a model",disabled:A||M.length===0,favoriteProviders:l,favoriteModels:o,onToggleFavorite:d,onToggleModelFavorite:m})]}),e.jsx("div",{className:"quick-chat-panel-messages",ref:ye,"data-testid":"quick-chat-messages",children:Ee||_e?e.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Se.length===0&&!Oe&&!Ie&&!Pe?e.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):e.jsxs(e.Fragment,{children:[Se.map(ze=>{const at=ze.role==="user";return e.jsxs("div",{className:`quick-chat-panel-message ${at?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${ze.id}`,children:[e.jsx("p",{children:vt(ze.content)}),jm(ze.toolCalls,!0)]},ze.id)}),Pe&&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:Ie?"Thinking…":"Connecting…"}),jm(rt,!0),Ie&&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:Ie})]})]})]})}),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:P,onChange:yt,onKeyDown:Ft,onKeyUp:Mt,onClick:Et,onBlur:Ct,onFocus:Tt,placeholder:ce,disabled:Ue,"data-testid":"quick-chat-input"}),e.jsx($T,{agents:c,filter:R,highlightedIndex:_,visible:Z,onSelect:xt,position:"above"}),e.jsx(zT,{visible:G.mentionActive&&!Z,position:D,files:G.files,selectedIndex:G.selectedIndex,onSelect:ze=>{const at=G.selectFile(ze,P);C(at),G.dismissMention(),L(!1),He.current?.focus()},loading:G.loading}),De&&e.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[e.jsx("span",{children:`Queued: ${Ve}`}),e.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Xe,children:"×"})]})]}),Pe?e.jsx("button",{type:"button",className:"chat-input-stop",onClick:et,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:e.jsx(os,{size:14})}):e.jsx("button",{type:"button",onClick:()=>void Ae(),disabled:Ue||P.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 wm(t){return t.status==="generating"||t.status==="awaiting_input"}function XT(t){const[n,s]=a.useState([]),i=a.useRef(new Map),{sessions:r,broadcastUpdate:l,broadcastCompleted:o,requestSync:d}=ra(),m=a.useCallback(()=>{hh(t).then(g=>{const p=new Map;for(const f of g)p.set(f.id,yr(f.updatedAt));i.current=p,s(g)}).catch(g=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",g)})},[t]);a.useEffect(()=>{d(),m()},[m,d]),a.useEffect(()=>{s(g=>{if(r.size===0)return g;let p=!1;const f=new Map(g.map(b=>[b.id,b]));for(const b of r.values()){if(t&&b.projectId&&b.projectId!==t)continue;const x=b.lastEventTimestamp,y=i.current.get(b.sessionId)??0;if(x<y)continue;const v=f.get(b.sessionId),M=b.type??v?.type,N=b.title??v?.title;if(!v&&(!M||!N))continue;const A={id:b.sessionId,type:M??"planning",status:b.status,title:N??"AI Session",projectId:b.projectId??v?.projectId??t??null,lockedByTab:b.owningTabId??v?.lockedByTab??null,updatedAt:b.updatedAt??v?.updatedAt??new Date(x).toISOString()},w=f.get(b.sessionId);(!w||w.status!==A.status||w.title!==A.title||w.type!==A.type||w.projectId!==A.projectId||w.lockedByTab!==A.lockedByTab||w.updatedAt!==A.updatedAt)&&(f.set(b.sessionId,A),i.current.set(b.sessionId,x),p=!0)}return p?[...f.values()].sort((b,x)=>yr(x.updatedAt)-yr(b.updatedAt)):g})},[t,r]),a.useEffect(()=>{const g=t?`?projectId=${encodeURIComponent(t)}`:"",p=b=>{try{const x=JSON.parse(b.data),y=yr(x.updatedAt)||Date.now();s(v=>{const M=i.current.get(x.id)??0;if(y<M)return v;if(i.current.set(x.id,y),x.status==="complete"||x.status==="error")return v.filter(A=>A.id!==x.id);const N=v.findIndex(A=>A.id===x.id);if(N>=0){const A=[...v];return A[N]=x,A}return wm(x)?[x,...v]:v}),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:y}),(x.status==="complete"||x.status==="error")&&o({sessionId:x.id,status:x.status,timestamp:y})}catch{}},f=b=>{try{const x=JSON.parse(b.data);s(y=>y.filter(v=>v.id!==x)),i.current.delete(x)}catch{}};return Os(`/api/events${g}`,{events:{"ai_session:updated":p,"ai_session:deleted":f}})},[o,l,t]);const c=a.useCallback(async g=>{const f=n.find(v=>v.id===g)?.type,b=Si();let x=!1,y=!1;if(f==="planning")try{await ih(g,t,b)}catch(v){x=!0,v instanceof Error&&v.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${g}: locked by another tab`))}else if(f==="subtask")try{await lh(g,t,b)}catch(v){x=!0,v instanceof Error&&v.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${g}: locked by another tab`))}else if(f==="mission_interview")try{await mh(g,t,b)}catch(v){x=!0,v instanceof Error&&v.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${g}: locked by another tab`))}x&&!y&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${g}, attempting delete anyway`);try{await Mk(g)}catch{}s(v=>v.filter(M=>M.id!==g)),i.current.delete(g)},[t,n]),u=a.useMemo(()=>n.filter(g=>wm(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 Nm(t,n){return!t&&!n?0:t?n?t.localeCompare(n):1:-1}function ZT(t){const n=t?.projectId,s=t?.searchQuery,i=t?.sseEnabled??!0,[r,l]=a.useState([]),[o,d]=a.useState(!1),m=a.useRef(o);m.current=o;const c=a.useRef(r),u=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),b=a.useRef(0),x=a.useRef(n);c.current=r,g.current=s,x.current!==n&&(x.current=n,b.current++);const y=1e3,v=a.useCallback(async I=>{const _=++u.current,j=n,Q=I?.searchQueryOverride??s,Y=I?.includeArchivedOverride??m.current;try{const L=await dx(void 0,void 0,j,Q,Y);if(u.current!==_||n!==j)return;l(L.map(Kn)),f.current=Date.now()}catch{if(u.current!==_||n!==j)return;if(I?.clearOnError){l([]);return}l(L=>L)}},[n,s]);p.current=v;const M=a.useCallback(async()=>{m.current||(d(!0),m.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const I=setTimeout(()=>{v({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{v({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const _=Date.now();_-h.current<y||(h.current=_,v())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[v]),a.useEffect(()=>{if(i===!1)return;const I=b.current,_=n?`?projectId=${encodeURIComponent(n)}`:"",j=()=>b.current!==I;let Q=!0;const Y=J=>{if(j())return;const ue=Kn(JSON.parse(J.data));if(g.current){p.current({searchQueryOverride:g.current});return}l(z=>z.some(te=>te.id===ue.id)?z:[...z,ue])},L=J=>{if(j())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ue,to:z}=JSON.parse(J.data),te=Kn(ue);l(F=>F.map(fe=>fe.id===te.id?{...te,column:z}:fe)),f.current=Date.now()},D=J=>{if(j())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ue=Kn(JSON.parse(J.data));l(z=>z.map(te=>{if(te.id!==ue.id||Nm(ue.updatedAt,te.updatedAt)<0)return te;if(te.column===ue.column)return ue;const fe=Nm(te.columnMovedAt,ue.columnMovedAt);return te.columnMovedAt&&!ue.columnMovedAt?{...ue,column:te.column,columnMovedAt:te.columnMovedAt}:fe>0?{...ue,column:te.column,columnMovedAt:te.columnMovedAt}:ue})),f.current=Date.now()},U=J=>{if(j())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ue=Kn(JSON.parse(J.data));l(z=>z.filter(te=>te.id!==ue.id))},G=J=>{if(j())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ue}=JSON.parse(J.data),z=Kn(ue);l(te=>te.map(F=>F.id===z.id?{...z,column:"done"}:F))},E=Os(`/api/events${_}`,{events:{"task:created":Y,"task:moved":L,"task:updated":D,"task:deleted":U,"task:merged":G},onReconnect:()=>{Q&&(j()||p.current())}});return()=>{Q=!1,E()}},[n,i]);const N=a.useCallback(async I=>{const _=Kn(await Qm(I,n));return l(j=>j.some(Q=>Q.id===_.id)?j:[...j,_]),_},[n]),A=a.useCallback(async(I,_)=>Kn(await mx(I,_,n)),[n]),w=a.useCallback(async I=>Kn(await hx(I,n)),[n]),S=a.useCallback(async I=>px(I,n),[n]),k=a.useCallback(async I=>Kn(await fx(I,n)),[n]),P=a.useCallback(async I=>{const _=Kn(await gx(I,n));return l(j=>j.some(Q=>Q.id===_.id)?j:[...j,_]),_},[n]),C=a.useCallback(async(I,_)=>{const j=c.current.find(Y=>Y.id===I),Q=j?{...j,..._,updatedAt:new Date().toISOString()}:void 0;Q&&l(Y=>Y.map(L=>L.id===I?Q:L));try{const Y=Kn(await Ws(I,_,n));return l(L=>L.map(D=>D.id===I?Y:D)),Y}catch(Y){throw j&&l(L=>L.map(D=>D.id===I?j:D)),Y}},[n]),R=a.useCallback(async I=>{const _=Kn(await vx(I,n));return l(j=>j.map(Q=>Q.id===I?_:Q)),_},[n]),O=a.useCallback(async I=>{const _=Kn(await yx(I,n));return l(j=>j.map(Q=>Q.id===I?_:Q)),_},[n]),Z=a.useCallback(async()=>{const _=(await kx(n)).map(Kn);return l(j=>j.map(Q=>_.find(L=>L.id===Q.id)||Q)),_},[n]);return{tasks:r,createTask:N,moveTask:A,deleteTask:w,mergeTask:S,retryTask:k,duplicateTask:P,updateTask:C,archiveTask:R,unarchiveTask:O,archiveAllDone:Z,loadArchivedTasks:M,includeArchived:o,lastFetchTimeMs:f.current}}const eR=5e3,tR=1e3;function nR(){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 nd();n(g)}catch(g){l(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const b=performance.now();try{const x=await nd(),v=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${x.length} projects)`;console.log(`[useProjects] ${v}`),Ma("[useProjects]",v),g||(n(x),l(null))}catch(x){const v=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${x instanceof Error?x.message:String(x)}`;console.warn(`[useProjects] ${v}`),Ma("[useProjects]",v),g||l(x instanceof Error?x.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-d.current<tR||(d.current=b,m())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[m]),a.useEffect(()=>{if(!s)return o.current=setInterval(()=>{m()},eR),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async g=>{const p=await Ny(g);return n(f=>[...f,p]),p},[]),u=a.useCallback(async(g,p)=>{const f=await Py(g,p);return n(b=>b.map(x=>x.id===g?f:x)),f},[]),h=a.useCallback(async g=>{await ch(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:t,loading:s,error:r,refresh:m,register:c,update:u,unregister:h}}const sR="kb-dashboard-current-project";function iR(t){return t??"local"}function aR(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=iR(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ia();if(p)return;c.current=b.dashboardCurrentProjectIdByNode??{};const x=c.current[u];if(x){const y=t.find(v=>v.id===x);y&&(r(y),d.current=!0)}if(!x)try{const y=localStorage.getItem(sR);if(y){const v=JSON.parse(y);v?.id&&t.some(N=>N.id===v.id)&&(r(v),d.current=!0,c.current={...c.current,[u]:v.id},await Kt({dashboardCurrentProjectIdByNode:c.current}).catch(()=>{}))}}catch{}}catch{}finally{p||o(!1)}}return f(),()=>{p=!0}},[u,t]),a.useEffect(()=>{if(!l){if(i){if(!t.some(b=>b.id===i.id)&&t.length>0){const b=t.find(x=>x.status==="active");r(b||t[0]||null);return}const f={...c.current,[u]:i.id};c.current=f,Kt({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(t.length>0&&!m.current){const p=t.find(f=>f.status==="active");p&&r(p)}}},[i,t,l,u]);const h=a.useCallback(p=>{if(m.current=!1,r(p),p){const f={...c.current,[u]:p.id};c.current=f,Kt({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[u]),g=a.useCallback(()=>{m.current=!0,r(null);const p={...c.current};delete p[u],c.current=p,Kt({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[u]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:l}}const nf=a.createContext(null);function rR({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(nf.Provider,{value:{toasts:n,addToast:o,removeToast:l}},t)}function lR(){const t=a.useContext(nf);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const sf="kb-dashboard-theme-mode",af="kb-dashboard-color-theme",rf=[...sj],Lo="theme-data",ao="theme-data.css";function oR(){const t=document.baseURI||(typeof document.location<"u"?document.location.href:"");return t?t.endsWith("/")?t.slice(0,-1)+`/${ao}`:t.replace(/\/[^/]+$/,`/${ao}`):`/${ao}`}const js=typeof window<"u",cR=js?a.useLayoutEffect:a.useEffect;function lf(t){return t==="dark"||t==="light"||t==="system"}function Sm(){if(!js)return"dark";try{const t=localStorage.getItem(sf);if(lf(t))return t}catch{}return"dark"}function Cm(){if(!js)return"default";try{const t=localStorage.getItem(af);if(t&&rf.includes(t))return t}catch{}return"default"}function Em(t){if(js)try{localStorage.setItem(sf,t)}catch{}}function Mm(t){if(js)try{localStorage.setItem(af,t)}catch{}}function dR(t,n){return t==="system"?n?"dark":"light":t}function uR(t,n,s){if(!js)return;const i=dR(t,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Am(){if(!js)return;const t=oR(),n=document.getElementById(Lo);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=Lo,document.head.appendChild(s)}function Pm(){if(!js)return;const t=document.getElementById(Lo);t&&t.remove()}function mR(){const[t,n]=a.useState(()=>Sm()),[s,i]=a.useState(()=>Cm()),[r,l]=a.useState(!0),[o,d]=a.useState(()=>js?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(!js||!r)return;let f=!1;return ia().then(b=>{f||(lf(b.themeMode)&&!u.current&&(m.current!==b.themeMode&&(m.current=b.themeMode,n(b.themeMode)),Sm()!==b.themeMode&&Em(b.themeMode)),b.colorTheme&&rf.includes(b.colorTheme)&&!h.current&&(c.current!==b.colorTheme&&(c.current=b.colorTheme,i(b.colorTheme)),Cm()!==b.colorTheme&&Mm(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{f||l(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!js)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=x=>{d(x.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),cR(()=>{uR(t,s,o)},[t,s,o]),a.useEffect(()=>{!js||r||(s!=="default"?Am():Pm())},[s,r]);const g=a.useCallback(f=>{u.current=!0,m.current=f,n(f),Em(f),Kt({themeMode:f}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(f=>{h.current=!0,c.current=f,i(f),Mm(f),f!=="default"?Am():Pm(),Kt({colorTheme:f}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:t,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:o}}function hR(t){const{planningSessions:n}=t,[s,i]=a.useState(!1),[r,l]=a.useState(!1),[o,d]=a.useState(null),[m,c]=a.useState(void 0),[u,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(void 0),[x,y]=a.useState(null),[v,M]=a.useState("definition"),[N,A]=a.useState(!1),[w,S]=a.useState(void 0),[k,P]=a.useState(!1),[C,R]=a.useState(!1),[O,Z]=a.useState(!1),[I,_]=a.useState(!1),[j,Q]=a.useState(void 0),[Y,L]=a.useState(!1),[D,U]=a.useState("project"),[G,E]=a.useState(!1),[J,ue]=a.useState(!1),[z,te]=a.useState(!1),[F,fe]=a.useState(!1),[V,K]=a.useState(!1),[de,we]=a.useState(!1),[ve,Se]=a.useState(!1),Pe=!!(x||N||s||r||u||I||Y||G||J||z||V||F||O||k||C||de||ve),Oe=a.useCallback(()=>i(!0),[]),Ie=a.useCallback(()=>i(!1),[]),rt=a.useCallback(()=>l(!0),[]),Ee=a.useCallback($=>{d($),l(!0)},[]),_e=a.useCallback(()=>{const $=n[0];$&&(c($.id),l(!0))},[n]),Be=a.useCallback($=>{c($),l(!0)},[]),et=a.useCallback(()=>{l(!1),d(null),c(void 0)},[]),De=a.useCallback($=>{p($),h(!0)},[]),Xe=a.useCallback($=>{b($),h(!0)},[]),re=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),ne=a.useCallback(($,pe="definition")=>{y($),M(pe)},[]),ge=a.useCallback($=>{y($),M("changes")},[]),le=a.useCallback($=>{y(pe=>pe&&{...pe,...$})},[]),Te=a.useCallback(()=>{y(null)},[]),ye=a.useCallback($=>{S($),A(!0)},[]),He=a.useCallback(()=>{A(!1),S(void 0)},[]),nt=a.useCallback(()=>P(!0),[]),mt=a.useCallback(()=>P(!1),[]),he=a.useCallback(()=>R(!0),[]),ie=a.useCallback(()=>R(!1),[]),be=a.useCallback(()=>Z(!0),[]),Me=a.useCallback(()=>Z(!1),[]),Ze=a.useCallback(()=>{_($=>!$)},[]),je=a.useCallback(()=>{_(!1),Q(void 0)},[]),tt=a.useCallback(()=>L(!0),[]),Ce=a.useCallback(()=>L(!1),[]),qe=a.useCallback($=>{U($)},[]),ce=a.useCallback(()=>E(!0),[]),Ue=a.useCallback(()=>E(!1),[]),Ve=a.useCallback(()=>ue(!0),[]),Ae=a.useCallback(()=>ue(!1),[]),We=a.useCallback(()=>te(!0),[]),xt=a.useCallback(()=>te(!1),[]),yt=a.useCallback(()=>fe(!0),[]),Ct=a.useCallback(()=>fe(!1),[]),Tt=a.useCallback(()=>K(!0),[]),Et=a.useCallback(()=>K(!1),[]),Mt=a.useCallback(async($,pe)=>{K(!1),Q(pe),_(!0)},[]),vt=a.useCallback(()=>we(!0),[]),Ft=a.useCallback(()=>we(!1),[]),Je=a.useCallback(()=>Se(!0),[]),pt=a.useCallback(()=>Se(!1),[]),ze=a.useCallback(($,pe)=>{pe(`Created ${$.id} from planning mode`,"success"),l(!1),d(null)},[]),at=a.useCallback(($,pe)=>{const ct=$.map(bt=>bt.id).join(", ");pe(`Created ${ct} from planning mode`,"success"),l(!1),d(null)},[]),q=a.useCallback(($,pe)=>{const ct=$.map(bt=>bt.id).join(", ");pe(`Created ${ct} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:o,planningResumeSessionId:m,isSubtaskOpen:u,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:x,detailTaskInitialTab:v,settingsOpen:N,settingsInitialSection:w,schedulesOpen:k,githubImportOpen:C,usageOpen:O,terminalOpen:I,terminalInitialCommand:j,filesOpen:Y,fileBrowserWorkspace:D,activityLogOpen:G,gitManagerOpen:J,workflowStepsOpen:z,agentsOpen:F,scriptsOpen:V,setupWizardOpen:de,modelOnboardingOpen:ve,anyModalOpen:Pe,openNewTask:Oe,closeNewTask:Ie,openPlanning:rt,openPlanningWithInitialPlan:Ee,resumePlanning:_e,openPlanningWithSession:Be,closePlanning:et,openSubtaskBreakdown:De,openSubtaskWithSession:Xe,closeSubtask:re,openDetailTask:ne,openDetailWithChangesTab:ge,updateDetailTask:le,closeDetailTask:Te,openSettings:ye,closeSettings:He,openSchedules:nt,closeSchedules:mt,openGitHubImport:he,closeGitHubImport:ie,openUsage:be,closeUsage:Me,toggleTerminal:Ze,closeTerminal:je,openFiles:tt,closeFiles:Ce,setFileWorkspace:qe,openActivityLog:ce,closeActivityLog:Ue,openGitManager:Ve,closeGitManager:Ae,openWorkflowSteps:We,closeWorkflowSteps:xt,openAgents:yt,closeAgents:Ct,openScripts:Tt,closeScripts:Et,runScript:Mt,openSetupWizard:vt,closeSetupWizard:Ft,openModelOnboarding:Je,closeModelOnboarding:pt,onPlanningTaskCreated:ze,onPlanningTasksCreated:at,onSubtaskTasksCreated:q}}function pR(t){const[n,s]=a.useState(2),[i,r]=a.useState("."),[l,o]=a.useState(!0),[d,m]=a.useState(!1),[c,u]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[b,x]=a.useState(!1),[y,v]=a.useState({}),[M,N]=a.useState(!1),[A,w]=a.useState(!1),[S,k]=a.useState(!1),[P,C]=a.useState(!1),R=a.useCallback(async()=>{const[j,Q]=await Promise.allSettled([Nx(t),Ki(t)]);if(j.status==="fulfilled"&&(s(j.value.maxConcurrent),r(j.value.rootDir)),Q.status==="fulfilled"){const Y=Q.value;o(!!Y.autoMerge),m(!!Y.globalPause),u(!!Y.enginePaused),x(!!Y.prAuthAvailable),g(Y.taskStuckTimeoutMs),f(Y.showQuickChatFAB===!0),v(Y.experimentalFeatures??{});const L=Y.experimentalFeatures??{};N(L.insights===!0),w(L.roadmap===!0),k(L.memoryView===!0),C(L.devServerView===!0)}},[t]);a.useEffect(()=>{R()},[R]);const O=a.useCallback(async()=>{const j=!l;o(j);try{await Ca({autoMerge:j},t)}catch{o(!j)}},[l,t]),Z=a.useCallback(async()=>{const j=!d;m(j);try{await Ca({globalPause:j,globalPauseReason:j?"manual":void 0},t)}catch{m(!j)}},[d,t]),I=a.useCallback(async()=>{const j=!c;u(j);try{await Ca({enginePaused:j},t)}catch{u(!j)}},[c,t]),_=a.useCallback(async()=>{const j=!p;f(j);try{await Ca({showQuickChatFAB:j},t)}catch{f(!j)}},[p,t]);return{maxConcurrent:n,rootDir:i,autoMerge:l,globalPaused:d,enginePaused:c,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:y,insightsEnabled:M,roadmapEnabled:A,memoryEnabled:S,devServerEnabled:P,toggleAutoMerge:O,toggleGlobalPause:Z,toggleEnginePause:I,toggleShowQuickChatFAB:_,refresh:R}}function fR(t){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:l,addToast:o,openTaskDetail:d,closeTaskDetail:m}=t,c=a.useRef(!1),u=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const x=s.find(y=>y.id===p);if(!x){o(`Project '${p}' not found`,"error");return}r?.id!==x.id&&l(x)}if(c.current)return;c.current=!0,Mr(f,p??n).then(x=>{d(x),u.current=f}).catch(()=>{o(`Task ${f} not found`,"error")})},[n,s,i,r,l,o,d]),{handleDetailClose:a.useCallback(()=>{if(u.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),u.current=null}m()},[m])}}function gR(){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 Kt({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 Kt({favoriteProviders:s,favoriteModels:h})}catch(g){throw l(c),g}},[r,s]);return{availableModels:t,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:o,toggleFavoriteModel:d}}function bR({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 ia().then(c=>{const u=!!(c.defaultProvider&&c.defaultModelId);(c.modelOnboardingComplete===!1||c.modelOnboardingComplete===void 0)&&(!d||!u)&&!na()?r=!0:!d&&!na()&&(l=!0)})}).then(()=>{r?(ys("onboarding:auto-triggered",{trigger:"first-run"}),n()):l&&(ys("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[t,n,s])}const xR=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function Tm(t){return t!==null&&xR.includes(t)}function vR(t){return t==="devserver"?"dev-server":t}function yR(t){const{projectsLoading:n,currentProjectLoading:s,currentProject:i,projectsLength:r,setupWizardOpen:l,openSetupWizard:o,themeMode:d,setThemeMode:m}=t,[c,u]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[h,g]=a.useState(()=>{const x=In("kb-dashboard-task-view");return Tm(x)?x:"board"}),p=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",c)},[c]),a.useEffect(()=>{const x=In("kb-dashboard-task-view",i?.id);if(Tm(x)){const y=!p.current&&x==="devserver";g(y?"devserver":vR(x))}else g("board");i?.id&&(p.current=!0)},[i?.id]),a.useEffect(()=>{us("kb-dashboard-task-view",h,i?.id)},[i?.id,h]),a.useEffect(()=>{n||s||i&&c==="overview"&&u("project")},[n,s,i,c]),a.useEffect(()=>{if(n||s||l||r>0||i)return;const x=window.setTimeout(()=>{o()},500);return()=>window.clearTimeout(x)},[n,r,s,i,l,o]);const f=a.useCallback(x=>{g(x)},[]),b=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(d),v=x[(y+1)%x.length];m(v)},[d,m]);return{viewMode:c,setViewMode:u,taskView:h,setTaskView:g,handleChangeTaskView:f,handleToggleTheme:b}}function kR(t){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:l,toggleFavoriteProvider:o,toggleFavoriteModel:d,addToast:m,openSettings:c,openSetupWizard:u,closeSetupWizard:h,closeModelOnboarding:g}=t,p=a.useCallback(k=>{n(k),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{c()},[c]),x=a.useCallback(()=>{u()},[u]),y=a.useCallback(k=>{h(),n(k),i("project"),m(`Project ${k.name} registered successfully`,"success"),l()},[h,n,i,m,l]),v=a.useCallback(()=>{g()},[g]),M=a.useCallback(async k=>{try{await Cy(k.id),m(`Project ${k.name} paused`,"success"),await l()}catch{m(`Failed to pause project ${k.name}`,"error")}},[m,l]),N=a.useCallback(async k=>{try{await Ey(k.id),m(`Project ${k.name} resumed`,"success"),await l()}catch{m(`Failed to resume project ${k.name}`,"error")}},[m,l]),A=a.useCallback(async k=>{try{await ch(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]),S=a.useCallback(async k=>{try{await d(k)}catch{m("Failed to update model favorites","error")}},[d,m]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:x,handleSetupComplete:y,handleModelOnboardingComplete:v,handlePauseProject:M,handleResumeProject:N,handleRemoveProject:A,handleToggleFavorite:w,handleToggleModelFavorite:S}}function jR(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 wR(t){return Gr("/health",{nodeId:t})}async function NR(t){return Gr("/projects",{nodeId:t})}async function SR(t,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Gr(`/tasks?${i.toString()}`,{nodeId:t})}async function CR(t,n){return Gr(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:t})}async function RI(t){return B(`/nodes/${encodeURIComponent(t)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function _I(t){return B(`/nodes/${encodeURIComponent(t)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function II(t){return B(`/nodes/${encodeURIComponent(t)}/settings/sync-status`)}async function $I(t){return B(`/nodes/${encodeURIComponent(t)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function ER(t,n){const{projectId:s,searchQuery:i}=n??{},[r,l]=a.useState([]),[o,d]=a.useState([]),[m,c]=a.useState(null),[u,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),b=a.useCallback(async()=>{if(!t){l([]),d([]),c(null),h(!1),p(null);return}f.current?.abort();const y=new AbortController;f.current=y,h(!0),p(null);try{const v=[wR(t),NR(t)];s&&(v.push(SR(t,s,i)),v.push(CR(t,s)));const M=await Promise.allSettled(v);if(y.signal.aborted)return;const N=M[0],A=M[1];if(N.status==="rejected"){p(`Failed to fetch node health: ${N.reason}`),h(!1);return}if(c(N.value),A.status==="rejected"){p(`Failed to fetch projects: ${A.reason}`),h(!1);return}if(l(A.value),s&&M[2]){const w=M[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&d(w.value)}h(!1)}catch(v){y.signal.aborted||(p(v instanceof Error?v.message:"Unknown error"),h(!1))}},[t,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const x=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:o,health:m,loading:u,error:g,refresh:x}}function MR(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 AR="fusion-dashboard-current-node",of=a.createContext(null);function PR({children:t}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),l=a.useRef(!1),o=a.useRef(void 0);a.useEffect(()=>{let u=!1;async function h(){try{const g=await ia();if(u)return;o.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(l.current=!0),!p)try{const f=localStorage.getItem(AR);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(o.current=b.id,await Kt({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,Kt({dashboardCurrentNodeId:u}).catch(()=>{}))}else n===null&&o.current!==void 0&&(o.current=void 0,Kt({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const d=a.useCallback(u=>{s(u)},[]),m=a.useCallback(()=>{s(null),o.current=void 0,Kt({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),c={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:d,clearCurrentNode:m};return e.jsx(of.Provider,{value:c,children:t})}function TR(){const t=a.useContext(of);if(t===null)throw new Error("useNodeContext must be used within a NodeProvider");return t}const RR=a.lazy(()=>en(()=>import("./AgentsView-pO7WiBS5.js").then(t=>t.A),__vite__mapDeps([13,1,14,3,15])).then(t=>({default:t.AgentsView}))),_R=a.lazy(()=>en(()=>import("./DocumentsView-CS8aiwtz.js"),__vite__mapDeps([16,1,4,5,17])).then(t=>({default:t.DocumentsView}))),IR=a.lazy(()=>en(()=>import("./InsightsView-Bu9Cv8Ol.js"),__vite__mapDeps([18,1,4,5,19])).then(t=>({default:t.InsightsView}))),$R=a.lazy(()=>en(()=>import("./NodesView-BInPcedy.js"),__vite__mapDeps([20,1,14,4,5,21])).then(t=>({default:t.NodesView}))),DR=a.lazy(()=>en(()=>import("./ChatView-BOd-sxbT.js"),__vite__mapDeps([22,1,4,5])).then(t=>({default:t.ChatView}))),FR=a.lazy(()=>en(()=>import("./RoadmapsView-BbCexaoi.js"),__vite__mapDeps([23,1,4,5,24])).then(t=>({default:t.RoadmapsView}))),LR=a.lazy(()=>en(()=>import("./SkillsView-D3iqYCVf.js"),__vite__mapDeps([25,1,4,5,26])).then(t=>({default:t.SkillsView}))),zR=a.lazy(()=>en(()=>import("./MemoryView-CtqgDtV9.js"),__vite__mapDeps([27,1,4,5,28])).then(t=>({default:t.MemoryView}))),OR=a.lazy(()=>en(()=>import("./DevServerView-09GQf34f.js"),__vite__mapDeps([29,1,4,5,30])).then(t=>({default:t.DevServerView})));function BR(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{en(()=>import("./AgentsView-pO7WiBS5.js").then(n=>n.A),__vite__mapDeps([13,1,14,3,15])),en(()=>import("./DocumentsView-CS8aiwtz.js"),__vite__mapDeps([16,1,4,5,17])),en(()=>import("./InsightsView-Bu9Cv8Ol.js"),__vite__mapDeps([18,1,4,5,19])),en(()=>import("./NodesView-BInPcedy.js"),__vite__mapDeps([20,1,14,4,5,21])),en(()=>import("./ChatView-BOd-sxbT.js"),__vite__mapDeps([22,1,4,5])),en(()=>import("./RoadmapsView-BbCexaoi.js"),__vite__mapDeps([23,1,4,5,24])),en(()=>import("./SkillsView-D3iqYCVf.js"),__vite__mapDeps([25,1,4,5,26])),en(()=>import("./MemoryView-CtqgDtV9.js"),__vite__mapDeps([27,1,4,5,28])),en(()=>import("./DevServerView-09GQf34f.js"),__vite__mapDeps([29,1,4,5,30]))})}const ro="kb-setup-warning-dismissed";function UR(){const{toasts:t,addToast:n,removeToast:s}=lR(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{BR()},[]);const{projects:r,loading:l,refresh:o}=nR(),{nodes:d}=tT(),{currentNode:m,currentNodeId:c,isRemote:u,setCurrentNode:h,clearCurrentNode:g}=TR(),{currentProject:p,setCurrentProject:f,clearCurrentProject:b,loading:x}=aR(r,{nodeId:c}),{hasAiProvider:y,hasGithub:v,loading:M,hasWarnings:N}=Gp(p?.id);a.useEffect(()=>{if(c&&!m&&d.length>0){const ee=d.find(me=>me.id===c);if(ee){h(ee);return}}c&&d.length>0&&(d.some(me=>me.id===c)||g())},[c,m,d,h,g]);const[A,w]=a.useState(""),S=ER(c,{projectId:p?.id,searchQuery:A||void 0});MR(c);const k=u&&S.projects.length>0?S.projects:r,{themeMode:P,colorTheme:C,setThemeMode:R,setColorTheme:O}=mR(),{sessions:Z,generating:I,needsInput:_,planningSessions:j,dismissSession:Q}=XT(p?.id),Y=Z.filter(ee=>ee.status==="awaiting_input"||ee.status==="error"),L=hR({projectId:p?.id,planningSessions:j}),{viewMode:D,setViewMode:U,taskView:G,handleChangeTaskView:E}=yR({projectsLoading:l,currentProjectLoading:x,currentProject:p,projectsLength:r.length,setupWizardOpen:L.setupWizardOpen,openSetupWizard:L.openSetupWizard,themeMode:P,setThemeMode:R}),J=a.useCallback(ee=>{ee==="missions"&&(nt(void 0),he(void 0),be(void 0)),E(ee)},[E]),ue=G==="board"||G==="list",{tasks:z,createTask:te,moveTask:F,deleteTask:fe,mergeTask:V,retryTask:K,updateTask:de,duplicateTask:we,archiveTask:ve,unarchiveTask:Se,archiveAllDone:Pe,loadArchivedTasks:Oe,lastFetchTimeMs:Ie}=ZT({...p?{projectId:p.id}:{},searchQuery:A||void 0,sseEnabled:ue}),[rt,Ee]=a.useState(!1),_e=a.useRef(performance.now()),Be=a.useRef(!1),et=a.useRef(!1),De=a.useMemo(()=>l?"projects":x?"project":"tasks",[l,x]);a.useEffect(()=>{if(!l&&!Be.current){Be.current=!0;const ee=`projects loaded at ${Math.round(performance.now()-_e.current)}ms from mount`;console.log(`[App] ${ee}`),Ma("[App]",ee)}if(!x&&!et.current){et.current=!0;const ee=`current-project resolved at ${Math.round(performance.now()-_e.current)}ms from mount`;console.log(`[App] ${ee}`),Ma("[App]",ee)}},[l,x]),a.useEffect(()=>{if(rt||l||x)return;const ee=performance.now(),me=window.setTimeout(()=>{const ke=`dashboard ready at ${Math.round(performance.now()-_e.current)}ms from mount (settle delay=${Math.round(performance.now()-ee)}ms)`;console.log(`[App] ${ke}`),Ma("[App]",ke),Ee(!0)},200);return()=>{window.clearTimeout(me)}},[rt,l,x]);const re=Jr()==="mobile",[ne,ge]=a.useState(0),le=a.useCallback(()=>{ph(p?.id).then(ee=>{ge(ee.unreadCount)}).catch(ee=>{console.warn("[App] Failed to fetch mailbox unread count:",ee)})},[p?.id]);a.useEffect(()=>{le();const ee=new URLSearchParams;p?.id&&ee.set("projectId",p.id);const me=ee.size>0?`?${ee.toString()}`:"";return Os(`/api/events${me}`,{events:{"message:sent":le,"message:received":le,"message:read":le,"message:deleted":le}})},[p?.id,le]);const[Te,ye]=a.useState(!1),[He,nt]=a.useState(void 0),[mt,he]=a.useState(void 0),[ie,be]=a.useState(void 0),[Me,Ze]=a.useState(!1),[je,tt]=a.useState(()=>In(ro,p?.id)==="true");a.useEffect(()=>{tt(In(ro,p?.id)==="true")},[p?.id]);const Ce=a.useCallback(()=>{us(ro,"true",p?.id),tt(!0)},[p?.id]),{maxConcurrent:qe,autoMerge:ce,globalPaused:Ue,enginePaused:Ve,taskStuckTimeoutMs:Ae,showQuickChatFAB:We,prAuthAvailable:xt,experimentalFeatures:yt,insightsEnabled:Ct,roadmapEnabled:Tt,memoryEnabled:Et,devServerEnabled:Mt,toggleAutoMerge:vt,toggleGlobalPause:Ft,toggleEnginePause:Je,refresh:pt}=pR(p?.id),ze=yt.skillsView===!0,at=yt.nodesView===!0,q=!0;a.useEffect(()=>{Object.keys(yt).length!==0&&(G==="insights"&&!Ct&&E("board"),G==="roadmaps"&&!Tt&&E("board"),G==="memory"&&!Et&&E("board"),(G==="devserver"||G==="dev-server")&&!Mt&&E("board"))},[G,Ct,Tt,yt,E,q,Et,Mt]),a.useEffect(()=>{Te&&!at&&ye(!1)},[Te,at]);const{availableModels:$,favoriteProviders:pe,favoriteModels:ct,toggleFavoriteProvider:bt,toggleFavoriteModel:Nt}=gR();bR({projectId:p?.id,openModelOnboarding:L.openModelOnboarding,openSettings:L.openSettings});const{handleSelectProject:Bt,handleViewAllProjects:Lt,handleOpenSettings:wn,handleAddProject:hn,handleSetupComplete:nn,handleModelOnboardingComplete:Pn,handlePauseProject:on,handleResumeProject:Un,handleRemoveProject:gn,handleToggleFavorite:Zt,handleToggleModelFavorite:Wt}=kR({setCurrentProject:f,clearCurrentProject:b,setViewMode:U,currentProject:p,refreshProjects:o,toggleFavoriteProvider:bt,toggleFavoriteModel:Nt,addToast:n,openSettings:L.openSettings,openSetupWizard:L.openSetupWizard,closeSetupWizard:L.closeSetupWizard,closeModelOnboarding:L.closeModelOnboarding}),{handleDetailClose:Tn}=fR({projectId:p?.id,projects:r,projectsLoading:l,currentProject:p,setCurrentProject:f,addToast:n,openTaskDetail:L.openDetailTask,closeTaskDetail:L.closeDetailTask}),{handleBoardQuickCreate:bn,handleModalCreate:sn,handlePlanningTaskCreated:Hn,handlePlanningTasksCreated:xn,handleSubtaskTasksCreated:qt,handleGitHubImport:$n}=jR({createTask:te,onPlanningTaskCreated:L.onPlanningTaskCreated,onPlanningTasksCreated:L.onPlanningTasksCreated,onSubtaskTasksCreated:L.onSubtaskTasksCreated,addToast:n}),qn=a.useCallback((ee,me)=>{if(me==="changes"){L.openDetailWithChangesTab(ee);return}L.openDetailTask(ee,me)},[L]),Nn=a.useCallback(()=>{at&&ye(ee=>!ee)},[at]),Dn=a.useCallback(ee=>{he(ee),nt(void 0),E("missions")},[E]),se=a.useCallback(ee=>{ee.type==="planning"?L.openPlanningWithSession(ee.id):ee.type==="subtask"?L.openSubtaskWithSession(ee.id):ee.type==="mission_interview"?(he(void 0),nt(ee.id),be(void 0),E("missions")):(ee.type==="milestone_interview"||ee.type==="slice_interview")&&(nt(void 0),he(void 0),be(ee.id),E("missions"))},[E,L]),Fe=a.useCallback(()=>{for(const ee of Y)Q(ee.id)},[Q,Y]),st=()=>Te?e.jsx("div",{className:"nodes-management-overlay",children:e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx($R,{addToast:n,onClose:()=>ye(!1)})})})}):D==="overview"?e.jsx(Zn,{children:e.jsx(xw,{projects:r,loading:l,onSelectProject:Bt,onAddProject:hn,onPauseProject:on,onResumeProject:Un,onRemoveProject:gn,nodes:d})}):G==="skills"?ze?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(LR,{addToast:n,projectId:p?.id,onClose:()=>E("board")})})}):(E("board"),null):G==="chat"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(DR,{addToast:n,projectId:p?.id})})}):G==="mailbox"?e.jsx(Zn,{children:e.jsx(uN,{projectId:p?.id,addToast:n,onUnreadCountChange:ge})}):G==="roadmaps"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(FR,{addToast:n,projectId:p?.id})})}):G==="missions"?e.jsx(Zn,{children:e.jsx(rN,{isInline:!0,isOpen:!0,onClose:()=>{he(void 0),nt(void 0),be(void 0),E("board")},addToast:n,projectId:p?.id,onSelectTask:ee=>{const me=z.find(ke=>ke.id===ee);me&&L.openDetailTask(me)},availableTasks:z.map(ee=>({id:ee.id,title:ee.title})),resumeSessionId:He,targetMissionId:mt,milestoneSliceResumeSessionId:ie,onMilestoneSliceResumeFetchError:()=>be(void 0)})}):G==="agents"&&q?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(RR,{addToast:n,projectId:p?.id})})}):G==="documents"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(_R,{projectId:p?.id,addToast:n,onOpenDetail:L.openDetailTask})})}):G==="insights"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(IR,{projectId:p?.id,addToast:n,onClose:()=>E("board")})})}):G==="memory"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(zR,{addToast:n,projectId:p?.id})})}):G==="devserver"||G==="dev-server"?e.jsx(Zn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(OR,{addToast:n,projectId:p?.id})})}):G==="board"?e.jsx(Zn,{children:e.jsx(rw,{tasks:u&&S.tasks.length>0?S.tasks:z,projectId:p?.id,maxConcurrent:qe,onMoveTask:F,onOpenDetail:L.openDetailTask,addToast:n,onQuickCreate:bn,onNewTask:L.openNewTask,onPlanningMode:L.openPlanningWithInitialPlan,onSubtaskBreakdown:L.openSubtaskBreakdown,autoMerge:ce,onToggleAutoMerge:vt,globalPaused:Ue,onUpdateTask:de,onArchiveTask:ve,onUnarchiveTask:Se,onDeleteTask:fe,onArchiveAllDone:Pe,onLoadArchivedTasks:Oe,searchQuery:A,availableModels:$,onOpenDetailWithTab:qn,favoriteProviders:pe,favoriteModels:ct,onToggleFavorite:Zt,onToggleModelFavorite:Wt,taskStuckTimeoutMs:Ae,onOpenMission:Dn,lastFetchTimeMs:Ie})}):e.jsx(Zn,{children:e.jsx(ow,{tasks:u&&S.tasks.length>0?S.tasks:z,projectId:p?.id,onMoveTask:F,onOpenDetail:L.openDetailTask,addToast:n,globalPaused:Ue,onNewTask:L.openNewTask,onQuickCreate:bn,onPlanningMode:L.openPlanningWithInitialPlan,onSubtaskBreakdown:L.openSubtaskBreakdown,availableModels:$,favoriteProviders:pe,favoriteModels:ct,onToggleFavorite:Zt,onToggleModelFavorite:Wt,taskStuckTimeoutMs:Ae,searchQuery:A,lastFetchTimeMs:Ie})});if(!rt)return e.jsxs(e.Fragment,{children:[e.jsx(bT,{stage:De}),e.jsx(Xp,{toasts:t,onRemove:s})]});const T=!L.modelOnboardingOpen&&OP(),W=!L.modelOnboardingOpen&&!T&&na()&&!Yp();return e.jsxs(e.Fragment,{children:[e.jsx(Jk,{isElectron:i,onOpenSettings:wn,onOpenGitHubImport:L.openGitHubImport,onOpenPlanning:L.openPlanning,onResumePlanning:L.resumePlanning,activePlanningSessionCount:j.length,onOpenUsage:L.openUsage,onOpenActivityLog:L.openActivityLog,onOpenMailbox:()=>J("mailbox"),mailboxUnreadCount:ne,onOpenSchedules:L.openSchedules,onOpenGitManager:L.openGitManager,onOpenNodes:Nn,showNodesButton:at,onOpenWorkflowSteps:L.openWorkflowSteps,onOpenScripts:L.openScripts,onRunScript:L.runScript,onToggleTerminal:L.toggleTerminal,onOpenFiles:L.openFiles,filesOpen:L.filesOpen,globalPaused:Ue,enginePaused:Ve,onToggleGlobalPause:Ft,onToggleEnginePause:Je,view:G,onChangeView:D==="project"&&p?J:void 0,showSkillsTab:ze,showAgentsTab:q,searchQuery:A,onSearchChange:w,projects:k,currentProject:p,onSelectProject:Bt,onViewAllProjects:Lt,projectId:p?.id,mobileNavEnabled:re,availableNodes:d,currentNode:m,onSelectNode:ee=>{ee===null?g():h(ee)},isRemote:u,experimentalFeatures:{insights:Ct,roadmap:Tt,memoryView:Et,devServer:Mt,devServerView:Mt}}),D==="project"&&p&&!Te&&G!=="missions"&&!L.isPlanningOpen&&e.jsx(PT,{sessions:Y,onResumeSession:se,onDismissSession:Q,onDismissAll:Fe}),D==="project"&&p&&T&&e.jsx(TT,{onResume:L.openModelOnboarding}),D==="project"&&p&&W&&e.jsx(RT,{onOpenModelOnboarding:L.openModelOnboarding,onOpenSettings:ee=>L.openSettings(ee)}),D==="project"&&p&&!M&&N&&!je&&e.jsx(Jp,{hasAiProvider:y,hasGithub:v,onDismiss:Ce}),e.jsx("div",{className:`project-content${D==="project"&&p?" project-content--with-footer":""}${re?" project-content--with-mobile-nav":""}`,children:st()}),D==="project"&&p&&!Te&&e.jsx(ET,{tasks:u&&S.tasks.length>0?S.tasks:z,projectId:p.id,taskStuckTimeoutMs:Ae,backgroundSessions:Z,backgroundGenerating:I,backgroundNeedsInput:_,onOpenBackgroundSession:se,onDismissBackgroundSession:Q,lastFetchTimeMs:Ie}),e.jsx(IT,{view:G,onChangeView:D==="project"&&p?J:()=>{},footerVisible:D==="project"&&!!p,modalOpen:L.anyModalOpen,onOpenSettings:wn,onOpenActivityLog:L.openActivityLog,onOpenMailbox:()=>J("mailbox"),mailboxUnreadCount:ne,onOpenGitManager:L.openGitManager,onOpenWorkflowSteps:L.openWorkflowSteps,onOpenSchedules:L.openSchedules,onOpenScripts:L.openScripts,onToggleTerminal:L.toggleTerminal,onOpenFiles:L.openFiles,onOpenGitHubImport:L.openGitHubImport,onOpenPlanning:L.openPlanning,onResumePlanning:L.resumePlanning,activePlanningSessionCount:j.length,onOpenUsage:L.openUsage,onViewAllProjects:Lt,onRunScript:L.runScript,projectId:p?.id,showSkillsTab:ze,experimentalFeatures:{insights:Ct,roadmap:Tt,memoryView:Et,devServer:Mt,devServerView:Mt}}),D==="project"&&p&&G!=="chat"&&G!=="mailbox"&&G!=="insights"&&G!=="devserver"&&G!=="dev-server"&&e.jsx(QT,{projectId:p.id,addToast:n,showFAB:We,open:Me,onOpenChange:Ze,favoriteProviders:pe,favoriteModels:ct,onToggleFavorite:Zt,onToggleModelFavorite:Wt}),e.jsx(fT,{projectId:p?.id,tasks:z,projects:r,currentProject:p,addToast:n,toasts:t,removeToast:s,modalManager:L,projectActions:{handleAddProject:hn,handleSetupComplete:nn,handleModelOnboardingComplete:Pn},taskHandlers:{handleModalCreate:sn,handlePlanningTaskCreated:Hn,handlePlanningTasksCreated:xn,handleSubtaskTasksCreated:qt,handleGitHubImport:$n},taskOperations:{moveTask:F,deleteTask:fe,mergeTask:V,retryTask:K,duplicateTask:we},deepLink:{handleDetailClose:Tn},settings:{prAuthAvailable:xt,themeMode:P,colorTheme:C,setThemeMode:R,setColorTheme:O},onSettingsClose:()=>{L.closeSettings(),pt()},onReopenOnboarding:()=>{L.closeSettings(),L.openModelOnboarding()}})]})}function HR(){return e.jsx(rR,{children:e.jsx(PR,{children:e.jsx(UR,{})})})}lx();yf.createRoot(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(Xb,{children:e.jsx(HR,{})})}));"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{o_ as $,ws as A,an as B,tn as C,ln as D,rn as E,xi as F,vi as G,to as H,Ht as I,$s as J,zt as K,lt as L,_P as M,hy as N,CP as O,ss as P,EP as Q,Mn as R,zi as S,Uo as T,py as U,M_ as V,fy as W,Dt as X,l_ as Y,jn as Z,en as _,us as a,X_ as a$,Mr as a0,wv as a1,mg as a2,Oo as a3,sa as a4,ni as a5,si as a6,Ds as a7,CI as a8,AI as a9,Ok as aA,NI as aB,SI as aC,Bk as aD,Uk as aE,BT as aF,Jr as aG,zo as aH,$T as aI,zT as aJ,os as aK,fi as aL,Zs as aM,Jb as aN,z_ as aO,B_ as aP,O_ as aQ,U_ as aR,H_ as aS,q_ as aT,V_ as aU,W_ as aV,K_ as aW,G_ as aX,J_ as aY,Y_ as aZ,Q_ as a_,MI as aa,EI as ab,PI as ac,On as ad,is as ae,Ob as af,Vb as ag,Ls as ah,dg as ai,Br as aj,Hi as ak,II as al,RI as am,_I as an,$I as ao,Cr as ap,Tb as aq,Ia as ar,lg as as,Ln as at,Km as au,tT as av,nR as aw,wI as ax,od as ay,Da as az,F_ as b,a_ as b$,eI as b0,tI as b1,Z_ as b2,En as b3,Bo as b4,qi as b5,kI as b6,yI as b7,jI as b8,jM as b9,Hv as bA,qv as bB,Bv as bC,c_ as bD,Ks as bE,Xs as bF,Vr as bG,Wi as bH,Ny as bI,WR as bJ,KR as bK,uI as bL,jb as bM,ho as bN,bI as bO,xI as bP,pI as bQ,hI as bR,fI as bS,mI as bT,gI as bU,L_ as bV,An as bW,s_ as bX,t_ as bY,n_ as bZ,Dm as b_,Sx as ba,Bc as bb,JR as bc,Cx as bd,Ax as be,Px as bf,ZR as bg,YR as bh,QR as bi,XR as bj,Ex as bk,GR as bl,e_ as bm,Bp as bn,m_ as bo,u_ as bp,x_ as bq,d_ as br,h_ as bs,p_ as bt,f_ as bu,g_ as bv,Vv as bw,b_ as bx,qo as by,Uv as bz,Ge as c,r_ as c0,i_ as c1,nI as c2,iI as c3,lI as c4,aI as c5,sI as c6,rI as c7,oI as c8,oh as c9,Uc as ca,Bg as cb,cI as cc,P_ as cd,S_ as ce,E_ as cf,C_ as cg,__ as ch,R_ as ci,Om as cj,w_ as ck,j_ as cl,SP as cm,A_ as cn,Ba as co,F2 as cp,y_ as cq,v_ as cr,Nv as cs,k_ as ct,N_ as cu,dI as cv,$_ as d,D_ as e,vI as f,In as g,Jn as h,aa as i,Gt as j,my as k,I_ as l,LT as m,Ki as n,Ca as o,xe as p,aj as q,T_ as r,Os as s,uo as t,Kt as u,Fs as v,Vt as w,Sr as x,MP as y,TI as z};