@runfusion/fusion 0.2.5 → 0.2.7

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 (32) hide show
  1. package/dist/bin.js +329 -53
  2. package/dist/client/assets/{AgentDetailView-CkuuGA1O.js → AgentDetailView-B4lRk--v.js} +1 -1
  3. package/dist/client/assets/{AgentsView-CWFLMIDP.js → AgentsView-yCYBY2km.js} +3 -3
  4. package/dist/client/assets/{ChatView-C_T91ebd.js → ChatView-CH9T0dDs.js} +1 -1
  5. package/dist/client/assets/{DevServerView-ChWTzTvy.js → DevServerView-jXXtoQUx.js} +1 -1
  6. package/dist/client/assets/DirectoryPicker-izgMlS27.js +1 -0
  7. package/dist/client/assets/{DocumentsView-Co9to4Zp.css → DocumentsView-DV2DrCZb.css} +1 -1
  8. package/dist/client/assets/{DocumentsView-CjfVl8mZ.js → DocumentsView-DkkoHRwL.js} +1 -1
  9. package/dist/client/assets/{InsightsView-Rb735C9_.js → InsightsView-DaRtUPHX.js} +1 -1
  10. package/dist/client/assets/{MemoryView-LLc_uNtG.js → MemoryView-85NKuU3h.js} +1 -1
  11. package/dist/client/assets/{NodesView-BviqBWRA.js → NodesView-BsUk_oiU.js} +1 -1
  12. package/dist/client/assets/PiExtensionsManager-BF5pxrSE.js +11 -0
  13. package/dist/client/assets/PiExtensionsManager-K7HQ08L4.css +1 -0
  14. package/dist/client/assets/PluginManager-ccq3uK50.css +1 -0
  15. package/dist/client/assets/{PluginManager-BywTPbLB.js → PluginManager-s6btydh5.js} +1 -1
  16. package/dist/client/assets/{RoadmapsView-Dhl--4vY.js → RoadmapsView-SQol126Y.js} +1 -1
  17. package/dist/client/assets/{SetupWizardModal-CVtmwoJC.js → SetupWizardModal-CQc1uGSq.js} +1 -1
  18. package/dist/client/assets/{SkillsView-CG9y4fsE.js → SkillsView-BtUhs_QW.js} +1 -1
  19. package/dist/client/assets/{folder-open-BVDq27HP.js → folder-open-CI4TCD7P.js} +1 -1
  20. package/dist/client/assets/index-Ct-OqLpP.css +1 -0
  21. package/dist/client/assets/index-rNf7s96d.js +649 -0
  22. package/dist/client/assets/{upload-BDvpReDO.js → upload-CAlKC4qI.js} +1 -1
  23. package/dist/client/index.html +2 -2
  24. package/dist/extension.js +75 -8
  25. package/dist/pi-claude-cli/package.json +1 -1
  26. package/package.json +5 -5
  27. package/dist/client/assets/DirectoryPicker-BMJIT7HD.js +0 -1
  28. package/dist/client/assets/PiExtensionsManager-CPgmJgDk.css +0 -1
  29. package/dist/client/assets/PiExtensionsManager-CriZBkQe.js +0 -11
  30. package/dist/client/assets/PluginManager-D64RIzmL.css +0 -1
  31. package/dist/client/assets/index-CikysL-d.js +0 -644
  32. package/dist/client/assets/index-Da1qmtc7.css +0 -1
@@ -0,0 +1,649 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/PluginManager-s6btydh5.js","assets/vendor-react-K0fH_qHe.js","assets/DirectoryPicker-izgMlS27.js","assets/folder-open-CI4TCD7P.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/PluginManager-ccq3uK50.css","assets/PiExtensionsManager-BF5pxrSE.js","assets/PiExtensionsManager-K7HQ08L4.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-CQc1uGSq.js","assets/AgentsView-yCYBY2km.js","assets/upload-CAlKC4qI.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-DkkoHRwL.js","assets/DocumentsView-DV2DrCZb.css","assets/InsightsView-DaRtUPHX.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-BsUk_oiU.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-CH9T0dDs.js","assets/RoadmapsView-SQol126Y.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-BtUhs_QW.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-85NKuU3h.js","assets/MemoryView-DhinauGs.css","assets/DevServerView-jXXtoQUx.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
2
+ import{r as a,j as e,a as _a,g as Vm,R as Wm,c as Mf}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 Km=(...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 Af=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 Pf=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 qc=t=>{const n=Pf(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 Cl={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 If=t=>{for(const n in t)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},_f=a.createContext({}),Rf=()=>a.useContext(_f),Tf=a.forwardRef(({color:t,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:l,iconNode:o,...d},m)=>{const{size:c=24,strokeWidth:u=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=Rf()??{},f=i??h?Number(s??u)*24/Number(n??c):s??u;return a.createElement("svg",{ref:m,...Cl,width:n??c??Cl.width,height:n??c??Cl.height,stroke:t??g,strokeWidth:f,className:Km("lucide",p,r),...!l&&!If(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 Ze=(t,n)=>{const s=a.forwardRef(({className:i,...r},l)=>a.createElement(Tf,{ref:l,iconNode:n,className:Km(`lucide-${Af(qc(t))}`,`lucide-${t}`,i),...r}));return s.displayName=qc(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 $f=[["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"}]],Ss=Ze("activity",$f);/**
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 Ff=[["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"}]],nl=Ze("archive",Ff);/**
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 Df=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Ka=Ze("arrow-down",Df);/**
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 Lf=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],oa=Ze("arrow-left",Lf);/**
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 zf=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ga=Ze("arrow-right",zf);/**
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 Of=[["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"}]],Gm=Ze("arrow-up-down",Of);/**
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 Bf=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ji=Ze("arrow-up",Bf);/**
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 Uf=[["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"}]],Jm=Ze("book-open",Uf);/**
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 Hf=[["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"}]],rn=Ze("bot",Hf);/**
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 qf=[["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"}]],So=Ze("box",qf);/**
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 Vf=[["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"}]],Lr=Ze("brain",Vf);/**
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 Wf=[["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"}]],Ym=Ze("calendar",Wf);/**
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 Kf=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Gf=Ze("check-check",Kf);/**
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 Jf=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],An=Ze("check",Jf);/**
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 Yf=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Ot=Ze("chevron-down",Yf);/**
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 Qf=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],sc=Ze("chevron-left",Qf);/**
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 Xf=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],on=Ze("chevron-right",Xf);/**
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 Zf=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],qs=Ze("chevron-up",Zf);/**
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 eg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],ss=Ze("circle-alert",eg);/**
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 tg=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],sn=Ze("circle-check-big",tg);/**
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 ng=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],sl=Ze("circle-dot",ng);/**
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 sg=[["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"}]],Vc=Ze("circle-question-mark",sg);/**
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 ig=[["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"}]],Ja=Ze("circle-x",ig);/**
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 ag=[["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"}]],rg=Ze("clipboard-list",ag);/**
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 lg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ki=Ze("clock",lg);/**
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 og=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Qm=Ze("code",og);/**
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 cg=[["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"}]],dg=Ze("columns-3",cg);/**
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 ug=[["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"}]],Gi=Ze("copy",ug);/**
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 mg=[["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"}]],hg=Ze("cpu",mg);/**
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 pg=[["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"}]],fg=Ze("download",pg);/**
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 gg=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]],bg=Ze("ellipsis-vertical",gg);/**
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 xg=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],Co=Ze("ellipsis",xg);/**
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 vg=[["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"}]],yg=Ze("external-link",vg);/**
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 jg=[["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"}]],kg=Ze("eye-off",jg);/**
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 wg=[["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"}]],ic=Ze("eye",wg);/**
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 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:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Rs=Ze("file-code",Ng);/**
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 Sg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],Xm=Ze("file-diff",Sg);/**
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 Cg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],Eg=Ze("file-minus",Cg);/**
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 Mg=[["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"}]],Zm=Ze("file-pen",Mg);/**
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 Ag=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],Pg=Ze("file-plus",Ag);/**
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 Ig=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],_g=Ze("file-question-mark",Ig);/**
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 Rg=[["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"}]],wi=Ze("file-text",Rg);/**
248
+ * @license lucide-react v1.7.0 - ISC
249
+ *
250
+ * This source code is licensed under the ISC license.
251
+ * See the LICENSE file in the root directory of this source tree.
252
+ */const Tg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M11 18h2",key:"12mj7e"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M9 13v-.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 .5.5v.5",key:"qbrxap"}]],$g=Ze("file-type",Tg);/**
253
+ * @license lucide-react v1.7.0 - ISC
254
+ *
255
+ * This source code is licensed under the ISC license.
256
+ * See the LICENSE file in the root directory of this source tree.
257
+ */const 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:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],eh=Ze("file",Fg);/**
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 Dg=[["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"}]],Eo=Ze("folder-git-2",Dg);/**
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 Lg=[["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"}]],Wc=Ze("folder-root",Lg);/**
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 zg=[["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"}]],Sn=Ze("folder",zg);/**
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 Og=[["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"}]],zr=Ze("funnel",Og);/**
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 Bg=[["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"}]],Vs=Ze("git-branch",Bg);/**
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 Ug=[["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"}]],Oa=Ze("git-commit-horizontal",Ug);/**
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 Hg=[["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"}]],th=Ze("git-merge",Hg);/**
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 qg=[["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"}]],es=Ze("git-pull-request",qg);/**
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 Vg=[["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"}]],Ni=Ze("globe",Vg);/**
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 Wg=[["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"}]],nh=Ze("grid-3x3",Wg);/**
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 Kg=[["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"}]],ac=Ze("grip-vertical",Kg);/**
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 Gg=[["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"}]],Jg=Ze("hard-drive",Gg);/**
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 Yg=[["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"}]],Qg=Ze("heart",Yg);/**
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 Xg=[["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"}]],Ba=Ze("history",Xg);/**
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 Zg=[["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"}]],Ra=Ze("inbox",Zg);/**
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 eb=[["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"}]],sh=Ze("key",eb);/**
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 tb=[["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"}]],Si=Ze("layers",tb);/**
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 nb=[["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"}]],Ci=Ze("layout-grid",nb);/**
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 sb=[["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"}]],Ws=Ze("lightbulb",sb);/**
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 ib=[["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"}]],Ji=Ze("link",ib);/**
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 ab=[["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"}]],rb=Ze("list-plus",ab);/**
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 lb=[["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"}]],il=Ze("list-tree",lb);/**
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 ob=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],Mo=Ze("list",ob);/**
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 cb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ut=Ze("loader-circle",cb);/**
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 db=[["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"}]],al=Ze("lock",db);/**
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 ub=[["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"}]],Yi=Ze("mail",ub);/**
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 mb=[["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"}]],Ao=Ze("map",mb);/**
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 hb=[["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"}]],li=Ze("maximize-2",hb);/**
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 pb=[["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"}]],oi=Ze("message-square",pb);/**
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 fb=[["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"}]],ei=Ze("minimize-2",fb);/**
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 gb=[["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"}]],rl=Ze("monitor",gb);/**
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 bb=[["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"}]],ih=Ze("moon",bb);/**
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 xb=[["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"}]],vb=Ze("move",xb);/**
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 yb=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],Po=Ze("package",yb);/**
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 jb=[["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"}]],kb=Ze("paperclip",jb);/**
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 wb=[["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"}]],Hs=Ze("pause",wb);/**
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 Nb=[["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"}]],$n=Ze("pencil",Nb);/**
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 Sb=[["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"}]],ln=Ze("play",Sb);/**
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 Cb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Vt=Ze("plus",Cb);/**
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 Eb=[["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"}]],ah=Ze("radio",Eb);/**
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 Mb=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],vn=Ze("refresh-cw",Mb);/**
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 Ab=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],Kc=Ze("rocket",Ab);/**
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 Pb=[["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"}]],Ib=Ze("rotate-ccw",Pb);/**
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 _b=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],rh=Ze("save",_b);/**
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 Rb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],qi=Ze("search",Rb);/**
483
+ * @license lucide-react v1.7.0 - ISC
484
+ *
485
+ * This source code is licensed under the ISC license.
486
+ * See the LICENSE file in the root directory of this source tree.
487
+ */const Tb=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],yi=Ze("send",Tb);/**
488
+ * @license lucide-react v1.7.0 - ISC
489
+ *
490
+ * This source code is licensed under the ISC license.
491
+ * See the LICENSE file in the root directory of this source tree.
492
+ */const $b=[["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"}]],Or=Ze("server",$b);/**
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 Fb=[["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"}]],Db=Ze("settings-2",Fb);/**
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 Lb=[["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"}]],Ua=Ze("settings",Lb);/**
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 zb=[["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"}]],Ob=Ze("shield",zb);/**
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 Bb=[["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"}]],Dn=Ze("sparkles",Bb);/**
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 Ub=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],os=Ze("square",Ub);/**
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 Hb=[["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"}]],lh=Ze("sun",Hb);/**
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 qb=[["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"}]],ts=Ze("target",qb);/**
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 Vb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Ks=Ze("terminal",Vb);/**
533
+ * @license lucide-react v1.7.0 - ISC
534
+ *
535
+ * This source code is licensed under the ISC license.
536
+ * See the LICENSE file in the root directory of this source tree.
537
+ */const Wb=[["path",{d:"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"}]],Br=Ze("text-wrap",Wb);/**
538
+ * @license lucide-react v1.7.0 - ISC
539
+ *
540
+ * This source code is licensed under the ISC license.
541
+ * See the LICENSE file in the root directory of this source tree.
542
+ */const Kb=[["path",{d:"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"}]],qt=Ze("trash-2",Kb);/**
543
+ * @license lucide-react v1.7.0 - ISC
544
+ *
545
+ * This source code is licensed under the ISC license.
546
+ * See the LICENSE file in the root directory of this source tree.
547
+ */const Gb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Jb=Ze("trending-up",Gb);/**
548
+ * @license lucide-react v1.7.0 - ISC
549
+ *
550
+ * This source code is licensed under the ISC license.
551
+ * See the LICENSE file in the root directory of this source tree.
552
+ */const Yb=[["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"}]],rc=Ze("triangle-alert",Yb);/**
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 Qb=[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]],Gc=Ze("unlink",Qb);/**
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 Xb=[["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"}]],Ti=Ze("user",Xb);/**
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 Zb=[["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"}]],ex=Ze("users",Zb);/**
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 tx=[["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"}]],oh=Ze("webhook",tx);/**
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 nx=[["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"}]],Io=Ze("workflow",nx);/**
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 sx=[["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"}]],ix=Ze("wrench",sx);/**
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 ax=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Lt=Ze("x",ax);/**
588
+ * @license lucide-react v1.7.0 - ISC
589
+ *
590
+ * This source code is licensed under the ISC license.
591
+ * See the LICENSE file in the root directory of this source tree.
592
+ */const rx=[["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"}]],Nn=Ze("zap",rx);class ll 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(rc,{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 Xn({children:t,onError:n}){return e.jsx(ll,{level:"page",onError:n,children:t})}function gi({children:t,onError:n}){return e.jsx(ll,{level:"modal",onError:n,children:t})}function lx({children:t,onError:n}){return e.jsx(ll,{level:"root",onError:n,children:t})}const ox="modulepreload",cx=function(t){return"/"+t},Jc={},nn=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=cx(c),c in Jc)return;Jc[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":ox,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)})},lc="fn.authToken",Yc="token",dx="fn_token";let Vi,Qc=!1,Ur=!1;const _o="fn:auth-token-recovery-required";function ux(){try{const t=window.localStorage.getItem(lc);return t&&t.length>0?t:void 0}catch{return}}function ch(t){try{window.localStorage.setItem(lc,t)}catch{}}function mx(){if(!(Qc||typeof window>"u")){Qc=!0;try{const t=new URL(window.location.href),n=t.searchParams.get(Yc);if(!n)return;ch(n),t.searchParams.delete(Yc);const s=t.pathname+(t.search?t.search:"")+t.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Qi(){if(Vi!==void 0)return Vi;const t=mx();if(t)return Vi=t,t;const n=ux();if(n)return Vi=n,n}function hx(t){Vi=t,Ur=!1,ch(t)}function px(){Vi=void 0,Ur=!1;try{window.localStorage.removeItem(lc)}catch{}}function Xc(t){return t==="ws:"?"http:":t==="wss:"?"https:":t}function fx(t){return t==="http:"||t==="https:"||t==="ws:"||t==="wss:"}function gx(t){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!fx(t.protocol))return!1;const s=t.hostname===n.hostname,i=t.port===n.port,r=Xc(t.protocol)===Xc(n.protocol);return s&&i&&r}function bx(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 $s(t){const n=Qi();if(!n||typeof window>"u")return t;const s=bx(t);return!s||!gx(s.parsed)?t:(s.parsed.searchParams.set(dx,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function mi(t){const n=Qi();if(!n)return t;const s=new Headers(t??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function xx(t){if(!t||typeof t!="object")return!1;const n=t;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function vx(){typeof window>"u"||Ur||(Ur=!0,window.dispatchEvent(new CustomEvent(_o)))}async function yx(t){if(t.status===401)try{const n=t.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();xx(i)&&vx()}catch{}}function jx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Qi();const t=window.fetch.bind(window);window.fetch=function(s,i){const r=Qi(),l=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const m=new URL(l,window.location.origin);return m.origin!==window.location.origin?!1:m.pathname.startsWith("/api/")||m.pathname==="/api"}catch{return l.startsWith("/api/")||l==="/api"}})())return t(s,i);const d=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!d.has("Authorization")&&d.set("Authorization",`Bearer ${r}`),t(s,{...i,headers:d}).then(m=>(yx(m),m))}}class kx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function wx(t){const n=t.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Wn(t){return`/api${t}`}async function L(t,n={}){const s=Wn(t),i=Qi(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),mi(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),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")||wx(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 kx(h?.error||`Request failed for ${s}: ${l.status} ${l.statusText}`,l.status,h?.details)}return u}function Nx(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 L(`/tasks${o}`)}async function Hr(t,n){const i=Wn(Q(`/tasks/${t}`,n));for(let r=1;r<=2;r++){const l=await fetch(i,{headers:mi({"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 dh(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:v,reviewLevel:y,executionMode:M,priority:j}=t;return L(Q("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:l,breakIntoSubtasks:o,enabledWorkflowSteps:d,assignedAgentId:m,modelPresetId:c,modelProvider:u,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:x,summarize:v,reviewLevel:y,executionMode:M,priority:j})})}function Zs(t,n,s){return L(Q(`/tasks/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Sx(t,n,s,i,r,l,o,d){return L(Q("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:t,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:l,planningModelId:o})})}function Cx(t,n,s){return L(Q(`/tasks/${t}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Ex(t,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(Q(`/tasks/${t}${r}`,n),{method:"DELETE"})}function Mx(t,n){return L(Q(`/tasks/${t}/merge`,n),{method:"POST"})}function Ax(t,n){return L(Q(`/tasks/${t}/retry`,n),{method:"POST"})}function Px(t,n){return L(Q(`/tasks/${t}/duplicate`,n),{method:"POST"})}function Ix(t,n){return L(Q(`/tasks/${t}/pause`,n),{method:"POST"})}function _x(t,n){return L(Q(`/tasks/${t}/unpause`,n),{method:"POST"})}function Rx(t,n){return L(Q(`/tasks/${t}/archive`,n),{method:"POST"})}function Tx(t,n){return L(Q(`/tasks/${t}/unarchive`,n),{method:"POST"})}function $x(t){return L(Q("/tasks/archive-all-done",t),{method:"POST"}).then(n=>n.archived)}function Fx(t,n){return L(Q(`/tasks/${t}/approve-plan`,n),{method:"POST"})}function Dx(t,n){return L(Q(`/tasks/${t}/reject-plan`,n),{method:"POST"})}function Lx(t){return L(Q("/config",t))}function Xi(t){return L(Q("/settings",t))}function Ta(t,n){return L(Q("/settings",n),{method:"PUT",body:JSON.stringify(t)})}function cR(t){return L(Q("/memory",t))}function dR(t,n){return L(Q("/memory",n),{method:"PUT",body:JSON.stringify({content:t})})}function Zc(t){return L(Q("/memory/files",t))}function zx(t,n){const s=`path=${encodeURIComponent(t)}`;return L(Q(`/memory/file?${s}`,n))}function Ox(t,n,s){return L(Q("/memory/file",s),{method:"PUT",body:JSON.stringify({path:t,content:n})})}function Bx(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 L(Q("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function uR(t){return L(Q("/memory/insights",t))}function mR(t,n){return L(Q("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:t})})}function hR(t){return L(Q("/memory/extract",t),{method:"POST"})}function pR(t){return L(Q("/memory/audit",t))}function fR(t){return L(Q("/memory/stats",t))}function Ux(t){return L(Q("/memory/backend",t))}function Hx(t){return L(Q("/memory/install-qmd",t),{method:"POST"})}function qx(t,n){return L(Q("/memory/test",n),{method:"POST",body:JSON.stringify({query:t})})}function ca(){return L("/settings/global")}function Jt(t){return L("/settings/global",{method:"PUT",body:JSON.stringify(t)})}function Vx(t){return L(Q("/settings/scopes",t))}function gR(t){return L(Q("/settings/pi-extensions",t))}function bR(t,n){return L(Q("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:t})})}function Wx(t,n){return L(Q("/settings/test-ntfy",n),{method:"POST",body:t?JSON.stringify(t):void 0})}function xR(){return L("/pi-settings")}async function vR(t){return L("/pi-settings",{method:"PUT",body:JSON.stringify(t)})}async function yR(t){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:t})})}async function jR(t){return L(Q("/pi-settings/reinstall-fusion",t),{method:"POST"})}async function Ha(t,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Wn(Q(`/tasks/${t}/attachments`,s)),{method:"POST",headers:mi(),body:i}),l=await r.json();if(!r.ok)throw new Error(l.error||"Upload failed");return l}async function Kx(t,n,s){return L(Q(`/tasks/${t}/attachments/${n}`,s),{method:"DELETE"})}async function ed(t,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",l=Q(`/tasks/${t}/logs${r}`,n),o=await fetch(Wn(l),{headers:mi()});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 Gx(t,n,s,i){return L(Q(`/tasks/${t}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Jx(t,n,s){return L(Q(`/tasks/${t}/comments/${n}`,s),{method:"DELETE"})}function Yx(t,n){return L(Q(`/tasks/${t}/documents`,n))}function Qx(t,n,s){return L(Q(`/tasks/${t}/documents/${n}/revisions`,s))}async function kR(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 L(Q(r,n))}function wR(t,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return L(Q(r,t))}function td(t,n,s,i,r){return L(Q(`/tasks/${t}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Xx(t,n,s){return L(Q(`/tasks/${t}/documents/${n}`,s),{method:"DELETE"})}function Zx(t,n,s){return L(Q(`/tasks/${t}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function ev(t,n,s){return L(Q(`/tasks/${t}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function tv(t,n){return L(Q(`/tasks/${t}/spec/rebuild`,n),{method:"POST"})}function nv(t,n,s){return L(Q(`/tasks/${t}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Vn(){return L("/models")}function sv(){return L("/usage")}function iv(){return L("/providers/claude-cli/status")}function av(t){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:t})})}function Ei(){return L("/auth/status")}function uh(t){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:t})})}function mh(t){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:t})})}function hh(t,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:t,apiKey:n})})}function ph(t){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:t})})}function rv(t,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s,labels:i})})}function lv(t,n,s,i){return L(Q("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,issueNumber:s})})}function ov(t,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:t,repo:n,limit:s})})}function cv(t,n,s,i){return L(Q("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:t,repo:n,prNumber:s})})}function dv(t){return L(Q("/git/remotes",t))}function fh(t){return L(Q("/git/remotes/detailed",t))}function uv(t,n,s){return L(Q("/git/remotes",s),{method:"POST",body:JSON.stringify({name:t,url:n})})}function mv(t,n){return L(Q(`/git/remotes/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function hv(t,n,s){return L(Q(`/git/remotes/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function pv(t,n,s){return L(Q(`/git/remotes/${encodeURIComponent(t)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function fv(t,n,s){return L(Q(`/tasks/${t}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function gv(t,n){return L(Q(`/tasks/${t}/pr/refresh`,n),{method:"POST"})}async function bv(t,n){return(await L(Q("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:t})})).results}function pr(t,n,s,i){return L(Q("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:t,cols:n,rows:s})})}function nd(t,n){return L(Q(`/terminal/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function xv(t){return L(Q("/terminal/sessions",t))}function _s(t){return L(Q("/git/status",t))}function vv(t,n){const s=t?`?limit=${t}`:"";return L(Q(`/git/commits${s}`,n))}function qr(t,n){return L(Q(`/git/commits/${t}/diff`,n))}function yv(t){return L(Q("/git/commits/ahead",t))}function jv(t,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const l=r.size>0?`?${r.toString()}`:"";return L(Q(`/git/remotes/${encodeURIComponent(t)}/commits${l}`,i))}function ba(t){return L(Q("/git/branches",t))}function kv(t,n,s){const i=`?limit=${n}`;return L(Q(`/git/branches/${encodeURIComponent(t)}/commits${i}`,s))}function wv(t){return L(Q("/git/worktrees",t))}function Nv(t,n,s){return L(Q("/git/branches",s),{method:"POST",body:JSON.stringify({name:t,base:n})})}function Sv(t,n){return L(Q(`/git/branches/${encodeURIComponent(t)}/checkout`,n),{method:"POST"})}function sd(t,n,s){const i=n?"?force=true":"";return L(Q(`/git/branches/${encodeURIComponent(t)}${i}`,s),{method:"DELETE"})}function Cv(t,n){return L(Q("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:t})})}function Ev(t){return L(Q("/git/pull",t),{method:"POST"})}function Mv(t){return L(Q("/git/push",t),{method:"POST"})}function fr(t){return L(Q("/git/stashes",t))}function Av(t,n){return L(Q("/git/stashes",n),{method:"POST",body:JSON.stringify({message:t})})}function Pv(t,n,s){return L(Q(`/git/stashes/${t}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Iv(t,n){return L(Q(`/git/stashes/${t}`,n),{method:"DELETE"})}function _v(t,n,s){const i=new URLSearchParams;return i.set("path",t),i.set("staged",String(n)),L(Q(`/git/diff/file?${i.toString()}`,s))}function $i(t){return L(Q("/git/changes",t))}function id(t,n){return L(Q("/git/stage",n),{method:"POST",body:JSON.stringify({files:t})})}function Rv(t,n){return L(Q("/git/unstage",n),{method:"POST",body:JSON.stringify({files:t})})}function ad(t,n){return L(Q("/git/commit",n),{method:"POST",body:JSON.stringify({message:t})})}function Tv(t,n){return L(Q("/git/discard",n),{method:"POST",body:JSON.stringify({files:t})})}function $v(t){return L(Q("/workspaces",t))}function Fv(t,n,s){const i=new URLSearchParams({workspace:t});return n&&i.set("path",n),s&&i.set("projectId",s),L(`/files?${i.toString()}`)}function Dv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Lv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function zv(t,n,s){const i=new URLSearchParams({q:t});return n&&i.set("workspace",n),s&&i.set("projectId",s),L(`/files/search?${i.toString()}`)}function Ov(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Bv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Uv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Hv(t,n,s,i){const r=new URLSearchParams({workspace:t});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function gh(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function qv(t,n,s){const i=new URLSearchParams({workspace:t});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Vv(t,n,s){return L(Q("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:t,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Wv(t,n,s,i){return L(Q("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Kv(t,n,s){return L(Q(`/planning/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function bh(t,n,s){return L(Q("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Gv(t,n,s){return L(Q("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Jv(t,n,s){return L(Q("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:t,summary:n}:{sessionId:t})})}function Yv(t,n,s){return L(Q("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:t,subtasks:n})})}const Ro=new Set;if(typeof window<"u"){const t=()=>{for(const n of Array.from(Ro))try{n.close()}catch{}};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t)}function Qv(t,n){if(n===null||n<=0)return t;const s=t.includes("?")?"&":"?";return`${t}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ya(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=Qv(t,m),f=new EventSource($s(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,v=>{const y=v;u(y)&&x(y)});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(),Ro.delete(g)},isConnected:()=>!l&&r?.readyState===EventSource.OPEN};return Ro.add(g),g}function rd(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 Zi(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 Xv(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)=>Xv(i,r+1));return{lines:s,totalLines:typeof t.totalLines=="number"&&Number.isFinite(t.totalLines)?t.totalLines:s.length}}function ey(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 ld(t){return Array.isArray(t)?t.map(rd):(t.candidates??[]).map(rd)}async function ty(t){try{const n=await L(Q("/dev-server/candidates",t));return ld(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(Q("/dev-server/detect",t));return ld(s)}throw n}}function oc(t){return L(Q("/dev-server/status",t)).then(Zi)}async function NR(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 L(Q(`/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 oc(n);return ey(l.logs,t)}throw r}}function ny(t,n){const s=t.cwd??t.packagePath??".",i=t.scriptName;return L(Q("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:t.command,scriptName:i,scriptId:i,cwd:s,packagePath:t.packagePath})}).then(Zi)}function sy(t){return L(Q("/dev-server/stop",t),{method:"POST"}).then(Zi)}function iy(t){return L(Q("/dev-server/restart",t),{method:"POST"}).then(Zi)}async function ay(t,n){const s=typeof t=="string"?{url:t}:t;try{const i=await L(Q("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Zi(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(Q("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Zi(r)}throw i}}function SR(t){return Wn(Q("/dev-server/logs/stream",t))}async function CR(t){try{return(await L(Q("/devserver",t))).sessions??[]}catch{try{const n=await oc(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 ER(t,n){try{return await L(Q(`/devserver/${encodeURIComponent(t)}`,n))}catch{try{const s=await oc(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 MR(t,n){try{return await L(Q(`/devserver/${encodeURIComponent(t)}/start`,n),{method:"POST"})}catch{const s=await ny({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 AR(t,n){try{return await L(Q(`/devserver/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}catch{const s=await sy(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 PR(t,n){try{return await L(Q(`/devserver/${encodeURIComponent(t)}/restart`,n),{method:"POST"})}catch{const s=await iy(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 IR(t,n,s){try{const i=await L(Q(`/devserver/${encodeURIComponent(t)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await ay({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function _R(t){try{return(await L(Q("/devserver/detect",t))).candidates??[]}catch{try{return(await ty(t)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function RR(t,n){return Wn(Q(`/devserver/${encodeURIComponent(t)}/logs/stream`,n))}function Qa(t,n,s=25e3){const i=setInterval(()=>{Hj(t,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function ry(t,n){return Wn(Q(`/planning/${encodeURIComponent(t)}/stream`,n))}function ly(t,n,s,i){const r=ry(t,n);let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ya(r,{onOpen:()=>{d(),l=Qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[planning] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[planning] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Xa(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 oy(t){return L(Xa("/routines",t))}function cy(t,n){return L(Xa("/routines",n),{method:"POST",body:JSON.stringify(t)})}function od(t,n,s){return L(Xa(`/routines/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function dy(t,n){await L(Xa(`/routines/${t}`,n),{method:"DELETE"})}function uy(t,n){return L(Xa(`/routines/${t}/trigger`,n),{method:"POST"})}function cd(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 L(`/activity${s}`)}function my(t){const n=Q("/activity",t);return L(n,{method:"DELETE"})}function ol(t){return L(Q("/workflow-steps",t))}function dd(t,n){return L(Q("/workflow-steps",n),{method:"POST",body:JSON.stringify(t)})}function hy(t,n,s){return L(Q(`/workflow-steps/${t}`,s),{method:"PATCH",body:JSON.stringify(n)})}function py(t,n){return L(Q(`/workflow-steps/${t}`,n),{method:"DELETE"})}function ud(t,n){return L(Q(`/workflow-steps/${t}/refine`,n),{method:"POST"})}function fy(t,n){return L(Q(`/tasks/${encodeURIComponent(t)}/workflow-results`,n))}function gy(){return L("/workflow-step-templates")}function by(t,n){return L(Q(`/workflow-step-templates/${encodeURIComponent(t)}/create`,n),{method:"POST"})}function Za(t){return L(Q("/scripts",t))}function xy(t,n,s){return L(Q("/scripts",s),{method:"POST",body:JSON.stringify({name:t,command:n})})}function vy(t,n){return L(Q(`/scripts/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function xh(t,n,s){return(await L(Q("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:t,type:n})})).refined}const gr={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 vh(t){if(!(t instanceof Error))return gr.NETWORK;const n=t.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?gr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?gr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?t.message:gr.NETWORK}function yy(t,n){return L(Q("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:t})})}function jy(t,n,s){return L(Q(`/subtasks/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ky(t,n){return Wn(Q(`/subtasks/${encodeURIComponent(t)}/stream`,n))}function wy(t,n,s,i){let r=null,l=null;const o=()=>{r?.stop(),r=null},d=Ya(ky(t,n),{onOpen:()=>{o(),r=Qa(t,n)},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},subtasks:m=>{try{s.onSubtasks?.(JSON.parse(m.data))}catch(c){console.error("[subtasks] Failed to parse subtasks event:",c)}},error:m=>{try{const c=JSON.parse(m.data),u=typeof c=="string"&&c.length>0?c:null;s.onError?.(u||"Stream error")}catch{s.onError?.("Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{o(),s.onError?.(m)}});return l={close:()=>{o(),d.close()},isConnected:d.isConnected},l}function Ny(t,n,s,i){return L(Q("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:t,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function yh(t,n,s){return L(Q("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Q(t,n){if(!n)return t;const s=t.includes("?")?"&":"?";return`${t}${s}projectId=${encodeURIComponent(n)}`}function Sy(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 cl(t,n){const{nodeId:s,localNodeId:i,...r}=n??{},l=Sy(t,s,i);return L(l,r)}function da(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 L(`/agents${i}`)}function jh(t,n){return L(Q(`/agents/${encodeURIComponent(t)}`,n))}function Cy(t,n){return L(Q("/agents",n),{method:"POST",body:JSON.stringify(t)})}function Ey(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TR(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function $R(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function FR(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function DR(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/memory/files`,n))}function LR(t,n,s){const i=`path=${encodeURIComponent(n)}`;return L(Q(`/agents/${encodeURIComponent(t)}/memory/file?${i}`,s))}function zR(t,n,s,i){return L(Q(`/agents/${encodeURIComponent(t)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function My(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ay(t,n){return L(Q(`/agents/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function OR(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 L(`/agents/${encodeURIComponent(t)}/runs${r}`)}function BR(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}`,s))}function UR(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/runs/${encodeURIComponent(n)}/logs`,s))}function HR(t,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(Q(`/agents/${encodeURIComponent(t)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function qR(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/runs/stop`,n),{method:"POST"})}function Py(t){return L(Q("/agents/stats",t))}function VR(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/chain-of-command`,n))}function WR(t,n){const s=new URLSearchParams;t&&s.set("projectId",t),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return L(`/agents/org-tree${i?`?${i}`:""}`)}function KR(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function md(t,n,s){return L(Q(`/tasks/${encodeURIComponent(t)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function GR(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/tasks`,n))}function JR(){return L("/agents/companies")}function YR(t,n){return L(Q("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:t})})}function QR(t,n){return L(Q("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:t})})}function XR(t,n){return L(Q(`/agents/generate/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function hd(t){return L(Q("/backups",t))}function Iy(t){return L(Q("/backups",t),{method:"POST"})}function _y(t,n){const s=Q("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(t)}`;return L(i)}function Ry(t,n,s){return L(Q("/settings/import",s),{method:"POST",body:JSON.stringify({data:t,scope:n?.scope??"both",merge:n?.merge??!0})})}function pd(){return L("/projects/across-nodes")}function Fa(t,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:t,message:n})}).catch(()=>{})}function fd(){return L("/nodes")}function Ty(t){return L("/nodes",{method:"POST",body:JSON.stringify(t)})}function $y(t,n){return L(`/nodes/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function Fy(t){return L(`/nodes/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Dy(t){const n=await L(`/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 ZR(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=Qi();o&&l.set("fn_token",o);const d=l.toString(),m=`/browse-directory${d?`?${d}`:""}`;return L(m)}function Ly(t){return L("/projects",{method:"POST",body:JSON.stringify(t)})}function kh(t){return L(`/projects/${encodeURIComponent(t)}`,{method:"DELETE"})}function gd(t){return L(`/projects/${encodeURIComponent(t)}/health`)}function zy(t){return L(Q("/executor/stats",t))}function bd(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 L(`/activity-feed${s}`)}function Oy(t){return L(`/projects/${encodeURIComponent(t)}/pause`,{method:"POST"})}function By(t){return L(`/projects/${encodeURIComponent(t)}/resume`,{method:"POST"})}function Uy(){return L("/global-concurrency")}function Hy(t){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(t)})}function qy(t,n){return L(`/projects/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}function wh(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 L(`/tasks/${encodeURIComponent(t)}/diff${r}`)}function Vy(t){return L(Q("/missions",t))}function Wy(t,n){return L(Q("/missions",n),{method:"POST",body:JSON.stringify(t)})}function Nh(t,n){return L(Q(`/missions/${encodeURIComponent(t)}`,n))}function Ky(t,n,s){return L(Q(`/missions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Gy(t,n){return L(Q(`/missions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Jy(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 L(Q(`/missions/${encodeURIComponent(t)}/events${r}`,s))}function Yy(t){return L(Q("/missions/health",t))}function Qy(t,n,s){return L(Q(`/missions/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(t,n,s){return L(Q(`/missions/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(t,n){return L(Q(`/missions/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function ej(t,n,s){return L(Q(`/missions/milestones/${encodeURIComponent(t)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function tj(t,n,s){return L(Q(`/missions/slices/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function nj(t,n){return L(Q(`/missions/slices/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function sj(t,n){return L(Q(`/missions/slices/${encodeURIComponent(t)}/activate`,n),{method:"POST"})}function ij(t,n,s){return L(Q(`/missions/slices/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function aj(t,n,s){return L(Q(`/missions/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function rj(t,n){return L(Q(`/missions/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function lj(t,n,s){return L(Q(`/missions/features/${encodeURIComponent(t)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function oj(t,n){return L(Q(`/missions/features/${encodeURIComponent(t)}/unlink-task`,n),{method:"POST"})}function cj(t,n,s,i){return L(Q(`/missions/features/${encodeURIComponent(t)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function dj(t,n){return L(Q(`/missions/slices/${encodeURIComponent(t)}/triage-all`,n),{method:"POST"})}function El(t,n){return L(Q(`/missions/milestones/${encodeURIComponent(t)}/assertions`,n))}function uj(t,n,s){return L(Q(`/missions/milestones/${encodeURIComponent(t)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function mj(t,n,s){return L(Q(`/missions/assertions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hj(t,n,s){return L(Q(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function pj(t,n,s){return L(Q(`/missions/features/${encodeURIComponent(t)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function fj(t,n){return L(Q(`/missions/assertions/${encodeURIComponent(t)}/features`,n))}function Ml(t,n){return L(Q(`/missions/milestones/${encodeURIComponent(t)}/validation`,n))}function xd(t,n){return L(Q(`/missions/milestones/${encodeURIComponent(t)}/validation-telemetry`,n))}function gj(t,n){return L(Q(`/missions/features/${encodeURIComponent(t)}/validate`,n),{method:"POST"})}function vd(t,n){return L(Q(`/missions/features/${encodeURIComponent(t)}/validation-loop`,n))}function bj(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 L(Q(`/missions/features/${encodeURIComponent(t)}/validation-runs${r}`,s)).then(l=>l.runs)}function xj(t,n){return L(Q(`/missions/validation-runs/${encodeURIComponent(t)}`,n))}function vj(t,n){return L(Q(`/missions/${encodeURIComponent(t)}/resume`,n),{method:"POST"})}function yj(t,n){return L(Q(`/missions/${encodeURIComponent(t)}/stop`,n),{method:"POST"})}function jj(t,n){return L(Q(`/missions/${encodeURIComponent(t)}/start`,n),{method:"POST"})}function kj(t,n,s){return L(Q(`/missions/${encodeURIComponent(t)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function wj(t,n,s){return L(Q("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:t,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function Nj(t,n,s,i){return L(Q("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Sj(t,n,s){return L(Q(`/missions/interview/${encodeURIComponent(t)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Sh(t,n,s){return L(Q("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:t,tabId:s})})}function Cj(t,n,s){return L(Q("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function Ej(t,n,s,i){const r=Wn(Q(`/missions/interview/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ya(r,{onOpen:()=>{d(),l=Qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[mission-interview] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[mission-interview] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function er(t,n,s){return Q(`/missions/milestones/${encodeURIComponent(t)}/interview${n}`,s)}function tr(t,n,s){return Q(`/missions/slices/${encodeURIComponent(t)}/interview${n}`,s)}function Mj(t,n){return L(er(t,"/start",n),{method:"POST"})}function Aj(t,n,s,i){return L(er(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function Pj(t,n,s,i){const r=Wn(er(t,`/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ya(r,{onOpen:()=>{d(),l=Qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[milestone-interview] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[milestone-interview] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Ij(t,n,s){return L(er(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function _j(t,n){return L(er(t,"/skip",n),{method:"POST"})}function Rj(t,n){return L(tr(t,"/start",n),{method:"POST"})}function Tj(t,n,s,i){return L(tr(t,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:t,responses:n,tabId:i})})}function $j(t,n,s,i){const r=Wn(tr(t,`/${encodeURIComponent(t)}/stream`,n));let l=null,o=null;const d=()=>{l?.stop(),l=null},m=Ya(r,{onOpen:()=>{d(),l=Qa(t,n)},onMessage:c=>{c.data.startsWith(":")},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},question:c=>{try{s.onQuestion?.(JSON.parse(c.data))}catch(u){console.error("[slice-interview] Failed to parse question event:",u)}},summary:c=>{try{s.onSummary?.(JSON.parse(c.data))}catch(u){console.error("[slice-interview] Failed to parse summary event:",u)}},error:c=>{try{const u=JSON.parse(c.data);s.onError?.(u.message||u)}catch{s.onError?.(c.data||"Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{d(),s.onError?.(c)}});return o={close:()=>{d(),m.close()},isConnected:m.isConnected},o}function Fj(t,n,s){return L(tr(t,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:t,summary:n})})}function Dj(t,n){return L(tr(t,"/skip",n),{method:"POST"})}async function Lj(t,n){try{return await L(Q(`/missions/features/${encodeURIComponent(t)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function eT(t){return L(Q("/roadmaps",t))}function tT(t,n){return L(Q("/roadmaps",n),{method:"POST",body:JSON.stringify(t)})}function nT(t,n){return L(Q(`/roadmaps/${encodeURIComponent(t)}`,n))}function sT(t,n,s){return L(Q(`/roadmaps/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function iT(t,n){return L(Q(`/roadmaps/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function aT(t,n,s){return L(Q(`/roadmaps/${encodeURIComponent(t)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function rT(t,n,s){return L(Q(`/roadmaps/milestones/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function lT(t,n){return L(Q(`/roadmaps/milestones/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function oT(t,n,s){return L(Q(`/roadmaps/milestones/${encodeURIComponent(t)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function cT(t,n,s){return L(Q(`/roadmaps/features/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function dT(t,n){return L(Q(`/roadmaps/features/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function uT(t,n,s){return L(Q(`/roadmaps/${encodeURIComponent(t)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function mT(t,n,s){return L(Q(`/roadmaps/milestones/${encodeURIComponent(t)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function hT(t,n,s,i){return L(Q(`/roadmaps/features/${encodeURIComponent(t)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function pT(t,n){return L(Q(`/roadmaps/${encodeURIComponent(t)}/handoff`,n))}function fT(t,n,s,i){return L(Q(`/roadmaps/${encodeURIComponent(t)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function gT(t,n,s){return L(Q(`/roadmaps/milestones/${encodeURIComponent(t)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function ea(t){if(!t)return[];try{const n=JSON.parse(t);return Array.isArray(n)?n:[]}catch{return[]}}async function Ch(t){const n=t?`?projectId=${encodeURIComponent(t)}`:"",s=await fetch(Wn(`/ai-sessions${n}`),{headers:mi()});return s.ok?(await s.json()).sessions??[]:[]}async function ti(t){const n=await fetch(Wn(`/ai-sessions/${encodeURIComponent(t)}`),{headers:mi()});return n.ok?n.json():null}async function zj(t,n){const s=await L(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Oj(t,n){return L(`/ai-sessions/${encodeURIComponent(t)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Bj(t,n){return L(`/ai-sessions/${encodeURIComponent(t)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Uj(t){await fetch(Wn(`/ai-sessions/${encodeURIComponent(t)}`),{method:"DELETE",headers:mi()})}function Hj(t,n){return L(Q(`/ai-sessions/${encodeURIComponent(t)}/ping`,n),{method:"POST"})}function qj(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 L(`/messages/inbox${i}`)}function Vj(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 L(`/messages/outbox${i}`)}function Eh(t){return L(Q("/messages/unread-count",t))}function Wj(t,n){return L(Q("/messages",n),{method:"POST",body:JSON.stringify(t)})}function Kj(t,n){return L(Q(`/messages/${encodeURIComponent(t)}/read`,n),{method:"POST"})}function Gj(t){return L(Q("/messages/read-all",t),{method:"POST"})}function Jj(t,n){return L(Q(`/messages/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function Yj(t,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(t)}`;return L(Q(i,s))}function Qj(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/mailbox`,n))}function bT(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 L(`/agents/${encodeURIComponent(t)}/reflections${r}`)}function xT(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/reflections`,n),{method:"POST"})}function vT(t,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(t)}/performance${r}`)}function yT(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 L(`/agents/${encodeURIComponent(t)}/ratings${r}`)}function jT(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function kT(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/ratings/summary`,n))}function wT(t,n,s){return L(Q(`/agents/${encodeURIComponent(t)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function NT(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/budget`,n))}function ST(t,n){return L(Q(`/agents/${encodeURIComponent(t)}/budget/reset`,n),{method:"POST"})}async function CT(t){return L(Q("/plugins",t))}async function ET(t,n){return L(Q("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...t})})}async function MT(t,n){return L(Q(`/plugins/${encodeURIComponent(t)}/enable`,n),{method:"POST"})}async function AT(t,n){return L(Q(`/plugins/${encodeURIComponent(t)}/disable`,n),{method:"POST"})}async function PT(t,n){return L(Q(`/plugins/${encodeURIComponent(t)}`,n),{method:"DELETE"})}async function IT(t,n){return L(Q(`/plugins/${encodeURIComponent(t)}/settings`,n))}async function _T(t,n,s){return L(Q(`/plugins/${encodeURIComponent(t)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function RT(t,n){return L(Q(`/plugins/${encodeURIComponent(t)}/reload`,n),{method:"POST"})}async function Xj(t){return L(Q("/plugins/ui-slots",t))}async function TT(t){return(await L(Q("/skills/discovered",t))).skills}async function $T(t,n,s){return L(Q("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:t,enabled:n})})}async function FT(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 L(Q(`/skills/catalog${r}`,s))}async function DT(t,n){return(await L(Q(`/skills/${encodeURIComponent(t)}/content`,n))).content}function LT(t,n){const s=new URLSearchParams;t&&s.set("projectId",t);const i=s.toString();return L(`/chat/sessions${i?`?${i}`:""}`)}async function Zj(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 L(`/chat/sessions?${l.toString()}`)).sessions[0]??null}}function ek(t,n){return L(Q("/chat/sessions",n),{method:"POST",body:JSON.stringify(t)})}function zT(t,n,s){return L(Q(`/chat/sessions/${encodeURIComponent(t)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function OT(t,n){return L(Q(`/chat/sessions/${encodeURIComponent(t)}`,n),{method:"DELETE"})}function yd(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 L(Q(`/chat/sessions/${encodeURIComponent(t)}/messages${r?`?${r}`:""}`,s))}function tk(t,n){return L(Q(`/chat/sessions/${encodeURIComponent(t)}/cancel`,n),{method:"POST"})}function nk(t,n,s,i,r){const l=Wn(Q(`/chat/sessions/${encodeURIComponent(t)}/messages`,i)),o=new AbortController;let d=!1;const m=(c,u)=>{if(!(!c||!u))switch(c){case"thinking":try{s.onThinking?.(JSON.parse(u))}catch{s.onThinking?.(u)}break;case"text":try{s.onText?.(JSON.parse(u))}catch{s.onText?.(u)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(u))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(u))}catch{}break;case"done":try{s.onDone?.(JSON.parse(u))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(u);s.onError?.(h.message||h)}catch{s.onError?.(u||"Stream error")}break}};return(async()=>{try{const c=await fetch(l,{method:"POST",headers:mi({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:o.signal});if(!c.ok){const x=await c.text();let v=`Request failed: ${c.status}`;try{v=JSON.parse(x).error||v}catch{}s.onError?.(v);return}if(!c.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const u=c.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const b=(x,v=!1)=>{g+=x;const y=g.split(`
593
+ `);g=y.pop()||"",v&&g.length>0&&(y.push(g),g="");for(const M of y){const j=M.endsWith("\r")?M.slice(0,-1):M;if(j.startsWith("event:"))p=j.slice(6).trim();else if(j.startsWith("data:")){const P=j.slice(5);f.push(P.startsWith(" ")?P.slice(1):P)}else if(j===""){const P=f.join(`
594
+ `);m(p,P),p="",f=[]}}if(v&&p&&f.length>0){const M=f.join(`
595
+ `);m(p,M),p="",f=[]}};for(;;){const{done:x,value:v}=await u.read();if(x){b(h.decode(),!0);break}b(h.decode(v,{stream:!0}))}}catch(c){if(c instanceof DOMException&&c.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(c instanceof Error?c.message:"Connection error")}})(),{close:()=>{d=!0,o.abort()},isConnected:()=>!d}}function BT(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 L(Q(`/insights${i}`,n))}function UT(t,n){return L(Q(`/insights/${encodeURIComponent(t)}/dismiss`,n),{method:"POST"})}function HT(t="manual",n,s){return L(Q("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:t,inputMetadata:n})})}function qT(t){return L(Q("/insights/runs",t))}function VT(t,n){return L(Q(`/insights/${encodeURIComponent(t)}/create-task`,n),{method:"POST"})}function sk({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 _=window.visualViewport;return _&&_.width>0&&_.height>0?{width:_.width,height:_.height,offsetTop:_.offsetTop,offsetLeft:_.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),v=a.useCallback(()=>{const _=f.current;if(!_)return;const E=_.getBoundingClientRect(),T=b.current,{width:D,height:Z,offsetTop:$,offsetLeft:R}=x(),N=16,W=16,Y=6,H=T?.offsetWidth||Math.max(E.width,260),A=Math.min(H,Math.max(D-N*2,160)),z=T?.offsetHeight||280,J=Math.min(z,Math.max(Z-W*2,160)),C=E.top-$,q=E.bottom-$,oe=E.left-R,O=Z-q,V=C,F=O<J&&V>O,ue=Math.min(Math.max(oe,N),D-N-A)+R,ce=F?Math.max(W+$,C-J-Y+$):Math.min(q+Y+$,Z+$-W-J);g({top:ce,left:ue,width:A})},[x]),y=a.useMemo(()=>Object.entries(l).sort(([_],[E])=>_.localeCompare(E)),[l]),M=y.length>0,j=y.length+(M?1:0);a.useEffect(()=>{if(!i)return;let _=!1;return m(!0),Za(s).then(E=>{_||o(E)}).catch(()=>{_||o({})}).finally(()=>{_||m(!1)}),()=>{_=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const _=E=>{p.current&&!p.current.contains(E.target)&&f.current&&!f.current.contains(E.target)&&r(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[i]),a.useEffect(()=>{if(!i)return;const _=E=>{E.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i]),a.useEffect(()=>{if(i){u(-1);const _=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(_)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const _=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(_)},[i,d,y.length,M,v]),a.useEffect(()=>{if(!i)return;const _=()=>v();window.addEventListener("resize",_),window.addEventListener("scroll",_,!0);const E=window.visualViewport;return E&&(E.addEventListener("resize",_),E.addEventListener("scroll",_)),()=>{window.removeEventListener("resize",_),window.removeEventListener("scroll",_,!0),E&&(E.removeEventListener("resize",_),E.removeEventListener("scroll",_))}},[i,v]);const P=a.useCallback(_=>{switch(_.key){case"ArrowDown":_.preventDefault(),u(E=>E<j-1?E+1:0);break;case"ArrowUp":_.preventDefault(),u(E=>E>0?E-1:j-1);break;case"Enter":if(_.preventDefault(),c>=0)if(c<y.length){const[E,T]=y[c];S(E,T)}else M&&c===y.length&&k();break;case"Home":_.preventDefault(),u(0);break;case"End":_.preventDefault(),u(j-1);break}},[c,j,y,M]),w=a.useCallback(()=>{r(_=>!_)},[]),S=a.useCallback((_,E)=>{n(_,E),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(Ks,{size:16}),e.jsx(Ot,{size:14,className:`quick-scripts-dropdown__trigger-chevron ${i?"rotate":""}`})]}),i&&e.jsx("div",{ref:b,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:P,"data-testid":"quick-scripts-dropdown",style:h?{position:"fixed",top:`${h.top}px`,left:`${h.left}px`,width:`${h.width}px`,right:"auto"}:void 0,children:d?e.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[e.jsx(ut,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts..."})]}):y.length===0?e.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[e.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:e.jsx(Ks,{size:16})}),e.jsx("p",{children:"No scripts configured"}),e.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:k,children:"Add your first script"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"quick-scripts-dropdown__list",children:y.map(([_,E],T)=>e.jsxs("button",{className:`quick-scripts-dropdown__item ${c===T?"highlighted":""}`,onClick:()=>S(_,E),role:"option","aria-selected":c===T,"data-testid":`quick-script-item-${_}`,children:[e.jsx(ln,{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:_}),e.jsx("span",{className:"quick-scripts-dropdown__item-command",title:E,children:E.length>50?`${E.slice(0,50)}...`:E})]})]},_))}),e.jsx("div",{className:"quick-scripts-dropdown__footer",children:e.jsxs("button",{className:`quick-scripts-dropdown__manage ${M&&c===y.length?"highlighted":""}`,onClick:k,"data-testid":"quick-scripts-manage",children:[e.jsx(Ua,{size:14}),e.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function ik(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 ak({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}=ik(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 jd=new Map,rk=6e4;function Mh(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=jd.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 Xj(t);if(h||m.current)return;jd.set(u,{slots:b,expiresAt:Date.now()+rk}),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 nr({slotId:t,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Mh(n);if(i||r||!t)return null;const l=s(t);return l.length===0?null:e.jsx(ll,{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 lk(){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 sr(){const[t,n]=a.useState(lk);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 Ah={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function ok({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.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>l(m=>!m),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[e.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),e.jsx(Ot,{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=Ah[m.status]?.color;return e.jsxs("button",{className:`project-selector-item${c?" project-selector-item--current":""}`,onClick:()=>d(m),role:"option","aria-selected":c,children:[e.jsx("span",{className:"project-selector-dot",style:{backgroundColor:u||"var(--text-muted)"}}),e.jsxs("div",{className:"project-selector-info",children:[e.jsx("span",{className:"project-selector-name",children:m.name}),e.jsx("span",{className:"project-selector-path",children:m.path.split("/").slice(-2).join("/")})]}),c&&e.jsx(An,{size:14,className:"project-selector-check"})]},m.id)}),e.jsx("div",{className:"project-selector-divider",role:"presentation"}),e.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),l(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function kd({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 ck({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:v,filesOpen:y,globalPaused:M,enginePaused:j,onToggleGlobalPause:P,onToggleEnginePause:w,view:S="board",onChangeView:k,showSkillsTab:_,showAgentsTab:E,searchQuery:T="",onSearchChange:D,projects:Z=[],currentProject:$,onSelectProject:R,onViewAllProjects:N,projectId:W,isElectron:Y=!1,mobileNavEnabled:H,availableNodes:A=[],currentNode:z,onSelectNode:J,isRemote:C=!1,experimentalFeatures:q}){const oe=sr(),O=oe==="mobile",F=O||oe==="tablet",ue=O&&H,[ce,K]=a.useState(!1),[de,Fe]=a.useState(!1),[we,Ee]=a.useState(!1),[ie,Pe]=a.useState(!1),[ze,$e]=a.useState(!1),[He,Me]=a.useState(!1),[Te,Ve]=a.useState(!1),[_e,et]=a.useState(!1),[le,X]=a.useState(!1),[ke,se]=a.useState({}),[Le,ve]=a.useState(!1),Ye=a.useRef(null),mt=a.useRef(null),ht=a.useRef(null),me=a.useRef(null),te=a.useRef(null),je=a.useRef(null),Ae=a.useRef(!1),Qe=a.useRef(null),be=a.useRef(null),st=a.useRef(null),Se=a.useRef(null),Je=a.useMemo(()=>A.filter(tt=>tt.type==="remote"),[A]),it=Je.length>0,ye=a.useMemo(()=>Object.entries(ke).sort(([tt],[bt])=>tt.localeCompare(bt)),[ke]),Ge=a.useMemo(()=>!!(q?.insights||q?.roadmap||_||q?.memoryView||q?.devServerView),[q,_]);a.useEffect(()=>{Ae.current=ze},[ze]),a.useEffect(()=>{if(!ze||!F)return;let tt=!1;return ve(!0),Za(W).then(bt=>{tt||se(bt)}).catch(()=>{tt||se({})}).finally(()=>{tt||ve(!1)}),()=>{tt=!0}},[ze,F,W]);const Ne=ce||T.length>0,at=(de||T.length>0)&&!we,dt=(S==="board"||S==="list")&&!O&&D&&!we&&T.length===0,vt=(S==="board"||S==="list")&&!O&&D;a.useEffect(()=>{T===""&&Ee(!1)},[T]),a.useEffect(()=>{if(!ie)return;const tt=bt=>{mt.current&&!mt.current.contains(bt.target)&&Ye.current&&!Ye.current.contains(bt.target)&&Pe(!1)};return document.addEventListener("mousedown",tt),()=>document.removeEventListener("mousedown",tt)},[ie]),a.useEffect(()=>{if(!le)return;const tt=bt=>{me.current&&!me.current.contains(bt.target)&&ht.current&&!ht.current.contains(bt.target)&&X(!1)};return document.addEventListener("mousedown",tt),()=>document.removeEventListener("mousedown",tt)},[le]),a.useEffect(()=>{if(!He)return;const tt=bt=>{Qe.current&&!Qe.current.contains(bt.target)&&Me(!1)};return document.addEventListener("mousedown",tt),()=>document.removeEventListener("mousedown",tt)},[He]),a.useEffect(()=>{const tt=bt=>{if(bt.key==="Escape"){if(et(!1),X(!1),Ae.current){$e(!1);return}Pe(!1),K(!1),Me(!1),Ve(!1)}};return document.addEventListener("keydown",tt),()=>document.removeEventListener("keydown",tt)},[]),a.useEffect(()=>{if(!Te)return;const tt=bt=>{be.current&&!be.current.contains(bt.target)&&Ve(!1)};return document.addEventListener("mousedown",tt),()=>document.removeEventListener("mousedown",tt)},[Te]),a.useEffect(()=>{if(!_e)return;const tt=bt=>{st.current&&!st.current.contains(bt.target)&&Se.current&&!Se.current.contains(bt.target)&&et(!1)};return document.addEventListener("mousedown",tt),()=>document.removeEventListener("mousedown",tt)},[_e]);const It=a.useCallback(()=>{K(tt=>!tt)},[]),_t=a.useCallback(()=>{Fe(!0),Ee(!1)},[]),Mt=a.useCallback(()=>{Fe(!1),Ee(!0),D&&D("")},[D]),zt=a.useCallback(()=>{Pe(tt=>!tt)},[]),Nt=a.useCallback(tt=>{tt&&tt(),Pe(!1),$e(!1)},[]),Pt=a.useCallback(()=>{K(!1),D&&D("")},[D]);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"})]}),O&&Z.length>=1&&R&&e.jsxs("div",{className:"mobile-project-switch",ref:be,children:[e.jsx("button",{className:`mobile-project-switch-trigger${Te?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ve(tt=>!tt),title:"Switch project","aria-label":"Switch project","aria-expanded":Te,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:e.jsx(Ot,{size:14,className:`mobile-project-switch-chevron${Te?" mobile-project-switch-chevron--open":""}`})}),Te&&e.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:Z.map(tt=>{const bt=$?.id===tt.id,Ue=Ah[tt.status]?.color;return e.jsxs("button",{className:`mobile-project-switch-item${bt?" mobile-project-switch-item--current":""}`,onClick:()=>{R(tt),Ve(!1)},role:"option","aria-selected":bt,"data-testid":`mobile-project-switch-item-${tt.id}`,children:[e.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Ue||"var(--text-muted)"}}),e.jsxs("div",{className:"mobile-project-switch-info",children:[e.jsx("span",{className:"mobile-project-switch-name",children:tt.name}),e.jsx("span",{className:"mobile-project-switch-path",children:tt.path.split("/").slice(-2).join("/")})]}),bt&&e.jsx(An,{size:14,className:"mobile-project-switch-check"})]},tt.id)})})]}),!F&&Z.length>=1&&N&&e.jsx(ok,{projects:Z,currentProject:$??null,onViewAll:N,onSelectProject:R}),it&&e.jsxs("div",{className:`header-node-selector${O?" header-node-selector--mobile":""}`,ref:O?void 0:Qe,children:[e.jsx(ak,{node:z??null,showDetails:!O}),!O&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:`btn-icon node-selector-trigger${He?" node-selector-trigger--open":""}`,onClick:()=>Me(tt=>!tt),title:"Switch node","aria-label":"Switch node","aria-expanded":He,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:e.jsx(on,{size:12,className:`node-selector-chevron${He?" node-selector-chevron--open":""}`})}),He&&e.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[e.jsxs("button",{className:`node-selector-option${C?"":" node-selector-option--active"}`,onClick:()=>{J?.(null),Me(!1)},role:"option","aria-selected":!C,"data-testid":"node-option-local",children:[e.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),e.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Je.map(tt=>e.jsxs("button",{className:`node-selector-option${z?.id===tt.id?" node-selector-option--active":""}`,onClick:()=>{J?.(tt),Me(!1)},role:"option","aria-selected":z?.id===tt.id,"data-testid":`node-option-${tt.id}`,children:[e.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${tt.status}`}),e.jsx("span",{className:"node-selector-option-label",children:tt.name}),e.jsx("span",{className:"node-selector-option-status",children:tt.status})]},tt.id))]})]})]})]}),e.jsxs("div",{className:"header-actions",children:[ue&&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(Ci,{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(Mo,{size:16})})]}),D&&O&&(ue||S==="board"||S==="list")&&!Ne&&e.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:It,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:e.jsx(qi,{size:16})}),dt&&e.jsx("button",{className:"btn-icon",onClick:_t,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:e.jsx(qi,{size:16})}),O&&ue&&l&&e.jsx("button",{className:"btn-icon",onClick:l,title:"View usage","data-testid":"mobile-header-usage-btn",children:e.jsx(Ss,{size:16})}),!ue&&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(Ci,{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(Mo,{size:16})}),E&&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(rn,{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(ts,{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(oi,{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(wi,{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(Yi,{size:16})}),Ge&&e.jsxs(e.Fragment,{children:[e.jsx("button",{ref:Se,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(S)?" active":""}`,onClick:()=>et(tt=>!tt),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":_e,"data-testid":"view-toggle-overflow-trigger",children:e.jsx(Ot,{size:12})}),_e&&e.jsxs("div",{ref:st,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[q?.insights&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="insights"?" active":""}`,onClick:()=>{k("insights"),et(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[e.jsx(Dn,{size:14}),e.jsx("span",{children:"Insights"})]}),q?.roadmap&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="roadmaps"?" active":""}`,onClick:()=>{k("roadmaps"),et(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[e.jsx(Ao,{size:14}),e.jsx("span",{children:"Roadmaps"})]}),_&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="skills"?" active":""}`,onClick:()=>{k("skills"),et(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[e.jsx(Nn,{size:14}),e.jsx("span",{children:"Skills"})]}),q?.memoryView&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="memory"?" active":""}`,onClick:()=>{k("memory"),et(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[e.jsx(Lr,{size:14}),e.jsx("span",{children:"Memory"})]}),q?.devServerView&&e.jsxs("button",{className:`view-toggle-overflow-item${S==="dev-server"||S==="devserver"?" active":""}`,onClick:()=>{k("devserver"),et(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[e.jsx(rl,{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(Ss,{size:16})}),!F&&o&&e.jsx("button",{className:"btn-icon",onClick:o,title:"View Activity Log",children:e.jsx(Ba,{size:16})}),!F&&!Y&&e.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:e.jsx(kd,{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(Ws,{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(Ks,{size:16})}),!F&&v&&e.jsx("button",{className:`btn-icon${y?" btn-icon--active":""}`,onClick:v,title:"Browse files","data-testid":"files-toggle-btn",children:e.jsx(Sn,{size:16})}),!F&&u&&e.jsx("button",{className:"btn-icon",onClick:u,title:"Git Manager","data-testid":"git-manager-btn",children:e.jsx(Vs,{size:16})}),!F&&p&&e.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:e.jsx(Io,{size:16})}),!F&&f&&b&&e.jsx(sk,{onOpenScripts:f,onRunScript:b,projectId:W}),!F&&e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{ref:ht,className:"btn-icon",onClick:()=>X(tt=>!tt),title:"More actions","aria-label":"More actions","aria-expanded":le,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:e.jsx(Co,{size:16})}),le&&e.jsxs("div",{ref:me,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&e.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),X(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[e.jsx(Or,{size:14}),e.jsx("span",{children:"Nodes"})]}),e.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Nt(c),X(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[e.jsx(Ki,{size:14}),e.jsx("span",{children:"Automation"})]})]})]}),e.jsx("button",{className:`btn-icon${j?" btn-icon--paused":""}`,onClick:w,title:j?"Resume scheduling":"Pause scheduling",disabled:!!M,children:j?e.jsx(ln,{size:16}):e.jsx(Hs,{size:16})}),e.jsx("button",{className:`btn-icon${M?" btn-icon--stopped":""}`,onClick:P,title:M?"Start AI engine":"Stop AI engine",children:M?e.jsx(ln,{size:16}):e.jsx(os,{size:16})}),!F&&e.jsx("button",{className:"btn-icon",onClick:t,title:"Settings",children:e.jsx(Ua,{size:16})}),e.jsx(nr,{slotId:"header-action",projectId:W}),F&&!ue&&e.jsx("button",{ref:Ye,className:"btn-icon compact-overflow-trigger",onClick:zt,title:"More header actions","aria-label":"More header actions","aria-expanded":ie,"aria-haspopup":"menu",children:e.jsx(Co,{size:16})}),F&&!ue&&ie&&e.jsxs("div",{ref:mt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[Z.length>=1&&N&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(N),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[e.jsx(nh,{size:16}),e.jsx("span",{children:"Projects"})]}),v&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(v),role:"menuitem","data-testid":"overflow-files-btn",children:[e.jsx(Sn,{size:16}),e.jsx("span",{children:"Browse Files"})]}),e.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Nt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[e.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[e.jsx(Ws,{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:()=>Nt(u),role:"menuitem","data-testid":"overflow-git-btn",children:[e.jsx(Vs,{size:16}),e.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[e.jsx(Or,{size:16}),e.jsx("span",{children:"Nodes"})]}),!Y&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(n),role:"menuitem",children:[e.jsx(kd,{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:()=>Nt(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[e.jsx(Ks,{size:16}),e.jsx("span",{children:"Terminal"})]}),e.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>$e(tt=>!tt),role:"menuitem","aria-expanded":ze,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:e.jsx(on,{size:14,className:`mobile-overflow-chevron${ze?" mobile-overflow-chevron--open":""}`})})]}),ze&&e.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Le?e.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[e.jsx(ut,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts…"})]}):ye.length>0?e.jsxs(e.Fragment,{children:[ye.map(([tt,bt])=>e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(tt,bt),Pe(!1),$e(!1)},role:"menuitem","data-testid":`overflow-script-item-${tt}`,children:[e.jsx(ln,{size:14}),e.jsx("span",{children:tt})]},tt)),f&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Nt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Rs,{size:14}),e.jsx("span",{children:"Manage Scripts…"})]})]}):f&&e.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Nt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[e.jsx(Rs,{size:14}),e.jsx("span",{children:"No scripts — add one…"})]})})]}),e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(c),role:"menuitem","data-testid":"overflow-schedules-btn",children:[e.jsx(Ki,{size:16}),e.jsx("span",{children:"Automation"})]}),o&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(o),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[e.jsx(Ba,{size:16}),e.jsx("span",{children:"View Activity Log"})]}),d&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[e.jsx(Yi,{size:16}),e.jsxs("span",{children:["Mailbox",m>0?` (${m})`:""]})]}),l&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(l),role:"menuitem","data-testid":"overflow-usage-btn",children:[e.jsx(Ss,{size:16}),e.jsx("span",{children:"View Usage"})]}),p&&e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[e.jsx(Io,{size:16}),e.jsx("span",{children:"Workflow Steps"})]}),e.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Nt(t),role:"menuitem",children:[e.jsx(Ua,{size:16}),e.jsx("span",{children:"Settings"})]})]})]})]}),vt&&at&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{className:"header-search",children:[e.jsx(qi,{size:14,className:"header-search-icon"}),e.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:T,onChange:tt=>D(tt.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:Mt,"aria-label":"Close search",children:e.jsx(Lt,{size:14})})]})}),D&&O&&Ne&&e.jsx("div",{className:"header-floating-search",children:e.jsxs("div",{ref:te,className:"header-search mobile-search-expanded",children:[e.jsx(qi,{size:14,className:"header-search-icon"}),e.jsx("input",{ref:je,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:T,onChange:tt=>D(tt.target.value),className:"header-search-input"}),e.jsx("button",{className:"header-search-clear",onClick:Pt,"aria-label":"Close search",children:e.jsx(Lt,{size:14})})]})})]})}const dk={themeMode:"dark",colorTheme:"default",defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90},uk={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:{}},mk=Object.freeze(Object.keys(dk)),hk=Object.freeze(Object.keys(uk));function pk(t){return mk.includes(t)}function fk(t){return hk.includes(t)}function fe(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}const gk=["off","minimal","low","medium","high"],ki=["triage","todo","in-progress","in-review","done","archived"],cc=["low","normal","high","urgent"],cs="normal",bk=["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"},xk={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"},To={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 vk(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 yk(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 jk(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 Ph({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(es,{size:12}),e.jsxs("span",{children:["#",t.number]})]}),n&&e.jsxs("span",{className:`card-github-badge ${jk(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[e.jsx(sl,{size:12}),e.jsxs("span",{children:["#",n.number]})]})]})}function br(t,n){return`${t??"default"}:${n}`}class kk{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=br(this.projectId,l);this.subscriptionsByTask.set(o,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=br(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,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=br(this.projectId,s),r=this.subscriptionsByTask.get(i);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(i),this.badgeUpdates.delete(i),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const i=s.split(":").slice(1).join(":");this.unsubscribeTask(n,i)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(i+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket($s(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=br(this.projectId,o.taskId),m=this.badgeUpdates.get(d);this.badgeUpdates.set(d,{prInfo:wd(o,"prInfo")?o.prInfo??null:m?.prInfo,issueInfo:wd(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 bi=new kk;let wk=0;function wd(t,n){return Object.prototype.hasOwnProperty.call(t,n)}function Ih(t){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${wk++}`);const s=a.useSyncExternalStore(l=>bi.subscribe(l),()=>bi.getSnapshot(),()=>bi.getSnapshot()),i=a.useCallback(l=>{bi.subscribeTask(n.current,l)},[]),r=a.useCallback(l=>{bi.unsubscribeTask(n.current,l)},[]);return a.useEffect(()=>{bi.setProjectId(t??null)},[t]),a.useEffect(()=>()=>{bi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Vr(t,n,s,i){return t===void 0||!n?s:!i||n>=i?t??void 0:s}function Nk({taskId:t,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:l}){const{badgeUpdates:o,subscribeToBadge:d,unsubscribeFromBadge:m}=Ih(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=Vr(u?.prInfo,u?.timestamp,n,n?.lastCheckedAt??i),g=Vr(u?.issueInfo,u?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:e.jsx(Ph,{prInfo:h,issueInfo:g})}const Sk=a.memo(Nk);Sk.displayName="TaskCardBadge";const js={data:new Map,pendingPromise:null,lastFetchTime:null},Ck=5e3;function $r(t,n){return n?`${n}::${t}`:t}function Ek(t,n){const s=js.data.get($r(t,n));if(!(!s||Date.now()-s.timestamp>Ck))return s}function Mk(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 bv(d,t)}catch(h){c=h instanceof Error?h:new Error(String(h));const g=fe(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,u),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(c)throw c;return{}},[t]),l=a.useCallback(async d=>{if(d.length===0)return;const c=Date.now()-5e3;if(d.every(g=>{const p=js.data.get($r(g,t));return p&&p.timestamp>c})&&js.lastFetchTime&&js.lastFetchTime>c)return;if(i.current&&(clearTimeout(i.current),i.current=null),js.pendingPromise){s(!0);try{await js.pendingPromise}finally{s(!1)}return}s(!0);const h=r(d);js.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))js.data.set($r(f,t),{result:b,timestamp:p});js.lastFetchTime=p}catch{}finally{js.pendingPromise=null,s(!1)}},[r,t]),o=a.useCallback(d=>js.data.get($r(d,t)),[t]);return{fetchBatch:l,isLoading:n,lastFetchTime:js.lastFetchTime,getBatchData:o}}const $o=new Map,Ak=3e4;function _h(t,n,s,i){return`${t}:${n??""}:${s??""}:${i??""}`}function Pk(t,n,s,i){const r=_h(t,n,s,i),l=$o.get(r);return l?Date.now()>l.expiresAt?($o.delete(r),null):l.stats:null}function Ik(t,n,s,i,r){const l=_h(t,n,s,i);$o.set(l,{stats:r,expiresAt:Date.now()+Ak})}function _k(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 v=!1;async function y(j=!1){if(!j){const P=Pk(t,i,b,x);if(P){v||(u(P),g(!1));return}}g(!0);try{const P=await wh(t,b,i);v||(u(P.stats),Ik(t,i,b,x,P.stats))}catch{v||u(null)}finally{v||g(!1)}}y();let M;return m&&f&&(M=setInterval(()=>{y(!0)},m)),()=>{v=!0,M&&clearInterval(M)}},[t,n,s,i,l,o,d,m]),{stats:c,loading:h}}const Rk=new Set(["failed","stuck-killed"]);function Wr(t,n,s){if(t.column!=="in-progress"||t.status&&Rk.has(t.status)||!n||n<=0)return!1;const i=new Date(t.updatedAt).getTime();return(s??Date.now())-i>n}function Tk(t){switch(t){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function $k(t){return t==="done"||t==="skipped"}function Fk(t,n,s){const i=s?.get(t)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||t}function Rh(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:Fk(m,c,n),status:c?Tk(c.status):"pending",source:"workflow",phase:c?.phase??"pre-merge"}}),l=[...s,...r],o=l.length,d=l.filter(m=>$k(m.status)).length;return{total:o,completed:d,items:l}}const Fo=new Map;async function Dk(t,n){const s=Fo.get(t);if(s)return s;try{const i=await Nh(t,n);return Fo.set(t,i.title),i.title}catch{return t}}const Nd=12;function Lk(t){return t.length<=Nd?t:t.slice(0,Nd-3)+"..."}const Do=new Map;async function zk(t,n){const s=Do.get(t);if(s)return s;try{const i=await jh(t,n);return Do.set(t,i.name),i.name}catch{return t}}function Ok(t){return typeof t=="string"&&cc.includes(t)?t:cs}function Bk(t,n){return t.length<=n?t:t.slice(0,n-3)+"..."}const Uk=new Set(["triage","todo"]),Sd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Hk={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"};function Cd(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 qk(t,n){return t.length!==n.length?!1:t.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Vk(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function Wk(t,n){return!t&&!n?!0:!t||!n||t.length!==n.length?!1:t.every((s,i)=>s===n[i])}function Kk(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 Gk(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 Jk(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 Yk(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 Qk(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.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&Jk(s.attachments,i.attachments)&&Yk(s.comments,i.comments)&&Vk(s.dependencies,i.dependencies)&&qk(s.steps,i.steps)&&Wk(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Gk(s.workflowStepResults,i.workflowStepResults)&&Cd(s.prInfo,i.prInfo)&&Cd(s.issueInfo,i.issueInfo)}function Xk({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,v]=a.useState(!1),[y,M]=a.useState(!1),[j,P]=a.useState(!1),[w,S]=a.useState(t.description||""),[k,_]=a.useState(!1),[E,T]=a.useState(t.column==="in-progress"||t.column==="triage"&&t.steps.some(ge=>ge.status==="done"||ge.status==="skipped")),[D,Z]=a.useState(null),[$,R]=a.useState(null),[N,W]=a.useState(!1),Y=a.useRef(null),H=a.useRef(!1),A=a.useRef(null),z=a.useRef(null),[J,C]=a.useState(!1),{badgeUpdates:q,subscribeToBadge:oe,unsubscribeFromBadge:O}=Ih(n),V=a.useRef(null),F=a.useRef(!1),ue=a.useCallback(ge=>ge instanceof Element?!!ge.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{S(t.description||"")},[t.id,t.description]),a.useEffect(()=>{if(!N)return;const ge=Oe=>{z.current&&!z.current.contains(Oe.target)&&W(!1)};return document.addEventListener("click",ge),()=>document.removeEventListener("click",ge)},[N]),a.useEffect(()=>{if(!t.missionId){Z(null);return}const ge=Fo.get(t.missionId);if(ge){Z(ge);return}let Oe=!1;return Dk(t.missionId,n).then(ee=>{Oe||Z(ee)}),()=>{Oe=!0}},[t.missionId,n]),a.useEffect(()=>{if(!t.assignedAgentId){R(null);return}const ge=Do.get(t.assignedAgentId);if(ge){R(ge);return}R(null);let Oe=!1;return zk(t.assignedAgentId,n).then(ee=>{Oe||R(ee)}),()=>{Oe=!0}},[t.assignedAgentId,n]),a.useEffect(()=>{if(j&&Y.current){const ge=Y.current;ge.focus(),ge.style.height="auto",ge.style.height=ge.scrollHeight+"px"}},[j]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){C(!0);return}const ge=A.current;if(!ge)return;const Oe=new IntersectionObserver(([ee])=>{C(ee?.isIntersecting??!0)},{rootMargin:"200px"});return Oe.observe(ge),()=>Oe.disconnect()},[j,t.id]);const ce=a.useCallback(ge=>{ge.dataTransfer.setData("text/plain",t.id),ge.dataTransfer.effectAllowed="move",v(!0)},[t.id]),K=a.useCallback(()=>{v(!1)},[]),de=a.useCallback(ge=>ge.dataTransfer.types.includes("Files"),[]),Fe=a.useCallback(ge=>{de(ge)&&(ge.preventDefault(),ge.stopPropagation(),ge.dataTransfer.dropEffect="copy",M(!0))},[de]),we=a.useCallback(ge=>{de(ge)&&(ge.preventDefault(),ge.stopPropagation(),M(!1))},[de]),Ee=a.useCallback(async ge=>{if(!de(ge))return;ge.preventDefault(),ge.stopPropagation(),M(!1);const Oe=Array.from(ge.dataTransfer.files);for(const ee of Oe)try{await Ha(t.id,ee,n),r(`Attached ${ee.name} to ${t.id}`,"success")}catch(Ie){r(`Failed to attach ${ee.name}: ${fe(Ie)}`,"error")}},[t.id,de,r]),ie=a.useCallback(()=>{j||i(t)},[t,i,j]),Pe=a.useCallback(ge=>{if(H.current){H.current=!1;return}ue(ge.target)||ie()},[ie,ue]),ze=a.useCallback(ge=>{const Oe=ge.touches[0];Oe&&(V.current={x:Oe.clientX,y:Oe.clientY,time:Date.now()},F.current=!1)},[]),$e=a.useCallback(ge=>{if(!V.current)return;const Oe=ge.touches[0];if(!Oe)return;const ee=Math.abs(Oe.clientX-V.current.x),Ie=Math.abs(Oe.clientY-V.current.y);(ee>Ed||Ie>Ed)&&(F.current=!0)},[]),He=a.useCallback(ge=>{if(ue(ge.target)||!V.current)return;const ee=Date.now()-V.current.time<Zk,Ie=!F.current;ee&&Ie&&(H.current=!0,ie()),V.current=null,F.current=!1},[ie,ue]),Me=a.useCallback(async(ge,Oe)=>{ge.stopPropagation();try{const ee=await Hr(Oe,n);i(ee)}catch{r(`Failed to load dependency ${Oe}`,"error")}},[i,r]),Te=t.status==="failed",Ve=t.paused===!0,_e=Ok(t.priority),et=_e!==cs,le=Wr(t,h,f),X=t.column==="triage"&&t.status==="awaiting-approval",ke=t.column==="archived",se=!l&&!s&&!Te&&!Ve&&!le&&!X&&(t.column==="in-progress"||Sd.has(t.status)),Le=!s&&!Ve&&!j&&!ke,ve=Uk.has(t.column)&&!se&&!Ve&&!s&&o,Ye=!!(t.prInfo||t.issueInfo),mt=!!(t.assignedAgentId&&$===null),ht=a.useMemo(()=>Rh(t,b),[t.steps,t.enabledWorkflowSteps,t.workflowStepResults,b]),me=ht.total>0&&(t.status==="executing"||t.column==="in-progress");a.useEffect(()=>{if(!Ye||!J){O(t.id);return}return oe(t.id),()=>{O(t.id)}},[Ye,J,oe,t.id,O]);const te=q.get(`${n??"default"}:${t.id}`),je=t.column==="in-progress"||t.column==="in-review",Ae=a.useMemo(()=>t.steps.map(ge=>`${ge.name}:${ge.status}`).join("|"),[t.steps]),{stats:Qe}=_k(t.id,t.column,t.mergeDetails?.commitSha,n,{enabled:J,worktree:t.worktree,stepVersion:je?Ae:void 0,pollIntervalMs:je?3e4:void 0}),be=a.useMemo(()=>Ek(t.id,n),[t.id,n]),st=a.useMemo(()=>{const ge=te?.prInfo,Oe=te?.timestamp,ee=be?.result?.prInfo,Ie=be?.timestamp?new Date(be.timestamp).toISOString():void 0,xt=t.prInfo,he=t.prInfo?.lastCheckedAt??t.updatedAt;let Be=Vr(ge,Oe,xt,he);const gt=Oe&&Oe>=he?Oe:he;return ee&&Ie&&(!gt||Ie>gt)&&(Be=ee),Be},[te,be,t.prInfo,t.updatedAt]),Se=a.useMemo(()=>{const ge=te?.issueInfo,Oe=te?.timestamp,ee=be?.result?.issueInfo,Ie=be?.timestamp?new Date(be.timestamp).toISOString():void 0,xt=t.issueInfo,he=t.issueInfo?.lastCheckedAt??t.updatedAt;let Be=Vr(ge,Oe,xt,he);const gt=Oe&&Oe>=he?Oe:he;return ee&&Ie&&(!gt||Ie>gt)&&(Be=ee),Be},[te,be,t.issueInfo,t.updatedAt]),Je=a.useCallback(ge=>{ge?.stopPropagation(),!(!ve||k)&&(P(!0),S(t.description||""))},[ve,k,t.description]),it=a.useCallback(()=>{P(!1),S(t.description||"")},[t.description]),ye=a.useCallback(()=>w!==(t.description||""),[w,t.description]),Ge=a.useCallback(async()=>{if(!(!o||k)){if(!ye()){it();return}_(!0);try{await o(t.id,{description:w.trim()||void 0}),r(`Updated ${t.id}`,"success"),P(!1)}catch(ge){r(`Failed to update ${t.id}: ${fe(ge)}`,"error")}finally{_(!1)}}},[o,t.id,w,k,ye,it,r]),Ne=a.useCallback(ge=>{ge.key==="Enter"&&!ge.shiftKey?(ge.preventDefault(),Ge()):ge.key==="Escape"&&(ge.preventDefault(),it())},[Ge,it]),at=a.useCallback(()=>{setTimeout(()=>{const ge=document.activeElement;ge===Y.current||ge?.closest(".card-editing-content")||(ye()?Ge():it())},0)},[ye,Ge,it]),dt=a.useCallback(ge=>{ve&&(ge.stopPropagation(),Je(ge))},[ve,Je]),vt=a.useCallback(ge=>{ge.stopPropagation(),Je(ge)},[Je]),It=a.useCallback(ge=>{S(ge.target.value);const Oe=ge.target;Oe.style.height="auto",Oe.style.height=Oe.scrollHeight+"px"},[]),_t=a.useCallback(ge=>{ge.stopPropagation(),d&&d(t.id).then(()=>{r(`Archived ${t.id}`,"success")}).catch(Oe=>{r(`Failed to archive ${t.id}: ${fe(Oe)}`,"error")})},[r,d,t.id]),Mt=a.useCallback(ge=>{ge.stopPropagation(),m&&m(t.id).then(()=>{r(`Unarchived ${t.id}`,"success")}).catch(Oe=>{r(`Failed to unarchive ${t.id}: ${fe(Oe)}`,"error")})},[r,m,t.id]),zt=a.useCallback(ge=>{ge.stopPropagation(),c&&window.confirm(`Delete ${t.id}?`)&&c(t.id).then(()=>{r(`Deleted ${t.id}`,"success")}).catch(Oe=>{const ee=Kk(Oe);if(!ee||ee.dependentIds.length===0){r(`Failed to delete ${t.id}: ${fe(Oe)}`,"error");return}const Ie=ee.dependentIds.join(", ");window.confirm(`${t.id} is a dependency of ${Ie}.
596
+
597
+ Delete anyway by removing these dependency references first?`)&&c(t.id,{removeDependencyReferences:!0}).then(()=>{r(`Deleted ${t.id} after removing dependency references`,"success")}).catch(he=>{r(`Failed to delete ${t.id}: ${fe(he)}`,"error")})})},[r,c,t.id]),Nt=a.useCallback(ge=>{ge.stopPropagation(),u?.(t,"changes")},[t,u]),Pt=a.useCallback(ge=>{ge.stopPropagation(),T(Oe=>!Oe)},[]),tt=a.useCallback(ge=>{ge.stopPropagation(),t.missionId&&g&&g(t.missionId)},[t.missionId,g]),bt=a.useCallback(ge=>{ge.stopPropagation(),W(Oe=>!Oe)},[]),Ue=a.useCallback((ge,Oe)=>{ge.stopPropagation(),W(!1),p&&p(t.id,Oe).then(()=>{r(`Moved ${t.id} to ${ds[Oe]}`,"success")}).catch(ee=>{r(`Failed to move ${t.id}: ${fe(ee)}`,"error")})},[r,p,t.id]),ot=`card${x?" dragging":""}${s?" queued":""}${se?" agent-active":""}${Te?" failed":""}${Ve?" paused":""}${le?" stuck":""}${X?" awaiting-approval":""}${y?" file-drop-target":""}${j?" card-editing":""}${k?" card-saving":""}`;return j?e.jsx("div",{ref:A,className:ot,"data-id":t.id,onDoubleClick:dt,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:It,onKeyDown:Ne,onBlur:at,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:A,className:ot,"data-id":t.id,draggable:Le,onDragStart:Le?ce:void 0,onDragEnd:Le?K:void 0,onDragOver:Fe,onDragLeave:we,onDrop:Ee,onClick:Pe,onTouchStart:ze,onTouchMove:$e,onTouchEnd:He,onDoubleClick:dt,children:[e.jsxs("div",{className:"card-header",children:[e.jsx("span",{className:"card-id",children:t.id}),Ve&&e.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Ve&&t.status&&t.status!=="queued"&&e.jsx("span",{className:`card-status-badge card-status-badge--${t.column}${X?" awaiting-approval":""}${Sd.has(t.status)?" pulsing":""}${Te?" failed":""}${le?" stuck":""}`,children:le?"Stuck":X?"Awaiting Approval":t.status}),le&&(Ve||!t.status||t.status==="queued")&&e.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Ye&&e.jsx(Ph,{prInfo:st,issueInfo:Se}),et&&e.jsx("span",{className:`card-priority-badge card-priority-badge--${_e}`,children:_e}),t.executionMode==="fast"&&e.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),t.missionId&&e.jsxs("span",{className:"card-mission-badge",onClick:tt,title:`Mission: ${D??t.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[e.jsx(ts,{size:11}),Lk(D??t.missionId)]}),e.jsxs("div",{className:"card-header-actions",children:[ve&&e.jsx("button",{className:"card-edit-btn",onClick:vt,title:"Edit task","aria-label":"Edit task",children:e.jsx($n,{size:12})}),t.column==="triage"&&c&&e.jsx("button",{className:"card-delete-btn",onClick:zt,title:"Delete task","aria-label":"Delete task",children:e.jsx(qt,{size:12})}),t.column==="done"&&d&&e.jsx("button",{className:"card-archive-btn",onClick:_t,title:"Archive task","aria-label":"Archive task",children:"Archive"}),t.column==="archived"&&m&&e.jsx("button",{className:"card-unarchive-btn",onClick:Mt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),t.column==="in-progress"&&p&&e.jsxs("div",{className:"card-send-back",ref:z,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:bt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":N,children:["Send back",e.jsx(Ot,{size:10})]}),N&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:To["in-progress"].filter(ge=>ge!=="in-review").map(ge=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Oe=>Ue(Oe,ge),children:ds[ge]},ge))})]}),t.column==="in-review"&&p&&e.jsxs("div",{className:"card-send-back",ref:z,children:[e.jsxs("button",{className:"card-send-back-btn",onClick:bt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":N,children:["Move",e.jsx(Ot,{size:10})]}),N&&e.jsx("div",{className:"card-send-back-menu",role:"menu",children:To["in-review"].map(ge=>e.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Oe=>Ue(Oe,ge),children:ge==="done"?"Done (no merge)":ds[ge]},ge))})]}),t.size&&e.jsx("span",{className:`card-size-badge size-${t.size.toLowerCase()}`,children:t.size})]})]}),Te&&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:Ad(t.title,Md)||Ad(t.description,Md)||t.id}),me&&(()=>{const ge=ht.completed/ht.total*100;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"card-progress",children:[e.jsx("div",{className:"card-progress-bar",children:e.jsx("div",{className:"card-progress-fill",style:{width:`${ge}%`,backgroundColor:Hk[t.column]}})}),e.jsxs("span",{className:"card-progress-label",children:[ht.completed,"/",ht.total]})]}),e.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Pt,"aria-expanded":E,"aria-label":E?"Hide steps":"Show steps",children:[e.jsxs("span",{children:[ht.total," step",ht.total===1?"":"s"]}),e.jsx(Ot,{size:14,className:`card-steps-toggle-icon${E?" expanded":""}`})]}),E&&e.jsx("div",{className:"card-steps-list",children:ht.items.map(Oe=>e.jsxs("div",{className:"card-step-item",children:[e.jsx("span",{className:`card-step-dot card-step-dot--${Oe.status}`,"aria-hidden":"true"}),e.jsx("span",{className:`card-step-name${Oe.status==="done"?" completed":""}`,children:Oe.name}),Oe.source==="workflow"&&e.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${Oe.phase}`,title:"Workflow check",children:"workflow"})]},Oe.id))})]})})(),t.worktree&&(t.column==="in-progress"||t.column==="in-review")&&(()=>{const ge=Qe?.filesChanged;return ge==null||ge===0?null:e.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!u,children:[e.jsx(Sn,{size:12}),e.jsxs("span",{children:[ge," ",ge===1?"file":"files"," changed"]})]})})(),t.column==="done"&&(()=>{const ge=Qe?.filesChanged,Oe=t.mergeDetails?.filesChanged,ee=ge??Oe;if(ee!=null&&ee>0)return e.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!u,children:[e.jsx(Sn,{size:12}),e.jsxs("span",{children:[ee," ",ee===1?"file":"files"," changed"]})]});const Ie=t.modifiedFiles?.length;return Ie!=null&&Ie>0?e.jsxs("button",{type:"button",className:"card-session-files",onClick:Nt,disabled:!u,children:[e.jsx(Sn,{size:12}),e.jsxs("span",{children:[Ie," ",Ie===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(ge=>e.jsxs("span",{className:"card-dep-badge clickable",onClick:Oe=>void Me(Oe,ge),title:`Click to view ${ge}`,children:[e.jsx(Ji,{size:12,style:{verticalAlign:"middle"}})," ",ge]},ge))}),t.blockedBy&&e.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${t.blockedBy} (file overlap)`,children:[e.jsx(Si,{size:12,style:{verticalAlign:"middle"}})," ",t.blockedBy]}),(s||t.status==="queued")&&t.column!=="in-progress"&&e.jsxs("span",{className:"queued-badge",children:[e.jsx(Ki,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),t.assignedAgentId&&e.jsx("div",{className:"card-agent-row",children:e.jsxs("span",{className:`card-agent-badge${mt?" card-agent-badge--loading":""}`,title:`Assigned to ${$??t.assignedAgentId}`,children:[e.jsx(rn,{size:11}),e.jsx("span",{className:"card-agent-badge-text",children:Bk($??t.assignedAgentId,15)})]})}),e.jsx(nr,{slotId:"task-card-badge",projectId:n})]})}const Ed=10,Zk=300,Md=140;function Ad(t,n){return t?t.length>n?t.slice(0,n)+"…":t:""}const Kr=a.memo(Xk,Qk);Kr.displayName="TaskCard";function ew({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(rg,{size:14}):e.jsx(Vs,{size:14})}),e.jsx("span",{className:"worktree-label",children:t})]}),n.map(p=>e.jsx(Kr,{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(Kr,{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 Th=a.memo(ew);Th.displayName="WorktreeGroup";function Pd(t){return t.toLowerCase().replace(/[-_./]/g,"")}function tw(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 nw(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 sw(t,n){const s=Pd(t),i=Pd(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&&tw(s,l)||s.length>=4&&nw(s,l,1))return!0;return!1}function iw(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=>sw(l,r))})}const aw={sm:16,md:20,lg:24};function rw({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 Id({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 _d({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 lw({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 ow({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 cw({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 Al({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 dw({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 uw={anthropic:{component:rw,color:"#d4a27f"},"claude-cli":{component:dw,color:"#d4a27f",label:"Anthropic — via Claude CLI"},openai:{component:Id,color:"#10a37f"},"openai-codex":{component:Id,color:"#10a37f",label:"OpenAI Codex"},google:{component:_d,color:"#4285f4"},gemini:{component:_d,color:"#4285f4"},ollama:{component:lw,color:"#fff"},minimax:{component:ow,color:"#E73562"},zai:{component:cw,color:"#1A6DFF"},kimi:{component:Al,color:"#6C5CE7"},moonshot:{component:Al,color:"#6C5CE7"},"kimi-coding":{component:Al,color:"#6C5CE7",label:"Kimi"}};function ns({provider:t,size:n="sm"}){const s=t.toLowerCase(),i=uw[s],r=i?.component,l=i?.color??"var(--text-muted)",o=i?.label,d=aw[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(hg,{size:d})})}function Yt({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(""),[v,y]=a.useState(0),[M,j]=a.useState(null),[P,w]=a.useState(null),S=a.useRef(null),k=a.useRef(null),_=a.useRef(null),E=a.useRef(null),T=a.useRef(null),D=a.useMemo(()=>iw(t,b),[t,b]),Z=a.useMemo(()=>D.reduce((K,de)=>((K[de.provider]??=[]).push(de),K),{}),[D]),$=a.useMemo(()=>{const K=[];for(const de of c){const Fe=de.indexOf("/");if(Fe===-1)continue;const we=de.slice(0,Fe),Ee=de.slice(Fe+1),ie=D.find(Pe=>Pe.provider===we&&Pe.id===Ee);ie&&K.push({model:ie,fullId:de})}return K},[c,D]),R=a.useMemo(()=>{const K=Object.entries(Z),de=new Set(d);return K.sort(([Fe],[we])=>{const Ee=de.has(Fe),ie=de.has(we);if(Ee&&!ie)return-1;if(!Ee&&ie)return 1;if(Ee&&ie){const Pe=d.indexOf(Fe),ze=d.indexOf(we);if(Pe!==ze)return Pe-ze}return Fe.localeCompare(we)})},[Z,d]),N=typeof h=="string"&&h.length>0,W=a.useMemo(()=>{if(!n||N&&n===h)return null;const K=n.indexOf("/");return K===-1?null:n.slice(0,K)},[N,h,n]),Y=a.useMemo(()=>{const K=[];return N&&K.push({type:"no-change",value:h,label:g}),K.push({type:"default",value:"",label:"Use default"}),K},[N,g,h]),H=a.useMemo(()=>{const K=[...Y];for(const{model:de,fullId:Fe}of $)K.push({type:"favorite",value:Fe,label:de.name,provider:de.provider});return R.forEach(([de,Fe])=>{K.push({type:"provider",value:`__group_${de}`,label:de,provider:de}),Fe.forEach(we=>{K.push({type:"model",value:`${we.provider}/${we.id}`,label:we.name,provider:we.provider})})}),K},[$,R,Y]),A=a.useMemo(()=>{if(N&&n===h)return g;if(!n)return"Use default";const K=n.indexOf("/");if(K===-1)return n;const de=n.slice(0,K),Fe=n.slice(K+1);return t.find(Ee=>Ee.provider===de&&Ee.id===Fe)?.name||n},[N,g,h,n,t]),z=a.useMemo(()=>H.findIndex(K=>K.value===n),[H,n]),J=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}},[]),C=a.useCallback(()=>{const{height:K}=J(),de=typeof window.matchMedia=="function",Fe=de?window.matchMedia("(max-width: 640px)").matches:!1,we=de?window.matchMedia("(max-width: 768px)").matches:!1;return K<=0?320:Fe?Math.min(K*.6,360):we?Math.min(K*.7,420):320},[J]),q=a.useCallback(()=>{const K=k.current;if(!K)return;const de=K.getBoundingClientRect(),{width:Fe,height:we,offsetTop:Ee,offsetLeft:ie}=J(),Pe=16,ze=16,$e=4,He=C(),Me=de.bottom-Ee,Te=de.top-Ee,Ve=de.left-ie,_e=we-Me,et=Te,le=Math.max(_e-ze-$e,160),X=Math.max(et-ze-$e,160),ke=_e<He&&et>_e,se=Math.max(Math.min(ke?X:le,He),160),Le=Math.min(de.width,Fe-Pe*2),ve=Math.min(Math.max(Ve,Pe),Fe-Pe-Le)+ie,Ye=ke?Math.max(ze+Ee,Te-se-$e+Ee):Math.min(Me+$e+Ee,we+Ee-ze-se);j({top:Ye,left:ve,width:Le,maxHeight:se})},[J,C]);a.useEffect(()=>{w(document.body)},[]),a.useEffect(()=>{if(p){const K=H.findIndex((de,Fe)=>Fe>=(z>=0?z:0)&&de.type!=="provider");y(K>=0?K:0)}},[p,H,z]),a.useEffect(()=>{if(!p)return;q();const K=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(K)},[p,q]),a.useEffect(()=>{if(!p)return;const K=()=>q();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,q]),a.useEffect(()=>{if(!p)return;const K=de=>{const Fe=de.target,we=S.current?.contains(Fe),Ee=_.current?.contains(Fe);!we&&!Ee&&(f(!1),x(""))};return document.addEventListener("mousedown",K),()=>document.removeEventListener("mousedown",K)},[p]);const oe=a.useCallback(K=>{switch(K.key){case"ArrowDown":if(K.preventDefault(),!p)f(!0);else{let de=v;for(let Fe=1;Fe<=H.length;Fe++){const we=(v+Fe)%H.length;if(H[we]?.type!=="provider"){de=we;break}}y(de)}break;case"ArrowUp":if(K.preventDefault(),p){let de=v;for(let Fe=1;Fe<=H.length;Fe++){const we=(v-Fe+H.length)%H.length;if(H[we]?.type!=="provider"){de=we;break}}y(de)}break;case"Enter":if(K.preventDefault(),p){const de=H[v];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,v,H,s]),O=a.useCallback(K=>{s(K),f(!1),x("")},[s]),V=a.useCallback(()=>{x(""),E.current?.focus()},[]),F=a.useCallback(()=>{r||f(K=>!K)},[r]);a.useEffect(()=>{if(p&&T.current){const K=T.current.querySelector(`[data-index="${v}"]`);K&&typeof K.scrollIntoView=="function"&&K.scrollIntoView({block:"nearest"})}},[v,p]);const ue=b.length>0,ce=p&&M?e.jsxs("div",{ref:_,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:oe,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:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:K=>x(K.target.value),onClick:K=>K.stopPropagation()}),ue&&e.jsx("button",{type:"button",className:"model-combobox-clear",onClick:V,"aria-label":"Clear filter",children:"×"})]}),e.jsxs("div",{className:"model-combobox-results-count",children:[D.length," model",D.length!==1?"s":""]}),e.jsxs("div",{ref:T,className:"model-combobox-list",children:[Y.map((K,de)=>e.jsx("div",{"data-index":de,className:`model-combobox-option ${v===de?"model-combobox-option--highlighted":""} ${n===K.value?"model-combobox-option--selected":""}`,onClick:()=>O(K.value),onMouseEnter:()=>y(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}`)),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-combobox-divider"}),$.map(({model:K,fullId:de},Fe)=>{const we=Fe+Y.length,Ee=v===we,ie=n===de;return e.jsxs("div",{"data-index":we,className:`model-combobox-option model-combobox-option--favorite ${Ee?"model-combobox-option--highlighted":""} ${ie?"model-combobox-option--selected":""}`,onClick:()=>O(de),onMouseEnter:()=>y(we),role:"option","aria-selected":ie,children:[e.jsxs("span",{className:"model-combobox-option-main",children:[e.jsx("span",{className:"model-combobox-option-icon",children:e.jsx(ns,{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:Pe=>{Pe.stopPropagation(),u(de)},title:"Remove from favorites","aria-label":`Remove ${K.name} from favorites`,children:"★"})]},de)}),e.jsx("div",{className:"model-combobox-divider"})]}),R.map(([K,de])=>{const Fe=H.findIndex(ie=>ie.value===`__group_${K}`),we=d.includes(K),Ee=de.filter(ie=>{const Pe=`${ie.provider}/${ie.id}`;return!c.includes(Pe)});return Ee.length===0?null:e.jsxs("div",{className:"model-combobox-group",children:[e.jsxs("div",{className:"model-combobox-optgroup","data-index":Fe,children:[e.jsx(ns,{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 ${we?"model-combobox-optgroup-favorite--active":""}`,onClick:ie=>{ie.stopPropagation(),m(K)},title:we?"Remove from favorites":"Add to favorites","aria-label":we?`Remove ${K} from favorites`:`Add ${K} to favorites`,children:"★"})]}),Ee.map(ie=>{const Pe=`${ie.provider}/${ie.id}`,ze=H.findIndex(Te=>Te.value===Pe),$e=v===ze,He=n===Pe,Me=c.includes(Pe);return e.jsxs("div",{"data-index":ze,className:`model-combobox-option ${$e?"model-combobox-option--highlighted":""} ${He?"model-combobox-option--selected":""}`,onClick:()=>O(Pe),onMouseEnter:()=>y(ze),role:"option","aria-selected":He,children:[e.jsx("span",{className:"model-combobox-option-text",children:ie.name}),e.jsx("span",{className:"model-combobox-option-id",children:ie.id}),u&&e.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Me?"model-combobox-option-favorite--active":""}`,onClick:Te=>{Te.stopPropagation(),u(Pe)},title:Me?"Remove from favorites":"Add to favorites","aria-label":Me?`Remove ${ie.name} from favorites`:`Add ${ie.name} to favorites`,children:Me?"★":"☆"})]},Pe)})]},K)}),D.length===0&&ue&&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:oe,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:[W&&e.jsx("span",{className:"model-combobox-trigger-icon",children:e.jsx(ns,{provider:W,size:"sm"})}),e.jsx("span",{className:"model-combobox-trigger-text",children:A||i}),e.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),P&&ce?_a.createPortal(ce,P):null]})}function dc(t,n){return typeof n!="string"||n.length===0?t:`kb:${n}:${t}`}function Rn(t,n){return typeof window>"u"?null:window.localStorage.getItem(dc(t,n))}function us(t,n,s){typeof window>"u"||window.localStorage.setItem(dc(t,s),n)}function qa(t,n){typeof window>"u"||window.localStorage.removeItem(dc(t,n))}const xa="kb-quick-entry-text",mw=["image/png","image/jpeg","image/gif","image/webp"];function Pl(t,n){return t&&n?`${t}/${n}`:""}function Il(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 $h({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"&&Rn(xa,o)||""),[f,b]=a.useState(!1),[x,v]=a.useState(!1),[y,M]=a.useState(!1),j=a.useRef(null),P=a.useRef(null),w=a.useRef(!1),S=a.useRef(o),[k,_]=a.useState([]),E=a.useRef([]),[T,D]=a.useState([]),[Z,$]=a.useState(!1),[R,N]=a.useState(""),[W,Y]=a.useState(null),[H,A]=a.useState([]),[z,J]=a.useState(void 0),[C,q]=a.useState(!1),[oe,O]=a.useState(!1),[V,F]=a.useState(!1),[ue,ce]=a.useState(null),[K,de]=a.useState(void 0),[Fe,we]=a.useState(void 0),[Ee,ie]=a.useState(void 0),[Pe,ze]=a.useState(void 0),[$e,He]=a.useState(void 0),[Me,Te]=a.useState(void 0),Ve=a.useRef(null),_e=a.useRef(null),et=a.useRef(null),le=a.useRef(null),[X,ke]=a.useState(null),[se,Le]=a.useState(null),ve=a.useRef(null),Ye=a.useRef(null),[mt,ht]=a.useState(null),[me]=a.useState(()=>typeof document<"u"?document.body:null),[te,je]=a.useState(!1),[Ae,Qe]=a.useState(null),[be,st]=a.useState(i??[]),[Se,Je]=a.useState([]),[it,ye]=a.useState([]),[Ge,Ne]=a.useState(null),[at,dt]=a.useState(void 0),[vt,It]=a.useState(!1),[_t,Mt]=a.useState(!1),[zt,Nt]=a.useState(!1),Pt=a.useRef(null),tt=a.useRef(null),[bt,Ue]=a.useState(null),ot=m??Se,ge=c??it,Oe=!t;a.useEffect(()=>{if(i)st(i),je(!1),Qe(null);else{let ae=!1;return je(!0),Qe(null),Vn().then(De=>{ae||(st(De.models),m||Je(De.favoriteProviders),c||ye(De.favoriteModels))}).catch(De=>{ae||Qe(fe(De)||"Failed to load models")}).finally(()=>{ae||je(!1)}),Xi(o).then(De=>{ae||Ne(De)}).catch(()=>{}),()=>{ae=!0}}},[i,m,c,o]);const ee=Pl(K,Fe),Ie=Pl(Ee,Pe),xt=Pl($e,Me),he=!!(K&&Fe),Be=!!(Ee&&Pe),gt=!!($e&&Me),Kt=Number(he)+Number(Be)+Number(gt),yn=at?Ge?.modelPresets?.find(ae=>ae.id===at)?.name??"Models":Kt>0?`${Kt} model${Kt===1?"":"s"}`:"Models",mn=a.useCallback((ae,De)=>{if(!ae||!De)return"Using default";const ct=be.find(St=>St.provider===ae&&St.id===De);return ct?`${ct.provider}/${ct.id}`:`${ae}/${De}`},[be]);a.useEffect(()=>{p(Rn(xa,o)||"")},[o]),a.useEffect(()=>{typeof window<"u"&&us(xa,g,o)},[g,o]),a.useEffect(()=>{S.current!==o&&(S.current=o,A([]),J(void 0),Y(null),q(!1),ke(null))},[o]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{E.current=k},[k]),a.useEffect(()=>()=>{E.current.forEach(ae=>URL.revokeObjectURL(ae.previewUrl))},[]);const Kn=a.useCallback(()=>{const ae=j.current;if(!ae)return;ae.style.height="auto";const De=Math.min(ae.scrollHeight,200);ae.style.height=`${De}px`},[]);a.useEffect(()=>{x&&Kn()},[g,x,Kn]),a.useEffect(()=>{if(!f&&g===""&&j.current){const ae=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(ae)}},[f,g]),a.useEffect(()=>{Z||N("")},[Z]),a.useEffect(()=>{if(!_t)return;const ae=De=>{const ct=De.target,St=Pt.current?.contains(ct),Et=tt.current?.contains(ct);!St&&!Et&&Mt(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[_t]),a.useEffect(()=>{if(!V)return;const ae=De=>{const ct=De.target,St=Ve.current?.contains(ct),Et=_e.current?.contains(ct),cn=ct instanceof Element&&ct.closest?.(".model-combobox-dropdown--portal")!=null;!St&&!Et&&!cn&&(F(!1),ce(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[V]),a.useEffect(()=>{if(!C)return;const ae=De=>{const ct=De.target;et.current?.contains(ct)||le.current?.contains(ct)||(q(!1),ke(null))};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[C]);const Wt=a.useCallback(()=>{k.forEach(ae=>URL.revokeObjectURL(ae.previewUrl)),_([]),P.current&&(P.current.value=""),p(""),D([]),Y(null),q(!1),ke(null),de(void 0),we(void 0),ie(void 0),ze(void 0),He(void 0),Te(void 0),dt(void 0),It(!1),$(!1),F(!1),Le(null),ce(null),Mt(!1),Nt(!1),v(!1),M(!1),w.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&qa(xa,o)},[k,o]),Cn=a.useCallback(ae=>{if(!ae||ae.length===0)return;const De=[];for(let ct=0;ct<ae.length;ct++){const St=ae[ct];mw.includes(St.type)&&De.push({file:St,previewUrl:URL.createObjectURL(St)})}De.length>0&&_(ct=>[...ct,...De])},[]),Tn=a.useCallback(ae=>{f||Cn(ae.clipboardData?.files)},[Cn,f]),as=a.useCallback(ae=>{_(De=>{const ct=De[ae];return ct&&URL.revokeObjectURL(ct.previewUrl),De.filter((St,Et)=>Et!==ae)})},[]),Ut=a.useCallback(async()=>{const ae=g.trim();if(!(!ae||f||!t)){b(!0);try{const De=await t({description:ae,column:"triage",dependencies:T.length?T:void 0,...W?{assignedAgentId:W}:{},modelPresetId:at,modelProvider:he?K:void 0,modelId:he?Fe:void 0,validatorModelProvider:Be?Ee:void 0,validatorModelId:Be?Pe:void 0,planningModelProvider:gt?$e:void 0,planningModelId:gt?Me:void 0,...vt?{executionMode:"fast"}:{}});if(De&&k.length>0){const ct=[];for(const St of k)try{await Ha(De.id,St.file,o)}catch{ct.push(St.file.name)}ct.length>0&&n(`Failed to upload: ${ct.join(", ")}`,"error")}Wt()}catch(De){n(fe(De)||"Failed to create task","error")}finally{b(!1)}}},[g,f,t,T,W,he,K,Fe,Be,Ee,Pe,gt,$e,Me,k,o,n,Wt,vt]),Xt=a.useCallback(ae=>{if(ae.key==="Enter"){if(ae.shiftKey&&x)return;ae.preventDefault(),Ut()}else if(ae.key==="Escape"){if(ae.preventDefault(),ue){ce(null);return}if(V){F(!1),Le(null);return}if(Z){$(!1);return}if(_t){Mt(!1);return}if(C){q(!1),ke(null);return}g.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&qa(xa,o)),v(!1),M(!1),j.current?.blur()}},[Ut,g,x,Z,C,V,ue,_t,o,M]),hn=a.useCallback(()=>{w.current&&(w.current=!1)},[]),gn=a.useCallback(()=>{d&&v(!0)},[d]),En=a.useCallback(ae=>{D(De=>De.includes(ae)?De.filter(ct=>ct!==ae):[...De,ae])},[]),an=a.useCallback(()=>{const ae=window.visualViewport;return ae&&ae.width>0&&ae.height>0?{width:ae.width,height:ae.height,offsetTop:ae.offsetTop,offsetLeft:ae.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ft=a.useCallback(()=>{const ae=Ve.current;if(!ae)return;const De=ae.getBoundingClientRect(),{width:ct,height:St,offsetTop:Et,offsetLeft:cn}=an(),Gt=16,un=16,fn=4,kn=ct<=768,In=Math.min(kn?St*.6:St*.5,360),ps=kn?Math.min(ct-Gt*2,360):Math.max(De.width,240),On=Math.min(ps,Math.max(ct-Gt*2,200)),Jn=De.top-Et,Bn=De.bottom-Et,Yn=De.left-cn,bn=St-Bn,Un=Jn,fs=Math.max(bn-un-fn,160),Fs=Math.max(Un-un-fn,160),gs=bn<In&&Un>bn,wn=Math.max(Math.min(gs?Fs:fs,In),160),Qn=Math.min(Math.max(Yn,Gt),ct-Gt-On)+cn,bs=gs?Math.max(un+Et,Jn-wn-fn+Et):Math.min(Bn+fn+Et,St+Et-un-wn);Le({top:bs,left:Qn,width:On,maxHeight:wn})},[an]),pn=a.useCallback(()=>{const ae=Pt.current?.querySelector(".refine-button");if(!ae)return;const De=ae.getBoundingClientRect(),{width:ct,height:St,offsetTop:Et,offsetLeft:cn}=an(),Gt=8,un=12,fn=4,kn=Math.min(200,Math.max(St-un*2,160)),In=Math.min(200,ct-Gt*2),ps=De.top-Et,On=De.bottom-Et,Jn=De.left-cn,Bn=St-On,Yn=ps,bn=Bn<kn&&Yn>Bn,Un=Math.min(Math.max(Jn,Gt),ct-Gt-In)+cn,fs=bn?Math.max(un+Et,ps-kn-fn+Et):Math.min(On+fn+Et,St+Et-un-kn);Ue({top:fs,left:Un})},[an]),Mn=a.useCallback(()=>{const ae=ve.current;if(!ae)return;const De=ae.getBoundingClientRect(),{width:ct,height:St,offsetTop:Et,offsetLeft:cn}=an(),Gt=16,un=16,fn=4,kn=ct<=768,In=Math.min(kn?St*.6:St*.5,320),ps=kn?Math.min(ct-Gt*2,360):Math.max(De.width,280),On=Math.min(ps,Math.max(ct-Gt*2,240)),Jn=De.top-Et,Bn=De.bottom-Et,Yn=De.left-cn,bn=St-Bn,Un=Jn,fs=Math.max(bn-un-fn,200),Fs=Math.max(Un-un-fn,200),gs=bn<In&&Un>bn,wn=Math.max(Math.min(gs?Fs:fs,In),200),Qn=Math.min(Math.max(Yn,Gt),ct-Gt-On)+cn,bs=gs?Math.max(un+Et,Jn-wn-fn+Et):Math.min(Bn+fn+Et,St+Et-un-wn);ht({top:bs,left:Qn,width:On,maxHeight:wn})},[an]),jn=a.useCallback(()=>{const ae=et.current?.querySelector("button");if(!ae)return;const De=ae.getBoundingClientRect(),{width:ct,height:St,offsetTop:Et,offsetLeft:cn}=an(),Gt=16,un=16,fn=4,kn=ct<=768,In=Math.min(kn?St*.6:St*.5,320),ps=kn?Math.min(ct-Gt*2,280):Math.max(De.width,240),On=Math.min(ps,Math.max(ct-Gt*2,200)),Jn=De.top-Et,Bn=De.bottom-Et,Yn=De.left-cn,bn=St-Bn,Un=Jn,fs=Math.max(bn-un-fn,160),Fs=Math.max(Un-un-fn,160),gs=bn<In&&Un>bn,wn=Math.max(Math.min(gs?Fs:fs,In),160),Qn=Math.min(Math.max(Yn,Gt),ct-Gt-On)+cn,bs=gs?Math.max(un+Et,Jn-wn-fn+Et):Math.min(Bn+fn+Et,St+Et-un-wn);ke({top:bs,left:Qn,width:On,maxHeight:wn})},[an]);a.useEffect(()=>{if(!V)return;const ae=()=>Ft();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const De=window.visualViewport;return De&&(De.addEventListener("resize",ae),De.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),De&&(De.removeEventListener("resize",ae),De.removeEventListener("scroll",ae))}},[V,Ft]),a.useEffect(()=>{if(!_t)return;const ae=()=>pn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const De=window.visualViewport;return De&&(De.addEventListener("resize",ae),De.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),De&&(De.removeEventListener("resize",ae),De.removeEventListener("scroll",ae))}},[_t,pn]),a.useEffect(()=>{if(!Z)return;const ae=()=>Mn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const De=window.visualViewport;return De&&(De.addEventListener("resize",ae),De.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),De&&(De.removeEventListener("resize",ae),De.removeEventListener("scroll",ae))}},[Z,Mn]),a.useEffect(()=>{if(!C)return;const ae=()=>jn();window.addEventListener("resize",ae),window.addEventListener("scroll",ae,!0);const De=window.visualViewport;return De&&(De.addEventListener("resize",ae),De.addEventListener("scroll",ae)),()=>{window.removeEventListener("resize",ae),window.removeEventListener("scroll",ae,!0),De&&(De.removeEventListener("resize",ae),De.removeEventListener("scroll",ae))}},[C,jn]);const zn=a.useCallback(ae=>{const De=Il(ae);He(De.provider),Te(De.modelId)},[]),rs=a.useCallback(ae=>{const De=Il(ae);de(De.provider),we(De.modelId)},[]),Gn=a.useCallback(ae=>{const De=Il(ae);ie(De.provider),ze(De.modelId)},[]),Pn=a.useCallback(async ae=>{if(u){u(ae);return}const De=Se,St=De.includes(ae)?De.filter(Et=>Et!==ae):[ae,...De];Je(St);try{await Jt({favoriteProviders:St,favoriteModels:it})}catch{Je(De)}},[Se,it,u]),G=a.useCallback(async ae=>{if(h){h(ae);return}const De=it,St=De.includes(ae)?De.filter(Et=>Et!==ae):[ae,...De];ye(St);try{await Jt({favoriteProviders:Se,favoriteModels:St})}catch{ye(De)}},[it,Se,h]),Ke=a.useCallback(()=>{const ae=g.trim();if(!ae){n("Enter a description first","error");return}r?.(ae),Wt()},[g,r,n,Wt]),I=a.useCallback(()=>{const ae=g.trim();if(!ae){n("Enter a description first","error");return}l?.(ae),Wt()},[g,l,n,Wt]),B=a.useCallback(()=>{Ut()},[Ut]),re=a.useCallback(async ae=>{const De=g.trim();if(!(!De||zt)){Mt(!1),Nt(!0);try{const ct=await xh(De,ae,o);p(ct),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(ct){const St=vh(ct);n(St,"error")}finally{Nt(!1)}}},[g,zt,n,o]),pe=(ae,De)=>ae.length>De?ae.slice(0,De)+"…":ae,xe=a.useCallback(async()=>{if(i){st(i),Qe(null),je(!1);return}je(!0),Qe(null);try{const ae=await Vn();st(ae.models),m||Je(ae.favoriteProviders),c||ye(ae.favoriteModels)}catch(ae){Qe(fe(ae)||"Failed to load models")}finally{je(!1)}},[i,m,c]),Re=a.useCallback(async()=>{if(H.length>0&&z===o){q(!0),jn();return}O(!0);try{const ae=await da(void 0,o);A(ae),J(o),q(!0),jn()}catch(ae){const De=fe(ae);n(De?`Failed to load agents: ${De}`:"Failed to load agents","error"),q(!1)}finally{O(!1)}},[H.length,z,o,n,jn]),kt=(W?H.find(ae=>ae.id===W):void 0)?.name??W,We=y,wt=a.useCallback(()=>{M(ae=>{const De=!ae;return v(De),De})},[]);return e.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[e.jsx("div",{className:"description-with-refine",children:e.jsxs("div",{className:"quick-entry-main-row",children:[e.jsx("div",{className:"quick-entry-textarea-wrap",children:e.jsx("textarea",{ref:j,className:`quick-entry-input ${x?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ae=>p(ae.target.value),onKeyDown:Xt,onPaste:Tn,onFocus:gn,onBlur:hn,disabled:f||Oe,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),e.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:wt,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?e.jsx(qs,{size:14}):e.jsx(Ot,{size:14})})]})}),e.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!We,"aria-hidden":!We,children:[We&&!f&&e.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Ke,onMouseDown:ae=>ae.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[e.jsx(Ws,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:I,onMouseDown:ae=>ae.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[e.jsx(il,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),e.jsxs("div",{className:"refine-trigger-wrap",ref:Pt,children:[e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${zt?"refine-button--loading":""}`,onClick:()=>{Mt(ae=>{const De=!ae;return De?pn():Ue(null),De})},disabled:!g.trim()||zt,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),zt?"Refining...":"Refine"]}),_t&&me&&bt&&_a.createPortal(e.jsxs("div",{ref:tt,className:"refine-menu refine-menu--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${bt.top}px`,left:`${bt.left}px`},children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>re("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:()=>re("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:()=>re("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:()=>re("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"})]})]}),me)]}),e.jsx("div",{className:"dep-trigger-wrap",children:e.jsxs("button",{ref:ve,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ae=>{const De=!ae;return De?(F(!1),Le(null),ce(null),q(!1),Mn()):ht(null),De})},children:[e.jsx(Ji,{size:12,style:{verticalAlign:"middle"}}),T.length>0?`${T.length} deps`:"Deps"]})}),Z&&me&&mt&&(()=>{const ae=R.toLowerCase(),De=(ae?s.filter(ct=>ct.id.toLowerCase().includes(ae)||ct.title&&ct.title.toLowerCase().includes(ae)||ct.description&&ct.description.toLowerCase().includes(ae)):[...s]).sort((ct,St)=>{const Et=St.createdAt.localeCompare(ct.createdAt);if(Et!==0)return Et;const cn=parseInt(ct.id.slice(ct.id.lastIndexOf("-")+1),10)||0;return(parseInt(St.id.slice(St.id.lastIndexOf("-")+1),10)||0)-cn});return _a.createPortal(e.jsxs("div",{ref:Ye,className:"dep-dropdown dep-dropdown--portal",onMouseDown:ct=>ct.preventDefault(),style:{position:"fixed",top:`${mt.top}px`,left:`${mt.left}px`,width:`${mt.width}px`,maxHeight:mt.maxHeight?`${mt.maxHeight}px`:void 0,overflowY:mt.maxHeight?"auto":void 0},children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:R,onChange:ct=>N(ct.target.value),onClick:ct=>ct.stopPropagation()}),De.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):De.map(ct=>e.jsxs("div",{className:`dep-dropdown-item${T.includes(ct.id)?" selected":""}`,onMouseDown:St=>St.preventDefault(),onClick:()=>En(ct.id),children:[e.jsx("span",{className:"dep-dropdown-id",children:ct.id}),e.jsx("span",{className:"dep-dropdown-title",children:pe(ct.title||ct.description||ct.id,60)})]},ct.id))]}),me)})(),e.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>P.current?.click(),children:[e.jsx(kb,{size:12,style:{verticalAlign:"middle"}}),k.length>0?`Attach (${k.length})`:"Attach"]}),e.jsxs("button",{ref:Ve,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),q(!1),ce(null),F(!0),Ft()},children:[e.jsx(Lr,{size:12,style:{verticalAlign:"middle"}}),yn]}),e.jsx("div",{className:"agent-trigger-wrap",ref:et,children:e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{C?(q(!1),ke(null)):Re()},"data-testid":"quick-entry-agent-button",children:[e.jsx(rn,{size:12,style:{verticalAlign:"middle"}}),kt?` ${kt}`:" Agent"]})}),C&&me&&X&&_a.createPortal(e.jsxs("div",{ref:le,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ae=>ae.preventDefault(),style:{position:"fixed",top:`${X.top}px`,left:`${X.left}px`,width:`${X.width}px`,maxHeight:X.maxHeight?`${X.maxHeight}px`:void 0,overflowY:X.maxHeight?"auto":void 0},children:[e.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),oe&&e.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!oe&&H.filter(ae=>ae.state!=="terminated").map(ae=>e.jsxs("div",{className:`dep-dropdown-item${W===ae.id?" selected":""}`,onMouseDown:De=>De.preventDefault(),onClick:()=>{Y(ae.id===W?null:ae.id),q(!1),ke(null)},children:[e.jsx(rn,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:ae.role}),e.jsx("span",{className:"dep-dropdown-title",children:ae.name})]},ae.id)),!oe&&H.filter(ae=>ae.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),W&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:ae=>ae.preventDefault(),onClick:()=>{Y(null),q(!1),ke(null)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),me),e.jsx("button",{type:"button",className:`btn btn-sm ${vt?"btn-primary":""}`,onClick:()=>It(ae=>!ae),onMouseDown:ae=>ae.preventDefault(),"aria-pressed":vt,"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:B,onMouseDown:ae=>ae.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[e.jsx(rh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),k.length>0&&e.jsx("div",{className:"inline-create-previews",children:k.map((ae,De)=>e.jsxs("div",{className:"inline-create-preview",children:[e.jsx("img",{src:ae.previewUrl,alt:ae.file.name}),e.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>as(De),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${De}`,children:"×"})]},ae.previewUrl))}),V&&me&&se&&_a.createPortal(e.jsx("div",{ref:_e,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ae=>ae.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${se.top}px`,left:`${se.left}px`,width:`${se.width}px`,maxHeight:se.maxHeight?`${se.maxHeight}px`:void 0,overflowY:se.maxHeight?"auto":void 0},children:ue===null?e.jsxs("div",{className:"model-menu-items",children:[e.jsxs("button",{type:"button",className:`model-menu-item ${gt?"model-menu-item--active":""}`,onClick:()=>ce("plan"),"data-testid":"model-menu-plan",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Ws,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),e.jsx("span",{className:"model-menu-item-value",children:gt?mn($e,Me):"Using default"}),e.jsx(on,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${he?"model-menu-item--active":""}`,onClick:()=>ce("executor"),"data-testid":"model-menu-executor",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Dn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),e.jsx("span",{className:"model-menu-item-value",children:he?mn(K,Fe):"Using default"}),e.jsx(on,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),e.jsxs("button",{type:"button",className:`model-menu-item ${Be?"model-menu-item--active":""}`,onClick:()=>ce("validator"),"data-testid":"model-menu-validator",children:[e.jsxs("span",{className:"model-menu-item-label",children:[e.jsx(Lr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Validator"]}),e.jsx("span",{className:"model-menu-item-value",children:Be?mn(Ee,Pe):"Using default"}),e.jsx(on,{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:()=>ce(null),"data-testid":"model-submenu-back",children:[e.jsx(Ot,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),e.jsxs("div",{className:"model-submenu-header",children:[ue==="plan"&&"Plan Model",ue==="executor"&&"Executor Model",ue==="validator"&&"Validator Model"]}),e.jsx(Yt,{models:be,value:ue==="plan"?xt:ue==="executor"?ee:Ie,onChange:ue==="plan"?zn:ue==="executor"?rs:Gn,placeholder:"Using default",disabled:te,id:`model-${ue}-select`,label:`${ue} model`,favoriteProviders:ot,onToggleFavorite:Pn,favoriteModels:ge,onToggleModelFavorite:G}),Ae&&e.jsxs("div",{className:"model-submenu-error",children:[e.jsx("span",{children:Ae}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:xe,children:"Retry"})]})]})}),me)]}),e.jsx("input",{ref:P,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ae=>{Cn(ae.target.files),ae.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),e.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function hw(t){const n=t.replace(/\/+$/,"").split("/");return n[n.length-1]||t}function pw(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 fw(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=pw(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:hw(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 Rd=100,_l=50,Td=25;function gw({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:v,onToggleCollapse:y,allTasks:M,availableModels:j,onPlanningMode:P,onSubtaskBreakdown:w,onOpenDetailWithTab:S,favoriteProviders:k,favoriteModels:_,onToggleFavorite:E,onToggleModelFavorite:T,isSearchActive:D,taskStuckTimeoutMs:Z,onOpenMission:$,lastFetchTimeMs:R,workflowStepNameLookup:N}){const[W,Y]=a.useState(!1),[H,A]=a.useState(_l),[z,J]=a.useState(!1),[C,q]=a.useState(!1),oe=a.useRef(null),O=yk(n.length);a.useEffect(()=>{if(!z)return;function $e(Me){oe.current?.contains(Me.target)||J(!1)}function He(Me){Me.key==="Escape"&&J(!1)}return document.addEventListener("mousedown",$e),document.addEventListener("keydown",He),()=>{document.removeEventListener("mousedown",$e),document.removeEventListener("keydown",He)}},[z]);const V=t==="archived",F=V&&v,ue=!V&&!D&&t!=="in-progress"&&n.length>Rd;a.useEffect(()=>{A($e=>t==="in-progress"||V||n.length<=Rd?_l:Math.min(Math.max($e,_l),n.length))},[t,V,n.length]);const ce=a.useCallback($e=>{V||($e.preventDefault(),$e.dataTransfer.dropEffect="move",Y(!0))},[V]),K=a.useCallback($e=>{$e.currentTarget.contains($e.relatedTarget)||Y(!1)},[]),de=a.useCallback(async $e=>{$e.preventDefault(),Y(!1);const He=$e.dataTransfer.getData("text/plain");if(!He)return;const Me=n.find(Te=>Te.id===He);if(!(Me&&Me.column===t))try{await r(He,t)}catch(Te){o(fe(Te),"error")}},[t,r,o,n]),Fe=a.useMemo(()=>t!=="in-progress"?[]:fw(n,n,i),[t,n,i]),we=a.useMemo(()=>ue?n.slice(0,H):n,[ue,n,H]),Ee=Math.max(0,n.length-we.length),ie=a.useCallback(()=>{A($e=>Math.min($e+Td,n.length))},[n.length]),Pe=a.useCallback(async()=>{if(J(!1),!(n.length===0||!window.confirm(`Move all ${n.length} todo task${n.length===1?"":"s"} back to triage to be respecified?`))){q(!0);try{const He=await Promise.allSettled(n.map(Ve=>r(Ve.id,"triage"))),Me=He.filter(Ve=>Ve.status==="rejected").length,Te=He.length-Me;Me===0?o(`Moved ${Te} task${Te===1?"":"s"} to triage for respec`,"success"):o(`Moved ${Te} of ${He.length} tasks; ${Me} failed`,"error")}finally{q(!1)}}},[n,r,o]),ze=a.useCallback(async()=>{if(!(!x||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const He=await x();o(`Archived ${He.length} tasks`,"success")}catch(He){o(fe(He)||"Failed to archive tasks","error")}},[x,n.length,o]);return e.jsxs("div",{className:`column${W?" drag-over":""}${V?" column-archived":""}${F?" column-collapsed":""}`,"data-column":t,onDragOver:ce,onDragLeave:K,onDrop:de,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${O?" count-flash":""}`,children:n.length}),t==="in-review"&&u&&e.jsxs("label",{className:"auto-merge-toggle",title:c?"Auto-merge enabled":"Auto-merge disabled",children:[e.jsx("input",{type:"checkbox",checked:!!c,onChange:u}),e.jsx("span",{className:"toggle-slider"}),e.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),m&&e.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}),t==="done"&&x&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:ze,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:e.jsx(nl,{size:16})}),V&&y&&e.jsx("button",{className:"btn btn-icon btn-sm",onClick:y,title:v?"Expand archived tasks":"Collapse archived tasks","aria-label":v?"Expand archived tasks":"Collapse archived tasks",children:v?e.jsx(Ot,{size:16}):e.jsx(qs,{size:16})}),t==="todo"&&e.jsxs("div",{className:"column-menu",ref:oe,children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>J($e=>!$e),"aria-haspopup":"menu","aria-expanded":z,"aria-label":"Todo column actions",title:"Column actions",disabled:C,children:e.jsx(bg,{size:16})}),z&&e.jsx("div",{className:"column-menu-popover",role:"menu",children:e.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Pe(),disabled:n.length===0||C,children:["Respecify All",e.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Triage"]})]})})]})]}),!F&&e.jsx("p",{className:"column-desc",children:xk[t]}),!F&&e.jsxs("div",{className:"column-body",children:[t==="triage"&&d&&e.jsx($h,{onCreate:d,addToast:o,tasks:M??[],availableModels:j,onPlanningMode:P,onSubtaskBreakdown:w,projectId:s,autoExpand:!1,favoriteProviders:k,favoriteModels:_,onToggleFavorite:E,onToggleModelFavorite:T}),t==="in-progress"?Fe.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):Fe.map($e=>e.jsx(Th,{label:$e.label,activeTasks:$e.activeTasks,queuedTasks:$e.queuedTasks,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onOpenDetailWithTab:S,taskStuckTimeoutMs:Z,onOpenMission:$,lastFetchTimeMs:R,workflowStepNameLookup:N},$e.label)):n.length===0?e.jsx("div",{className:"empty-column",children:"No tasks"}):e.jsxs(e.Fragment,{children:[we.map($e=>e.jsx(Kr,{task:$e,projectId:s,onOpenDetail:l,addToast:o,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onOpenDetailWithTab:S,taskStuckTimeoutMs:Z,onOpenMission:$,onMoveTask:r,lastFetchTimeMs:R,workflowStepNameLookup:N},$e.id)),ue&&Ee>0&&e.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ie,children:["Load ",Math.min(Td,Ee)," more (",Ee," remaining)"]})]}),e.jsx(nr,{slotId:"board-column-footer",projectId:s})]})]})}const Fh=a.memo(gw);Fh.displayName="Column";function bw(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 xw(t,n){return t.length!==n.length?!1:t.every((s,i)=>s===n[i])}const $d=new Map;function vw(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 yw({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:v="",availableModels:y,onPlanningMode:M,onSubtaskBreakdown:j,onOpenDetailWithTab:P,favoriteProviders:w,favoriteModels:S,onToggleFavorite:k,onToggleModelFavorite:_,taskStuckTimeoutMs:E,onOpenMission:T,lastFetchTimeMs:D}){const[Z,$]=a.useState(!0),R=a.useRef(!1),{fetchBatch:N}=Mk(n),W=a.useRef(null),[Y,H]=a.useState($d),A=v.trim()!=="",z=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),J=a.useCallback(()=>{$(oe=>{const O=!oe;return!O&&!R.current&&x&&(R.current=!0,x()),O})},[x]),C=a.useMemo(()=>{const oe=Object.fromEntries(ki.map(F=>[F,[]]));for(const F of t)oe[F.column].push(F);const O=z.current,V={};for(const F of ki){const ue=bw(oe[F]);V[F]=xw(O[F],ue)?O[F]:ue}return z.current=V,V},[t]);a.useEffect(()=>{let oe=!1;return ol(n).then(O=>{if(oe)return;const V=new Map(O.map(F=>[F.id,F.name]));H(F=>vw(F,V)?F:V)}).catch(()=>{oe||H(O=>O.size===0?O:$d)}),()=>{oe=!0}},[n]);const q=a.useMemo(()=>t.filter(oe=>oe.prInfo||oe.issueInfo).map(oe=>oe.id),[t]);return a.useEffect(()=>{if(q.length!==0)return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{const oe=[];for(let O=0;O<q.length;O+=50)oe.push(q.slice(O,O+50));oe.forEach(O=>{N(O)})},500),()=>{W.current&&clearTimeout(W.current)}},[q,N]),e.jsx(e.Fragment,{children:e.jsx("main",{className:"board",id:"board",children:ki.map(oe=>e.jsx(Fh,{column:oe,tasks:C[oe],projectId:n,maxConcurrent:s,onMoveTask:i,onOpenDetail:r,addToast:l,globalPaused:u,onUpdateTask:h,onArchiveTask:g,onUnarchiveTask:p,onDeleteTask:f,allTasks:t,availableModels:y,onOpenDetailWithTab:P,favoriteProviders:w,favoriteModels:S,onToggleFavorite:k,onToggleModelFavorite:_,isSearchActive:A,taskStuckTimeoutMs:E,onOpenMission:T,lastFetchTimeMs:D,workflowStepNameLookup:Y,...oe==="triage"?{onQuickCreate:o,onNewTask:d,onPlanningMode:M,onSubtaskBreakdown:j}:{},...oe==="in-review"?{autoMerge:m,onToggleAutoMerge:c}:{},...oe==="done"?{onArchiveAllDone:b}:{},...oe==="archived"?{collapsed:Z,onToggleCollapse:J}:{}},oe))})})}const va={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Fd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Lo=["id","title","status","column","dependencies","progress"];function Dd(t){try{const n=Rn("kb-dashboard-list-columns",t);if(n){const i=JSON.parse(n).filter(r=>Lo.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Lo)}function Ld(t){try{const n=Rn("kb-dashboard-hide-done",t);if(n!==null)return n==="true"}catch{}return!1}function zd(t){try{const n=Rn("kb-dashboard-list-collapsed",t);if(n){const i=JSON.parse(n).filter(r=>ki.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Od(t){try{const n=Rn("kb-dashboard-selected-tasks",t);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function jw(t){return t.status==="executing"||t.column==="in-progress"}function Bd(t){const n=Rh(t);return n.total===0||!jw(t)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function kw({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:v,searchQuery:y="",lastFetchTimeMs:M}){const[j,P]=a.useState("id"),[w,S]=a.useState("desc"),[k,_]=a.useState(null),[E,T]=a.useState(null),[D,Z]=a.useState(null),R=sr()==="mobile",[N,W]=a.useState(()=>Dd(b)),[Y,H]=a.useState(()=>Ld(b)),[A,z]=a.useState(()=>zd(b));a.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-columns",JSON.stringify([...N]),b)},[b,N]),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([...A]),b)},[A,b]);const[J,C]=a.useState(!1),q=a.useRef(null),[oe,O]=a.useState(()=>Od(b));a.useEffect(()=>{W(Dd(b)),H(Ld(b)),z(zd(b)),O(Od(b))},[b]),a.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-selected-tasks",JSON.stringify([...oe]),b)},[b,oe]);const V=a.useCallback(te=>{O(je=>{const Ae=new Set(je);return Ae.has(te)?Ae.delete(te):Ae.add(te),Ae})},[]),F=a.useCallback(()=>{O(new Set)},[]),ue=a.useCallback(te=>{W(je=>{const Ae=new Set(je);return Ae.has(te)?Ae.size>1&&Ae.delete(te):Ae.add(te),Ae})},[]);a.useEffect(()=>{if(!J)return;const te=Ae=>{q.current&&!q.current.contains(Ae.target)&&C(!1)},je=Ae=>{Ae.key==="Escape"&&C(!1)};return document.addEventListener("mousedown",te),document.addEventListener("keydown",je),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",je)}},[J]);const ce={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},K=a.useCallback(te=>{j===te?S(je=>je==="asc"?"desc":"asc"):(P(te),S("asc"))},[j]),de=a.useCallback(te=>{Z(je=>je===te?null:te)},[]),Fe=a.useCallback(te=>{z(je=>{const Ae=new Set(je);return Ae.has(te)?Ae.delete(te):Ae.add(te),Ae})},[]),we=a.useCallback(()=>{Z(null)},[]),Ee=a.useMemo(()=>{let te=y?t.filter(be=>be.id.toLowerCase().includes(y.toLowerCase())||be.title&&be.title.toLowerCase().includes(y.toLowerCase())||be.description.toLowerCase().includes(y.toLowerCase())):[...t];Y&&!D&&(te=te.filter(be=>be.column!=="done"&&be.column!=="archived"));const Ae=[...D?te.filter(be=>be.column===D):te].sort((be,st)=>{let Se=0;switch(j){case"id":Se=be.id.localeCompare(st.id);break;case"title":Se=(be.title||be.description).localeCompare(st.title||st.description);break;case"status":Se=(be.status||"").localeCompare(st.status||"");break;case"column":Se=be.column.localeCompare(st.column);break}return w==="asc"?Se:-Se}),Qe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Ae.forEach(be=>Qe[be.column].push(be)),Qe},[t,y,j,w,Y,D]),ie=a.useMemo(()=>Object.values(Ee).reduce((te,je)=>te+je.length,0),[Ee]),Pe=a.useMemo(()=>t.filter(te=>te.column==="done"||te.column==="archived").length,[t]),ze=a.useMemo(()=>Y?Pe:0,[Y,Pe]),$e=a.useCallback(()=>{const te=Object.values(Ee).flat().filter(je=>je.column!=="archived").map(je=>je.id);O(je=>{if(te.every(Qe=>je.has(Qe))){const Qe=new Set(je);return te.forEach(be=>Qe.delete(be)),Qe}else return new Set([...je,...te])})},[Ee]),He=a.useMemo(()=>{const te=Object.values(Ee).flat().filter(je=>je.column!=="archived");return te.length===0?!1:te.every(je=>oe.has(je.id))},[Ee,oe]),Me=a.useMemo(()=>{const te=Object.values(Ee).flat().filter(Ae=>Ae.column!=="archived");if(te.length===0)return!1;const je=te.filter(Ae=>oe.has(Ae.id)).length;return je>0&&je<te.length},[Ee,oe]),[Te,Ve]=a.useState("__no_change__"),[_e,et]=a.useState("__no_change__"),[le,X]=a.useState(!1),ke=a.useCallback(async()=>{if(oe.size===0)return;const te=Array.from(oe).filter(Ae=>{const Qe=t.find(be=>be.id===Ae);return Qe&&Qe.column!=="archived"});if(te.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const je={taskIds:te};if(Te!=="__no_change__")if(Te==="")je.modelProvider=null,je.modelId=null;else{const Ae=Te.indexOf("/");Ae!==-1&&(je.modelProvider=Te.slice(0,Ae),je.modelId=Te.slice(Ae+1))}if(_e!=="__no_change__")if(_e==="")je.validatorModelProvider=null,je.validatorModelId=null;else{const Ae=_e.indexOf("/");Ae!==-1&&(je.validatorModelProvider=_e.slice(0,Ae),je.validatorModelId=_e.slice(Ae+1))}if(Object.keys(je).length===1){i("No changes to apply","info");return}X(!0);try{const Ae=await Sx(je.taskIds,je.modelProvider,je.modelId,je.validatorModelProvider,je.validatorModelId,void 0,void 0,b);f&&Ae.updated.length>0&&f(Ae.updated),i(`Updated ${Ae.count} task${Ae.count===1?"":"s"}`,"success"),F(),Ve("__no_change__"),et("__no_change__")}catch(Ae){i(fe(Ae)||"Failed to update models","error")}finally{X(!1)}},[oe,t,Te,_e,b,i,F,f]),se=a.useCallback(te=>{s(te)},[s]),Le=a.useCallback((te,je)=>{if(je.paused){te.preventDefault();return}te.dataTransfer.setData("text/plain",je.id),te.dataTransfer.effectAllowed="move",_(je.id)},[]),ve=a.useCallback(()=>{_(null),T(null)},[]),Ye=a.useCallback((te,je)=>{te.preventDefault(),te.dataTransfer.dropEffect="move",T(je)},[]),mt=a.useCallback(()=>{T(null)},[]),ht=a.useCallback(async(te,je)=>{te.preventDefault(),T(null);const Ae=te.dataTransfer.getData("text/plain");if(Ae){if(je==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Ae,je)}catch(Qe){i(fe(Qe),"error")}}},[n,i]),me=te=>j!==te?e.jsx(Gm,{size:14,className:"sort-icon"}):w==="asc"?e.jsx(ji,{size:14,className:"sort-icon active"}):e.jsx(Ka,{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:q,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>C(te=>!te),"aria-expanded":J,"aria-haspopup":"menu",children:[e.jsx(dg,{size:14}),"Columns"]}),J&&e.jsx("div",{className:"list-column-dropdown",role:"menu",children:Lo.map(te=>{const je=N.has(te),Ae=je&&N.size===1;return e.jsxs("label",{className:`list-column-dropdown-item${Ae?" disabled":""}`,role:"menuitem",title:Ae?"At least one column must be visible":"",children:[e.jsx("input",{type:"checkbox",checked:je,onChange:()=>ue(te),disabled:Ae}),e.jsx("span",{children:ce[te]})]},te)})})]}),e.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>H(te=>!te),"aria-pressed":Y,title:Y?"Show done tasks":"Hide done tasks",children:[Y?e.jsx(ic,{size:14}):e.jsx(kg,{size:14}),Y?"Show Done":"Hide Done"]}),e.jsxs("div",{className:"list-stats",children:[D?`${ie} of ${t.length} tasks in ${ds[D]}`:`${ie} of ${t.length} tasks`,ze>0&&!D&&e.jsxs("span",{className:"list-stats-hidden",children:[" (",ze," hidden)"]}),D&&e.jsx("button",{className:"btn btn-sm",onClick:we,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),oe.size>0&&e.jsxs("div",{className:"list-selection-stats",children:[e.jsxs("span",{className:"selection-count",children:[oe.size," selected"]}),e.jsx("button",{className:"btn btn-sm btn-link",onClick:F,children:"Clear"})]}),oe.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(Yt,{models:d,value:Te,onChange:Ve,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(Yt,{models:d,value:_e,onChange:et,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:ke,disabled:le||Te==="__no_change__"&&_e==="__no_change__",children:le?"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:ki.map(te=>{const je=t.filter(st=>st.column===te).length,Ae=te==="done"||te==="archived",Qe=Y&&Ae?0:je,be=Y&&Ae&&je>0;return e.jsxs("div",{className:`list-drop-zone${E===te?" drag-over":""}${D===te?" active":""}`,onClick:()=>de(te),onDragOver:st=>Ye(st,te),onDragLeave:mt,onDrop:st=>ht(st,te),"data-column":te,children:[e.jsx("span",{className:"drop-zone-dot",style:{background:va[te]}}),e.jsx("span",{className:"drop-zone-label",children:ds[te]}),e.jsx("span",{className:"drop-zone-count",children:be?`${Qe} of ${je}`:je})]},te)})}),e.jsxs("div",{className:"list-table-container",children:[e.jsx("div",{className:"list-quick-entry-above-table",children:e.jsx($h,{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})}),ie===0?e.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):R?e.jsx("div",{className:"list-cards",children:ki.map(te=>{if(D&&te!==D||Y&&(te==="done"||te==="archived")&&!D)return null;const je=Ee[te],Ae=je.length===0;if(y&&Ae)return null;const Qe=A.has(te);return e.jsxs(a.Fragment,{children:[e.jsxs("div",{className:`list-card-section-header${Qe?" list-section-header--collapsed":""}`,onClick:()=>Fe(te),"aria-expanded":!Qe,role:"button",tabIndex:0,onKeyDown:be=>{(be.key==="Enter"||be.key===" ")&&(be.preventDefault(),Fe(te))},children:[e.jsx(on,{size:14,className:`list-section-chevron${Qe?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${te}`}),e.jsx("span",{className:"list-section-title",children:ds[te]}),e.jsx("span",{className:"list-section-count",children:je.length})]}),!Qe&&e.jsx(e.Fragment,{children:Ae?e.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):je.map(be=>{const st=be.status==="failed",Se=be.paused===!0,Je=Wr(be,v,M),it=!r&&!st&&!Se&&!Je&&(be.column==="in-progress"||Fd.has(be.status)),ye=typeof be.status=="string"&&be.status.trim().length>0,Ge=!!(be.dependencies&&be.dependencies.length>0),Ne=Bd(be),at=Ne.hasProgress,dt=oe.size>0;return e.jsxs("div",{className:`list-card${it?" agent-active":""}${dt?" list-card--selectable":""}`,onClick:()=>se(be),"data-id":be.id,children:[dt&&e.jsx("label",{className:"list-card-checkbox",onClick:vt=>vt.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:oe.has(be.id),onChange:vt=>{vt.stopPropagation(),V(be.id)},onClick:vt=>vt.stopPropagation(),disabled:be.column==="archived","aria-label":`Select ${be.id}`})}),e.jsxs("div",{className:"list-card-row",children:[e.jsx("span",{className:"list-card-id",children:be.id}),be.executionMode==="fast"&&e.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),e.jsx("span",{className:"list-card-spacer"}),Je?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ye?e.jsx("span",{className:`list-status-badge list-status-badge--${be.column}${st?" failed":""}${it?" pulsing":""}`,children:be.status}):null]}),e.jsx("div",{className:"list-card-row",children:e.jsx("div",{className:"list-card-title",children:be.title||be.description})}),(Ge||at)&&e.jsxs("div",{className:"list-card-row list-card-meta",children:[Ge&&e.jsxs("span",{className:"list-dep-badge",title:be.dependencies.join(", "),children:[e.jsx(Ji,{size:12})," ",be.dependencies.length]}),at&&e.jsxs("div",{className:"list-progress",children:[e.jsx("div",{className:"list-progress-bar",children:e.jsx("div",{className:"list-progress-fill",style:{width:`${Ne.percent}%`,backgroundColor:va[be.column]}})}),e.jsx("span",{className:"list-progress-label",children:Ne.label})]})]})]},be.id)})})]},te)})}):e.jsxs("table",{className:"list-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"list-header-cell list-header-checkbox",children:e.jsx("input",{type:"checkbox",checked:He,ref:te=>{te&&(te.indeterminate=Me)},onChange:$e,"aria-label":"Select all visible tasks"})}),N.has("id")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("id"),children:["ID ",me("id")]}),N.has("title")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("title"),children:["Title ",me("title")]}),N.has("status")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("status"),children:["Status ",me("status")]}),N.has("column")&&e.jsxs("th",{className:"list-header-cell",onClick:()=>K("column"),children:["Column ",me("column")]}),N.has("dependencies")&&e.jsx("th",{className:"list-header-cell",children:"Dependencies"}),N.has("progress")&&e.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),e.jsx("tbody",{children:ki.map(te=>{if(D&&te!==D||Y&&(te==="done"||te==="archived")&&!D)return null;const je=Ee[te],Ae=je.length===0;if(y&&Ae)return null;const Qe=A.has(te);return e.jsxs(a.Fragment,{children:[e.jsx("tr",{className:`list-section-header${Qe?" list-section-header--collapsed":""}`,onClick:()=>Fe(te),"aria-expanded":!Qe,children:e.jsxs("th",{colSpan:N.size+1,className:"list-section-cell",children:[e.jsx(on,{size:14,className:`list-section-chevron${Qe?"":" list-section-chevron--expanded"}`}),e.jsx("span",{className:`list-section-dot dot-${te}`}),e.jsx("span",{className:"list-section-title",children:ds[te]}),e.jsx("span",{className:"list-section-count",children:je.length})]})}),!Qe&&e.jsx(e.Fragment,{children:Ae?e.jsx("tr",{className:"list-section-empty",children:e.jsx("td",{colSpan:N.size+1,className:"list-empty-cell",children:"No tasks"})}):je.map(be=>{const st=be.status==="failed",Se=be.paused===!0,Je=Wr(be,v,M),it=!r&&!st&&!Se&&!Je&&(be.column==="in-progress"||Fd.has(be.status)),ye=k===be.id;return e.jsxs("tr",{className:`list-row${st?" failed":""}${Se?" paused":""}${Je?" stuck":""}${it?" agent-active":""}${ye?" dragging":""}`,onClick:()=>se(be),draggable:!Se,onDragStart:Ge=>Le(Ge,be),onDragEnd:ve,"data-id":be.id,children:[e.jsx("td",{className:"list-cell list-cell-checkbox",children:e.jsx("input",{type:"checkbox",checked:oe.has(be.id),onChange:Ge=>{Ge.stopPropagation(),V(be.id)},onClick:Ge=>Ge.stopPropagation(),disabled:be.column==="archived","aria-label":`Select ${be.id}`})}),N.has("id")&&e.jsx("td",{className:"list-cell list-cell-id",children:be.id}),N.has("title")&&e.jsx("td",{className:"list-cell list-cell-title",children:e.jsxs("div",{className:"list-title-content",children:[be.executionMode==="fast"&&e.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),e.jsx("span",{className:"list-title-text",children:be.title||be.description})]})}),N.has("status")&&e.jsx("td",{className:"list-cell",children:Je?e.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):be.status?e.jsx("span",{className:`list-status-badge list-status-badge--${be.column}${st?" failed":""}${it?" pulsing":""}`,children:be.status}):e.jsx("span",{className:"list-status-badge",children:"-"})}),N.has("column")&&e.jsx("td",{className:"list-cell",children:e.jsx("span",{className:"list-column-badge",style:{background:`${va[be.column]}20`,color:va[be.column]},children:ds[be.column]})}),N.has("dependencies")&&e.jsx("td",{className:"list-cell list-cell-deps",children:be.dependencies&&be.dependencies.length>0?e.jsxs("span",{className:"list-dep-badge",title:be.dependencies.join(", "),children:[e.jsx(Ji,{size:12})," ",be.dependencies.length]}):"-"}),N.has("progress")&&e.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ge=Bd(be);return Ge.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:`${Ge.percent}%`,backgroundColor:va[be.column]}})}),e.jsx("span",{className:"list-progress-label",children:Ge.label})]}):"-"})()})]},be.id)})})]},te)})})]})]})]})}const ww={active:{label:"Active",color:"var(--success)",icon:ln},paused:{label:"Paused",color:"var(--warning)",icon:Hs},errored:{label:"Error",color:"var(--color-error)",icon:ss},initializing:{label:"Initializing",color:"var(--info)",icon:ut}};function Nw(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 Sw(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 Cw(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 Ew({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=ww[t.status],g=h.icon,p=a.useCallback(()=>{s(t)},[s,t]),f=a.useCallback(j=>{j.stopPropagation(),i(t)},[i,t]),b=a.useCallback(j=>{j.stopPropagation(),r(t)},[r,t]),x=a.useCallback(j=>{if(j.stopPropagation(),!c){u(!0);return}l(t),u(!1)},[c,l,t]),v=t.status==="paused",y=t.status==="errored",M=t.status==="initializing";return e.jsxs("div",{className:`project-card ${m?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":t.id,role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),p())},children:[e.jsxs("div",{className:"project-card-header",children:[e.jsx("div",{className:"project-card-icon",children:e.jsx(Sn,{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:Sw(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:Nw(t.lastActivityAt||n?.lastActivityAt)})]}),e.jsxs("div",{className:"project-card-actions",children:[v?e.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:m,title:"Resume project","aria-label":"Resume project",children:[e.jsx(ln,{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(Hs,{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(Ga,{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(qt,{size:14}),e.jsx("span",{children:c?"Confirm":""})]})]})]})]})}const Mw=a.memo(Ew,Cw);function Aw(){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(Sn,{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(Ss,{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(sn,{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(ss,{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 Pw=1e4,Ud=5;function Iw(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+=Ud){const b=t.slice(f,f+Ud),x=await Promise.allSettled(b.map(async v=>{try{return await gd(v)}catch{return null}}));if(b.forEach((v,y)=>{const M=x[y];p[v]=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 gd(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()},Pw),()=>{d.current&&(clearInterval(d.current),d.current=null)}},[u,t.length]),{healthMap:n,loading:i,error:l,refresh:u,refreshProject:h}}function _w({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 $=JSON.parse(Z);v($)}catch{}},[]);const[x,v]=a.useState([]),y=a.useMemo(()=>t.map(Z=>Z.id),[t]),{healthMap:M,loading:j}=Iw(y),P=a.useMemo(()=>t.map(Z=>({project:Z,health:M[Z.id]||null})),[t,M]),w=a.useMemo(()=>{let Z=[...P];return m!=="all"&&(Z=Z.filter(({project:$})=>$.status===m)),u!==null&&(Z=Z.filter(({project:$})=>$.nodeId===u)),Z},[P,m,u]),S=a.useMemo(()=>{const Z=[...w];return Z.sort(($,R)=>{let N=0;switch(g){case"name":N=$.project.name.localeCompare(R.project.name);break;case"activity":{const W=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,Y=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt;N=new Date(Y).getTime()-new Date(W).getTime();break}case"status":{const W={errored:0,initializing:1,paused:2,active:3};N=W[$.project.status]-W[R.project.status];break}}return f==="asc"?N:-N}),Z},[w,g,f]),k=a.useMemo(()=>{const Z=t.length,$=t.filter(z=>z.status==="active").length,R=t.filter(z=>z.status==="errored").length,N=new Set;t.forEach(z=>{z.nodeId&&N.add(z.nodeId)});const W=N.size||(Z>0?1:0);let Y=0,H=0,A=0;return Object.values(M).forEach(z=>{z&&(Y+=z.activeTaskCount,H+=z.totalTasksCompleted,A+=z.inFlightAgentCount)}),{totalProjects:Z,activeProjects:$,erroredProjects:R,totalNodes:W,totalActiveTasks:Y,totalCompletedTasks:H,totalInFlightAgents:A}},[t,M]),_=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]),E=a.useMemo(()=>{const Z=new Map;return t.forEach($=>{const R=$.nodeId,N=Z.get(R);if(N)N.count++;else{const Y=d.find(H=>H.id===R)?.name??$._sourceNodeName??"Local";Z.set(R,{name:Y,count:1})}}),Array.from(Z.entries()).map(([$,{name:R,count:N}])=>({nodeId:$??null,name:R,count:N}))},[t,d]),T=a.useCallback(Z=>{const $=[Z.id,...x.filter(R=>R!==Z.id)].slice(0,3);v($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(Z)},[s,x]);return n||j&&t.length>0&&Object.keys(M).length===0?e.jsx(Aw,{}):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(Ra,{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(Ci,{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(Sn,{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(Ss,{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(sn,{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(ss,{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(Or,{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:_.all})]}),e.jsxs("button",{className:`project-filter-tab ${m==="active"?"active":""}`,onClick:()=>c("active"),children:["Active",e.jsx("span",{className:"project-filter-count",children:_.active})]}),e.jsxs("button",{className:`project-filter-tab ${m==="paused"?"active":""}`,onClick:()=>c("paused"),children:["Paused",e.jsx("span",{className:"project-filter-count",children:_.paused})]}),e.jsxs("button",{className:`project-filter-tab ${m==="errored"?"active":""} ${_.errored>0?"has-errors":""}`,onClick:()=>c("errored"),children:["Errored",e.jsx("span",{className:"project-filter-count",children:_.errored})]})]}),E.length>1&&e.jsxs("div",{className:"project-node-filter",children:[e.jsx(Or,{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"}),E.map(({nodeId:Z,name:$,count:R})=>e.jsxs("option",{value:Z??"",children:[$," (",R,")"]},Z??"local"))]})]}),e.jsxs("div",{className:"project-sort",children:[e.jsx(zr,{size:14}),e.jsxs("select",{value:`${g}-${f}`,onChange:Z=>{const[$,R]=Z.target.value.split("-");p($),b(R)},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(Gm,{size:14})]})]}),e.jsx("div",{className:"project-grid",children:S.map(({project:Z,health:$})=>{const R=d.find(W=>W.id===Z.nodeId),N=R?void 0:Z._sourceNodeName;return e.jsx(Mw,{project:Z,health:$,node:R,nodeNameFallback:N,onSelect:T,onPause:r,onResume:l,onRemove:o},Z.id)})}),S.length===0&&e.jsxs("div",{className:"project-overview__no-results",children:[e.jsx(zr,{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 Rw=45e3,Tw=3e3,$w=2e3,Fw=1500,Hd="fusion:sse-client-id";let Fi=null;const ci=new Map;function qd(){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 Dh(){if(!(typeof window>"u")){if(Fi)return Fi;try{const t=window.sessionStorage.getItem(Hd);if(t)return Fi=t,t;const n=qd();return window.sessionStorage.setItem(Hd,n),Fi=n,n}catch{return Fi=qd(),Fi}}}function Lh(t){if(!(typeof window>"u"))try{return{parsed:new URL(t,window.location.origin),preserveRelativePath:t.startsWith("/")}}catch{return}}function zh(t){return t.origin===window.location.origin&&t.pathname==="/api/events"}function Dw(t){const n=Dh();if(!n)return t;const s=Lh(t);return!s||!zh(s.parsed)?t:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function uc(t,n){const s=Dh();if(!s)return;const i=Lh(t);if(!i||!zh(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),$s(`${r.pathname}${r.search}${r.hash}`)}function Lw(t){if(typeof window>"u")return;const n=uc(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 dl(t){t.keepaliveTimer&&(clearInterval(t.keepaliveTimer),t.keepaliveTimer=null)}function Vd(t){if(typeof window>"u"||typeof window.fetch!="function")return;const n=uc(t.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),Fw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function zw(t){dl(t),uc(t.url,"keepalive")&&(Vd(t),t.keepaliveTimer=window.setInterval(()=>{Vd(t)},$w))}if(typeof window<"u"){const t=()=>{for(const s of Array.from(ci.values()))if(!s.closed){if(dl(s),Lw(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(ci.values()))i.subscribers.size!==0&&(i.closed=!1,mc(i))};window.addEventListener("pagehide",t),window.addEventListener("beforeunload",t),window.addEventListener("pageshow",n)}function $a(t){t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),t.heartbeatTimer=setTimeout(()=>{Oh(t)},Rw)}function Oh(t){if(t.heartbeatTimer&&(clearTimeout(t.heartbeatTimer),t.heartbeatTimer=null),t.es&&(t.es.close(),t.es=null),dl(t),t.nativeListeners.clear(),t.closed||t.subscribers.size===0||t.reconnectTimer)return;const n=ci.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=ci.get(t.url);s&&s===t&&t.subscribers.size>0&&mc(t)},Tw)}}function mc(t){if(t.es||t.closed)return;t.reconnectTimer&&(clearTimeout(t.reconnectTimer),t.reconnectTimer=null);const n=new EventSource($s(Dw(t.url)));t.es=n,zw(t),n.addEventListener("open",()=>{$a(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);Oh(t)}),n.addEventListener("message",()=>$a(t)),n.addEventListener("heartbeat",()=>$a(t)),Bh(t),$a(t)}function Bh(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=>{$a(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 Ow(t){t.closed=!0,t.heartbeatTimer&&clearTimeout(t.heartbeatTimer),dl(t),t.reconnectTimer&&clearTimeout(t.reconnectTimer),t.es&&t.es.close(),t.es=null,t.nativeListeners.clear(),ci.delete(t.url)}function Gs(t,n={}){let s=ci.get(t);s||(s={url:t,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ci.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),mc(s),Bh(s);let r=!0;return()=>{if(!r)return;r=!1;const l=ci.get(t);l&&(l.subscribers.delete(i),l.subscribers.size===0&&Ow(l))}}const hc="kb-planning-last-description",pc="kb-subtask-last-description",fc="kb-mission-last-goal";function Bw(t,n){us(hc,t,n)}function Uw(t){return Rn(hc,t)||""}function Di(t){qa(hc,t)}function Hw(t,n){us(pc,t,n)}function qw(t){return Rn(pc,t)||""}function Rl(t){qa(pc,t)}function Vw(t,n){us(fc,t,n)}function Ww(t){return Rn(fc,t)||""}function ii(t){qa(fc,t)}function Kw(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 Gw(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 Jw(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 Cs({entries:t,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=Jw(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?Kw(l):void 0,h=l.question&&u!==void 0?Gw(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 Wd="fusion-tab-id";function Yw(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Pi(){if(typeof window>"u")return"server-tab";const t=window.sessionStorage.getItem(Wd);if(t)return t;const n=Yw();return window.sessionStorage.setItem(Wd,n),n}function ul(t){const n=a.useMemo(()=>Pi(),[]),[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(zj(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=Oj(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=$s(`/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:Gs("/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(Bj(t,n)),i(!1),l(null)}finally{d(!1)}}},[t,n]);return{isLockedByOther:s,currentHolder:r,takeControl:m,isLoading:o}}const Qw="fusion:ai-session-sync",Kd="fusion:ai-session-sync",Xw=3e4,Zw=6e4;function zs(){return Date.now()}function eN(){const t=globalThis.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Gd(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 tN{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=eN(),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:zs()})}broadcastUpdate(n){const s=n.timestamp??zs();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??zs();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=zs();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=zs();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=zs();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(Qw),this.channel.onmessage=s=>{const i=Gd(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Kd||!s.newValue))try{const i=JSON.parse(s.newValue),r=Gd(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=zs();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Xw)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=zs();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(Kd,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:zs()});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=zs(),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 Os=new tN;function ua(){const t=a.useSyncExternalStore(d=>Os.subscribe(d),()=>Os.getSnapshot(),()=>Os.getSnapshot());a.useEffect(()=>{Os.requestSync()},[]);const n=a.useCallback(d=>{Os.broadcastUpdate(d)},[]),s=a.useCallback(d=>{Os.broadcastCompleted(d)},[]),i=a.useCallback((d,m)=>{Os.broadcastLock(d,m)},[]),r=a.useCallback((d,m)=>{Os.broadcastUnlock(d,m)},[]),l=a.useCallback(d=>{Os.broadcastHeartbeat(d)},[]),o=a.useCallback(()=>{Os.requestSync()},[]);return{tabId:t.tabId,sessions:t.sessions,activeTabMap:t.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:l,requestSync:o}}function nN(t,n){return t&&n?`${t}/${n}`:""}function sN(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 iN=["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 aN({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,v]=a.useState(null),[y,M]=a.useState(!1),j=a.useRef(!1),[P,w]=a.useState(""),[S,k]=a.useState(!0),[_,E]=a.useState(!1),[T,D]=a.useState(!1),[Z,$]=a.useState(!1),R=a.useRef(null),N=a.useRef(null),W=a.useRef(null),Y=a.useRef(null),[H,A]=a.useState(l??null),z=a.useMemo(()=>Pi(),[]),{isLockedByOther:J,takeControl:C,isLoading:q}=ul(t?H:null),{activeTabMap:oe,broadcastUpdate:O,broadcastCompleted:V,broadcastLock:F,broadcastUnlock:ue,broadcastHeartbeat:ce}=ua(),[K,de]=a.useState(void 0),[Fe,we]=a.useState(void 0),[Ee,ie]=a.useState([]),[Pe,ze]=a.useState(!0),[$e,He]=a.useState(null),[Me,Te]=a.useState([]),[Ve,_e]=a.useState([]),et=nN(K,Fe);a.useEffect(()=>{(async()=>{try{ze(!0);const Je=await Vn();ie(Je.models),Te(Je.favoriteProviders),_e(Je.favoriteModels)}catch(Je){He(fe(Je)||"Failed to load models")}finally{ze(!1)}})()},[]);const le=a.useCallback(Se=>{Te(Je=>{const it=Je,Ge=it.includes(Se)?it.filter(Ne=>Ne!==Se):[Se,...it];return Jt({favoriteProviders:Ge,favoriteModels:Ve}).catch(()=>{Te(it)}),Ge})},[Ve]),X=a.useCallback(Se=>{_e(Je=>{const it=Je,Ge=it.includes(Se)?it.filter(Ne=>Ne!==Se):[Se,...it];return Jt({favoriteProviders:Me,favoriteModels:Ge}).catch(()=>{_e(it)}),Ge})},[Me]),ke=a.useCallback((Se,Je)=>{if(!Se||!Je)return"Using default";const it=Ee.find(ye=>ye.provider===Se&&ye.id===Je);return it?`${it.provider}/${it.id}`:`${Se}/${Je}`},[Ee]),se=a.useCallback(Se=>{N.current?.close();const Je=Ej(Se,i,{onThinking:it=>{w(ye=>ye+it),O({sessionId:Se,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onQuestion:it=>{E(!1),D(!1),ii(i),c({type:"question",sessionId:Se,question:it}),w(""),M(!0),O({sessionId:Se,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onSummary:it=>{E(!1),D(!1),ii(i),c({type:"summary",sessionId:Se,summary:it}),v(it),w(""),M(!0),O({sessionId:Se,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null})},onError:it=>{const ye=it||"Session failed while contacting the AI.";E(!1),D(!1),h(null),c({type:"error",sessionId:Se,errorMessage:ye}),w(""),M(!0),W.current=Se,O({sessionId:Se,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:o.trim()||"Mission interview",projectId:i??null}),V({sessionId:Se,status:"error"})},onComplete:()=>{E(!1),D(!1),W.current=null,V({sessionId:Se,status:"complete"})},onConnectionStateChange:it=>{E(it==="reconnecting")}});N.current=Je},[V,O,o,i,z]),Le=a.useCallback(async Se=>{const Je=Se??o;if(Je.trim()){h(null),w(""),p([]),b([]),E(!1),c({type:"loading"});try{const{sessionId:it}=await wj(Je.trim(),i,K&&Fe?{modelProvider:K,modelId:Fe}:void 0);W.current=it,A(it),ii(i),se(it),p([])}catch(it){E(!1),h(fe(it)||"Failed to start interview session"),c({type:"initial"}),W.current=null,A(null)}}},[se,o,K,Fe,i]);a.useEffect(()=>{t&&m.type==="initial"&&R.current?.focus()},[t,m.type]),a.useEffect(()=>{if(t&&r&&!j.current&&m.type==="initial"){d(r);const Se=setTimeout(()=>{j.current=!0,Le(r)},0);return()=>clearTimeout(Se)}else if(t&&!r&&!j.current&&m.type==="initial"){const Se=Ww(i);Se&&d(Se)}},[t,r,m.type,Le]),a.useEffect(()=>{t||(j.current=!1,E(!1),D(!1),A(null))},[t]),a.useEffect(()=>{if(!t||!l||m.type!=="initial")return;let Se=!1;return ti(l).then(Je=>{if(Se||!Je)return;const it=ea(Je.conversationHistory);if(b(it),A(Je.id),p(it.map(ye=>ye.response).filter(ye=>!!(ye&&typeof ye=="object"&&!Array.isArray(ye)))),Je.status==="awaiting_input"&&Je.currentQuestion)try{ii(i);const ye=JSON.parse(Je.currentQuestion);W.current=Je.id,M(!0),c({type:"question",sessionId:Je.id,question:ye})}catch{h("Failed to restore session question.")}else if(Je.status==="complete"&&Je.result)try{ii(i);const ye=JSON.parse(Je.result);W.current=Je.id,M(!0),v(ye),c({type:"summary",sessionId:Je.id,summary:ye})}catch{h("Failed to restore session result.")}else Je.status==="generating"?(W.current=Je.id,M(!0),Je.thinkingOutput&&w(Je.thinkingOutput),c({type:"loading"}),se(Je.id)):Je.status==="error"&&(W.current=Je.id,M(!0),h(null),c({type:"error",sessionId:Je.id,errorMessage:Je.error??"The session encountered an error."}))}).catch(()=>{Se||h("Failed to resume session.")}),()=>{Se=!0}},[se,t,l,m.type,i]),a.useEffect(()=>{if(!t){Y.current&&(ue(Y.current,z),Y.current=null);return}if(H&&Y.current!==H){Y.current&&ue(Y.current,z),F(H,z),Y.current=H;return}!H&&Y.current&&(ue(Y.current,z),Y.current=null)},[F,ue,t,H,z]),a.useEffect(()=>{if(!t||!H||Y.current!==H)return;ce(z);const Se=setInterval(()=>{ce(z)},3e4);return()=>{clearInterval(Se)}},[ce,t,H,z]),a.useEffect(()=>()=>{N.current?.close(),N.current=null,Y.current&&(ue(Y.current,z),Y.current=null)},[ue,z]),a.useEffect(()=>{if(!t)return;const Se=Je=>{(m.type==="question"||m.type==="summary")&&(Je.preventDefault(),Je.returnValue=""),N.current?.close()};return window.addEventListener("beforeunload",Se),()=>window.removeEventListener("beforeunload",Se)},[t,m]);const ve=a.useCallback(()=>{N.current?.close(),N.current=null,n()},[n]),Ye=a.useCallback(async()=>{if(o&&Vw(o,i),!(y&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(N.current?.close(),N.current=null,m.type==="question"||m.type==="summary"||m.type==="error")try{await Sh(m.sessionId,i,z)}catch{}d(""),c({type:"initial"}),h(null),p([]),b([]),v(null),w(""),E(!1),D(!1),M(!1),$(!1),de(void 0),we(void 0),W.current=null,A(null),n()}},[o,y,m,n,i,z]);a.useEffect(()=>{if(!t)return;const Se=Je=>{Je.key==="Escape"&&(y?confirm("Are you sure you want to close? Your interview progress will be lost.")&&Ye():Ye())};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[t,y,Ye]);const mt=a.useCallback(async Se=>{if(m.type!=="question")return;const{sessionId:Je}=m;h(null),p(it=>[...it,Se]),b(it=>[...it,{question:m.question,response:Se}]),c({type:"loading"}),w("");try{se(Je),await Nj(Je,Se,i,z),M(!0)}catch(it){N.current?.close(),N.current=null,h(fe(it)||"Failed to submit response"),c({type:"question",sessionId:Je,question:m.question})}},[m,i,z,se]),ht=a.useCallback(async()=>{if(m.type!=="error")return;const Se=m.sessionId;h(null),D(!0),w(""),c({type:"loading"}),se(Se);try{W.current=Se,A(Se),await Sj(Se,i,z)}catch(Je){let it=Je;if((fe(Je)||"").includes("not in an error state"))try{const Ge=await ti(Se);if(!Ge)throw new Error("Failed to refresh interview session.");const Ne=ea(Ge.conversationHistory);if(b(Ne),p(Ne.map(at=>at.response).filter(at=>!!(at&&typeof at=="object"&&!Array.isArray(at)))),W.current=Ge.id,A(Ge.id),M(!0),Ge.status==="generating")w(Ge.thinkingOutput??""),c({type:"loading"}),N.current?.isConnected()||se(Ge.id);else if(Ge.status==="awaiting_input"){if(!Ge.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ii(i);const at=JSON.parse(Ge.currentQuestion);c({type:"question",sessionId:Ge.id,question:at}),N.current?.isConnected()||se(Ge.id)}else if(Ge.status==="complete"){if(!Ge.result)throw new Error("Interview session is complete but has no result.");ii(i);const at=JSON.parse(Ge.result);v(at),c({type:"summary",sessionId:Ge.id,summary:at})}else Ge.status==="error"&&c({type:"error",sessionId:Ge.id,errorMessage:Ge.error??"Retry failed. Please try again."});E(!1);return}catch(Ge){it=Ge}N.current?.close(),N.current=null,c({type:"error",sessionId:Se,errorMessage:fe(it)||"Retry failed. Please try again."}),E(!1)}finally{D(!1)}},[se,i,z,m]),me=a.useCallback(async()=>{if(m.type==="summary"){h(null),$(!0);try{const Se=await Cj(m.sessionId,x||void 0,i);s(Se),ii(i),N.current?.close(),N.current=null,d(""),c({type:"initial"}),h(null),p([]),b([]),v(null),w(""),E(!1),D(!1),M(!1),$(!1),W.current=null,A(null),n()}catch(Se){h(fe(Se)||"Failed to create mission"),$(!1)}}},[m,x,s,n,i]),te=()=>m.type==="question"?Math.min(g.length+1,6):6,je=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",Ae=H?oe.get(H):null,Qe=Ae&&Ae.tabId!==z,be=!!(Qe&&!Ae.stale),st=J&&(!Qe||Ae.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:Se=>Se.target===Se.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(ts,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Plan Mission with AI"})]}),e.jsxs("div",{className:"modal-header-actions",children:[je&&e.jsx("button",{className:"modal-send-to-background",onClick:ve,title:"Send to background","aria-label":"Send to background",children:e.jsx(ei,{size:16})}),e.jsx("button",{className:"modal-close",onClick:Ye,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[u&&e.jsx("div",{className:"form-error planning-error",children:u}),_&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),be&&e.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),m.type==="initial"&&e.jsxs("div",{className:"planning-initial",children:[e.jsxs("div",{className:"planning-view-scroll",children:[e.jsxs("div",{className:"planning-intro",children:[e.jsx(Dn,{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:R,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:Se=>d(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&!Se.shiftKey&&o.trim()&&(Se.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:iN.map((Se,Je)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>d(Se),children:Se.length>45?Se.slice(0,45)+"...":Se},Je))})]}),e.jsxs("div",{className:"planning-model-select-group",children:[e.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Pe&&e.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),e.jsx(Yt,{id:"mission-interview-modal-model",label:"Planning Model",value:et,onChange:Se=>{const{provider:Je,modelId:it}=sN(Se);de(Je),we(it)},models:Ee,disabled:Pe,favoriteProviders:Me,onToggleFavorite:le,favoriteModels:Ve,onToggleModelFavorite:X}),$e&&e.jsxs("div",{className:"form-hint form-hint-error",children:[$e," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{ze(!0);const Se=await Vn();ie(Se.models),Te(Se.favoriteProviders),_e(Se.favoriteModels),He(null)}catch(Se){He(fe(Se)||"Failed to load models")}finally{ze(!1)}})()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${K&&Fe?"model-badge-custom":"model-badge-default"}`,children:ke(K,Fe)})})]})]}),e.jsx("div",{className:"planning-view-footer",children:e.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Le(),disabled:!o.trim(),children:[e.jsx(ts,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),m.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ut,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:P?"AI is thinking...":"Preparing next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>k(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&P&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:P})})]})]}),m.type==="error"&&e.jsx("div",{className:"planning-summary",children:e.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Cs,{entries:f}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:m.errorMessage}),e.jsxs("div",{className:"ai-error-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:T,children:[T?e.jsx(ut,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:T?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:Ye,disabled:T,children:"Cancel"})]})]})]})}),m.type==="question"&&e.jsx(rN,{question:m.question,progress:te(),historyEntries:f,onSubmit:mt}),m.type==="summary"&&x&&e.jsx(lN,{summary:x,historyEntries:f,onSummaryChange:v,onApprove:me,onStartOver:()=>{c({type:"initial"}),M(!1),v(null),p([]),b([]),A(null),N.current?.close(),N.current=null},isCreating:Z}),J&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(al,{size:16}),e.jsx("span",{children:st?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),st&&e.jsx("button",{type:"button",onClick:()=>{C()},disabled:q,className:"btn btn-primary session-lock-take-control",children:q?"Taking control...":"Take Control"})]})})]})]})}):null}function rN({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(Cs,{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(sn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Lt,{size:18}),"No"]})]})]})]})]})]}),e.jsx("div",{className:"planning-actions",children:e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!c(),children:["Continue",e.jsx(Ga,{size:16,className:"icon-ml-4"})]})})]})}function lN({summary:t,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:l}){const[o,d]=a.useState(()=>new Set(t.milestones.map((j,P)=>P))),[m,c]=a.useState(()=>{const j=new Set;return t.milestones.forEach((P,w)=>{P.slices.forEach((S,k)=>j.add(`${w}-${k}`))}),j}),u=j=>{d(P=>{const w=new Set(P);return w.has(j)?w.delete(j):w.add(j),w})},h=j=>{c(P=>{const w=new Set(P);return w.has(j)?w.delete(j):w.add(j),w})},g=(j,P)=>{const w=[...t.milestones];w[j]={...w[j],...P},s({...t,milestones:w})},p=(j,P,w)=>{const S=[...t.milestones],k=[...S[j].slices];k[P]={...k[P],...w},S[j]={...S[j],slices:k},s({...t,milestones:S})},f=(j,P,w,S)=>{const k=[...t.milestones],_=[...k[j].slices],E=[..._[P].features];E[w]={...E[w],...S},_[P]={..._[P],features:E},k[j]={...k[j],slices:_},s({...t,milestones:k})},b=j=>{const P=t.milestones.filter((w,S)=>S!==j);s({...t,milestones:P})},x=(j,P)=>{const w=[...t.milestones];w[j]={...w[j],slices:w[j].slices.filter((S,k)=>k!==P)},s({...t,milestones:w})},v=(j,P,w)=>{const S=[...t.milestones],k=[...S[j].slices];k[P]={...k[P],features:k[P].features.filter((_,E)=>E!==w)},S[j]={...S[j],slices:k},s({...t,milestones:S})},y=(j,P)=>{const w=[...t.milestones],S=[...w[j].slices];S[P]={...S[P],features:[...S[P].features,{title:"New feature",description:""}]},w[j]={...w[j],slices:S},s({...t,milestones:w})},M=t.milestones.reduce((j,P)=>j+P.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(Cs,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(sn,{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:j=>s({...t,missionTitle:j.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Mission Description"}),e.jsx("textarea",{className:"planning-textarea",rows:3,value:t.missionDescription||"",onChange:j=>s({...t,missionDescription:j.target.value})})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Roadmap"}),e.jsx("div",{className:"roadmap-list",children:t.milestones.map((j,P)=>e.jsxs("div",{className:"roadmap-card",children:[e.jsxs("div",{className:"roadmap-card-header",onClick:()=>u(P),children:[o.has(P)?e.jsx(Ot,{size:16,className:"icon-text-secondary"}):e.jsx(on,{size:16,className:"icon-text-secondary"}),e.jsx(Si,{size:16,className:"icon-milestone"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:w=>g(P,{title:w.target.value}),onClick:w=>w.stopPropagation()}),t.milestones.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),b(P)},title:"Remove milestone",children:e.jsx(qt,{size:14,className:"icon-text-secondary"})})]}),o.has(P)&&e.jsxs("div",{className:"roadmap-card-body",children:[e.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:w=>g(P,{description:w.target.value})}),e.jsxs("div",{className:"roadmap-field-group",children:[e.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),e.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:j.verification||"",onChange:w=>g(P,{verification:w.target.value})})]}),j.slices.map((w,S)=>{const k=`${P}-${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(Ot,{size:14,className:"icon-text-secondary"}):e.jsx(on,{size:14,className:"icon-text-secondary"}),e.jsx(Po,{size:14,className:"icon-slice"}),e.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:_=>p(P,S,{title:_.target.value}),onClick:_=>_.stopPropagation()}),j.slices.length>1&&e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:_=>{_.stopPropagation(),x(P,S)},title:"Remove slice",children:e.jsx(qt,{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,S,{verification:_.target.value})})]}),w.features.map((_,E)=>e.jsxs("div",{className:"roadmap-feature-row",children:[e.jsx(So,{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:_.title,onChange:T=>f(P,S,E,{title:T.target.value})}),_.description&&e.jsx("p",{className:"roadmap-feature-text",children:_.description}),_.acceptanceCriteria&&e.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",_.acceptanceCriteria]})]}),e.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>v(P,S,E),title:"Remove feature",children:e.jsx(qt,{size:12,className:"icon-text-secondary"})})]},E)),e.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(P,S),children:[e.jsx(Vt,{size:12}),"Add Feature"]})]})]},S)})]})]},P))})]})]})]}),e.jsxs("div",{className:"planning-actions planning-summary-actions",children:[e.jsxs("button",{className:"btn",onClick:r,disabled:l,children:[e.jsx(oa,{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(ut,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function oN({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([]),[v,y]=a.useState(null),[M,j]=a.useState(""),[P,w]=a.useState(!0),[S,k]=a.useState(!1),[_,E]=a.useState(!1),T=a.useRef(null),D=a.useRef(null),Z=a.useRef(null),$=a.useRef(null),[R,N]=a.useState(null),W=a.useMemo(()=>Pi(),[]);ul(t?R:null);const{activeTabMap:Y,broadcastUpdate:H,broadcastCompleted:A,broadcastLock:z,broadcastUnlock:J,broadcastHeartbeat:C}=ua(),q=i==="milestone"?Mj:Rj,oe=i==="milestone"?Aj:Tj,O=i==="milestone"?Pj:$j,V=i==="milestone"?Ij:Fj,F=i==="milestone"?_j:Dj,ue=i==="milestone"?"Milestone":"Slice",ce=i==="milestone"?"milestone_interview":"slice_interview",K=a.useCallback(_e=>{D.current?.close();const et=O(_e,d,{onThinking:le=>{j(X=>X+le),H({sessionId:_e,status:"generating",needsInput:!1,owningTabId:W,type:ce,title:l,projectId:d??null})},onQuestion:le=>{k(!1),de(),u({type:"question",sessionId:_e,question:le}),j(""),H({sessionId:_e,status:"awaiting_input",needsInput:!0,owningTabId:W,type:ce,title:l,projectId:d??null})},onSummary:le=>{k(!1),de(),u({type:"summary",sessionId:_e,summary:le}),y(le),j(""),H({sessionId:_e,status:"complete",needsInput:!1,owningTabId:W,type:ce,title:l,projectId:d??null})},onError:le=>{const X=le||"Session failed while contacting the AI.";k(!1),g(null),u({type:"error",sessionId:_e,errorMessage:X}),j(""),Z.current=_e,H({sessionId:_e,status:"error",needsInput:!1,owningTabId:W,type:ce,title:l,projectId:d??null}),A({sessionId:_e,status:"error"})},onComplete:()=>{k(!1),Z.current=null,A({sessionId:_e,status:"complete"})},onConnectionStateChange:le=>{k(le==="reconnecting")}});D.current=et},[A,H,O,ce,d,W,l]),de=()=>{y(null),f([]),x([]),j("")},Fe=a.useCallback(async()=>{g(null),de(),k(!1),u({type:"loading"});try{const{sessionId:_e}=await q(r,d);Z.current=_e,N(_e),K(_e)}catch(_e){k(!1),g(fe(_e)||`Failed to start ${ue.toLowerCase()} interview`),u({type:"initial"}),Z.current=null,N(null)}},[K,d,q,r,ue]),we=a.useCallback(async()=>{g(null),E(!0);try{await F(r,d),s(),u({type:"applied"})}catch(_e){g(fe(_e)||`Failed to skip ${ue.toLowerCase()} interview`),E(!1)}},[s,d,F,r,ue]);a.useEffect(()=>{t&&c.type==="initial"&&T.current?.focus()},[t,c.type]),a.useEffect(()=>{if(!t||!m||c.type!=="initial")return;let _e=!1;return ti(m).then(et=>{if(_e||!et)return;const le=ea(et.conversationHistory);if(x(le),N(et.id),f(le.map(X=>X.response).filter(X=>!!(X&&typeof X=="object"&&!Array.isArray(X)))),et.status==="awaiting_input"&&et.currentQuestion)try{const X=JSON.parse(et.currentQuestion);Z.current=et.id,u({type:"question",sessionId:et.id,question:X})}catch{g("Failed to restore session question.")}else if(et.status==="complete"&&et.result)try{const X=JSON.parse(et.result);Z.current=et.id,y(X),u({type:"summary",sessionId:et.id,summary:X})}catch{g("Failed to restore session result.")}else et.status==="generating"?(Z.current=et.id,et.thinkingOutput&&j(et.thinkingOutput),u({type:"loading"}),K(et.id)):et.status==="error"&&(Z.current=et.id,g(null),u({type:"error",sessionId:et.id,errorMessage:et.error??"The session encountered an error."}))}).catch(()=>{_e||g("Failed to resume session.")}),()=>{_e=!0}},[K,t,m,c.type]),a.useEffect(()=>{t||(k(!1),N(null))},[t]),a.useEffect(()=>{if(!(!t||!R)){if($.current!==R){$.current&&J($.current,W),z(R,W),$.current=R;return}!R&&$.current&&(J($.current,W),$.current=null)}},[z,J,t,R,W]),a.useEffect(()=>{if(!t||!R||$.current!==R)return;C(W);const _e=setInterval(()=>{C(W)},3e4);return()=>{clearInterval(_e)}},[C,t,R,W]),a.useEffect(()=>()=>{D.current?.close(),D.current=null,$.current&&(J($.current,W),$.current=null)},[J,W]);const Ee=a.useCallback(()=>{D.current?.close(),D.current=null,n()},[n]),ie=a.useCallback(async()=>{D.current?.close(),D.current=null,de(),u({type:"initial"}),g(null),Z.current=null,N(null),n()},[n]),Pe=a.useCallback(async _e=>{if(c.type!=="question")return;const{sessionId:et}=c;g(null),f(le=>[...le,_e]),x(le=>[...le,{question:c.question,response:_e}]),u({type:"loading"}),j("");try{K(et),await oe(et,_e,d,W)}catch(le){D.current?.close(),D.current=null,g(fe(le)||"Failed to submit response"),u({type:"question",sessionId:et,question:c.question})}},[K,d,oe,W,c]),ze=a.useCallback(async()=>{if(c.type==="summary"){g(null),E(!0);try{await V(c.sessionId,v||void 0,d),s(),u({type:"applied"})}catch(_e){g(fe(_e)||"Failed to apply interview results"),E(!1)}}},[V,v,s,d,c]),$e=()=>c.type==="question"?Math.min(p.length+1,6):6,He=c.type==="loading"||c.type==="question"||c.type==="summary"||c.type==="error",Me=R?Y.get(R):null,Ve=!!(Me&&Me.tabId!==W&&!Me.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:_e=>_e.target===_e.currentTarget&&ie(),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(Dn,{size:20,className:"icon-triage"}),e.jsxs("h3",{children:["Plan ",ue,": ",l]})]}),e.jsxs("div",{className:"modal-header-actions",children:[He&&e.jsx("button",{className:"modal-send-to-background",onClick:Ee,title:"Send to background","aria-label":"Send to background",children:e.jsx(ei,{size:16})}),e.jsx("button",{className:"modal-close",onClick:ie,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[h&&e.jsx("div",{className:"form-error planning-error",children:h}),S&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ve&&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(Dn,{size:32,className:"icon-triage-lg"}),e.jsxs("h4",{children:["Refine ",ue," 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 Fe(),children:[e.jsx(Dn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),e.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void we(),disabled:_,children:[_?e.jsx(ut,{size:16,className:"spin"}):null,"Use Mission Context"]}),e.jsx("button",{className:"btn",onClick:ie,children:"Cancel"})]})]}),c.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ut,{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(!P),type:"button",children:P?"Hide thinking":"Show thinking"}),P&&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(Cs,{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:ie,children:"Cancel"})})]})]})}),c.type==="question"&&e.jsx(cN,{question:c.question,progress:$e(),historyEntries:b,onSubmit:Pe}),c.type==="summary"&&v&&e.jsx(dN,{summary:v,historyEntries:b,onSummaryChange:y,onApply:ze,onCancel:ie,isApplying:_}),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(sn,{size:48,className:"icon-success"}),e.jsxs("h4",{children:[ue," 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 cN({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(Cs,{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(sn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${r[t.id]===!1?"selected":""}`,onClick:()=>l({[t.id]:!1}),children:[e.jsx(Lt,{size:18}),"No"]})]})]})]})]})]}),e.jsx("div",{className:"planning-actions",children:e.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!c(),children:["Continue",e.jsx(Ga,{size:16,className:"icon-ml-4"})]})})]})}function dN({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(Cs,{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(Ot,{size:16}):e.jsx(on,{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(ut,{size:16,className:"spin"}):null,"Apply"]}),e.jsx("button",{className:"btn",onClick:r,disabled:l,children:"Cancel"})]})]})}const ya={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)"}},Jd={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)"}},Yd={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)"}},xr={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)"}},vr={inactive:{bg:"var(--autopilot-inactive-bg)",text:"var(--autopilot-inactive-text)"},watching:{bg:"var(--autopilot-watching-bg)",text:"var(--autopilot-watching-text)"},activating:{bg:"var(--autopilot-activating-bg)",text:"var(--autopilot-activating-text)"},completing:{bg:"var(--autopilot-completing-bg)",text:"var(--autopilot-completing-text)"}},yr={pending:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},passed:{bg:"var(--assertion-passed-bg)",text:"var(--assertion-passed-text)"},failed:{bg:"var(--assertion-failed-bg)",text:"var(--assertion-failed-text)"},blocked:{bg:"var(--assertion-blocked-bg)",text:"var(--assertion-blocked-text)"}},Qd={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)"}},uN=3;function mN(t){return t==="completed"?"planned":t==="needs_update"?"needs_update":"not_started"}function Xd({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 Zd(t){return t?t.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Tl={title:"",description:"",status:"planning",autopilotEnabled:!1},$l={title:"",description:"",status:"planning",dependencies:[]},Fl={title:"",description:"",status:"pending"},Dl={title:"",description:"",acceptanceCriteria:"",status:"defined"},hN=3600*1e3;function Gr(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 pN(t){if(!t)return"healthy";const n=typeof t.lastErrorAt=="string"&&Date.now()-new Date(t.lastErrorAt).getTime()<=hN,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 fN(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 gN(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 Ll(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 Uh=["feature_triaged","feature_completed"],Hh=["slice_activated","slice_completed","milestone_completed"],qh=["mission_started","mission_paused","mission_resumed","mission_completed"],Vh=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function eu(t,n){switch(n){case"errors":return t==="error"||t==="warning";case"state_changes":return qh.includes(t);case"tasks":return Uh.includes(t);case"slices":return Hh.includes(t);case"autopilot":return Vh.includes(t);default:return!0}}function bN(t){return t==="error"||t==="warning"?"mission-event__type--error":qh.includes(t)?"mission-event__type--state":Uh.includes(t)?"mission-event__type--task":Hh.includes(t)?"mission-event__type--slice":Vh.includes(t)?"mission-event__type--autopilot":"mission-event__type--default"}function xN(t){return t.replace(/_/g," ")}function vN(t,n){return n?t==="watching"?`Watching since ${Gr(n)}`:`Last activation ${Gr(n)}`:null}function yN({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,v]=a.useState(!0),[y,M]=a.useState(!1),[j,P]=a.useState(!1),[w,S]=a.useState(null),[k,_]=a.useState(Tl),[E,T]=a.useState(!1),[D,Z]=a.useState(new Set),[$,R]=a.useState(new Set),[N,W]=a.useState(null),[Y,H]=a.useState($l),[A,z]=a.useState(!1),[J,C]=a.useState(null),[q,oe]=a.useState(Fl),[O,V]=a.useState(!1),[F,ue]=a.useState(null),[ce,K]=a.useState(null),[de,Fe]=a.useState(Dl),[we,Ee]=a.useState(!1),[ie,Pe]=a.useState(null),[ze,$e]=a.useState(null),[He,Me]=a.useState(""),[Te,Ve]=a.useState(!1),[_e,et]=a.useState([]),[le,X]=a.useState(void 0),ke=le??d,[se,Le]=a.useState(null),[ve,Ye]=a.useState(null),[mt,ht]=a.useState(null);a.useEffect(()=>{h&&ke&&Ve(!0)},[h,ke]),a.useEffect(()=>{if(!h||ke)return;let U=!1;return Ch(r).then(Ce=>{if(U)return;const qe=Ce.filter(yt=>yt.type==="mission_interview"&&(yt.status==="awaiting_input"||yt.status==="error"));et(qe)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{U=!0}},[h,r,ke]),a.useEffect(()=>{if(!h||!c)return;let U=!1;return ti(c).then(Ce=>{if(!(U||!Ce))try{const qe=JSON.parse(Ce.inputPayload||"{}");qe.targetId&&qe.targetType&&Le({type:qe.targetType,id:qe.targetId,title:qe.targetTitle||Ce.title,resumeSessionId:c})}catch{Le({type:"milestone",id:"",title:Ce.title,resumeSessionId:c})}}).catch(Ce=>{U||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),u?.())}),()=>{U=!0}},[h,c,u]);const[me,te]=a.useState(null),[je,Ae]=a.useState(new Map),[Qe,be]=a.useState(null),[st,Se]=a.useState({title:"",assertion:"",status:"pending"}),[Je,it]=a.useState(!1),[ye,Ge]=a.useState(null),[Ne,at]=a.useState(new Map),[dt,vt]=a.useState(new Set),[It,_t]=a.useState(new Set),[Mt,zt]=a.useState(null),[Nt,Pt]=a.useState(new Map),[tt,bt]=a.useState(null),[Ue,ot]=a.useState(null),[ge,Oe]=a.useState(!0),[ee,Ie]=a.useState(new Set),[xt,he]=a.useState(new Map),[Be,gt]=a.useState(null),[Kt,yn]=a.useState(new Map),[mn,Kn]=a.useState(null),[Wt,Cn]=a.useState(new Map),[Tn,as]=a.useState(new Map),[Ut,Xt]=a.useState("structure"),[hn,gn]=a.useState([]),En=a.useRef([]),an=a.useRef([]),Ft=a.useRef(null),pn=a.useRef(null),Mn=a.useRef("structure"),jn=a.useRef("all"),[zn,rs]=a.useState(!1),[Gn,Pn]=a.useState(0),[G,Ke]=a.useState("all"),[I,B]=a.useState(new Set),re=a.useRef(null),pe=a.useRef(null);an.current=g,Ft.current=f,pn.current=tt,Mn.current=Ut,jn.current=G;const xe=a.useCallback((U="auto")=>{const Ce=pe.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:U});return}const qe=re.current;qe&&(qe.scrollTop=qe.scrollHeight)},[]),Re=a.useCallback(()=>{const U=re.current;return U?U.scrollHeight-U.scrollTop-U.clientHeight<=100:!0},[]),pt=a.useCallback(async U=>{if(U.length===0){as(new Map);return}const Ce=await Yy(r);as(qe=>{const yt=new Map(qe);for(const[Zt,Rt]of Object.entries(Ce))fN(Rt)&&yt.set(Zt,Rt);return yt})},[r]),kt=a.useCallback(async()=>{try{v(!0);const U=await Vy(r);p(U),pt(U)}catch(U){i(fe(U)||"Failed to load missions","error")}finally{v(!1)}},[i,r,pt]),We=a.useCallback(async U=>{try{M(!0);const Ce=await Nh(U,r);if(b(Ce),Ce.milestones.length>0){const qe=Ce.milestones[0].id;bt(qe),Oe(!0),Z(new Set([qe])),El(qe,r).then(yt=>{Ae(Zt=>{const Rt=new Map(Zt);return Rt.set(qe,yt),Rt})}).catch(()=>{}),Ml(qe,r).then(yt=>{Pt(Zt=>{const Rt=new Map(Zt);return Rt.set(qe,yt),Rt})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&R(new Set([Ce.milestones[0].slices[0].id]))}else bt(null),ot(null)}catch(Ce){i(fe(Ce)||"Failed to load mission details","error")}finally{M(!1)}},[i,r]);a.useEffect(()=>{if(!h||!tt){ot(null);return}let U=!1;return ot(null),xd(tt,r).then(Ce=>{if(!U){if(!Ll(Ce)){ot(null);return}ot(Ce),Pt(qe=>{const yt=new Map(qe);return yt.set(tt,Ce.rollup),yt})}}).catch(()=>{U||ot(null)}),()=>{U=!0}},[h,tt,r]),a.useEffect(()=>{Oe(!0)},[tt]);const wt=a.useCallback(U=>{!U||U!==pn.current||xd(U,r).then(Ce=>{pn.current!==U||!Ll(Ce)||(ot(Ce),Pt(qe=>{const yt=new Map(qe);return yt.set(U,Ce.rollup),yt}))}).catch(()=>{})},[r]),ae=a.useCallback(async(U,Ce)=>{const qe=Ce?.append??!1,yt=qe?En.current.length:0;qe||(rs(!0),B(new Set));try{const Zt=await Jy(U,{limit:50,offset:yt,eventType:void 0},r),Rt=Zt.events.filter(Ht=>eu(Ht.eventType,G));gn(Ht=>{if(!qe)return Rt;const Xe=new Set(Ht.map(jt=>jt.id)),nt=[...Ht];for(const jt of Rt)Xe.has(jt.id)||nt.push(jt);return nt}),Pn(Zt.total),qe||requestAnimationFrame(()=>{xe("auto")})}catch(Zt){i(fe(Zt)||"Failed to load mission activity","error")}finally{qe||rs(!1)}},[i,G,r,xe]);a.useEffect(()=>{En.current=hn},[hn]),a.useEffect(()=>{h&&(kt(),b(null),bt(null),ot(null),gn([]),Pn(0),Xt("structure"),Ke("all"),B(new Set))},[h,kt]);const De=a.useRef(null);a.useEffect(()=>{h&&m&&De.current!==m&&g.length>0&&(De.current=m,We(m))},[h,m,g,We]),a.useEffect(()=>{h||(De.current=null)},[h]),a.useEffect(()=>{!h||!f||Ut!=="activity"||ae(f.id)},[Ut,h,ae,f,G]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const U=new URLSearchParams;r&&U.set("projectId",r);const Ce=`/api/events${U.size>0?`?${U.toString()}`:""}`,qe=()=>{pt(an.current)},yt=_n=>{qe();const dn=_n;if(dn.data)try{const $t=JSON.parse(dn.data);$t?.id&&p(fi=>fi.map(ys=>ys.id===$t.id?{...ys,...$t}:ys))}catch{}Ft.current&&We(Ft.current.id)},Zt=_n=>{qe(),Ft.current&&We(Ft.current.id)},Rt=()=>{qe(),Ft.current&&We(Ft.current.id)},Ht=_n=>{qe(),Ft.current&&We(Ft.current.id)},Xe=_n=>{const dn=_n;if(dn.data)try{const $t=JSON.parse(dn.data);$t&&$t.featureId&&(xs($t.featureId),Ls($t.featureId),$t.milestoneId&&wt($t.milestoneId))}catch{}},nt=_n=>{const dn=_n;if(dn.data)try{const $t=JSON.parse(dn.data);$t&&$t.featureId&&(xs($t.featureId),Ls($t.featureId),$t.milestoneId&&wt($t.milestoneId),Ft.current&&We(Ft.current.id))}catch{}},jt=_n=>{const dn=_n;if(dn.data)try{const $t=JSON.parse(dn.data);$t&&$t.milestoneId&&(At($t.milestoneId),wt($t.milestoneId))}catch{}},en=_n=>{const dn=_n;if(dn.data)try{const $t=JSON.parse(dn.data);$t&&$t.milestoneId&&(ft($t.milestoneId),At($t.milestoneId),wt($t.milestoneId))}catch{}};return Gs(Ce,{events:{"mission:updated":yt,"slice:updated":Zt,"feature:updated":Rt,"milestone:updated":Ht,"mission:event":_n=>{qe();const dn=Ft.current;if(!dn||Mn.current!=="activity")return;const $t=Re(),fi=_n;if(fi.data)try{const ys=JSON.parse(fi.data);if(!gN(ys)||ys.missionId!==dn.id||!eu(ys.eventType,jn.current))return;gn(Qs=>{const Nl=Qs.filter(Sl=>Sl.id!==ys.id);return[ys,...Nl].slice(0,100)}),Pn(Qs=>Qs+1),$t&&requestAnimationFrame(()=>{const Qs=re.current;Qs&&(Qs.scrollTop=0)})}catch{}},"validator-run:started":Xe,"validator-run:completed":nt,"milestone:validation:updated":jt,"assertion:created":en,"assertion:updated":en,"assertion:deleted":en,"assertion:linked":en,"assertion:unlinked":en,"fix-feature:created":_n=>{const dn=_n;if(dn.data)try{const $t=JSON.parse(dn.data);if($t&&$t.sourceFeatureId){xs($t.sourceFeatureId);const fi=$t?.feature?.sliceId,ys=Ft.current;if(fi&&ys){const Qs=ys.milestones.find(Nl=>Nl.slices.some(Sl=>Sl.id===fi));Qs&&wt(Qs.id)}Ft.current&&We(Ft.current.id)}}catch{}}}})},[h,Re,We,pt,r,wt]);const ct=a.useCallback(()=>{P(!0),S(null),_(Tl)},[]),St=a.useCallback(U=>{S(U.id),P(!1),_({title:U.title,description:U.description||"",status:U.status,autopilotEnabled:U.autopilotEnabled??!1})},[]),Et=a.useCallback(()=>{S(null),P(!1),_(Tl)},[]),cn=a.useCallback(async()=>{if(!k.title.trim()){i("Mission title is required","error");return}try{if(T(!0),j)await Wy({title:k.title.trim(),description:k.description.trim()||void 0,autopilotEnabled:k.autopilotEnabled},r),i("Mission created","success");else if(w){const U={title:k.title.trim(),description:k.description.trim()||void 0,status:k.status,autopilotEnabled:k.autopilotEnabled};k.autopilotEnabled&&(U.autoAdvance=!0),await Ky(w,U,r),i("Mission updated","success"),f?.id===w&&await We(w)}await kt(),Et()}catch(U){i(fe(U)||"Failed to save mission","error")}finally{T(!1)}},[k,j,w,i,kt,We,f,Et,r]),Gt=a.useCallback(async U=>{try{await Gy(U,r),i("Mission deleted","success"),f?.id===U&&b(null),await kt(),te(null)}catch(Ce){i(fe(Ce)||"Failed to delete mission","error")}},[i,kt,f,r]),un=a.useCallback(()=>{z(!0),W(null),H($l)},[]),fn=a.useCallback(U=>{W(U.id),z(!1),H({title:U.title,description:U.description||"",status:U.status,dependencies:U.dependencies})},[]),kn=a.useCallback(()=>{W(null),z(!1),H($l)},[]),In=a.useCallback(async()=>{if(!Y.title.trim()){i("Milestone title is required","error");return}try{T(!0),A&&f?(await Qy(f.id,{title:Y.title.trim(),description:Y.description.trim()||void 0,dependencies:Y.dependencies},r),i("Milestone created","success")):N&&(await Xy(N,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status,dependencies:Y.dependencies},r),i("Milestone updated","success")),await We(f.id),kn()}catch(U){i(fe(U)||"Failed to save milestone","error")}finally{T(!1)}},[Y,A,N,f,i,We,kn,k.title,r]),ps=a.useCallback(async U=>{try{await Zy(U,r),i("Milestone deleted","success"),await We(f.id),te(null)}catch(Ce){i(fe(Ce)||"Failed to delete milestone","error")}},[i,We,f,r]),On=a.useCallback(U=>{bt(U),Oe(!0),Z(Ce=>{const qe=new Set(Ce);return!qe.has(U)?(qe.add(U),El(U,r).then(Zt=>{Ae(Rt=>{const Ht=new Map(Rt);return Ht.set(U,Zt),Ht})}).catch(()=>{}),Ml(U,r).then(Zt=>{Pt(Rt=>{const Ht=new Map(Rt);return Ht.set(U,Zt),Ht})}).catch(()=>{})):qe.delete(U),qe})},[r]),Jn=a.useCallback(U=>{ue(U),V(!0),C(null),oe(Fl)},[]),Bn=a.useCallback(U=>{C(U.id),V(!1),oe({title:U.title,description:U.description||"",status:U.status})},[]),Yn=a.useCallback(()=>{C(null),V(!1),ue(null),oe(Fl)},[]),bn=a.useCallback(async()=>{if(!q.title.trim()){i("Slice title is required","error");return}try{T(!0),O&&F?(await ej(F,{title:q.title.trim(),description:q.description.trim()||void 0},r),i("Slice created","success")):J&&(await tj(J,{title:q.title.trim(),description:q.description.trim()||void 0,status:q.status},r),i("Slice updated","success")),await We(f.id),Yn()}catch(U){i(fe(U)||"Failed to save slice","error")}finally{T(!1)}},[q,O,J,F,f,i,We,Yn,r]),Un=a.useCallback(async U=>{try{await nj(U,r),i("Slice deleted","success"),await We(f.id),te(null)}catch(Ce){i(fe(Ce)||"Failed to delete slice","error")}},[i,We,f,r]),fs=a.useCallback(async U=>{try{await sj(U,r),i("Slice activated","success"),await We(f.id)}catch(Ce){i(fe(Ce)||"Failed to activate slice","error")}},[i,We,f,r]),Fs=a.useCallback(U=>{R(Ce=>{const qe=new Set(Ce);return qe.has(U)?qe.delete(U):qe.add(U),qe})},[]),gs=a.useCallback(U=>{Pe(U),Ee(!0),K(null),Fe(Dl)},[]),wn=a.useCallback(U=>{K(U.id),Ee(!1),Fe({title:U.title,description:U.description||"",acceptanceCriteria:U.acceptanceCriteria||"",status:U.status})},[]),Qn=a.useCallback(()=>{K(null),Ee(!1),Pe(null),Fe(Dl)},[]),bs=a.useCallback(async()=>{if(!de.title.trim()){i("Feature title is required","error");return}try{T(!0),we&&ie?(await ij(ie,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):ce&&(await aj(ce,{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 We(f.id),Qn()}catch(U){i(fe(U)||"Failed to save feature","error")}finally{T(!1)}},[de,we,ce,ie,f,i,We,Qn,r]),bl=a.useCallback(async U=>{try{await rj(U,r),i("Feature deleted","success"),await We(f.id),te(null)}catch(Ce){i(fe(Ce)||"Failed to delete feature","error")}},[i,We,f,r]),lr=a.useCallback(async()=>{if(!ze||!He.trim()){i("Task ID is required","error");return}try{await lj(ze,He.trim(),r),i("Feature linked to task","success"),await We(f.id),$e(null),Me("")}catch(U){i(fe(U)||"Failed to link feature to task","error")}},[ze,He,i,We,f,r]),or=a.useCallback(async U=>{try{await oj(U,r),i("Feature unlinked from task","success"),await We(f.id)}catch(Ce){i(fe(Ce)||"Failed to unlink feature","error")}},[i,We,f,r]),Es=a.useCallback(async U=>{try{T(!0),await cj(U,void 0,void 0,r),i("Feature triaged — task created","success"),await We(f.id)}catch(Ce){i(fe(Ce)||"Failed to triage feature","error")}finally{T(!1)}},[i,We,f,r]),xl=a.useCallback(async U=>{ht(U);try{const Ce=await Lj(U,r);Ye({featureId:U,enrichedDescription:Ce.description})}catch{await Es(U)}finally{ht(null)}},[Es,r]),cr=a.useCallback(async()=>{ve&&(Ye(null),await Es(ve.featureId))},[Es,ve]),ne=a.useCallback(()=>{Ye(null)},[]),rt=a.useCallback(async U=>{try{T(!0);const Ce=await dj(U,r);i(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await We(f.id)}catch(Ce){i(fe(Ce)||"Failed to triage slice features","error")}finally{T(!1)}},[i,We,f,r]),ft=a.useCallback(async U=>{try{const Ce=await El(U,r);Ae(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch{}},[r]),At=a.useCallback(async U=>{try{const Ce=await Ml(U,r);Pt(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch{}},[r]),Ms=a.useCallback(async U=>{if(!st.title.trim()||!st.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await uj(U,{title:st.title.trim(),assertion:st.assertion.trim(),status:st.status},r),i("Assertion created","success"),await ft(U),await At(U),it(!1),Se({title:"",assertion:"",status:"pending"})}catch(Ce){i(fe(Ce)||"Failed to create assertion","error")}finally{T(!1)}},[st,i,ft,At,r]),Ys=a.useCallback(U=>{be(U.id),Se({title:U.title,assertion:U.assertion,status:U.status})},[]),_i=a.useCallback(()=>{be(null),it(!1),Se({title:"",assertion:"",status:"pending"})},[]),dr=a.useCallback(async(U,Ce)=>{if(!st.title.trim()||!st.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await mj(U,{title:st.title.trim(),assertion:st.assertion.trim(),status:st.status},r),i("Assertion updated","success"),await ft(Ce),await At(Ce),_i()}catch(qe){i(fe(qe)||"Failed to update assertion","error")}finally{T(!1)}},[st,i,ft,At,_i,r]),Ds=a.useCallback(async U=>{try{const Ce=await fj(U,r);at(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch{}},[r]),ur=a.useCallback(async U=>{const Ce=ye!==U;Ge(qe=>qe===U?null:U),Ce&&await Ds(U)},[ye,Ds]),mr=a.useCallback(U=>{Ge(U),Ds(U),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${U}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Ds]),vl=a.useCallback(async(U,Ce)=>{try{vt(qe=>new Set(qe).add(Ce)),await hj(U,Ce,r),i("Feature linked to assertion","success"),await Ds(Ce),zt(null)}catch(qe){i(fe(qe)||"Failed to link feature","error")}finally{vt(qe=>{const yt=new Set(qe);return yt.delete(Ce),yt})}},[i,Ds,r]),pa=a.useCallback(async(U,Ce)=>{const qe=`${U}-${Ce}`;try{_t(yt=>new Set(yt).add(qe)),await pj(U,Ce,r),i("Feature unlinked from assertion","success"),await Ds(Ce)}catch(yt){i(fe(yt)||"Failed to unlink feature","error")}finally{_t(yt=>{const Zt=new Set(yt);return Zt.delete(qe),Zt})}},[i,Ds,r]),fa=a.useCallback(async U=>{try{Ie(qe=>new Set(qe).add(U)),await gj(U,r),i("Validation triggered","success");const Ce=await vd(U,r);he(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch(Ce){i(fe(Ce)||"Failed to trigger validation","error")}finally{Ie(Ce=>{const qe=new Set(Ce);return qe.delete(U),qe})}},[i,r]),xs=a.useCallback(async U=>{try{const Ce=await vd(U,r);he(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch{}},[r]),Ls=a.useCallback(async U=>{try{const Ce=await bj(U,{limit:10},r);yn(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch{}},[r]),ga=a.useCallback(U=>{const Ce=Ft.current;if(Ce){for(const qe of Ce.milestones)for(const yt of qe.slices)if(yt.features.find(Rt=>Rt.id===U)){Z(Rt=>{const Ht=new Set(Rt);return Ht.add(qe.id),Ht}),R(Rt=>{const Ht=new Set(Rt);return Ht.add(yt.id),Ht}),gt(U),bt(qe.id),xs(U),Ls(U),requestAnimationFrame(()=>{const Rt=document.querySelector(`[data-mission-feature-id="${U}"]`);Rt instanceof HTMLElement&&typeof Rt.scrollIntoView=="function"&&Rt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[xs,Ls]),yl=a.useCallback(async U=>{try{const Ce=await xj(U,r);Cn(qe=>{const yt=new Map(qe);return yt.set(U,Ce),yt})}catch{}},[r]),As=a.useCallback(async U=>{Be===U?gt(null):(gt(U),await xs(U),await Ls(U))},[Be,xs,Ls]),si=a.useCallback(async U=>{mn===U?Kn(null):(Kn(U),await yl(U))},[mn,yl]),Ps=a.useCallback(async U=>{try{await vj(U,r),i("Mission resumed","success"),await We(U),kt()}catch(Ce){i(fe(Ce)||"Failed to resume mission","error")}},[i,We,kt,r]),Is=a.useCallback(async U=>{try{const qe=(await yj(U,r)).pausedTaskIds?.length??0;i(`Mission stopped (${qe} task${qe!==1?"s":""} paused)`,"success"),await We(U),kt()}catch(Ce){i(fe(Ce)||"Failed to stop mission","error")}},[i,We,kt,r]),jl=a.useCallback(async U=>{try{await jj(U,r),i("Mission started — first slice activated","success"),await We(U),kt()}catch(Ce){i(fe(Ce)||"Failed to start mission","error")}},[i,We,kt,r]),kf=a.useCallback(async(U,Ce)=>{try{await kj(U,{enabled:Ce},r),i(Ce?"Autopilot enabled":"Autopilot disabled","success"),await We(U),kt()}catch(qe){i(fe(qe)||"Failed to update autopilot","error")}},[i,We,kt,r]),$c=a.useCallback(U=>{Xt("structure"),bt(null),ot(null),gn([]),Pn(0),Ke("all"),B(new Set),We(U.id)},[We]),wf=a.useCallback(()=>{b(null),bt(null),ot(null),Xt("structure"),gn([]),Pn(0),Ke("all"),B(new Set),kt()},[kt]),kl=hn.length<Gn,Ri=f?.autopilotState??"inactive",Fc=Ri==="watching"||Ri==="activating",Dc=vN(Ri,f?.lastAutopilotActivityAt),hr=a.useMemo(()=>!Ue||!tt||!Ll(Ue)?null:Ue.rollup.milestoneId===tt?Ue:null,[tt,Ue]),Nf=a.useMemo(()=>{const U=new Map;for(const Ce of hr?.validationTelemetry.validationRounds??[]){const qe=U.get(Ce.featureId);(!qe||Ce.startedAt>qe.startedAt)&&U.set(Ce.featureId,Ce)}return U},[hr]),Sf=a.useCallback(()=>{!f||zn||!kl||ae(f.id,{append:!0})},[zn,kl,ae,f]),Cf=a.useCallback(U=>{B(Ce=>{const qe=new Set(Ce);return qe.has(U)?qe.delete(U):qe.add(U),qe})},[]),wl=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),cn())},[cn]),Lc=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),In())},[In]),zc=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),bn())},[bn]),Oc=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),bs())},[bs]),Ef=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const U=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[h,s]),!h)return null;const Bc=e.jsxs("div",{ref:Ef,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:wf,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:e.jsx(sc,{size:18})}):null,e.jsx(ts,{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(Lt,{size:18})})]}),e.jsx("div",{className:"mission-manager__body",children:x?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(ut,{size:24,className:"spinner"}),e.jsx("span",{children:"Loading missions..."})]}):y?e.jsxs("div",{className:"mission-manager__loading",children:[e.jsx(ut,{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:[Fc&&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:(ya[f.status]||ya.planning).bg,color:(ya[f.status]||ya.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:U=>kf(f.id,U.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(Nn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),e.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(vr[Ri]||vr.inactive).bg,color:(vr[Ri]||vr.inactive).text},"data-testid":"autopilot-state-badge",children:[Fc&&e.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ri]})]}),Dc&&e.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Dc})]}),e.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Is(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:()=>Ps(f.id),title:"Resume mission","aria-label":"Resume mission",children:e.jsx(ln,{size:14})}),f.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>jl(f.id),title:"Start mission","aria-label":"Start mission",children:e.jsx(ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>St(f),title:"Edit mission","aria-label":"Edit mission",children:e.jsx($n,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:e.jsx(qt,{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:U=>_({...k,title:U.target.value}),onKeyDown:wl,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:U=>_({...k,description:U.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:k.status,onChange:U=>_({...k,status:U.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:U=>_({...k,autopilotEnabled:U.target.checked})}),e.jsx(Nn,{size:12})," Autopilot"]})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:cn,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Et,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[e.jsx("button",{className:`mission-btn ${Ut==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Xt("structure"),role:"tab","aria-selected":Ut==="structure","data-testid":"mission-tab-structure",children:"Structure"}),e.jsxs("button",{className:`mission-btn ${Ut==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Xt("activity"),role:"tab","aria-selected":Ut==="activity","data-testid":"mission-tab-activity",children:["Activity (",Gn,")"]})]}),Ut==="structure"?e.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(U=>{const Ce=hr?.rollup.milestoneId===U.id?hr:null,qe=Ce?.rollup??Nt.get(U.id),yt=Ce?.validationTelemetry.validationRounds??[],Zt=Ce?.fixFeatures??[],Rt=Qd[qe?.state??"not_started"]??Qd.not_started,Ht=qe&&(qe.state==="blocked"||qe.state==="failed")?Ce?.validationTelemetry.validationRounds.find(Xe=>Xe.blockedReason)?.blockedReason:void 0;return e.jsxs("div",{className:"mission-milestone",children:[e.jsxs("div",{className:"mission-milestone__header",onClick:()=>On(U.id),children:[e.jsx("button",{className:"mission-milestone__expand",children:D.has(U.id)?e.jsx(Ot,{size:16}):e.jsx(on,{size:16})}),e.jsx(Si,{size:16,className:"mission-milestone__icon"}),e.jsx("span",{className:"mission-milestone__title",children:U.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Jd[U.status].bg,color:Jd[U.status].text},children:U.status}),e.jsxs("span",{className:"mission-milestone__count",children:[U.slices.length," slices"]}),e.jsx(Xd,{state:mN(U.interviewState)}),qe&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Rt.bg,color:Rt.text},title:"Validation state",children:Zd(qe.state)}),qe.totalAssertions>0&&e.jsx("div",{className:"mission-milestone__coverage-bar",title:`${qe.passedAssertions??0} of ${qe.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(qe.passedAssertions??0)/qe.totalAssertions*100}%`,backgroundColor:(qe.passedAssertions??0)===qe.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),U.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"milestone",id:U.id,title:U.title}),title:"Plan milestone","aria-label":"Plan milestone",children:e.jsx(wi,{size:14})}),e.jsxs("div",{className:"mission-milestone__actions",onClick:Xe=>Xe.stopPropagation(),children:[e.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(U.id),title:"Add slice",children:e.jsx(Vt,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>fn(U),title:"Edit milestone",children:e.jsx($n,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"milestone",id:U.id}),title:"Delete milestone",children:e.jsx(qt,{size:14})})]})]}),D.has(U.id)&&e.jsxs("div",{className:"mission-milestone__body",children:[(A||N===U.id)&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:Xe=>H({...Y,title:Xe.target.value}),onKeyDown:Lc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:Xe=>H({...Y,description:Xe.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:In,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),N?"Update":"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:kn,children:"Cancel"})]})]}),Ce&&e.jsxs("div",{className:"mission-validation-telemetry",children:[e.jsxs("div",{className:"mission-validation-telemetry__header",children:[e.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),e.jsxs("span",{className:"mission-validation-telemetry__meta",children:[Ce.validationTelemetry.totalRuns," rounds",Ce.validationTelemetry.lastValidatorStatus?` · Last ${Ce.validationTelemetry.lastValidatorStatus}`:""]})]}),Ht&&e.jsxs("div",{className:"mission-blocked-reason",children:[e.jsx("strong",{children:"Blocked reason:"})," ",Ht]}),yt.length>0&&e.jsxs("div",{className:"mission-validation-rounds",children:[e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>Oe(Xe=>!Xe),title:ge?"Hide validation rounds":"Show validation rounds",children:[ge?e.jsx(Ot,{size:12}):e.jsx(on,{size:12}),"Validation rounds (",yt.length,")"]}),ge&&e.jsx("div",{className:"mission-validation-rounds__list",children:yt.map(Xe=>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--${Xe.validatorStatus}`,children:Xe.validatorStatus}),e.jsx("span",{className:"mission-validation-round__feature",children:Xe.featureTitle}),e.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Xe.implementationAttempt," · validator #",Xe.validatorAttempt]})]}),e.jsxs("div",{className:"mission-validation-round__links",children:[e.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Xe.failedAssertionIds.length>0?e.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(nt=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>mr(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):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:"}),Xe.generatedFixFeatureIds.length>0?e.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.generatedFixFeatureIds.map(nt=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ga(nt),title:`Jump to fix feature ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):e.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Xe.blockedReason&&e.jsx("div",{className:"mission-validation-round__blocked-reason",children:Xe.blockedReason})]},Xe.roundId))})]}),Zt.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:Zt.map(Xe=>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:()=>ga(Xe.id),title:`Jump to feature ${Xe.id}`,children:Xe.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:xr[Xe.status].bg,color:xr[Xe.status].text},children:Xe.status}),Xe.loopState&&e.jsx("span",{className:`mission-loop-state mission-loop-state--${Xe.loopState}`,children:Xe.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:()=>ga(Xe.sourceFeatureId),title:`Jump to source feature ${Xe.sourceFeatureId}`,children:Xe.sourceFeatureId}),e.jsx("span",{children:"Run:"}),e.jsx("span",{className:"mission-fix-feature__run",children:Xe.runId})]}),Xe.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:Xe.failedAssertionIds.map(nt=>e.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>mr(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.id}-${nt}`))})]})]},Xe.id))})]})]}),e.jsxs("div",{className:"mission-slices",children:[U.slices.map(Xe=>e.jsxs("div",{className:"mission-slice",children:[e.jsxs("div",{className:"mission-slice__header",onClick:()=>Fs(Xe.id),children:[e.jsx("button",{className:"mission-slice__expand",children:$.has(Xe.id)?e.jsx(Ot,{size:16}):e.jsx(on,{size:16})}),e.jsx(Po,{size:16,className:"mission-slice__icon"}),e.jsx("span",{className:"mission-slice__title",children:Xe.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yd[Xe.status].bg,color:Yd[Xe.status].text},children:Xe.status}),e.jsxs("span",{className:"mission-slice__count",children:[Xe.features?.length||0," features"]}),e.jsx(Xd,{state:Xe.planState??"not_started"}),Xe.status!=="complete"&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>Le({type:"slice",id:Xe.id,title:Xe.title}),title:"Plan slice","aria-label":"Plan slice",children:e.jsx(wi,{size:14})}),e.jsxs("div",{className:"mission-slice__actions",onClick:nt=>nt.stopPropagation(),children:[Xe.status==="pending"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>fs(Xe.id),title:"Activate slice",children:e.jsx(ln,{size:14})}),Xe.status==="active"&&Xe.features?.some(nt=>nt.status==="defined")&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>rt(Xe.id),title:"Triage all features",disabled:E,children:E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(Nn,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>gs(Xe.id),title:"Add feature",children:e.jsx(Vt,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Bn(Xe),title:"Edit slice",children:e.jsx($n,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"slice",id:Xe.id}),title:"Delete slice",children:e.jsx(qt,{size:14})})]})]}),$.has(Xe.id)&&e.jsxs("div",{className:"mission-slice__body",children:[O&&F===U.id&&!J&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:q.title,onChange:nt=>oe({...q,title:nt.target.value}),onKeyDown:zc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:q.description,onChange:nt=>oe({...q,description:nt.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bn,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),J===Xe.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Slice title",value:q.title,onChange:nt=>oe({...q,title:nt.target.value}),onKeyDown:zc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:q.description,onChange:nt=>oe({...q,description:nt.target.value}),rows:2}),e.jsxs("select",{value:q.status,onChange:nt=>oe({...q,status:nt.target.value}),children:[e.jsx("option",{value:"pending",children:"Pending"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"complete",children:"Complete"})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bn,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-features",children:[Xe.features?.map(nt=>e.jsxs("div",{className:"mission-feature","data-mission-feature-id":nt.id,children:[e.jsxs("div",{className:"mission-feature__header",children:[e.jsx("button",{className:"mission-feature__expand",onClick:()=>As(nt.id),title:Be===nt.id?"Collapse details":"Expand to show run history",children:Be===nt.id?e.jsx(Ot,{size:14}):e.jsx(on,{size:14})}),e.jsx(So,{size:14,className:"mission-feature__icon"}),e.jsx("span",{className:"mission-feature__title",children:nt.title}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:xr[nt.status].bg,color:xr[nt.status].text},children:nt.status}),nt.loopState&&nt.loopState!=="idle"&&e.jsxs("span",{className:`mission-loop-state mission-loop-state--${nt.loopState}`,title:`Loop state: ${nt.loopState}`,children:[nt.loopState==="implementing"&&"⏳",nt.loopState==="validating"&&"🔄",nt.loopState==="needs_fix"&&"🔧",nt.loopState==="passed"&&"✅",nt.loopState==="blocked"&&"🚫"]}),nt.generatedFromFeatureId&&e.jsx("button",{className:"mission-feature__lineage",onClick:()=>ga(nt.generatedFromFeatureId),title:`Generated from feature: ${nt.generatedFromFeatureId}`,children:"🔗 Fix"}),(nt.loopState==="validating"||nt.loopState==="needs_fix")&&(()=>{const jt=xt.get(nt.id),en=Nf.get(nt.id),vs=jt?.implementationAttemptCount??en?.implementationAttempt??nt.implementationAttemptCount??0,pi=jt?.retryBudgetRemaining??Math.max(0,uN-vs);return e.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",vs," · ",pi," ",pi===1?"retry":"retries"," left"]})})(),nt.loopState==="implementing"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>fa(nt.id),title:"Validate feature",disabled:ee.has(nt.id),children:ee.has(nt.id)?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(Dn,{size:14})}),nt.taskId&&e.jsx("span",{className:"mission-feature__task-link",onClick:()=>l?.(nt.taskId),title:"Click to view task",children:nt.taskId}),e.jsxs("div",{className:"mission-feature__actions",children:[nt.status==="defined"&&!nt.taskId&&e.jsx("button",{className:"mission-icon-btn",onClick:()=>xl(nt.id),title:"Triage — create task",disabled:E||mt===nt.id,children:mt===nt.id?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(Nn,{size:14})}),nt.taskId?e.jsx("button",{className:"mission-icon-btn",onClick:()=>or(nt.id),title:"Unlink task",children:e.jsx(Gc,{size:14})}):nt.status!=="defined"?e.jsx("button",{className:"mission-icon-btn",onClick:()=>$e(nt.id),title:"Link to task",children:e.jsx(Ji,{size:14})}):null,e.jsx("button",{className:"mission-icon-btn",onClick:()=>wn(nt),title:"Edit feature",children:e.jsx($n,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"feature",id:nt.id}),title:"Delete feature",children:e.jsx(qt,{size:14})})]})]}),nt.description&&e.jsx("p",{className:"mission-feature__description",children:nt.description}),nt.acceptanceCriteria&&e.jsxs("p",{className:"mission-feature__criteria",children:[e.jsx("strong",{children:"Acceptance:"})," ",nt.acceptanceCriteria]}),ve?.featureId===nt.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:ve.enrichedDescription}),e.jsxs("div",{className:"mission-triage-preview__actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:cr,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):null,"Create Task"]}),e.jsx("button",{className:"btn",onClick:ne,disabled:E,children:"Cancel"})]})]}),ce===nt.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:jt=>Fe({...de,title:jt.target.value}),onKeyDown:Oc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:jt=>Fe({...de,description:jt.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:jt=>Fe({...de,acceptanceCriteria:jt.target.value}),rows:2}),e.jsxs("select",{value:de.status,onChange:jt=>Fe({...de,status:jt.target.value}),children:[e.jsx("option",{value:"defined",children:"Defined"}),e.jsx("option",{value:"triaged",children:"Triaged"}),e.jsx("option",{value:"in-progress",children:"In Progress"}),e.jsx("option",{value:"done",children:"Done"})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bs,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),Be===nt.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"})}),(Kt.get(nt.id)??[]).map(jt=>e.jsxs("div",{className:"mission-run",children:[e.jsxs("div",{className:"mission-run__header",onClick:()=>si(jt.id),children:[e.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${jt.status}`,title:jt.status,children:jt.status}),e.jsx("span",{className:"mission-run__time",children:new Date(jt.startedAt).toLocaleString()}),jt.completedAt&&e.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(jt.completedAt).getTime()-new Date(jt.startedAt).getTime())/1e3),"s"]}),jt.triggerType&&e.jsx("span",{className:"mission-run__trigger",children:jt.triggerType}),e.jsx("button",{className:"mission-icon-btn",title:mn===jt.id?"Hide details":"Show details",children:mn===jt.id?e.jsx(Ot,{size:12}):e.jsx(on,{size:12})})]}),mn===jt.id&&Wt.get(jt.id)&&e.jsxs("div",{className:"mission-run__details",children:[jt.summary&&e.jsx("p",{className:"mission-run__summary",children:jt.summary}),jt.blockedReason&&e.jsxs("p",{className:"mission-run__blocked-reason",children:[e.jsx("strong",{children:"Blocked:"})," ",jt.blockedReason]}),Wt.get(jt.id)?.failures&&Wt.get(jt.id).failures.length>0&&e.jsxs("div",{className:"mission-run__failures",children:[e.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Wt.get(jt.id).failures.map(en=>e.jsxs("div",{className:"mission-run__failure",children:[e.jsx("span",{className:"mission-run__failure-message",children:en.message}),en.expected&&e.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",en.expected]}),en.actual&&e.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",en.actual]})]},en.id))]}),(!Wt.get(jt.id)?.failures||Wt.get(jt.id).failures.length===0)&&e.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},jt.id)),(!Kt.get(nt.id)||Kt.get(nt.id).length===0)&&e.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},nt.id)),we&&ie===Xe.id&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:nt=>Fe({...de,title:nt.target.value}),onKeyDown:Oc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:nt=>Fe({...de,description:nt.target.value}),rows:2}),e.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:nt=>Fe({...de,acceptanceCriteria:nt.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:bs,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),!we&&(!Xe.features||Xe.features.length===0)&&e.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[e.jsx(So,{size:16}),e.jsx("span",{children:"No fix features generated."})]})]})]})]},Xe.id)),U.slices.length===0&&!O&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(Po,{size:16}),e.jsx("span",{children:"No slices yet"})]}),e.jsxs("div",{className:"mission-assertions",children:[e.jsxs("div",{className:"mission-assertions__header",children:[e.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),qe&&e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Rt.bg,color:Rt.text},children:Zd(qe.state)}),qe&&qe.totalAssertions>0&&e.jsx("div",{className:"mission-assertions__coverage-bar",title:`${qe.passedAssertions??0} of ${qe.totalAssertions} assertions passing`,children:e.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(qe.passedAssertions??0)/qe.totalAssertions*100}%`,backgroundColor:(qe.passedAssertions??0)===qe.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>{it(!0),be(null),Se({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:e.jsx(Vt,{size:14})})]}),Je&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:st.title,onChange:Xe=>Se({...st,title:Xe.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:st.assertion,onChange:Xe=>Se({...st,assertion:Xe.target.value}),rows:2}),e.jsxs("select",{value:st.status,onChange:Xe=>Se({...st,status:Xe.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:()=>Ms(U.id),disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_i,children:"Cancel"})]})]}),e.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(je.get(U.id))?je.get(U.id):[]).map(Xe=>e.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Xe.id,children:[e.jsx("div",{className:"mission-assertion__header",children:Qe===Xe.id?e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Assertion title",value:st.title,onChange:nt=>Se({...st,title:nt.target.value}),autoFocus:!0}),e.jsx("textarea",{placeholder:"Assertion text",value:st.assertion,onChange:nt=>Se({...st,assertion:nt.target.value}),rows:2}),e.jsxs("select",{value:st.status,onChange:nt=>Se({...st,status:nt.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:()=>dr(Xe.id,U.id),disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Save"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_i,children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(yr[Xe.status]??yr.pending).bg,color:(yr[Xe.status]??yr.pending).text},children:Xe.status}),e.jsx("span",{className:"mission-assertion__title",children:Xe.title}),(()=>{const jt=Ne.get(Xe.id)?.length??0;return jt>0?e.jsxs("span",{className:"mission-assertion__linked-count",title:`${jt} linked feature${jt!==1?"s":""}`,children:["(",jt," linked)"]}):null})(),e.jsx("button",{className:"mission-icon-btn",onClick:()=>ur(Xe.id),title:"Toggle details",children:ye===Xe.id?e.jsx(Ot,{size:14}):e.jsx(on,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>Ys(Xe),title:"Edit assertion",children:e.jsx($n,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"assertion",id:Xe.id}),title:"Delete assertion",children:e.jsx(qt,{size:14})})]})}),ye===Xe.id&&e.jsxs("div",{className:"mission-assertion__body",children:[e.jsx("p",{className:"mission-assertion__text",children:Xe.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()=>{ye!==Xe.id&&await ur(Xe.id),zt(Mt===Xe.id?null:Xe.id)},title:"Link a feature",children:[e.jsx(Ji,{size:12}),"Link Feature"]})]}),Mt===Xe.id&&e.jsx("div",{className:"mission-assertion__feature-picker",children:e.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const nt=new Set((Ne.get(Xe.id)??[]).map(en=>en.id)),jt=[];return f?.milestones.forEach(en=>en.slices.forEach(vs=>jt.push(...vs.features.filter(pi=>!nt.has(pi.id))))),jt.length===0?e.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):jt.map(en=>e.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>vl(en.id,Xe.id),disabled:dt.has(Xe.id),children:[e.jsx("span",{className:"mission-assertion__feature-picker-title",children:en.title}),dt.has(Xe.id)&&e.jsx(ut,{size:12,className:"spinner"})]},en.id))})()})}),(()=>{const nt=Ne.get(Xe.id)??[];return nt.length===0?e.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):nt.map(jt=>{const en=`${jt.id}-${Xe.id}`,vs=It.has(en);return e.jsxs("div",{className:"mission-assertion__linked-feature",children:[e.jsx("span",{className:"mission-assertion__linked-feature-title",children:jt.title}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>pa(jt.id,Xe.id),disabled:vs,title:"Unlink feature",children:vs?e.jsx(ut,{size:12,className:"spinner"}):e.jsx(Gc,{size:12})})]},jt.id)})})()]})]})]},Xe.id)),(!je.get(U.id)||je.get(U.id)?.length===0)&&!Je&&e.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:e.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},U.id)}),f&&!A&&N===null&&e.jsxs("button",{className:"mission-add-btn",onClick:un,children:[e.jsx(Vt,{size:16}),"Add Milestone"]}),A&&N===null&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Milestone title",value:Y.title,onChange:U=>H({...Y,title:U.target.value}),onKeyDown:Lc,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:U=>H({...Y,description:U.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:In,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:kn,children:"Cancel"})]})]}),f.milestones.length===0&&!A&&e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(Si,{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:G,onChange:U=>Ke(U.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:[hn.length," of ",Gn]})]}),!zn&&kl&&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:Sf,"data-testid":"mission-activity-load-more",children:"Load more"})}),zn?e.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[e.jsx(ut,{size:18,className:"spinner"}),e.jsx("span",{children:"Loading mission activity..."})]}):hn.length===0?e.jsxs("div",{className:"mission-manager__empty",children:[e.jsx(Ss,{size:18}),e.jsx("span",{children:"No events yet."})]}):e.jsxs("div",{ref:re,className:"mission-events","data-testid":"mission-activity-events",children:[hn.map(U=>{const Ce=!!(U.metadata&&Object.keys(U.metadata).length>0),qe=I.has(U.id);return e.jsxs("div",{className:"mission-event",children:[e.jsxs("div",{className:"mission-event__header",children:[e.jsx("span",{className:`mission-event__type ${bN(U.eventType)}`,children:xN(U.eventType)}),e.jsx("span",{className:"mission-event__time",children:Gr(U.timestamp)})]}),e.jsx("p",{className:"mission-event__description",children:U.description}),e.jsx("span",{className:"mission-event__timestamp",children:new Date(U.timestamp).toLocaleString()}),Ce&&e.jsxs("div",{className:"mission-event__metadata",children:[e.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Cf(U.id),"data-testid":`mission-event-metadata-${U.id}`,children:[qe?"Hide":"Show"," metadata"]}),qe&&e.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(U.metadata,null,2)})]})]},U.id)}),e.jsx("div",{ref:pe})]})]})]}):e.jsxs("div",{className:"mission-list",children:[j&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:U=>_({...k,title:U.target.value}),onKeyDown:wl,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:U=>_({...k,description:U.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:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Create"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Et,children:"Cancel"})]})]}),g.map(U=>{const Ce=U,qe=f,yt=qe&&qe.id===Ce.id,Zt=ya[Ce.status]||{bg:"",text:""},Rt=Ce.summary,Ht=Tn.get(Ce.id),Xe=pN(Ht),nt=!!(Rt&&(Rt.totalMilestones>0||Rt.totalFeatures>0)),jt=Ht?.totalTasks??0,en=Ht?.tasksCompleted??0,vs=Ht?.tasksFailed??0,pi=Ht?.estimatedCompletionPercent??Rt?.progressPercent??0,_n=nt||jt>0||vs>0||!!Ht?.lastActivityAt,dn=Ce.status==="active"&&(Ht?.currentMilestoneId||Ht?.currentSliceId)?"Current milestone/slice in progress":null;return e.jsxs("div",{className:`mission-list__item ${yt?"mission-list__item--selected":""}`,onClick:()=>$c(U),children:[e.jsxs("div",{className:"mission-list__item-content",children:[e.jsxs("div",{className:"mission-list__item-header",children:[e.jsx(ts,{size:16,className:"mission-list__item-icon"}),e.jsx("span",{className:"mission-list__item-title",children:Ce.title}),U.autopilotEnabled&&e.jsx("span",{title:"Autopilot enabled",children:e.jsx(Nn,{size:12,className:"mission-list__item-autopilot-icon"})}),e.jsx("span",{className:`mission-health-badge mission-health-badge--${Xe}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${Xe}`}),e.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Zt.bg,color:Zt.text},children:Ce.status})]}),Ce.description&&e.jsx("p",{className:"mission-list__item-description",children:Ce.description}),dn&&e.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",dn]}),_n&&e.jsxs("div",{className:"mission-list__item-summary",children:[nt&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"mission-list__item-stat",children:[Rt.completedMilestones,"/",Rt.totalMilestones," milestones"]}),e.jsxs("span",{className:"mission-list__item-stat",children:[Rt.completedFeatures,"/",Rt.totalFeatures," features"]})]}),e.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[en,"/",jt," tasks"]}),vs>0&&e.jsxs("button",{className:"mission-list__item-failed",onClick:$t=>{$t.stopPropagation(),$c(U)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[vs," failed"]}),e.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",Gr(Ht?.lastActivityAt)]}),e.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Xe}`,children:e.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${pi}%`}})})]})]}),e.jsxs("div",{className:"mission-list__item-actions",onClick:$t=>$t.stopPropagation(),children:[Ce.status==="active"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Is(Ce.id),title:"Stop mission",children:e.jsx(os,{size:14})}),Ce.status==="blocked"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ps(Ce.id),title:"Resume mission",children:e.jsx(ln,{size:14})}),Ce.status==="planning"&&e.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>jl(Ce.id),title:"Start mission",children:e.jsx(ln,{size:14})}),e.jsx("button",{className:"mission-icon-btn",onClick:()=>St(U),title:"Edit mission",children:e.jsx($n,{size:14})}),e.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>te({type:"mission",id:Ce.id}),title:"Delete mission",children:e.jsx(qt,{size:14})})]})]},Ce.id)}),w&&e.jsxs("div",{className:"mission-form-card",children:[e.jsx("input",{type:"text",placeholder:"Mission title",value:k.title,onChange:U=>_({...k,title:U.target.value}),onKeyDown:wl,autoFocus:!0}),e.jsx("textarea",{placeholder:"Description (optional)",value:k.description,onChange:U=>_({...k,description:U.target.value}),rows:2}),e.jsxs("div",{className:"mission-form-card__row",children:[e.jsxs("select",{value:k.status,onChange:U=>_({...k,status:U.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:U=>_({...k,autopilotEnabled:U.target.checked})}),e.jsx(Nn,{size:12})," Autopilot"]})]}),e.jsxs("div",{className:"mission-form-card__actions",children:[e.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:cn,disabled:E,children:[E?e.jsx(ut,{size:14,className:"spinner"}):e.jsx(An,{size:14}),"Update"]}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Et,children:"Cancel"})]})]}),g.length===0&&!j&&e.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[e.jsx(ts,{size:32}),e.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!j&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[_e.length>0&&e.jsxs("div",{className:"mission-resume-prompt",children:[e.jsx(ss,{size:16}),e.jsx("span",{children:_e.length===1?`Resume "${_e[0].title}"?`:`${_e.length} interview sessions pending`}),e.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:_e.map(U=>e.jsxs("button",{className:"mission-add-btn",onClick:()=>{X(U.id),Ve(!0),et([])},children:[U.status==="error"?e.jsx(vn,{size:14}):e.jsx(Dn,{size:14}),U.status==="error"?"Retry":"Resume"]},U.id))})]}),e.jsxs("div",{style:{display:"flex",gap:"8px"},children:[e.jsxs("button",{className:"mission-add-btn",onClick:()=>Ve(!0),children:[e.jsx(Dn,{size:16}),"Plan with AI"]}),e.jsxs("button",{className:"mission-add-btn",onClick:ct,children:[e.jsx(Vt,{size:16}),"New Mission"]})]})]})]})}),me&&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 ",me.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()=>{me.type==="mission"?await Gt(me.id):me.type==="milestone"?await ps(me.id):me.type==="slice"?await Un(me.id):me.type==="feature"&&await bl(me.id)},children:"Delete"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>te(null),children:"Cancel"})]})]})}),ze&&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:He,onChange:U=>Me(U.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(U=>e.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Me(U.id),children:[U.id,": ",U.title||"Untitled"]},U.id))})]}),e.jsxs("div",{className:"mission-confirm-panel__actions",children:[e.jsx("button",{className:"mission-btn mission-btn--primary",onClick:lr,children:"Link"}),e.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{$e(null),Me("")},children:"Cancel"})]})]})})]}),Uc=e.jsx(aN,{isOpen:Te,onClose:()=>Ve(!1),onMissionCreated:()=>{kt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:ke}),Hc=se?e.jsx(oN,{isOpen:!0,onClose:()=>Le(null),onApplied:()=>{Le(null),f&&We(f.id)},targetType:se.type,targetId:se.id,targetTitle:se.title,missionContext:f?.title,projectId:r,resumeSessionId:se.resumeSessionId}):null;return n?e.jsxs(e.Fragment,{children:[Bc,Uc,Hc]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mission-manager-overlay open",onClick:U=>U.target===U.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Bc}),Uc,Hc]})}const jr=2e3;function tu({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,v]=a.useState(null),y=m.trim()!==""&&g.trim().length>0&&g.length<=jr,M=a.useCallback(async()=>{if(!(!y||f)){b(!0),v(null);try{const P=u==="agent"?"user-to-agent":"system";await Wj({toId:m.trim(),toType:u,content:g.trim(),type:P,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(P){const w=fe(P)||"Failed to send message";v(w),o?.(w,"error")}finally{b(!1)}}},[y,f,m,u,g,n,i,r,o]),j=a.useCallback(P=>{c(P),h("agent")},[]);return e.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[e.jsxs("div",{className:"message-composer-header",children:[e.jsx("span",{children:n?"Reply":"New Message"}),e.jsx("button",{className:"btn-icon",onClick:l,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:e.jsx(Lt,{size:16})})]}),e.jsxs("div",{className:"message-composer-body",children:[!t&&e.jsxs("div",{className:"message-composer-field",children:[e.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),e.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:m,onChange:P=>j(P.target.value),disabled:d||s.length===0,"data-testid":"message-composer-recipient",children:[e.jsx("option",{value:"",children:d?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(P=>e.jsx("option",{value:P.id,children:P.name||P.id},P.id))]})]}),t&&e.jsxs("div",{className:"message-composer-field",children:[e.jsx("span",{className:"message-composer-label",children:"To:"}),e.jsxs("span",{className:"message-composer-recipient-fixed",children:[e.jsx(rn,{size:14}),t.id]})]}),n&&e.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[e.jsx("span",{className:"message-composer-label",children:"Replying to:"}),e.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),e.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[e.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),e.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:P=>p(P.target.value),maxLength:jr,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>jr?"over-limit":"",children:[g.length,"/",jr]})})]}),x&&e.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[e.jsx(ss,{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:!y||f,"data-testid":"message-composer-send",children:f?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:14,className:"spin"}),e.jsx("span",{children:"Sending…"})]}):e.jsxs(e.Fragment,{children:[e.jsx(yi,{size:14}),e.jsx("span",{children:"Send"})]})})]})]})}function Li(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 jN(t,n,s){if(n==="user")return t==="dashboard"?"You":`User: ${t}`;if(n==="agent"){const i=s?.get(t)?.trim();return i?i===t?`Agent: ${t}`:`Agent: ${i} (${t})`:`Agent: ${t}`}return"System"}function kN(t){switch(t){case"agent-to-agent":return"Agent ↔ Agent";case"agent-to-user":return"Agent → You";case"user-to-agent":return"You → Agent";case"system":return"System"}}function nu(t,n=80){return t.length<=n?t:`${t.slice(0,n)}…`}function wN(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 NN({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([]),[v,y]=a.useState(!1),[M,j]=a.useState(null),[P,w]=a.useState(null),[S,k]=a.useState(null),[_,E]=a.useState("inbox"),[T,D]=a.useState(null),[Z,$]=a.useState([]),R=a.useMemo(()=>new Map(Z.map(ie=>[ie.id,ie.name??""])),[Z]),N=a.useCallback((ie,Pe)=>jN(ie,Pe,R),[R]),Y=sr()==="mobile",H=!Y,A=a.useCallback(async()=>{g(!0);try{const ie=await qj({limit:50},t);o(ie),u(ie.unreadCount),s?.(ie.unreadCount)}catch{}finally{g(!1)}},[t,s]),z=a.useCallback(async()=>{g(!0);try{const ie=await Vj({limit:50},t);m(ie)}catch{}finally{g(!1)}},[t]),J=a.useCallback(async ie=>{g(!0);try{const Pe=await Qj(ie,t);D(Pe)}catch{}finally{g(!1)}},[t]),C=a.useCallback(async()=>{try{const ie=await da(void 0,t);$(ie)}catch{}},[t]),q=a.useCallback(async()=>{try{const ie=await Eh(t);u(ie.unreadCount),s?.(ie.unreadCount)}catch{}},[t,s]);a.useEffect(()=>{i==="inbox"?A():i==="outbox"?z():i==="agents"&&C()},[i,A,z,C]),a.useEffect(()=>{S&&J(S)},[S,J]),a.useEffect(()=>{q()},[q]),a.useEffect(()=>{C()},[C]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ie=t?`?projectId=${encodeURIComponent(t)}`:"",Pe=()=>{q(),i==="inbox"?A():i==="outbox"&&z(),S&&J(S)};return Gs(`/api/events${ie}`,{events:{"message:sent":Pe,"message:received":Pe,"message:read":Pe,"message:deleted":Pe}})},[t,i,S,q,A,z,J]);const oe=a.useCallback(async ie=>{if(f(ie),!ie.read)try{const Pe=await Kj(ie.id,t);Pe&&o($e=>$e&&{...$e,messages:$e.messages.map(He=>He.id===Pe.id?Pe:He),unreadCount:Math.max(0,$e.unreadCount-1)});const ze=Math.max(0,c-1);u(ze),s?.(ze)}catch{}try{const Pe=await Yj(ie.fromId,ie.fromType,t);x(Pe)}catch{x([ie])}},[t,c,s]),O=a.useCallback(()=>{f(null),x([])},[]),V=a.useCallback(async()=>{try{const ie=await Gj(t);u(0),s?.(0),o(Pe=>Pe&&{...Pe,messages:Pe.messages.map(ze=>({...ze,read:!0})),unreadCount:0}),n?.(`Marked ${ie.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[t,n,s]),F=a.useCallback(async ie=>{try{await Jj(ie,t),f(null),x([]),i==="inbox"?A():i==="outbox"?z():S&&J(S),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[t,i,S,A,z,J,n]),ue=a.useCallback(ie=>{j({id:ie.fromId,type:ie.fromType}),w({messageId:ie.id,preview:nu(ie.content,120)}),y(!0)},[]),ce=a.useCallback(()=>{y(!1),j(null),w(null),n?.("Message sent","success"),i==="outbox"?z():i==="agents"&&S&&J(S),q()},[i,z,S,J,n,q]),K=a.useCallback(()=>{j(i==="agents"&&S?{id:S,type:"agent"}:null),w(null),y(!0)},[i,S]),de=a.useCallback(()=>{y(!1),j(null),w(null)},[]),Fe=()=>!p||v?null:e.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[e.jsxs("div",{className:"mailbox-message-detail-header",children:[Y&&e.jsx("button",{className:"btn btn-sm btn-secondary",onClick:O,"data-testid":"mailbox-back-to-list",children:"← Back"}),e.jsxs("div",{className:"mailbox-message-detail-meta",children:[e.jsx("span",{className:"mailbox-message-type",children:kN(p.type)}),e.jsx("span",{className:"mailbox-message-time",children:Li(p.createdAt)})]}),e.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ue(p),"data-testid":"mailbox-reply",children:[e.jsx(oi,{size:14}),e.jsx("span",{children:"Reply"})]}),e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>F(p.id),"data-testid":"mailbox-delete",children:[e.jsx(qt,{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(rn,{size:14}):e.jsx(Ti,{size:14}),N(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(rn,{size:14}):e.jsx(Ti,{size:14}),N(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(ie=>{const Pe=ie.metadata?.replyTo?.messageId,ze=Pe?b.find($e=>$e.id===Pe):void 0;return e.jsxs("div",{className:`mailbox-conversation-msg ${ie.id===p.id?"current":""}`,children:[e.jsxs("div",{className:"mailbox-conversation-msg-header",children:[e.jsx("span",{children:N(ie.fromId,ie.fromType)}),e.jsx("span",{className:"mailbox-message-time",children:Li(ie.createdAt)})]}),Pe&&e.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ie.id}`,children:["↪ Replying to ",ze?nu(ze.content,60):`message ${Pe}`]}),e.jsx("div",{className:"mailbox-conversation-msg-body",children:ie.content})]},ie.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})]})]}),we=()=>e.jsxs(e.Fragment,{children:[i==="inbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!l&&e.jsx(zl,{}),l&&l.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[e.jsx(Ra,{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:wN(l.messages).map(ie=>e.jsxs("div",{className:`mailbox-conversation-group ${ie.unreadCount>0?"unread":""}`,onClick:()=>oe(ie.latestMessage),"data-testid":`mailbox-conversation-${ie.key}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?e.jsx(rn,{size:16}):e.jsx(Ti,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsx("span",{className:"mailbox-item-from",children:N(ie.fromId,ie.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:Li(ie.latestMessage.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[ie.latestMessage.content.slice(0,80),ie.latestMessage.content.length>80?"…":""]})]}),ie.unreadCount>0&&e.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ie.key}`,children:ie.unreadCount>9?"9+":ie.unreadCount})]},ie.key))})]}),i==="outbox"&&e.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!d&&e.jsx(zl,{}),d&&d.messages.length===0&&e.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[e.jsx(yi,{size:32}),e.jsx("p",{children:"No sent messages"})]}),d?.messages.map(ie=>e.jsxs("div",{className:"mailbox-item",onClick:()=>oe(ie),"data-testid":`mailbox-item-${ie.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?e.jsx(rn,{size:16}):e.jsx(Ti,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsxs("span",{className:"mailbox-item-to",children:["To: ",N(ie.toId,ie.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:Li(ie.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.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(rn,{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:ie=>{k(ie.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[e.jsx("option",{value:"",children:"Select an agent…"}),Z.map(ie=>e.jsx("option",{value:ie.id,children:ie.name||ie.id},ie.id))]})}),e.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:K,"data-testid":"mailbox-compose-btn",children:[e.jsx(oi,{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 ${_==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[e.jsx(Ra,{size:12}),e.jsx("span",{children:"Inbox"}),T&&T.unreadCount>0&&e.jsx("span",{className:"mailbox-tab-badge",children:T.unreadCount})]}),e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${_==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[e.jsx(yi,{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(rn,{size:32}),e.jsx("p",{children:"Select an agent to view their mailbox"})]}),S&&h&&!T&&e.jsx(zl,{}),S&&T&&_==="inbox"&&T.inbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(Ra,{size:32}),e.jsx("p",{children:"No received messages for this agent"})]}),S&&T&&_==="outbox"&&T.outbox.length===0&&e.jsxs("div",{className:"mailbox-empty",children:[e.jsx(yi,{size:32}),e.jsx("p",{children:"No sent messages for this agent"})]}),S&&T&&_==="inbox"&&T.inbox.map(ie=>e.jsxs("div",{className:`mailbox-item ${ie.read?"":"unread"}`,onClick:()=>oe(ie),"data-testid":`mailbox-item-${ie.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:ie.fromType==="agent"?e.jsx(rn,{size:16}):e.jsx(Ti,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsx("span",{className:"mailbox-item-from",children:N(ie.fromId,ie.fromType)}),e.jsx("span",{className:"mailbox-item-time",children:Li(ie.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id)),S&&T&&_==="outbox"&&T.outbox.map(ie=>e.jsxs("div",{className:"mailbox-item",onClick:()=>oe(ie),"data-testid":`mailbox-item-${ie.id}`,children:[e.jsx("div",{className:"mailbox-item-avatar",children:ie.toType==="agent"?e.jsx(rn,{size:16}):e.jsx(Ti,{size:16})}),e.jsxs("div",{className:"mailbox-item-content",children:[e.jsxs("div",{className:"mailbox-item-header",children:[e.jsxs("span",{className:"mailbox-item-to",children:["To: ",N(ie.toId,ie.toType)]}),e.jsx("span",{className:"mailbox-item-time",children:Li(ie.createdAt)})]}),e.jsxs("div",{className:"mailbox-item-preview",children:[ie.content.slice(0,80),ie.content.length>80?"…":""]})]})]},ie.id))]})]})})]}),Ee=()=>v?e.jsx(tu,{recipient:M,replyContext:P,agents:Z,projectId:t,onSend:ce,onCancel:de,addToast:n}):p?Fe():e.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[e.jsx(Yi,{size:24}),e.jsx("p",{children:"Select a conversation to read messages"})]});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(Yi,{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:K,title:"Compose message","data-testid":"mailbox-header-compose",children:[e.jsx(oi,{size:14}),e.jsx("span",{children:"Compose"})]}),i==="inbox"&&c>0&&e.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:V,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[e.jsx(Gf,{size:14}),e.jsx("span",{children:"Mark all read"})]}),e.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?A():i==="outbox"?z():S&&J(S)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?e.jsx(ut,{size:14,className:"spin"}):e.jsx(vn,{size:14})})]})]}),e.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[e.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[e.jsx(Ra,{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(yi,{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(rn,{size:14}),e.jsx("span",{children:"Agents"})]})]}),e.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:H?e.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[e.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:we()}),e.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Ee()})]}):e.jsxs(e.Fragment,{children:[Fe(),v&&e.jsx(tu,{recipient:M,replyContext:P,agents:Z,projectId:t,onSend:ce,onCancel:de,addToast:n}),!p&&!v&&we()]})})]})}function zl(){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 SN(t,n){const s={};return(t[t.length-1]===""?[...t,""]:t).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const CN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,MN={};function su(t,n){return(MN.jsx?EN:CN).test(t)}const AN=/[ \t\n\f\r]/g;function PN(t){return typeof t=="object"?t.type==="text"?iu(t.value):!1:iu(t)}function iu(t){return t.replace(AN,"")===""}class ir{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}ir.prototype.normal={};ir.prototype.property={};ir.prototype.space=void 0;function Wh(t,n){const s={},i={};for(const r of t)Object.assign(s,r.property),Object.assign(i,r.normal);return new ir(s,i,n)}function zo(t){return t.toLowerCase()}class is{constructor(n,s){this.attribute=s,this.property=n}}is.prototype.attribute="";is.prototype.booleanish=!1;is.prototype.boolean=!1;is.prototype.commaOrSpaceSeparated=!1;is.prototype.commaSeparated=!1;is.prototype.defined=!1;is.prototype.mustUseProperty=!1;is.prototype.number=!1;is.prototype.overloadedBoolean=!1;is.prototype.property="";is.prototype.spaceSeparated=!1;is.prototype.space=void 0;let IN=0;const Tt=Ii(),xn=Ii(),Oo=Ii(),lt=Ii(),tn=Ii(),Wi=Ii(),ls=Ii();function Ii(){return 2**++IN}const Bo=Object.freeze(Object.defineProperty({__proto__:null,boolean:Tt,booleanish:xn,commaOrSpaceSeparated:ls,commaSeparated:Wi,number:lt,overloadedBoolean:Oo,spaceSeparated:tn},Symbol.toStringTag,{value:"Module"})),Ol=Object.keys(Bo);class gc extends is{constructor(n,s,i,r){let l=-1;if(super(n,s),au(this,"space",r),typeof i=="number")for(;++l<Ol.length;){const o=Ol[l];au(this,Ol[l],(i&Bo[o])===Bo[o])}}}gc.prototype.defined=!0;function au(t,n,s){s&&(t[n]=s)}function ma(t){const n={},s={};for(const[i,r]of Object.entries(t.properties)){const l=new gc(i,t.transform(t.attributes||{},i),r,t.space);t.mustUseProperty&&t.mustUseProperty.includes(i)&&(l.mustUseProperty=!0),n[i]=l,s[zo(i)]=i,s[zo(l.attribute)]=i}return new ir(n,s,t.space)}const Kh=ma({properties:{ariaActiveDescendant:null,ariaAtomic:xn,ariaAutoComplete:null,ariaBusy:xn,ariaChecked:xn,ariaColCount:lt,ariaColIndex:lt,ariaColSpan:lt,ariaControls:tn,ariaCurrent:null,ariaDescribedBy:tn,ariaDetails:null,ariaDisabled:xn,ariaDropEffect:tn,ariaErrorMessage:null,ariaExpanded:xn,ariaFlowTo:tn,ariaGrabbed:xn,ariaHasPopup:null,ariaHidden:xn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:tn,ariaLevel:lt,ariaLive:null,ariaModal:xn,ariaMultiLine:xn,ariaMultiSelectable:xn,ariaOrientation:null,ariaOwns:tn,ariaPlaceholder:null,ariaPosInSet:lt,ariaPressed:xn,ariaReadOnly:xn,ariaRelevant:null,ariaRequired:xn,ariaRoleDescription:tn,ariaRowCount:lt,ariaRowIndex:lt,ariaRowSpan:lt,ariaSelected:xn,ariaSetSize:lt,ariaSort:null,ariaValueMax:lt,ariaValueMin:lt,ariaValueNow:lt,ariaValueText:null,role:null},transform(t,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Gh(t,n){return n in t?t[n]:n}function Jh(t,n){return Gh(t,n.toLowerCase())}const _N=ma({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Wi,acceptCharset:tn,accessKey:tn,action:null,allow:null,allowFullScreen:Tt,allowPaymentRequest:Tt,allowUserMedia:Tt,alt:null,as:null,async:Tt,autoCapitalize:null,autoComplete:tn,autoFocus:Tt,autoPlay:Tt,blocking:tn,capture:null,charSet:null,checked:Tt,cite:null,className:tn,cols:lt,colSpan:null,content:null,contentEditable:xn,controls:Tt,controlsList:tn,coords:lt|Wi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Tt,defer:Tt,dir:null,dirName:null,disabled:Tt,download:Oo,draggable:xn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Tt,formTarget:null,headers:tn,height:lt,hidden:Oo,high:lt,href:null,hrefLang:null,htmlFor:tn,httpEquiv:tn,id:null,imageSizes:null,imageSrcSet:null,inert:Tt,inputMode:null,integrity:null,is:null,isMap:Tt,itemId:null,itemProp:tn,itemRef:tn,itemScope:Tt,itemType:tn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Tt,low:lt,manifest:null,max:null,maxLength:lt,media:null,method:null,min:null,minLength:lt,multiple:Tt,muted:Tt,name:null,nonce:null,noModule:Tt,noValidate:Tt,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:Tt,optimum:lt,pattern:null,ping:tn,placeholder:null,playsInline:Tt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Tt,referrerPolicy:null,rel:tn,required:Tt,reversed:Tt,rows:lt,rowSpan:lt,sandbox:tn,scope:null,scoped:Tt,seamless:Tt,selected:Tt,shadowRootClonable:Tt,shadowRootDelegatesFocus:Tt,shadowRootMode:null,shape:null,size:lt,sizes:null,slot:null,span:lt,spellCheck:xn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:lt,step:null,style:null,tabIndex:lt,target:null,title:null,translate:null,type:null,typeMustMatch:Tt,useMap:null,value:xn,width:lt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:tn,axis:null,background:null,bgColor:null,border:lt,borderColor:null,bottomMargin:lt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Tt,declare:Tt,event:null,face:null,frame:null,frameBorder:null,hSpace:lt,leftMargin:lt,link:null,longDesc:null,lowSrc:null,marginHeight:lt,marginWidth:lt,noResize:Tt,noHref:Tt,noShade:Tt,noWrap:Tt,object:null,profile:null,prompt:null,rev:null,rightMargin:lt,rules:null,scheme:null,scrolling:xn,standby:null,summary:null,text:null,topMargin:lt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:lt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Tt,disableRemotePlayback:Tt,prefix:null,property:null,results:lt,security:null,unselectable:null},space:"html",transform:Jh}),RN=ma({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:lt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:lt,amplitude:lt,arabicForm:null,ascent:lt,attributeName:null,attributeType:null,azimuth:lt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:lt,by:null,calcMode:null,capHeight:lt,className:tn,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:lt,diffuseConstant:lt,direction:null,display:null,dur:null,divisor:lt,dominantBaseline:null,download:Tt,dx:null,dy:null,edgeMode:null,editable:null,elevation:lt,enableBackground:null,end:null,event:null,exponent:lt,externalResourcesRequired:null,fill:null,fillOpacity:lt,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:Wi,g2:Wi,glyphName:Wi,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:lt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:lt,horizOriginX:lt,horizOriginY:lt,id:null,ideographic:lt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:lt,k:lt,k1:lt,k2:lt,k3:lt,k4:lt,kernelMatrix:ls,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:lt,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:lt,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:lt,overlineThickness:lt,paintOrder:null,panose1:null,path:null,pathLength:lt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:tn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:lt,pointsAtY:lt,pointsAtZ:lt,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:lt,specularExponent:lt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:lt,strikethroughThickness:lt,string:null,stroke:null,strokeDashArray:ls,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:lt,strokeOpacity:lt,strokeWidth:null,style:null,surfaceScale:lt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ls,tabIndex:lt,tableValues:null,target:null,targetX:lt,targetY:lt,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:lt,underlineThickness:lt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:lt,values:null,vAlphabetic:lt,vMathematical:lt,vectorEffect:null,vHanging:lt,vIdeographic:lt,version:null,vertAdvY:lt,vertOriginX:lt,vertOriginY:lt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:lt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Gh}),Yh=ma({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(t,n){return"xlink:"+n.slice(5).toLowerCase()}}),Qh=ma({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Jh}),Xh=ma({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(t,n){return"xml:"+n.slice(3).toLowerCase()}}),TN={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"},$N=/[A-Z]/g,ru=/-[a-z]/g,FN=/^data[-\w.:]+$/i;function DN(t,n){const s=zo(n);let i=n,r=is;if(s in t.normal)return t.property[t.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&FN.test(n)){if(n.charAt(4)==="-"){const l=n.slice(5).replace(ru,zN);i="data"+l.charAt(0).toUpperCase()+l.slice(1)}else{const l=n.slice(4);if(!ru.test(l)){let o=l.replace($N,LN);o.charAt(0)!=="-"&&(o="-"+o),n="data"+o}}r=gc}return new r(i,n)}function LN(t){return"-"+t.toLowerCase()}function zN(t){return t.charAt(1).toUpperCase()}const ON=Wh([Kh,_N,Yh,Qh,Xh],"html"),bc=Wh([Kh,RN,Yh,Qh,Xh],"svg");function BN(t){return t.join(" ").trim()}var zi={},Bl,lu;function UN(){if(lu)return Bl;lu=1;var t=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,l=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,o=/^[;\s]*/,d=/^\s+|\s+$/g,m=`
598
+ `,c="/",u="*",h="",g="comment",p="declaration";function f(x,v){if(typeof x!="string")throw new TypeError("First argument must be a string");if(!x)return[];v=v||{};var y=1,M=1;function j($){var R=$.match(n);R&&(y+=R.length);var N=$.lastIndexOf(m);M=~N?$.length-N:M+$.length}function P(){var $={line:y,column:M};return function(R){return R.position=new w($),_(),R}}function w($){this.start=$,this.end={line:y,column:M},this.source=v.source}w.prototype.content=x;function S($){var R=new Error(v.source+":"+y+":"+M+": "+$);if(R.reason=$,R.filename=v.source,R.line=y,R.column=M,R.source=x,!v.silent)throw R}function k($){var R=$.exec(x);if(R){var N=R[0];return j(N),x=x.slice(N.length),R}}function _(){k(s)}function E($){var R;for($=$||[];R=T();)R!==!1&&$.push(R);return $}function T(){var $=P();if(!(c!=x.charAt(0)||u!=x.charAt(1))){for(var R=2;h!=x.charAt(R)&&(u!=x.charAt(R)||c!=x.charAt(R+1));)++R;if(R+=2,h===x.charAt(R-1))return S("End of comment missing");var N=x.slice(2,R-2);return M+=2,j(N),x=x.slice(R),M+=2,$({type:g,comment:N})}}function D(){var $=P(),R=k(i);if(R){if(T(),!k(r))return S("property missing ':'");var N=k(l),W=$({type:p,property:b(R[0].replace(t,h)),value:N?b(N[0].replace(t,h)):h});return k(o),W}}function Z(){var $=[];E($);for(var R;R=D();)R!==!1&&($.push(R),E($));return $}return _(),Z()}function b(x){return x?x.replace(d,h):h}return Bl=f,Bl}var ou;function HN(){if(ou)return zi;ou=1;var t=zi&&zi.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(zi,"__esModule",{value:!0}),zi.default=s;const n=t(UN());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 zi}var ja={},cu;function qN(){if(cu)return ja;cu=1,Object.defineProperty(ja,"__esModule",{value:!0}),ja.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 ja.camelCase=m,ja}var ka,du;function VN(){if(du)return ka;du=1;var t=ka&&ka.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=t(HN()),s=qN();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,ka=i,ka}var WN=VN();const KN=Vm(WN),Zh=ep("end"),xc=ep("start");function ep(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 GN(t){const n=xc(t),s=Zh(t);if(n&&s)return{start:n,end:s}}function Da(t){return!t||typeof t!="object"?"":"position"in t||"type"in t?uu(t.position):"start"in t||"end"in t?uu(t):"line"in t||"column"in t?Uo(t):""}function Uo(t){return mu(t&&t.line)+":"+mu(t&&t.column)}function uu(t){return Uo(t&&t.start)+"-"+Uo(t&&t.end)}function mu(t){return t&&typeof t=="number"?t:1}class Ln 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=Da(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}}Ln.prototype.file="";Ln.prototype.name="";Ln.prototype.reason="";Ln.prototype.message="";Ln.prototype.stack="";Ln.prototype.column=void 0;Ln.prototype.line=void 0;Ln.prototype.ancestors=void 0;Ln.prototype.cause=void 0;Ln.prototype.fatal=void 0;Ln.prototype.place=void 0;Ln.prototype.ruleId=void 0;Ln.prototype.source=void 0;const vc={}.hasOwnProperty,JN=new Map,YN=/[A-Z]/g,QN=new Set(["table","tbody","thead","tfoot","tr"]),XN=new Set(["td","th"]),tp="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function ZN(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=l1(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=r1(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"?bc:ON,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},l=np(r,t,void 0);return l&&typeof l!="string"?l:r.create(t,r.Fragment,{children:l||void 0},void 0)}function np(t,n,s){if(n.type==="element")return e1(t,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return t1(t,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return s1(t,n,s);if(n.type==="mdxjsEsm")return n1(t,n);if(n.type==="root")return i1(t,n,s);if(n.type==="text")return a1(t,n)}function e1(t,n,s){const i=t.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=bc,t.schema=r),t.ancestors.push(n);const l=ip(t,n.tagName,!1),o=o1(t,n);let d=jc(t,n);return QN.has(n.tagName)&&(d=d.filter(function(m){return typeof m=="string"?!PN(m):!0})),sp(t,o,l,n),yc(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function t1(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)}Va(t,n.position)}function n1(t,n){if(n.data&&n.data.estree&&t.evaluater)return t.evaluater.evaluateProgram(n.data.estree);Va(t,n.position)}function s1(t,n,s){const i=t.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=bc,t.schema=r),t.ancestors.push(n);const l=n.name===null?t.Fragment:ip(t,n.name,!0),o=c1(t,n),d=jc(t,n);return sp(t,o,l,n),yc(o,d),t.ancestors.pop(),t.schema=i,t.create(n,l,o,s)}function i1(t,n,s){const i={};return yc(i,jc(t,n)),t.create(n,t.Fragment,i,s)}function a1(t,n){return n.value}function sp(t,n,s,i){typeof s!="string"&&s!==t.Fragment&&t.passNode&&(n.node=i)}function yc(t,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(t.children=s)}}function r1(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 l1(t,n){return s;function s(i,r,l,o){const d=Array.isArray(l.children),m=xc(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 o1(t,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&vc.call(n.properties,r)){const l=d1(t,r,n.properties[r]);if(l){const[o,d]=l;t.tableCellAlignToStyle&&o==="align"&&typeof d=="string"&&XN.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 c1(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 Va(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 Va(t,n.position);else l=i.value===null?!0:i.value;s[r]=l}return s}function jc(t,n){const s=[];let i=-1;const r=t.passKeys?new Map:JN;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=np(t,l,o);d!==void 0&&s.push(d)}return s}function d1(t,n,s){const i=DN(t.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?SN(s):BN(s)),i.property==="style"){let r=typeof s=="object"?s:u1(t,String(s));return t.stylePropertyNameCase==="css"&&(r=m1(r)),["style",r]}return[t.elementAttributeNameCase==="react"&&i.space?TN[i.property]||i.property:i.attribute,s]}}function u1(t,n){try{return KN(n,{reactCompat:!0})}catch(s){if(t.ignoreInvalidStyle)return{};const i=s,r=new Ln("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=tp+"#cannot-parse-style-attribute",r}}function ip(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=su(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=su(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return vc.call(t.components,r)?t.components[r]:r}if(t.evaluater)return t.evaluater.evaluateExpression(i);Va(t)}function Va(t,n){const s=new Ln("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=tp+"#cannot-handle-mdx-estrees-without-createevaluater",s}function m1(t){const n={};let s;for(s in t)vc.call(t,s)&&(n[h1(s)]=t[s]);return n}function h1(t){let n=t.replace(YN,p1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function p1(t){return"-"+t.toLowerCase()}const Ul={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"]},f1={};function kc(t,n){const s=f1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return ap(t,i,r)}function ap(t,n,s){if(g1(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 hu(t.children,n,s)}return Array.isArray(t)?hu(t,n,s):""}function hu(t,n,s){const i=[];let r=-1;for(;++r<t.length;)i[r]=ap(t[r],n,s);return i.join("")}function g1(t){return!!(t&&typeof t=="object")}const pu=document.createElement("i");function wc(t){const n="&"+t+";";pu.innerHTML=n;const s=pu.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 ws(t,n){return t.length>0?(ms(t,t.length,0,n),t):n}const fu={}.hasOwnProperty;function rp(t){const n={};let s=-1;for(;++s<t.length;)b1(n,t[s]);return n}function b1(t,n){let s;for(s in n){const r=(fu.call(t,s)?t[s]:void 0)||(t[s]={}),l=n[s];let o;if(l)for(o in l){fu.call(r,o)||(r[o]=[]);const d=l[o];x1(r[o],Array.isArray(d)?d:d?[d]:[])}}}function x1(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 lp(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 Ts(t){return t.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const qn=hi(/[A-Za-z]/),Fn=hi(/[\dA-Za-z]/),v1=hi(/[#-'*+\--9=?A-Z^-~]/);function Jr(t){return t!==null&&(t<32||t===127)}const Ho=hi(/\d/),y1=hi(/[\dA-Fa-f]/),j1=hi(/[!-/:-@[-`{-~]/);function Ct(t){return t!==null&&t<-2}function Qt(t){return t!==null&&(t<0||t===32)}function Dt(t){return t===-2||t===-1||t===32}const ml=hi(/\p{P}|\p{S}/u),Mi=hi(/\s/);function hi(t){return n;function n(s){return s!==null&&s>-1&&t.test(String.fromCharCode(s))}}function ha(t){const n=[];let s=-1,i=0,r=0;for(;++s<t.length;){const l=t.charCodeAt(s);let o="";if(l===37&&Fn(t.charCodeAt(s+1))&&Fn(t.charCodeAt(s+2)))r=2;else if(l<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(l))||(o=String.fromCharCode(l));else if(l>55295&&l<57344){const d=t.charCodeAt(s+1);l<56320&&d>56319&&d<57344?(o=String.fromCharCode(l,d),r=1):o="�"}else o=String.fromCharCode(l);o&&(n.push(t.slice(i,s),encodeURIComponent(o)),i=s+r+1,o=""),r&&(s+=r,r=0)}return n.join("")+t.slice(i)}function Bt(t,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let l=0;return o;function o(m){return Dt(m)?(t.enter(s),d(m)):n(m)}function d(m){return Dt(m)&&l++<r?(t.consume(m),d):(t.exit(s),n(m))}}const k1={tokenize:w1};function w1(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"),Bt(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 Ct(d)?(t.consume(d),t.exit("chunkText"),l):(t.consume(d),o)}}const N1={tokenize:S1},gu={tokenize:C1};function S1(t){const n=this,s=[];let i=0,r,l,o;return d;function d(M){if(i<s.length){const j=s[i];return n.containerState=j[1],t.attempt(j[0].continuation,m,c)(M)}return c(M)}function m(M){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const j=n.events.length;let P=j,w;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){w=n.events[P][1].end;break}v(i);let S=j;for(;S<n.events.length;)n.events[S][1].end={...w},S++;return ms(n.events,P+1,0,n.events.slice(j)),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(gu,u,h)(M)}function u(M){return r&&y(),v(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(gu,p,f)(M)}function p(M){return i++,s.push([n.currentConstruct,n.containerState]),g(M)}function f(M){if(M===null){r&&y(),v(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),v(0),t.consume(M);return}return Ct(M)?(t.consume(M),x(t.exit("chunkFlow")),i=0,n.interrupt=void 0,d):(t.consume(M),b)}function x(M,j){const P=n.sliceStream(M);if(j&&P.push(null),M.previous=l,l&&(l.next=M),l=M,r.defineSkip(M.start),r.write(P),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,_,E;for(;k--;)if(n.events[k][0]==="exit"&&n.events[k][1].type==="chunkFlow"){if(_){E=n.events[k][1].end;break}_=!0}for(v(i),w=S;w<n.events.length;)n.events[w][1].end={...E},w++;ms(n.events,k+1,0,n.events.slice(S)),n.events.length=w}}function v(M){let j=s.length;for(;j-- >M;){const P=s[j];n.containerState=P[1],P[0].exit.call(n,t)}s.length=M}function y(){r.write([null]),l=void 0,r=void 0,n.containerState._closeFlow=void 0}}function C1(t,n,s){return Bt(t,t.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ta(t){if(t===null||Qt(t)||Mi(t))return 1;if(ml(t))return 2}function hl(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 qo={name:"attention",resolveAll:E1,tokenize:M1};function E1(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};bu(h,-m),bu(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=ws(c,[["enter",t[i][1],n],["exit",t[i][1],n]])),c=ws(c,[["enter",r,n],["enter",o,n],["exit",o,n],["enter",l,n]]),c=ws(c,hl(n.parser.constructs.insideSpan.null,t.slice(i+1,s),n)),c=ws(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=ws(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 M1(t,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ta(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=ta(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 bu(t,n){t.column+=n,t.offset+=n,t._bufferIndex+=n}const A1={name:"autolink",tokenize:P1};function P1(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 qn(p)?(t.consume(p),o):p===64?s(p):c(p)}function o(p){return p===43||p===45||p===46||Fn(p)?(i=1,d(p)):c(p)}function d(p){return p===58?(t.consume(p),i=0,m):(p===43||p===45||p===46||Fn(p))&&i++<32?(t.consume(p),d):(i=0,c(p))}function m(p){return p===62?(t.exit("autolinkProtocol"),t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),n):p===null||p===32||p===60||Jr(p)?s(p):(t.consume(p),m)}function c(p){return p===64?(t.consume(p),u):v1(p)?(t.consume(p),c):s(p)}function u(p){return Fn(p)?h(p):s(p)}function h(p){return p===46?(t.consume(p),i=0,u):p===62?(t.exit("autolinkProtocol").type="autolinkEmail",t.enter("autolinkMarker"),t.consume(p),t.exit("autolinkMarker"),t.exit("autolink"),n):g(p)}function g(p){if((p===45||Fn(p))&&i++<63){const f=p===45?g:h;return t.consume(p),f}return s(p)}}const ar={partial:!0,tokenize:I1};function I1(t,n,s){return i;function i(l){return Dt(l)?Bt(t,r,"linePrefix")(l):r(l)}function r(l){return l===null||Ct(l)?n(l):s(l)}}const op={continuation:{tokenize:R1},exit:T1,name:"blockQuote",tokenize:_1};function _1(t,n,s){const i=this;return r;function r(o){if(o===62){const d=i.containerState;return d.open||(t.enter("blockQuote",{_container:!0}),d.open=!0),t.enter("blockQuotePrefix"),t.enter("blockQuoteMarker"),t.consume(o),t.exit("blockQuoteMarker"),l}return s(o)}function l(o){return Dt(o)?(t.enter("blockQuotePrefixWhitespace"),t.consume(o),t.exit("blockQuotePrefixWhitespace"),t.exit("blockQuotePrefix"),n):(t.exit("blockQuotePrefix"),n(o))}}function R1(t,n,s){const i=this;return r;function r(o){return Dt(o)?Bt(t,l,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o):l(o)}function l(o){return t.attempt(op,n,s)(o)}}function T1(t){t.exit("blockQuote")}const cp={name:"characterEscape",tokenize:$1};function $1(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 j1(l)?(t.enter("characterEscapeValue"),t.consume(l),t.exit("characterEscapeValue"),t.exit("characterEscape"),n):s(l)}}const dp={name:"characterReference",tokenize:F1};function F1(t,n,s){const i=this;let r=0,l,o;return d;function d(h){return t.enter("characterReference"),t.enter("characterReferenceMarker"),t.consume(h),t.exit("characterReferenceMarker"),m}function m(h){return h===35?(t.enter("characterReferenceMarkerNumeric"),t.consume(h),t.exit("characterReferenceMarkerNumeric"),c):(t.enter("characterReferenceValue"),l=31,o=Fn,u(h))}function c(h){return h===88||h===120?(t.enter("characterReferenceMarkerHexadecimal"),t.consume(h),t.exit("characterReferenceMarkerHexadecimal"),t.enter("characterReferenceValue"),l=6,o=y1,u):(t.enter("characterReferenceValue"),l=7,o=Ho,u(h))}function u(h){if(h===59&&r){const g=t.exit("characterReferenceValue");return o===Fn&&!wc(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 xu={partial:!0,tokenize:L1},vu={concrete:!0,name:"codeFenced",tokenize:D1};function D1(t,n,s){const i=this,r={partial:!0,tokenize:P};let l=0,o=0,d;return m;function m(w){return c(w)}function c(w){const 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"),Dt(w)?Bt(t,h,"whitespace")(w):h(w))}function h(w){return w===null||Ct(w)?(t.exit("codeFencedFence"),i.interrupt?n(w):t.check(xu,b,j)(w)):(t.enter("codeFencedFenceInfo"),t.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||Ct(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),h(w)):Dt(w)?(t.exit("chunkString"),t.exit("codeFencedFenceInfo"),Bt(t,p,"whitespace")(w)):w===96&&w===d?s(w):(t.consume(w),g)}function p(w){return w===null||Ct(w)?h(w):(t.enter("codeFencedFenceMeta"),t.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||Ct(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,j,x)(w)}function x(w){return t.enter("lineEnding"),t.consume(w),t.exit("lineEnding"),v}function v(w){return l>0&&Dt(w)?Bt(t,y,"linePrefix",l+1)(w):y(w)}function y(w){return w===null||Ct(w)?t.check(xu,b,j)(w):(t.enter("codeFlowValue"),M(w))}function M(w){return w===null||Ct(w)?(t.exit("codeFlowValue"),y(w)):(t.consume(w),M)}function j(w){return t.exit("codeFenced"),n(w)}function P(w,S,k){let _=0;return E;function E(R){return w.enter("lineEnding"),w.consume(R),w.exit("lineEnding"),T}function T(R){return w.enter("codeFencedFence"),Dt(R)?Bt(w,D,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):D(R)}function D(R){return R===d?(w.enter("codeFencedFenceSequence"),Z(R)):k(R)}function Z(R){return R===d?(_++,w.consume(R),Z):_>=o?(w.exit("codeFencedFenceSequence"),Dt(R)?Bt(w,$,"whitespace")(R):$(R)):k(R)}function $(R){return R===null||Ct(R)?(w.exit("codeFencedFence"),S(R)):k(R)}}}function L1(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 Hl={name:"codeIndented",tokenize:O1},z1={partial:!0,tokenize:B1};function O1(t,n,s){const i=this;return r;function r(c){return t.enter("codeIndented"),Bt(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):Ct(c)?t.attempt(z1,o,m)(c):(t.enter("codeFlowValue"),d(c))}function d(c){return c===null||Ct(c)?(t.exit("codeFlowValue"),o(c)):(t.consume(c),d)}function m(c){return t.exit("codeIndented"),n(c)}}function B1(t,n,s){const i=this;return r;function r(o){return i.parser.lazy[i.now().line]?s(o):Ct(o)?(t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),r):Bt(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):Ct(o)?r(o):s(o)}}const U1={name:"codeText",previous:q1,resolve:H1,tokenize:V1};function H1(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 q1(t){return t!==96||this.events[this.events.length-1][1].type==="characterEscape"}function V1(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)):Ct(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||Ct(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 W1{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&&wa(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),wa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),wa(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);wa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);wa(this.left,s.reverse())}}}function wa(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 up(t){const n={};let s=-1,i,r,l,o,d,m,c;const u=new W1(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,K1(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 K1(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 v=d.slice(x[g],x[g+1]),y=l.pop();m.push([y,y+v.length-1]),t.splice(y,2,v)}for(m.reverse(),g=-1;++g<m.length;)c[f+m[g][0]]=f+m[g][1],f+=m[g][1]-m[g][0]-1;return c}const G1={resolve:Y1,tokenize:Q1},J1={partial:!0,tokenize:X1};function Y1(t){return up(t),t}function Q1(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):Ct(d)?t.check(J1,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 X1(t,n,s){const i=this;return r;function r(o){return t.exit("chunkContent"),t.enter("lineEnding"),t.consume(o),t.exit("lineEnding"),Bt(t,l,"linePrefix")}function l(o){if(o===null||Ct(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 mp(t,n,s,i,r,l,o,d,m){const c=m||Number.POSITIVE_INFINITY;let u=0;return h;function h(v){return v===60?(t.enter(i),t.enter(r),t.enter(l),t.consume(v),t.exit(l),g):v===null||v===32||v===41||Jr(v)?s(v):(t.enter(i),t.enter(o),t.enter(d),t.enter("chunkString",{contentType:"string"}),b(v))}function g(v){return v===62?(t.enter(l),t.consume(v),t.exit(l),t.exit(r),t.exit(i),n):(t.enter(d),t.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(t.exit("chunkString"),t.exit(d),g(v)):v===null||v===60||Ct(v)?s(v):(t.consume(v),v===92?f:p)}function f(v){return v===60||v===62||v===92?(t.consume(v),p):p(v)}function b(v){return!u&&(v===null||v===41||Qt(v))?(t.exit("chunkString"),t.exit(d),t.exit(o),t.exit(i),n(v)):u<c&&v===40?(t.consume(v),u++,b):v===41?(t.consume(v),u--,b):v===null||v===32||v===40||Jr(v)?s(v):(t.consume(v),v===92?x:b)}function x(v){return v===40||v===41||v===92?(t.consume(v),b):b(v)}}function hp(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):Ct(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||Ct(p)||d++>999?(t.exit("chunkString"),u(p)):(t.consume(p),m||(m=!Dt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(t.consume(p),d++,h):h(p)}}function pp(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):Ct(g)?(t.enter("lineEnding"),t.consume(g),t.exit("lineEnding"),Bt(t,c,"linePrefix")):(t.enter("chunkString",{contentType:"string"}),u(g))}function u(g){return g===o||g===null||Ct(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 La(t,n){let s;return i;function i(r){return Ct(r)?(t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),s=!0,i):Dt(r)?Bt(t,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const Z1={name:"definition",tokenize:tS},eS={partial:!0,tokenize:nS};function tS(t,n,s){const i=this;let r;return l;function l(p){return t.enter("definition"),o(p)}function o(p){return hp.call(i,t,d,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function d(p){return r=Ts(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 Qt(p)?La(t,c)(p):c(p)}function c(p){return mp(t,u,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return t.attempt(eS,h,h)(p)}function h(p){return Dt(p)?Bt(t,g,"whitespace")(p):g(p)}function g(p){return p===null||Ct(p)?(t.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function nS(t,n,s){return i;function i(d){return Qt(d)?La(t,r)(d):s(d)}function r(d){return pp(t,l,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(d)}function l(d){return Dt(d)?Bt(t,o,"whitespace")(d):o(d)}function o(d){return d===null||Ct(d)?n(d):s(d)}}const sS={name:"hardBreakEscape",tokenize:iS};function iS(t,n,s){return i;function i(l){return t.enter("hardBreakEscape"),t.consume(l),r}function r(l){return Ct(l)?(t.exit("hardBreakEscape"),n(l)):s(l)}}const aS={name:"headingAtx",resolve:rS,tokenize:lS};function rS(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 lS(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||Qt(u)?(t.exit("atxHeadingSequence"),d(u)):s(u)}function d(u){return u===35?(t.enter("atxHeadingSequence"),m(u)):u===null||Ct(u)?(t.exit("atxHeading"),n(u)):Dt(u)?Bt(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||Qt(u)?(t.exit("atxHeadingText"),d(u)):(t.consume(u),c)}}const oS=["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"],yu=["pre","script","style","textarea"],cS={concrete:!0,name:"htmlFlow",resolveTo:mS,tokenize:hS},dS={partial:!0,tokenize:fS},uS={partial:!0,tokenize:pS};function mS(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 hS(t,n,s){const i=this;let r,l,o,d,m;return c;function c(C){return u(C)}function u(C){return t.enter("htmlFlow"),t.enter("htmlFlowData"),t.consume(C),h}function h(C){return C===33?(t.consume(C),g):C===47?(t.consume(C),l=!0,b):C===63?(t.consume(C),r=3,i.interrupt?n:A):qn(C)?(t.consume(C),o=String.fromCharCode(C),x):s(C)}function g(C){return C===45?(t.consume(C),r=2,p):C===91?(t.consume(C),r=5,d=0,f):qn(C)?(t.consume(C),r=4,i.interrupt?n:A):s(C)}function p(C){return C===45?(t.consume(C),i.interrupt?n:A):s(C)}function f(C){const q="CDATA[";return C===q.charCodeAt(d++)?(t.consume(C),d===q.length?i.interrupt?n:D:f):s(C)}function b(C){return qn(C)?(t.consume(C),o=String.fromCharCode(C),x):s(C)}function x(C){if(C===null||C===47||C===62||Qt(C)){const q=C===47,oe=o.toLowerCase();return!q&&!l&&yu.includes(oe)?(r=1,i.interrupt?n(C):D(C)):oS.includes(o.toLowerCase())?(r=6,q?(t.consume(C),v):i.interrupt?n(C):D(C)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(C):l?y(C):M(C))}return C===45||Fn(C)?(t.consume(C),o+=String.fromCharCode(C),x):s(C)}function v(C){return C===62?(t.consume(C),i.interrupt?n:D):s(C)}function y(C){return Dt(C)?(t.consume(C),y):E(C)}function M(C){return C===47?(t.consume(C),E):C===58||C===95||qn(C)?(t.consume(C),j):Dt(C)?(t.consume(C),M):E(C)}function j(C){return C===45||C===46||C===58||C===95||Fn(C)?(t.consume(C),j):P(C)}function P(C){return C===61?(t.consume(C),w):Dt(C)?(t.consume(C),P):M(C)}function w(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(t.consume(C),m=C,S):Dt(C)?(t.consume(C),w):k(C)}function S(C){return C===m?(t.consume(C),m=null,_):C===null||Ct(C)?s(C):(t.consume(C),S)}function k(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Qt(C)?P(C):(t.consume(C),k)}function _(C){return C===47||C===62||Dt(C)?M(C):s(C)}function E(C){return C===62?(t.consume(C),T):s(C)}function T(C){return C===null||Ct(C)?D(C):Dt(C)?(t.consume(C),T):s(C)}function D(C){return C===45&&r===2?(t.consume(C),N):C===60&&r===1?(t.consume(C),W):C===62&&r===4?(t.consume(C),z):C===63&&r===3?(t.consume(C),A):C===93&&r===5?(t.consume(C),H):Ct(C)&&(r===6||r===7)?(t.exit("htmlFlowData"),t.check(dS,J,Z)(C)):C===null||Ct(C)?(t.exit("htmlFlowData"),Z(C)):(t.consume(C),D)}function Z(C){return t.check(uS,$,J)(C)}function $(C){return t.enter("lineEnding"),t.consume(C),t.exit("lineEnding"),R}function R(C){return C===null||Ct(C)?Z(C):(t.enter("htmlFlowData"),D(C))}function N(C){return C===45?(t.consume(C),A):D(C)}function W(C){return C===47?(t.consume(C),o="",Y):D(C)}function Y(C){if(C===62){const q=o.toLowerCase();return yu.includes(q)?(t.consume(C),z):D(C)}return qn(C)&&o.length<8?(t.consume(C),o+=String.fromCharCode(C),Y):D(C)}function H(C){return C===93?(t.consume(C),A):D(C)}function A(C){return C===62?(t.consume(C),z):C===45&&r===2?(t.consume(C),A):D(C)}function z(C){return C===null||Ct(C)?(t.exit("htmlFlowData"),J(C)):(t.consume(C),z)}function J(C){return t.exit("htmlFlow"),n(C)}}function pS(t,n,s){const i=this;return r;function r(o){return Ct(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 fS(t,n,s){return i;function i(r){return t.enter("lineEnding"),t.consume(r),t.exit("lineEnding"),t.attempt(ar,n,s)}}const gS={name:"htmlText",tokenize:bS};function bS(t,n,s){const i=this;let r,l,o;return d;function d(A){return t.enter("htmlText"),t.enter("htmlTextData"),t.consume(A),m}function m(A){return A===33?(t.consume(A),c):A===47?(t.consume(A),P):A===63?(t.consume(A),M):qn(A)?(t.consume(A),k):s(A)}function c(A){return A===45?(t.consume(A),u):A===91?(t.consume(A),l=0,f):qn(A)?(t.consume(A),y):s(A)}function u(A){return A===45?(t.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(t.consume(A),g):Ct(A)?(o=h,W(A)):(t.consume(A),h)}function g(A){return A===45?(t.consume(A),p):h(A)}function p(A){return A===62?N(A):A===45?g(A):h(A)}function f(A){const z="CDATA[";return A===z.charCodeAt(l++)?(t.consume(A),l===z.length?b:f):s(A)}function b(A){return A===null?s(A):A===93?(t.consume(A),x):Ct(A)?(o=b,W(A)):(t.consume(A),b)}function x(A){return A===93?(t.consume(A),v):b(A)}function v(A){return A===62?N(A):A===93?(t.consume(A),v):b(A)}function y(A){return A===null||A===62?N(A):Ct(A)?(o=y,W(A)):(t.consume(A),y)}function M(A){return A===null?s(A):A===63?(t.consume(A),j):Ct(A)?(o=M,W(A)):(t.consume(A),M)}function j(A){return A===62?N(A):M(A)}function P(A){return qn(A)?(t.consume(A),w):s(A)}function w(A){return A===45||Fn(A)?(t.consume(A),w):S(A)}function S(A){return Ct(A)?(o=S,W(A)):Dt(A)?(t.consume(A),S):N(A)}function k(A){return A===45||Fn(A)?(t.consume(A),k):A===47||A===62||Qt(A)?_(A):s(A)}function _(A){return A===47?(t.consume(A),N):A===58||A===95||qn(A)?(t.consume(A),E):Ct(A)?(o=_,W(A)):Dt(A)?(t.consume(A),_):N(A)}function E(A){return A===45||A===46||A===58||A===95||Fn(A)?(t.consume(A),E):T(A)}function T(A){return A===61?(t.consume(A),D):Ct(A)?(o=T,W(A)):Dt(A)?(t.consume(A),T):_(A)}function D(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(t.consume(A),r=A,Z):Ct(A)?(o=D,W(A)):Dt(A)?(t.consume(A),D):(t.consume(A),$)}function Z(A){return A===r?(t.consume(A),r=void 0,R):A===null?s(A):Ct(A)?(o=Z,W(A)):(t.consume(A),Z)}function $(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||Qt(A)?_(A):(t.consume(A),$)}function R(A){return A===47||A===62||Qt(A)?_(A):s(A)}function N(A){return A===62?(t.consume(A),t.exit("htmlTextData"),t.exit("htmlText"),n):s(A)}function W(A){return t.exit("htmlTextData"),t.enter("lineEnding"),t.consume(A),t.exit("lineEnding"),Y}function Y(A){return Dt(A)?Bt(t,H,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):H(A)}function H(A){return t.enter("htmlTextData"),o(A)}}const Nc={name:"labelEnd",resolveAll:jS,resolveTo:kS,tokenize:wS},xS={tokenize:NS},vS={tokenize:SS},yS={tokenize:CS};function jS(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 kS(t,n){let s=t.length,i=0,r,l,o,d;for(;s--;)if(r=t[s][1],l){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;t[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(o){if(t[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(l=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(o=s);const m={type:t[l][1].type==="labelLink"?"link":"image",start:{...t[l][1].start},end:{...t[t.length-1][1].end}},c={type:"label",start:{...t[l][1].start},end:{...t[o][1].end}},u={type:"labelText",start:{...t[l+i+2][1].end},end:{...t[o-2][1].start}};return d=[["enter",m,n],["enter",c,n]],d=ws(d,t.slice(l+1,l+i+3)),d=ws(d,[["enter",u,n]]),d=ws(d,hl(n.parser.constructs.insideSpan.null,t.slice(l+i+4,o-3),n)),d=ws(d,[["exit",u,n],t[o-2],t[o-1],["exit",c,n]]),d=ws(d,t.slice(o+1)),d=ws(d,[["exit",m,n]]),ms(t,l,t.length,d),t}function wS(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(Ts(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(xS,u,o?u:h)(g):g===91?t.attempt(vS,u,o?c:h)(g):o?u(g):h(g)}function c(g){return t.attempt(yS,u,h)(g)}function u(g){return n(g)}function h(g){return l._balanced=!0,s(g)}}function NS(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 Qt(h)?La(t,l)(h):l(h)}function l(h){return h===41?u(h):mp(t,o,d,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function o(h){return Qt(h)?La(t,m)(h):u(h)}function d(h){return s(h)}function m(h){return h===34||h===39||h===40?pp(t,c,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):u(h)}function c(h){return Qt(h)?La(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 SS(t,n,s){const i=this;return r;function r(d){return hp.call(i,t,l,o,"reference","referenceMarker","referenceString")(d)}function l(d){return i.parser.defined.includes(Ts(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(d):s(d)}function o(d){return s(d)}}function CS(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 ES={name:"labelStartImage",resolveAll:Nc.resolveAll,tokenize:MS};function MS(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 AS={name:"labelStartLink",resolveAll:Nc.resolveAll,tokenize:PS};function PS(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 ql={name:"lineEnding",tokenize:IS};function IS(t,n){return s;function s(i){return t.enter("lineEnding"),t.consume(i),t.exit("lineEnding"),Bt(t,n,"linePrefix")}}const Fr={name:"thematicBreak",tokenize:_S};function _S(t,n,s){let i=0,r;return l;function l(c){return t.enter("thematicBreak"),o(c)}function o(c){return r=c,d(c)}function d(c){return c===r?(t.enter("thematicBreakSequence"),m(c)):i>=3&&(c===null||Ct(c))?(t.exit("thematicBreak"),n(c)):s(c)}function m(c){return c===r?(t.consume(c),i++,m):(t.exit("thematicBreakSequence"),Dt(c)?Bt(t,d,"whitespace")(c):d(c))}}const Zn={continuation:{tokenize:FS},exit:LS,name:"list",tokenize:$S},RS={partial:!0,tokenize:zS},TS={partial:!0,tokenize:DS};function $S(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:Ho(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(Fr,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 Ho(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(ar,i.interrupt?s:u,t.attempt(RS,g,h))}function u(p){return i.containerState.initialBlankLine=!0,l++,g(p)}function h(p){return Dt(p)?(t.enter("listItemPrefixWhitespace"),t.consume(p),t.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=l+i.sliceSerialize(t.exit("listItemPrefix"),!0).length,n(p)}}function FS(t,n,s){const i=this;return i.containerState._closeFlow=void 0,t.check(ar,r,l);function r(d){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Bt(t,n,"listItemIndent",i.containerState.size+1)(d)}function l(d){return i.containerState.furtherBlankLines||!Dt(d)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,o(d)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,t.attempt(TS,n,o)(d))}function o(d){return i.containerState._closeFlow=!0,i.interrupt=void 0,Bt(t,t.attempt(Zn,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(d)}}function DS(t,n,s){const i=this;return Bt(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 LS(t){t.exit(this.containerState.type)}function zS(t,n,s){const i=this;return Bt(t,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(l){const o=i.events[i.events.length-1];return!Dt(l)&&o&&o[1].type==="listItemPrefixWhitespace"?n(l):s(l)}}const ju={name:"setextUnderline",resolveTo:OS,tokenize:BS};function OS(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 BS(t,n,s){const i=this;let r;return l;function l(c){let u=i.events.length,h;for(;u--;)if(i.events[u][1].type!=="lineEnding"&&i.events[u][1].type!=="linePrefix"&&i.events[u][1].type!=="content"){h=i.events[u][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(t.enter("setextHeadingLine"),r=c,o(c)):s(c)}function o(c){return t.enter("setextHeadingLineSequence"),d(c)}function d(c){return c===r?(t.consume(c),d):(t.exit("setextHeadingLineSequence"),Dt(c)?Bt(t,m,"lineSuffix")(c):m(c))}function m(c){return c===null||Ct(c)?(t.exit("setextHeadingLine"),n(c)):s(c)}}const US={tokenize:HS};function HS(t){const n=this,s=t.attempt(ar,i,t.attempt(this.parser.constructs.flowInitial,r,Bt(t,t.attempt(this.parser.constructs.flow,r,t.attempt(G1,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 qS={resolveAll:gp()},VS=fp("string"),WS=fp("text");function fp(t){return{resolveAll:gp(t==="text"?KS: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 gp(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 KS(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 GS={42:Zn,43:Zn,45:Zn,48:Zn,49:Zn,50:Zn,51:Zn,52:Zn,53:Zn,54:Zn,55:Zn,56:Zn,57:Zn,62:op},JS={91:Z1},YS={[-2]:Hl,[-1]:Hl,32:Hl},QS={35:aS,42:Fr,45:[ju,Fr],60:cS,61:ju,95:Fr,96:vu,126:vu},XS={38:dp,92:cp},ZS={[-5]:ql,[-4]:ql,[-3]:ql,33:ES,38:dp,42:qo,60:[A1,gS],91:AS,92:[sS,cp],93:Nc,95:qo,96:U1},e0={null:[qo,qS]},t0={null:[42,95]},n0={null:[]},s0=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:t0,contentInitial:JS,disable:n0,document:GS,flow:QS,flowInitial:YS,insideSpan:e0,string:XS,text:ZS},Symbol.toStringTag,{value:"Module"}));function i0(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(P),check:S(w),consume:y,enter:M,exit:j,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(T){return o=ws(o,T),x(),o[o.length-1]!==null?[]:(k(n,0),c.events=hl(l,c.events,c),c.events)}function g(T,D){return r0(p(T),D)}function p(T){return a0(o,T)}function f(){const{_bufferIndex:T,_index:D,line:Z,column:$,offset:R}=i;return{_bufferIndex:T,_index:D,line:Z,column:$,offset:R}}function b(T){r[T.line]=T.column,E()}function x(){let T;for(;i._index<o.length;){const D=o[i._index];if(typeof D=="string")for(T=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===T&&i._bufferIndex<D.length;)v(D.charCodeAt(i._bufferIndex));else v(D)}}function v(T){u=u(T)}function y(T){Ct(T)?(i.line++,i.column=1,i.offset+=T===-3?2:1,E()):T!==-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=T}function M(T,D){const Z=D||{};return Z.type=T,Z.start=f(),c.events.push(["enter",Z,c]),d.push(Z),Z}function j(T){const D=d.pop();return D.end=f(),c.events.push(["exit",D,c]),D}function P(T,D){k(T,D.from)}function w(T,D){D.restore()}function S(T,D){return Z;function Z($,R,N){let W,Y,H,A;return Array.isArray($)?J($):"tokenize"in $?J([$]):z($);function z(O){return V;function V(F){const ue=F!==null&&O[F],ce=F!==null&&O.null,K=[...Array.isArray(ue)?ue:ue?[ue]:[],...Array.isArray(ce)?ce:ce?[ce]:[]];return J(K)(F)}}function J(O){return W=O,Y=0,O.length===0?N:C(O[Y])}function C(O){return V;function V(F){return A=_(),H=O,O.partial||(c.currentConstruct=O),O.name&&c.parser.constructs.disable.null.includes(O.name)?oe():O.tokenize.call(D?Object.assign(Object.create(c),D):c,m,q,oe)(F)}}function q(O){return T(H,A),R}function oe(O){return A.restore(),++Y<W.length?C(W[Y]):N}}}function k(T,D){T.resolveAll&&!l.includes(T)&&l.push(T),T.resolve&&ms(c.events,D,c.events.length-D,T.resolve(c.events.slice(D),c)),T.resolveTo&&(c.events=T.resolveTo(c.events,c))}function _(){const T=f(),D=c.previous,Z=c.currentConstruct,$=c.events.length,R=Array.from(d);return{from:$,restore:N};function N(){i=T,c.previous=D,c.currentConstruct=Z,c.events.length=$,d=R,E()}}function E(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function a0(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 r0(t,n){let s=-1;const i=[];let r;for(;++s<t.length;){const l=t[s];let o;if(typeof l=="string")o=l;else switch(l){case-5:{o="\r";break}case-4:{o=`
599
+ `;break}case-3:{o=`\r
600
+ `;break}case-2:{o=n?" ":" ";break}case-1:{if(!n&&r)continue;o=" ";break}default:o=String.fromCharCode(l)}r=l===-2,i.push(o)}return i.join("")}function l0(t){const i={constructs:rp([s0,...(t||{}).extensions||[]]),content:r(k1),defined:[],document:r(N1),flow:r(US),lazy:{},string:r(VS),text:r(WS)};return i;function r(l){return o;function o(d){return i0(i,l,d)}}}function o0(t){for(;!up(t););return t}const ku=/[\0\t\n\r]/g;function c0(){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(ku.lastIndex=h,c=ku.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 d0=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function u0(t){return t.replace(d0,m0)}function m0(t,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),l=r===120||r===88;return lp(s.slice(l?2:1),l?16:10)}return wc(s)||t}const bp={}.hasOwnProperty;function h0(t,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),p0(s)(o0(l0(s).document().write(c0()(t,n,!0))))}function p0(t){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:l($e),autolinkProtocol:_,autolinkEmail:_,atxHeading:l(Ee),blockQuote:l(ce),characterEscape:_,characterReference:_,codeFenced:l(K),codeFencedFenceInfo:o,codeFencedFenceMeta:o,codeIndented:l(K,o),codeText:l(de,o),codeTextData:_,data:_,codeFlowValue:_,definition:l(Fe),definitionDestinationString:o,definitionLabelString:o,definitionTitleString:o,emphasis:l(we),hardBreakEscape:l(ie),hardBreakTrailing:l(ie),htmlFlow:l(Pe,o),htmlFlowData:_,htmlText:l(Pe,o),htmlTextData:_,image:l(ze),label:o,link:l($e),listItem:l(Me),listItemValue:g,listOrdered:l(He,h),listUnordered:l(He),paragraph:l(Te),reference:C,referenceString:o,resourceDestinationString:o,resourceTitleString:o,setextHeading:l(Ee),strong:l(Ve),thematicBreak:l(et)},exit:{atxHeading:m(),atxHeadingSequence:P,autolink:m(),autolinkEmail:ue,autolinkProtocol:F,blockQuote:m(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:oe,characterReferenceMarkerNumeric:oe,characterReferenceValue:O,characterReference:V,codeFenced:m(x),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:E,codeIndented:m(v),codeText:m(R),codeTextData:E,data:E,definition:m(),definitionDestinationString:j,definitionLabelString:y,definitionTitleString:M,emphasis:m(),hardBreakEscape:m(D),hardBreakTrailing:m(D),htmlFlow:m(Z),htmlFlowData:E,htmlText:m($),htmlTextData:E,image:m(W),label:H,labelText:Y,lineEnding:T,link:m(N),listItem:m(),listOrdered:m(),listUnordered:m(),paragraph:m(),referenceString:q,resourceDestinationString:A,resourceTitleString:z,resource:J,setextHeading:m(k),setextHeadingLineSequence:S,setextHeadingText:w,strong:m(),thematicBreak:m()}};xp(n,(t||{}).mdastExtensions||[]);const s={};return i;function i(le){let X={type:"root",children:[]};const ke={stack:[X],tokenStack:[],config:n,enter:d,exit:c,buffer:o,resume:u,data:s},se=[];let Le=-1;for(;++Le<le.length;)if(le[Le][1].type==="listOrdered"||le[Le][1].type==="listUnordered")if(le[Le][0]==="enter")se.push(Le);else{const ve=se.pop();Le=r(le,ve,Le)}for(Le=-1;++Le<le.length;){const ve=n[le[Le][0]];bp.call(ve,le[Le][1].type)&&ve[le[Le][1].type].call(Object.assign({sliceSerialize:le[Le][2].sliceSerialize},ke),le[Le][1])}if(ke.tokenStack.length>0){const ve=ke.tokenStack[ke.tokenStack.length-1];(ve[1]||wu).call(ke,void 0,ve[0])}for(X.position={start:ai(le.length>0?le[0][1].start:{line:1,column:1,offset:0}),end:ai(le.length>0?le[le.length-2][1].end:{line:1,column:1,offset:0})},Le=-1;++Le<n.transforms.length;)X=n.transforms[Le](X)||X;return X}function r(le,X,ke){let se=X-1,Le=-1,ve=!1,Ye,mt,ht,me;for(;++se<=ke;){const te=le[se];switch(te[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{te[0]==="enter"?Le++:Le--,me=void 0;break}case"lineEndingBlank":{te[0]==="enter"&&(Ye&&!me&&!Le&&!ht&&(ht=se),me=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:me=void 0}if(!Le&&te[0]==="enter"&&te[1].type==="listItemPrefix"||Le===-1&&te[0]==="exit"&&(te[1].type==="listUnordered"||te[1].type==="listOrdered")){if(Ye){let je=se;for(mt=void 0;je--;){const Ae=le[je];if(Ae[1].type==="lineEnding"||Ae[1].type==="lineEndingBlank"){if(Ae[0]==="exit")continue;mt&&(le[mt][1].type="lineEndingBlank",ve=!0),Ae[1].type="lineEnding",mt=je}else if(!(Ae[1].type==="linePrefix"||Ae[1].type==="blockQuotePrefix"||Ae[1].type==="blockQuotePrefixWhitespace"||Ae[1].type==="blockQuoteMarker"||Ae[1].type==="listItemIndent"))break}ht&&(!mt||ht<mt)&&(Ye._spread=!0),Ye.end=Object.assign({},mt?le[mt][1].start:te[1].end),le.splice(mt||se,0,["exit",Ye,te[2]]),se++,ke++}if(te[1].type==="listItemPrefix"){const je={type:"listItem",_spread:!1,start:Object.assign({},te[1].start),end:void 0};Ye=je,le.splice(se,0,["enter",je,te[2]]),se++,ke++,ht=void 0,me=!0}}}return le[X][1]._spread=ve,ke}function l(le,X){return ke;function ke(se){d.call(this,le(se),se),X&&X.call(this,se)}}function o(){this.stack.push({type:"fragment",children:[]})}function d(le,X,ke){this.stack[this.stack.length-1].children.push(le),this.stack.push(le),this.tokenStack.push([X,ke||void 0]),le.position={start:ai(X.start),end:void 0}}function m(le){return X;function X(ke){le&&le.call(this,ke),c.call(this,ke)}}function c(le,X){const ke=this.stack.pop(),se=this.tokenStack.pop();if(se)se[0].type!==le.type&&(X?X.call(this,le,se[0]):(se[1]||wu).call(this,le,se[0]));else throw new Error("Cannot close `"+le.type+"` ("+Da({start:le.start,end:le.end})+"): it’s not open");ke.position.end=ai(le.end)}function u(){return kc(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(le){if(this.data.expectingFirstListItemValue){const X=this.stack[this.stack.length-2];X.start=Number.parseInt(this.sliceSerialize(le),10),this.data.expectingFirstListItemValue=void 0}}function p(){const le=this.resume(),X=this.stack[this.stack.length-1];X.lang=le}function f(){const le=this.resume(),X=this.stack[this.stack.length-1];X.meta=le}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function x(){const le=this.resume(),X=this.stack[this.stack.length-1];X.value=le.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function v(){const le=this.resume(),X=this.stack[this.stack.length-1];X.value=le.replace(/(\r?\n|\r)$/g,"")}function y(le){const X=this.resume(),ke=this.stack[this.stack.length-1];ke.label=X,ke.identifier=Ts(this.sliceSerialize(le)).toLowerCase()}function M(){const le=this.resume(),X=this.stack[this.stack.length-1];X.title=le}function j(){const le=this.resume(),X=this.stack[this.stack.length-1];X.url=le}function P(le){const X=this.stack[this.stack.length-1];if(!X.depth){const ke=this.sliceSerialize(le).length;X.depth=ke}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function S(le){const X=this.stack[this.stack.length-1];X.depth=this.sliceSerialize(le).codePointAt(0)===61?1:2}function k(){this.data.setextHeadingSlurpLineEnding=void 0}function _(le){const ke=this.stack[this.stack.length-1].children;let se=ke[ke.length-1];(!se||se.type!=="text")&&(se=_e(),se.position={start:ai(le.start),end:void 0},ke.push(se)),this.stack.push(se)}function E(le){const X=this.stack.pop();X.value+=this.sliceSerialize(le),X.position.end=ai(le.end)}function T(le){const X=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ke=X.children[X.children.length-1];ke.position.end=ai(le.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(X.type)&&(_.call(this,le),E.call(this,le))}function D(){this.data.atHardBreak=!0}function Z(){const le=this.resume(),X=this.stack[this.stack.length-1];X.value=le}function $(){const le=this.resume(),X=this.stack[this.stack.length-1];X.value=le}function R(){const le=this.resume(),X=this.stack[this.stack.length-1];X.value=le}function N(){const le=this.stack[this.stack.length-1];if(this.data.inReference){const X=this.data.referenceType||"shortcut";le.type+="Reference",le.referenceType=X,delete le.url,delete le.title}else delete le.identifier,delete le.label;this.data.referenceType=void 0}function W(){const le=this.stack[this.stack.length-1];if(this.data.inReference){const X=this.data.referenceType||"shortcut";le.type+="Reference",le.referenceType=X,delete le.url,delete le.title}else delete le.identifier,delete le.label;this.data.referenceType=void 0}function Y(le){const X=this.sliceSerialize(le),ke=this.stack[this.stack.length-2];ke.label=u0(X),ke.identifier=Ts(X).toLowerCase()}function H(){const le=this.stack[this.stack.length-1],X=this.resume(),ke=this.stack[this.stack.length-1];if(this.data.inReference=!0,ke.type==="link"){const se=le.children;ke.children=se}else ke.alt=X}function A(){const le=this.resume(),X=this.stack[this.stack.length-1];X.url=le}function z(){const le=this.resume(),X=this.stack[this.stack.length-1];X.title=le}function J(){this.data.inReference=void 0}function C(){this.data.referenceType="collapsed"}function q(le){const X=this.resume(),ke=this.stack[this.stack.length-1];ke.label=X,ke.identifier=Ts(this.sliceSerialize(le)).toLowerCase(),this.data.referenceType="full"}function oe(le){this.data.characterReferenceType=le.type}function O(le){const X=this.sliceSerialize(le),ke=this.data.characterReferenceType;let se;ke?(se=lp(X,ke==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):se=wc(X);const Le=this.stack[this.stack.length-1];Le.value+=se}function V(le){const X=this.stack.pop();X.position.end=ai(le.end)}function F(le){E.call(this,le);const X=this.stack[this.stack.length-1];X.url=this.sliceSerialize(le)}function ue(le){E.call(this,le);const X=this.stack[this.stack.length-1];X.url="mailto:"+this.sliceSerialize(le)}function ce(){return{type:"blockquote",children:[]}}function K(){return{type:"code",lang:null,meta:null,value:""}}function de(){return{type:"inlineCode",value:""}}function Fe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function we(){return{type:"emphasis",children:[]}}function Ee(){return{type:"heading",depth:0,children:[]}}function ie(){return{type:"break"}}function Pe(){return{type:"html",value:""}}function ze(){return{type:"image",title:null,url:"",alt:null}}function $e(){return{type:"link",title:null,url:"",children:[]}}function He(le){return{type:"list",ordered:le.type==="listOrdered",start:null,spread:le._spread,children:[]}}function Me(le){return{type:"listItem",spread:le._spread,checked:null,children:[]}}function Te(){return{type:"paragraph",children:[]}}function Ve(){return{type:"strong",children:[]}}function _e(){return{type:"text",value:""}}function et(){return{type:"thematicBreak"}}}function ai(t){return{line:t.line,column:t.column,offset:t.offset}}function xp(t,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?xp(t,i):f0(t,i)}}function f0(t,n){let s;for(s in n)if(bp.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 wu(t,n){throw t?new Error("Cannot close `"+t.type+"` ("+Da({start:t.start,end:t.end})+"): a different token (`"+n.type+"`, "+Da({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Da({start:n.start,end:n.end})+") is still open")}function g0(t){const n=this;n.parser=s;function s(i){return h0(i,{...n.data("settings"),...t,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function b0(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 x0(t,n){const s={type:"element",tagName:"br",properties:{},children:[]};return t.patch(n,s),[t.applyData(n,s),{type:"text",value:`
601
+ `}]}function v0(t,n){const s=n.value?n.value+`
602
+ `:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let l={type:"element",tagName:"code",properties:i,children:[{type:"text",value:s}]};return n.meta&&(l.data={meta:n.meta}),t.patch(n,l),l=t.applyData(n,l),l={type:"element",tagName:"pre",properties:{},children:[l]},t.patch(n,l),l}function y0(t,n){const s={type:"element",tagName:"del",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function j0(t,n){const s={type:"element",tagName:"em",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function k0(t,n){const s=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=ha(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 w0(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 N0(t,n){if(t.options.allowDangerousHtml){const s={type:"raw",value:n.value};return t.patch(n,s),t.applyData(n,s)}}function vp(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 S0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return vp(t,n);const r={src:ha(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 C0(t,n){const s={src:ha(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 E0(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 M0(t,n){const s=String(n.identifier).toUpperCase(),i=t.definitionById.get(s);if(!i)return vp(t,n);const r={href:ha(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 A0(t,n){const s={href:ha(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 P0(t,n,s){const i=t.all(n),r=s?I0(s):yp(n),l={},o=[];if(typeof n.checked=="boolean"){const u=i[0];let h;u&&u.type==="element"&&u.tagName==="p"?h=u:(h={type:"element",tagName:"p",properties:{},children:[]},i.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),l.className=["task-list-item"]}let d=-1;for(;++d<i.length;){const u=i[d];(r||d!==0||u.type!=="element"||u.tagName!=="p")&&o.push({type:"text",value:`
603
+ `}),u.type==="element"&&u.tagName==="p"&&!r?o.push(...u.children):o.push(u)}const m=i[i.length-1];m&&(r||m.type!=="element"||m.tagName!=="p")&&o.push({type:"text",value:`
604
+ `});const c={type:"element",tagName:"li",properties:l,children:o};return t.patch(n,c),t.applyData(n,c)}function I0(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=yp(s[i])}return n}function yp(t){const n=t.spread;return n??t.children.length>1}function _0(t,n){const s={},i=t.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<i.length;){const o=i[r];if(o.type==="element"&&o.tagName==="li"&&o.properties&&Array.isArray(o.properties.className)&&o.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const l={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:t.wrap(i,!0)};return t.patch(n,l),t.applyData(n,l)}function R0(t,n){const s={type:"element",tagName:"p",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function T0(t,n){const s={type:"root",children:t.wrap(t.all(n))};return t.patch(n,s),t.applyData(n,s)}function $0(t,n){const s={type:"element",tagName:"strong",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}function F0(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=xc(n.children[1]),m=Zh(n.children[n.children.length-1]);d&&m&&(o.position={start:d,end:m}),r.push(o)}const l={type:"element",tagName:"table",properties:{},children:t.wrap(r,!0)};return t.patch(n,l),t.applyData(n,l)}function D0(t,n,s){const i=s?s.children:void 0,l=(i?i.indexOf(n):1)===0?"th":"td",o=s&&s.type==="table"?s.align:void 0,d=o?o.length:n.children.length;let m=-1;const c=[];for(;++m<d;){const h=n.children[m],g={},p=o?o[m]:void 0;p&&(g.align=p);let f={type:"element",tagName:l,properties:g,children:[]};h&&(f.children=t.all(h),t.patch(h,f),f=t.applyData(h,f)),c.push(f)}const u={type:"element",tagName:"tr",properties:{},children:t.wrap(c,!0)};return t.patch(n,u),t.applyData(n,u)}function L0(t,n){const s={type:"element",tagName:"td",properties:{},children:t.all(n)};return t.patch(n,s),t.applyData(n,s)}const Nu=9,Su=32;function z0(t){const n=String(t),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const l=[];for(;i;)l.push(Cu(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return l.push(Cu(n.slice(r),r>0,!1)),l.join("")}function Cu(t,n,s){let i=0,r=t.length;if(n){let l=t.codePointAt(i);for(;l===Nu||l===Su;)i++,l=t.codePointAt(i)}if(s){let l=t.codePointAt(r-1);for(;l===Nu||l===Su;)r--,l=t.codePointAt(r-1)}return r>i?t.slice(i,r):""}function O0(t,n){const s={type:"text",value:z0(String(n.value))};return t.patch(n,s),t.applyData(n,s)}function B0(t,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return t.patch(n,s),t.applyData(n,s)}const U0={blockquote:b0,break:x0,code:v0,delete:y0,emphasis:j0,footnoteReference:k0,heading:w0,html:N0,imageReference:S0,image:C0,inlineCode:E0,linkReference:M0,link:A0,listItem:P0,list:_0,paragraph:R0,root:T0,strong:$0,table:F0,tableCell:L0,tableRow:D0,text:O0,thematicBreak:B0,toml:kr,yaml:kr,definition:kr,footnoteDefinition:kr};function kr(){}const jp=-1,pl=0,za=1,Yr=2,Sc=3,Cc=4,Ec=5,Mc=6,kp=7,wp=8,Eu=typeof self=="object"?self:globalThis,H0=(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 pl:case jp:return s(o,r);case za:{const d=s([],r);for(const m of o)d.push(i(m));return d}case Yr:{const d=s({},r);for(const[m,c]of o)d[i(m)]=i(c);return d}case Sc:return s(new Date(o),r);case Cc:{const{source:d,flags:m}=o;return s(new RegExp(d,m),r)}case Ec:{const d=s(new Map,r);for(const[m,c]of o)d.set(i(m),i(c));return d}case Mc:{const d=s(new Set,r);for(const m of o)d.add(i(m));return d}case kp:{const{name:d,message:m}=o;return s(new Eu[d](m),r)}case wp: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 Eu[l](o),r)};return i},Mu=t=>H0(new Map,t)(0),Oi="",{toString:q0}={},{keys:V0}=Object,Na=t=>{const n=typeof t;if(n!=="object"||!t)return[pl,n];const s=q0.call(t).slice(8,-1);switch(s){case"Array":return[za,Oi];case"Object":return[Yr,Oi];case"Date":return[Sc,Oi];case"RegExp":return[Cc,Oi];case"Map":return[Ec,Oi];case"Set":return[Mc,Oi];case"DataView":return[za,s]}return s.includes("Array")?[za,s]:s.includes("Error")?[kp,s]:[Yr,s]},wr=([t,n])=>t===pl&&(n==="function"||n==="symbol"),W0=(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]=Na(o);switch(d){case pl:{let u=o;switch(m){case"bigint":d=wp,u=o.toString();break;case"function":case"symbol":if(t)throw new TypeError("unable to serialize "+m);u=null;break;case"undefined":return r([jp],o)}return r([d,u],o)}case za:{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 Yr:{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 V0(o))(t||!wr(Na(o[g])))&&u.push([l(g),l(o[g])]);return h}case Sc:return r([d,o.toISOString()],o);case Cc:{const{source:u,flags:h}=o;return r([d,{source:u,flags:h}],o)}case Ec:{const u=[],h=r([d,u],o);for(const[g,p]of o)(t||!(wr(Na(g))||wr(Na(p))))&&u.push([l(g),l(p)]);return h}case Mc:{const u=[],h=r([d,u],o);for(const g of o)(t||!wr(Na(g)))&&u.push(l(g));return h}}const{message:c}=o;return r([d,{name:m,message:c}],o)};return l},Au=(t,{json:n,lossy:s}={})=>{const i=[];return W0(!(n||s),!!n,new Map,i)(t),i},Qr=typeof structuredClone=="function"?(t,n)=>n&&("json"in n||"lossy"in n)?Mu(Au(t,n)):structuredClone(t):(t,n)=>Mu(Au(t,n));function K0(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 G0(t,n){return"Back to reference "+(t+1)+(n>1?"-"+n:"")}function J0(t){const n=typeof t.options.clobberPrefix=="string"?t.options.clobberPrefix:"user-content-",s=t.options.footnoteBackContent||K0,i=t.options.footnoteBackLabel||G0,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=ha(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 y=typeof s=="string"?s:s(m,p);typeof y=="string"&&(y={type:"text",value:y}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(m,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const x=u[u.length-1];if(x&&x.type==="element"&&x.tagName==="p"){const y=x.children[x.children.length-1];y&&y.type==="text"?y.value+=" ":x.children.push({type:"text",value:" "}),x.children.push(...f)}else u.push(...f);const v={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:t.wrap(u,!0)};t.patch(c,v),d.push(v)}if(d.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:l,properties:{...Qr(o),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
605
+ `},{type:"element",tagName:"ol",properties:{},children:t.wrap(d,!0)},{type:"text",value:`
606
+ `}]}}const fl=(function(t){if(t==null)return Z0;if(typeof t=="function")return gl(t);if(typeof t=="object")return Array.isArray(t)?Y0(t):Q0(t);if(typeof t=="string")return X0(t);throw new Error("Expected function, string, or object as test")});function Y0(t){const n=[];let s=-1;for(;++s<t.length;)n[s]=fl(t[s]);return gl(i);function i(...r){let l=-1;for(;++l<n.length;)if(n[l].apply(this,r))return!0;return!1}}function Q0(t){const n=t;return gl(s);function s(i){const r=i;let l;for(l in t)if(r[l]!==n[l])return!1;return!0}}function X0(t){return gl(n);function n(s){return s&&s.type===t}}function gl(t){return n;function n(s,i,r){return!!(eC(s)&&t.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function Z0(){return!0}function eC(t){return t!==null&&typeof t=="object"&&"type"in t}const Np=[],tC=!0,Vo=!1,nC="skip";function Sp(t,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const l=fl(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=Np,f,b,x;if((!n||l(m,c,u[u.length-1]||void 0))&&(p=sC(s(m,u)),p[0]===Vo))return p;if("children"in m&&m.children){const v=m;if(v.children&&p[0]!==nC)for(b=(i?v.children.length:-1)+o,x=u.concat(v);b>-1&&b<v.children.length;){const y=v.children[b];if(f=d(y,b,x)(),f[0]===Vo)return f;b=typeof f[1]=="number"?f[1]:b+o}}return p}}}function sC(t){return Array.isArray(t)?t:typeof t=="number"?[tC,t]:t==null?Np:[t]}function Ac(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),Sp(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 Wo={}.hasOwnProperty,iC={};function aC(t,n){const s=n||iC,i=new Map,r=new Map,l=new Map,o={...U0,...s.handlers},d={all:c,applyData:lC,definitionById:i,footnoteById:r,footnoteCounts:l,footnoteOrder:[],handlers:o,one:m,options:s,patch:rC,wrap:cC};return Ac(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(Wo.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,v=Qr(x);return v.children=d.all(u),v}return Qr(u)}return(d.options.unknownHandler||oC)(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=Pu(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=Pu(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function rC(t,n){t.position&&(n.position=GN(t))}function lC(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,Qr(l)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function oC(t,n){const s=n.data||{},i="value"in n&&!(Wo.call(s,"hProperties")||Wo.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 cC(t,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
607
+ `});++i<t.length;)i&&s.push({type:"text",value:`
608
+ `}),s.push(t[i]);return n&&t.length>0&&s.push({type:"text",value:`
609
+ `}),s}function Pu(t){let n=0,s=t.charCodeAt(n);for(;s===9||s===32;)n++,s=t.charCodeAt(n);return t.slice(n)}function Iu(t,n){const s=aC(t,n),i=s.one(t,void 0),r=J0(s),l=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&l.children.push({type:"text",value:`
610
+ `},r),l}function dC(t,n){return t&&"run"in t?async function(s,i){const r=Iu(s,{file:i,...n});await t.run(r,i)}:function(s,i){return Iu(s,{file:i,...t||n})}}function _u(t){if(t)throw t}var Vl,Ru;function uC(){if(Ru)return Vl;Ru=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 Vl=function m(){var c,u,h,g,p,f,b=arguments[0],x=1,v=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},x=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});x<v;++x)if(c=arguments[x],c!=null)for(u in c)h=d(b,u),g=d(c,u),b!==g&&(y&&g&&(l(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&l(h)?h:{},o(b,{name:u,newValue:m(y,f,g)})):typeof g<"u"&&o(b,{name:u,newValue:g}));return b},Vl}var mC=uC();const Wl=Vm(mC);function Ko(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 hC(){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?pC(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 pC(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 Bs={basename:fC,dirname:gC,extname:bC,join:xC,sep:"/"};function fC(t,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');rr(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 gC(t){if(rr(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 bC(t){rr(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 xC(...t){let n=-1,s;for(;++n<t.length;)rr(t[n]),t[n]&&(s=s===void 0?t[n]:s+"/"+t[n]);return s===void 0?".":vC(s)}function vC(t){rr(t);const n=t.codePointAt(0)===47;let s=yC(t,!n);return s.length===0&&!n&&(s="."),s.length>0&&t.codePointAt(t.length-1)===47&&(s+="/"),n?"/"+s:s}function yC(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 rr(t){if(typeof t!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}const jC={cwd:kC};function kC(){return"/"}function Go(t){return!!(t!==null&&typeof t=="object"&&"href"in t&&t.href&&"protocol"in t&&t.protocol&&t.auth===void 0)}function wC(t){if(typeof t=="string")t=new URL(t);else if(!Go(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 NC(t)}function NC(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 Kl=["history","path","basename","stem","extname","dirname"];class Cp{constructor(n){let s;n?Go(n)?s={path:n}:typeof n=="string"||SC(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":jC.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Kl.length;){const l=Kl[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)Kl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Bs.basename(this.path):void 0}set basename(n){Jl(n,"basename"),Gl(n,"basename"),this.path=Bs.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Bs.dirname(this.path):void 0}set dirname(n){Tu(this.basename,"dirname"),this.path=Bs.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Bs.extname(this.path):void 0}set extname(n){if(Gl(n,"extname"),Tu(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=Bs.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Go(n)&&(n=wC(n)),Jl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Bs.basename(this.path,this.extname):void 0}set stem(n){Jl(n,"stem"),Gl(n,"stem"),this.path=Bs.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 Ln(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 Gl(t,n){if(t&&t.includes(Bs.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Bs.sep+"`")}function Jl(t,n){if(!t)throw new Error("`"+n+"` cannot be empty")}function Tu(t,n){if(!t)throw new Error("Setting `"+n+"` requires `path` to be set too")}function SC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const CC=(function(t){const i=this.constructor.prototype,r=i[t],l=function(){return r.apply(l,arguments)};return Object.setPrototypeOf(l,i),l}),EC={}.hasOwnProperty;class Pc extends CC{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=hC()}copy(){const n=new Pc;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Wl(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Xl("data",this.frozen),this.namespace[n]=s,this):EC.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Xl("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=Nr(n),i=this.parser||this.Parser;return Yl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Yl("process",this.parser||this.Parser),Ql("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(l,o){const d=Nr(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);PC(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(),Yl("processSync",this.parser||this.Parser),Ql("processSync",this.compiler||this.Compiler),this.process(n,r),Fu("processSync","process",s),i;function r(l,o){s=!0,_u(l),i=o}}run(n,s,i){$u(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=Nr(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),Fu("runSync","run",i),r;function l(o,d){_u(o),r=d,i=!0}}stringify(n,s){this.freeze();const i=Nr(s),r=this.compiler||this.Compiler;return Ql("stringify",r),$u(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Xl("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=Wl(!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];Ko(b)&&Ko(p)&&(p=Wl(!0,b,p)),i[g]=[c,p,...f]}}}}const MC=new Pc().freeze();function Yl(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `parser`")}function Ql(t,n){if(typeof n!="function")throw new TypeError("Cannot `"+t+"` without `compiler`")}function Xl(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 $u(t){if(!Ko(t)||typeof t.type!="string")throw new TypeError("Expected node, got `"+t+"`")}function Fu(t,n,s){if(!s)throw new Error("`"+t+"` finished async. Use `"+n+"` instead")}function Nr(t){return AC(t)?t:new Cp(t)}function AC(t){return!!(t&&typeof t=="object"&&"message"in t&&"messages"in t)}function PC(t){return typeof t=="string"||IC(t)}function IC(t){return!!(t&&typeof t=="object"&&"byteLength"in t&&"byteOffset"in t)}const _C="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Du=[],Lu={allowDangerousHtml:!0},RC=/^(https?|ircs?|mailto|xmpp)$/i,TC=[{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 di(t){const n=$C(t),s=FC(t);return DC(n.runSync(n.parse(s),s),t)}function $C(t){const n=t.rehypePlugins||Du,s=t.remarkPlugins||Du,i=t.remarkRehypeOptions?{...t.remarkRehypeOptions,...Lu}:Lu;return MC().use(g0).use(s).use(dC,i).use(n)}function FC(t){const n=t.children||"",s=new Cp;return typeof n=="string"&&(s.value=n),s}function DC(t,n){const s=n.allowedElements,i=n.allowElement,r=n.components,l=n.disallowedElements,o=n.skipHtml,d=n.unwrapDisallowed,m=n.urlTransform||LC;for(const u of TC)Object.hasOwn(n,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+_C+u.id,void 0);return Ac(t,c),ZN(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 Ul)if(Object.hasOwn(Ul,p)&&Object.hasOwn(u.properties,p)){const f=u.properties[p],b=Ul[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 LC(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||RC.test(t.slice(0,n))?t:""}function zu(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 zC(t){if(typeof t!="string")throw new TypeError("Expected a string");return t.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function OC(t,n,s){const r=fl((s||{}).ignore||[]),l=BC(n);let o=-1;for(;++o<l.length;)Sp(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 v=!1,y=[];g.lastIndex=0;let M=g.exec(c.value);for(;M;){const j=M.index,P={index:M.index,input:M.input,stack:[...u,c]};let w=p(...M,P);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=j+1:(f!==j&&y.push({type:"text",value:c.value.slice(f,j)}),Array.isArray(w)?y.push(...w):w&&y.push(w),f=j+M[0].length,v=!0),!g.global)break;M=g.exec(c.value)}return v?(f<c.value.length&&y.push({type:"text",value:c.value.slice(f)}),h.children.splice(x,1,...y)):y=[c],x+y.length}}function BC(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([UC(r[0]),HC(r[1])])}return n}function UC(t){return typeof t=="string"?new RegExp(zC(t),"g"):t}function HC(t){return typeof t=="function"?t:function(){return t}}const Zl="phrasing",eo=["autolink","link","image","label"];function qC(){return{transforms:[QC],enter:{literalAutolink:WC,literalAutolinkEmail:to,literalAutolinkHttp:to,literalAutolinkWww:to},exit:{literalAutolink:YC,literalAutolinkEmail:JC,literalAutolinkHttp:KC,literalAutolinkWww:GC}}}function VC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Zl,notInConstruct:eo},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Zl,notInConstruct:eo},{character:":",before:"[ps]",after:"\\/",inConstruct:Zl,notInConstruct:eo}]}}function WC(t){this.enter({type:"link",title:null,url:"",children:[]},t)}function to(t){this.config.enter.autolinkProtocol.call(this,t)}function KC(t){this.config.exit.autolinkProtocol.call(this,t)}function GC(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 JC(t){this.config.exit.autolinkEmail.call(this,t)}function YC(t){this.exit(t)}function QC(t){OC(t,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,XC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,ZC]],{ignore:["link","linkReference"]})}function XC(t,n,s,i,r){let l="";if(!Ep(r)||(/^w/i.test(n)&&(s=n+s,n="",l="http://"),!eE(s)))return!1;const o=tE(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 ZC(t,n,s,i){return!Ep(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function eE(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 tE(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=zu(t,"(");let l=zu(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 Ep(t,n){const s=t.input.charCodeAt(t.index-1);return(t.index===0||Mi(s)||ml(s))&&(!n||s!==47)}Mp.peek=dE;function nE(){this.buffer()}function sE(t){this.enter({type:"footnoteReference",identifier:"",label:""},t)}function iE(){this.buffer()}function aE(t){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},t)}function rE(t){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ts(this.sliceSerialize(t)).toLowerCase(),s.label=n}function lE(t){this.exit(t)}function oE(t){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Ts(this.sliceSerialize(t)).toLowerCase(),s.label=n}function cE(t){this.exit(t)}function dE(){return"["}function Mp(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 uE(){return{enter:{gfmFootnoteCallString:nE,gfmFootnoteCall:sE,gfmFootnoteDefinitionLabelString:iE,gfmFootnoteDefinition:aE},exit:{gfmFootnoteCallString:rE,gfmFootnoteCall:lE,gfmFootnoteDefinitionLabelString:oE,gfmFootnoteDefinition:cE}}}function mE(t){let n=!1;return t&&t.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Mp},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,l,o){const d=l.createTracker(o);let m=d.move("[^");const c=l.enter("footnoteDefinition"),u=l.enter("label");return m+=d.move(l.safe(l.associationId(i),{before:m,after:"]"})),u(),m+=d.move("]:"),i.children&&i.children.length>0&&(d.shift(4),m+=d.move((n?`
611
+ `:" ")+l.indentLines(l.containerFlow(i,d.current()),n?Ap:hE))),c(),m}}function hE(t,n,s){return n===0?t:Ap(t,n,s)}function Ap(t,n,s){return(s?"":" ")+t}const pE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Pp.peek=vE;function fE(){return{canContainEols:["delete"],enter:{strikethrough:bE},exit:{strikethrough:xE}}}function gE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:pE}],handlers:{delete:Pp}}}function bE(t){this.enter({type:"delete",children:[]},t)}function xE(t){this.exit(t)}function Pp(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 vE(){return"~"}function yE(t){return t.length}function jE(t,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||yE,l=[],o=[],d=[],m=[];let c=0,u=-1;for(;++u<t.length;){const b=[],x=[];let v=-1;for(t[u].length>c&&(c=t[u].length);++v<t[u].length;){const y=kE(t[u][v]);if(s.alignDelimiters!==!1){const M=r(y);x[v]=M,(m[v]===void 0||M>m[v])&&(m[v]=M)}b.push(y)}o[u]=b,d[u]=x}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<c;)l[h]=Ou(i[h]);else{const b=Ou(i);for(;++h<c;)l[h]=b}h=-1;const g=[],p=[];for(;++h<c;){const b=l[h];let x="",v="";b===99?(x=":",v=":"):b===108?x=":":b===114&&(v=":");let y=s.alignDelimiters===!1?1:Math.max(1,m[h]-x.length-v.length);const M=x+"-".repeat(y)+v;s.alignDelimiters!==!1&&(y=x.length+y+v.length,y>m[h]&&(m[h]=y),p[h]=y),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 v=[];for(;++h<c;){const y=b[h]||"";let M="",j="";if(s.alignDelimiters!==!1){const P=m[h]-(x[h]||0),w=l[h];w===114?M=" ".repeat(P):w===99?P%2?(M=" ".repeat(P/2+.5),j=" ".repeat(P/2-.5)):(M=" ".repeat(P/2),j=M):j=" ".repeat(P)}s.delimiterStart!==!1&&!h&&v.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&v.push(" "),s.alignDelimiters!==!1&&v.push(M),v.push(y),s.alignDelimiters!==!1&&v.push(j),s.padding!==!1&&v.push(" "),(s.delimiterEnd!==!1||h!==c-1)&&v.push("|")}f.push(s.delimiterEnd===!1?v.join("").replace(/ +$/,""):v.join(""))}return f.join(`
612
+ `)}function kE(t){return t==null?"":String(t)}function Ou(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 wE(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()),NE);return r(),o}function NE(t,n,s){return">"+(s?"":" ")+t}function SE(t,n){return Bu(t,n.inConstruct,!0)&&!Bu(t,n.notInConstruct,!1)}function Bu(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 Uu(t,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
613
+ `&&SE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
614
+ `}function CE(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 EE(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 ME(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 AE(t,n,s,i){const r=ME(s),l=t.value||"",o=r==="`"?"GraveAccent":"Tilde";if(EE(t,s)){const h=s.enter("codeIndented"),g=s.indentLines(l,PE);return h(),g}const d=s.createTracker(i),m=r.repeat(Math.max(CE(l,r)+1,3)),c=s.enter("codeFenced");let u=d.move(m);if(t.lang){const h=s.enter(`codeFencedLang${o}`);u+=d.move(s.safe(t.lang,{before:u,after:" ",encode:["`"],...d.current()})),h()}if(t.lang&&t.meta){const h=s.enter(`codeFencedMeta${o}`);u+=d.move(" "),u+=d.move(s.safe(t.meta,{before:u,after:`
615
+ `,encode:["`"],...d.current()})),h()}return u+=d.move(`
616
+ `),l&&(u+=d.move(l+`
617
+ `)),u+=d.move(m),c(),u}function PE(t,n,s){return(s?"":" ")+t}function Ic(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 IE(t,n,s,i){const r=Ic(s),l=r==='"'?"Quote":"Apostrophe",o=s.enter("definition");let d=s.enter("label");const m=s.createTracker(i);let c=m.move("[");return c+=m.move(s.safe(s.associationId(t),{before:c,after:"]",...m.current()})),c+=m.move("]: "),d(),!t.url||/[\0- \u007F]/.test(t.url)?(d=s.enter("destinationLiteral"),c+=m.move("<"),c+=m.move(s.safe(t.url,{before:c,after:">",...m.current()})),c+=m.move(">")):(d=s.enter("destinationRaw"),c+=m.move(s.safe(t.url,{before:c,after:t.title?" ":`
618
+ `,...m.current()}))),d(),t.title&&(d=s.enter(`title${l}`),c+=m.move(" "+r),c+=m.move(s.safe(t.title,{before:c,after:r,...m.current()})),c+=m.move(r),d()),o(),c}function _E(t){const n=t.options.emphasis||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize emphasis with `"+n+"` for `options.emphasis`, expected `*`, or `_`");return n}function Wa(t){return"&#x"+t.toString(16).toUpperCase()+";"}function Xr(t,n,s){const i=ta(t),r=ta(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}}Ip.peek=RE;function Ip(t,n,s,i){const r=_E(s),l=s.enter("emphasis"),o=s.createTracker(i),d=o.move(r);let m=o.move(s.containerPhrasing(t,{after:r,before:d,...o.current()}));const c=m.charCodeAt(0),u=Xr(i.before.charCodeAt(i.before.length-1),c,r);u.inside&&(m=Wa(c)+m.slice(1));const h=m.charCodeAt(m.length-1),g=Xr(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+Wa(h));const p=o.move(r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+p}function RE(t,n,s){return s.options.emphasis||"*"}function TE(t,n){let s=!1;return Ac(t,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Vo}),!!((!t.depth||t.depth<3)&&kc(t)&&(n.options.setext||s))}function $E(t,n,s,i){const r=Math.max(Math.min(6,t.depth||1),1),l=s.createTracker(i);if(TE(t,s)){const u=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(t,{...l.current(),before:`
619
+ `,after:`
620
+ `});return h(),u(),g+`
621
+ `+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
622
+ `))+1))}const o="#".repeat(r),d=s.enter("headingAtx"),m=s.enter("phrasing");l.move(o+" ");let c=s.containerPhrasing(t,{before:"# ",after:`
623
+ `,...l.current()});return/^[\t ]/.test(c)&&(c=Wa(c.charCodeAt(0))+c.slice(1)),c=c?o+" "+c:o,s.options.closeAtx&&(c+=" "+o),m(),d(),c}_p.peek=FE;function _p(t){return t.value||""}function FE(){return"<"}Rp.peek=DE;function Rp(t,n,s,i){const r=Ic(s),l=r==='"'?"Quote":"Apostrophe",o=s.enter("image");let d=s.enter("label");const m=s.createTracker(i);let c=m.move("![");return c+=m.move(s.safe(t.alt,{before:c,after:"]",...m.current()})),c+=m.move("]("),d(),!t.url&&t.title||/[\0- \u007F]/.test(t.url)?(d=s.enter("destinationLiteral"),c+=m.move("<"),c+=m.move(s.safe(t.url,{before:c,after:">",...m.current()})),c+=m.move(">")):(d=s.enter("destinationRaw"),c+=m.move(s.safe(t.url,{before:c,after:t.title?" ":")",...m.current()}))),d(),t.title&&(d=s.enter(`title${l}`),c+=m.move(" "+r),c+=m.move(s.safe(t.title,{before:c,after:r,...m.current()})),c+=m.move(r),d()),c+=m.move(")"),o(),c}function DE(){return"!"}Tp.peek=LE;function Tp(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 LE(){return"!"}$p.peek=zE;function $p(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 zE(){return"`"}function Fp(t,n){const s=kc(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))}Dp.peek=OE;function Dp(t,n,s,i){const r=Ic(s),l=r==='"'?"Quote":"Apostrophe",o=s.createTracker(i);let d,m;if(Fp(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 OE(t,n,s){return Fp(t,s)?"<":"["}Lp.peek=BE;function Lp(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 BE(){return"["}function _c(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 UE(t){const n=_c(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 HE(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 zp(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 qE(t,n,s,i){const r=s.enter("list"),l=s.bulletCurrent;let o=t.ordered?HE(s):_c(s);const d=t.ordered?o==="."?")":".":UE(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),zp(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 VE(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 WE(t,n,s,i){const r=VE(s);let l=s.bulletCurrent||_c(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 KE(t,n,s,i){const r=s.enter("paragraph"),l=s.enter("phrasing"),o=s.containerPhrasing(t,i);return l(),r(),o}const GE=fl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function JE(t,n,s,i){return(t.children.some(function(o){return GE(o)})?s.containerPhrasing:s.containerFlow).call(s,t,i)}function YE(t){const n=t.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Op.peek=QE;function Op(t,n,s,i){const r=YE(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=Xr(i.before.charCodeAt(i.before.length-1),c,r);u.inside&&(m=Wa(c)+m.slice(1));const h=m.charCodeAt(m.length-1),g=Xr(i.after.charCodeAt(0),h,r);g.inside&&(m=m.slice(0,-1)+Wa(h));const p=o.move(r+r);return l(),s.attentionEncodeSurroundingInfo={after:g.outside,before:u.outside},d+m+p}function QE(t,n,s){return s.options.strong||"*"}function XE(t,n,s,i){return s.safe(t.value,i)}function ZE(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 e2(t,n,s){const i=(zp(s)+(s.options.ruleSpaces?" ":"")).repeat(ZE(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Bp={blockquote:wE,break:Uu,code:AE,definition:IE,emphasis:Ip,hardBreak:Uu,heading:$E,html:_p,image:Rp,imageReference:Tp,inlineCode:$p,link:Dp,linkReference:Lp,list:qE,listItem:WE,paragraph:KE,root:JE,strong:Op,text:XE,thematicBreak:e2};function t2(){return{enter:{table:n2,tableData:Hu,tableHeader:Hu,tableRow:i2},exit:{codeText:a2,table:s2,tableData:no,tableHeader:no,tableRow:no}}}function n2(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 s2(t){this.exit(t),this.data.inTable=void 0}function i2(t){this.enter({type:"tableRow",children:[]},t)}function no(t){this.exit(t)}function Hu(t){this.enter({type:"tableCell",children:[]},t)}function a2(t){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,r2));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(t)}function r2(t,n){return n==="|"?n:t}function l2(t){const n=t||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,l=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
624
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:o,tableCell:m,tableRow:d}};function o(p,f,b,x){return c(u(p,b,x),p.align)}function d(p,f,b,x){const v=h(p,b,x),y=c([v]);return y.slice(0,y.indexOf(`
625
+ `))}function m(p,f,b,x){const v=b.enter("tableCell"),y=b.enter("phrasing"),M=b.containerPhrasing(p,{...x,before:l,after:l});return y(),v(),M}function c(p,f){return jE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function u(p,f,b){const x=p.children;let v=-1;const y=[],M=f.enter("table");for(;++v<x.length;)y[v]=h(x[v],f,b);return M(),y}function h(p,f,b){const x=p.children;let v=-1;const y=[],M=f.enter("tableRow");for(;++v<x.length;)y[v]=m(x[v],p,f,b);return M(),y}function g(p,f,b){let x=Bp.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(x=x.replace(/\|/g,"\\$&")),x}}function o2(){return{exit:{taskListCheckValueChecked:qu,taskListCheckValueUnchecked:qu,paragraph:d2}}}function c2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:u2}}}function qu(t){const n=this.stack[this.stack.length-2];n.type,n.checked=t.type==="taskListCheckValueChecked"}function d2(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 u2(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=Bp.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 m2(){return[qC(),uE(),fE(),t2(),o2()]}function h2(t){return{extensions:[VC(),mE(t),gE(),l2(t),c2()]}}const p2={tokenize:y2,partial:!0},Up={tokenize:j2,partial:!0},Hp={tokenize:k2,partial:!0},qp={tokenize:w2,partial:!0},f2={tokenize:N2,partial:!0},Vp={name:"wwwAutolink",tokenize:x2,previous:Kp},Wp={name:"protocolAutolink",tokenize:v2,previous:Gp},ni={name:"emailAutolink",tokenize:b2,previous:Jp},Js={};function g2(){return{text:Js}}let xi=48;for(;xi<123;)Js[xi]=ni,xi++,xi===58?xi=65:xi===91&&(xi=97);Js[43]=ni;Js[45]=ni;Js[46]=ni;Js[95]=ni;Js[72]=[ni,Wp];Js[104]=[ni,Wp];Js[87]=[ni,Vp];Js[119]=[ni,Vp];function b2(t,n,s){const i=this;let r,l;return o;function o(h){return!Jo(h)||!Jp.call(i,i.previous)||Rc(i.events)?s(h):(t.enter("literalAutolink"),t.enter("literalAutolinkEmail"),d(h))}function d(h){return Jo(h)?(t.consume(h),d):h===64?(t.consume(h),m):s(h)}function m(h){return h===46?t.check(f2,u,c)(h):h===45||h===95||Fn(h)?(l=!0,t.consume(h),m):u(h)}function c(h){return t.consume(h),r=!0,m}function u(h){return l&&r&&qn(i.previous)?(t.exit("literalAutolinkEmail"),t.exit("literalAutolink"),n(h)):s(h)}}function x2(t,n,s){const i=this;return r;function r(o){return o!==87&&o!==119||!Kp.call(i,i.previous)||Rc(i.events)?s(o):(t.enter("literalAutolink"),t.enter("literalAutolinkWww"),t.check(p2,t.attempt(Up,t.attempt(Hp,l),s),s)(o))}function l(o){return t.exit("literalAutolinkWww"),t.exit("literalAutolink"),n(o)}}function v2(t,n,s){const i=this;let r="",l=!1;return o;function o(h){return(h===72||h===104)&&Gp.call(i,i.previous)&&!Rc(i.events)?(t.enter("literalAutolink"),t.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),t.consume(h),d):s(h)}function d(h){if(qn(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||Jr(h)||Qt(h)||Mi(h)||ml(h)?s(h):t.attempt(Up,t.attempt(Hp,u),s)(h)}function u(h){return t.exit("literalAutolinkHttp"),t.exit("literalAutolink"),n(h)}}function y2(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 j2(t,n,s){let i,r,l;return o;function o(c){return c===46||c===95?t.check(qp,m,d)(c):c===null||Qt(c)||Mi(c)||c!==45&&ml(c)?m(c):(l=!0,t.consume(c),o)}function d(c){return c===95?i=!0:(r=i,i=void 0),t.consume(c),o}function m(c){return r||i||!l?s(c):n(c)}}function k2(t,n){let s=0,i=0;return r;function r(o){return o===40?(s++,t.consume(o),r):o===41&&i<s?l(o):o===33||o===34||o===38||o===39||o===41||o===42||o===44||o===46||o===58||o===59||o===60||o===63||o===93||o===95||o===126?t.check(qp,n,l)(o):o===null||Qt(o)||Mi(o)?n(o):(t.consume(o),r)}function l(o){return o===41&&i++,t.consume(o),r}}function w2(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||Qt(d)||Mi(d)?n(d):s(d)}function r(d){return d===null||d===40||d===91||Qt(d)||Mi(d)?n(d):i(d)}function l(d){return qn(d)?o(d):s(d)}function o(d){return d===59?(t.consume(d),i):qn(d)?(t.consume(d),o):s(d)}}function N2(t,n,s){return i;function i(l){return t.consume(l),r}function r(l){return Fn(l)?s(l):n(l)}}function Kp(t){return t===null||t===40||t===42||t===95||t===91||t===93||t===126||Qt(t)}function Gp(t){return!qn(t)}function Jp(t){return!(t===47||Jo(t))}function Jo(t){return t===43||t===45||t===46||t===95||Fn(t)}function Rc(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 S2={tokenize:R2,partial:!0};function C2(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:P2,continuation:{tokenize:I2},exit:_2}},text:{91:{name:"gfmFootnoteCall",tokenize:A2},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:E2,resolveTo:M2}}}}function E2(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=Ts(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 M2(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 A2(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||Qt(h))return s(h);if(h===93){t.exit("chunkString");const g=t.exit("gfmFootnoteCallString");return r.includes(Ts(i.sliceSerialize(g)))?(t.enter("gfmFootnoteCallLabelMarker"),t.consume(h),t.exit("gfmFootnoteCallLabelMarker"),t.exit("gfmFootnoteCall"),n):s(h)}return Qt(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 P2(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||Qt(f))return s(f);if(f===93){t.exit("chunkString");const b=t.exit("gfmFootnoteDefinitionLabelString");return l=Ts(i.sliceSerialize(b)),t.enter("gfmFootnoteDefinitionLabelMarker"),t.consume(f),t.exit("gfmFootnoteDefinitionLabelMarker"),t.exit("gfmFootnoteDefinitionLabel"),g}return Qt(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),Bt(t,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function I2(t,n,s){return t.check(ar,n,t.attempt(S2,n,s))}function _2(t){t.exit("gfmFootnoteDefinition")}function R2(t,n,s){const i=this;return Bt(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 T2(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,hl(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=ta(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"),v=ta(f);return x._open=!v||v===2&&!!b,x._close=!b||b===2&&!!v,d(f)}}}class $2{constructor(){this.map=[]}add(n,s,i){F2(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 F2(t,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<t.map.length;){if(t.map[r][0]===n){t.map[r][1]+=s,t.map[r][2].push(...i);return}r+=1}t.map.push([n,s,i])}}function D2(t,n){let s=!1;const i=[];for(;n<t.length;){const r=t[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(t[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(t[n-1][1].type==="tableDelimiterMarker"){const l=i.length-1;i[l]=i[l]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function L2(){return{flow:{null:{name:"table",tokenize:z2,resolveAll:O2}}}}function z2(t,n,s){const i=this;let r=0,l=0,o;return d;function d(E){let T=i.events.length-1;for(;T>-1;){const $=i.events[T][1].type;if($==="lineEnding"||$==="linePrefix")T--;else break}const D=T>-1?i.events[T][1].type:null,Z=D==="tableHead"||D==="tableRow"?w:m;return Z===w&&i.parser.lazy[i.now().line]?s(E):Z(E)}function m(E){return t.enter("tableHead"),t.enter("tableRow"),c(E)}function c(E){return E===124||(o=!0,l+=1),u(E)}function u(E){return E===null?s(E):Ct(E)?l>1?(l=0,i.interrupt=!0,t.exit("tableRow"),t.enter("lineEnding"),t.consume(E),t.exit("lineEnding"),p):s(E):Dt(E)?Bt(t,u,"whitespace")(E):(l+=1,o&&(o=!1,r+=1),E===124?(t.enter("tableCellDivider"),t.consume(E),t.exit("tableCellDivider"),o=!0,u):(t.enter("data"),h(E)))}function h(E){return E===null||E===124||Qt(E)?(t.exit("data"),u(E)):(t.consume(E),E===92?g:h)}function g(E){return E===92||E===124?(t.consume(E),h):h(E)}function p(E){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(E):(t.enter("tableDelimiterRow"),o=!1,Dt(E)?Bt(t,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):f(E))}function f(E){return E===45||E===58?x(E):E===124?(o=!0,t.enter("tableCellDivider"),t.consume(E),t.exit("tableCellDivider"),b):P(E)}function b(E){return Dt(E)?Bt(t,x,"whitespace")(E):x(E)}function x(E){return E===58?(l+=1,o=!0,t.enter("tableDelimiterMarker"),t.consume(E),t.exit("tableDelimiterMarker"),v):E===45?(l+=1,v(E)):E===null||Ct(E)?j(E):P(E)}function v(E){return E===45?(t.enter("tableDelimiterFiller"),y(E)):P(E)}function y(E){return E===45?(t.consume(E),y):E===58?(o=!0,t.exit("tableDelimiterFiller"),t.enter("tableDelimiterMarker"),t.consume(E),t.exit("tableDelimiterMarker"),M):(t.exit("tableDelimiterFiller"),M(E))}function M(E){return Dt(E)?Bt(t,j,"whitespace")(E):j(E)}function j(E){return E===124?f(E):E===null||Ct(E)?!o||r!==l?P(E):(t.exit("tableDelimiterRow"),t.exit("tableHead"),n(E)):P(E)}function P(E){return s(E)}function w(E){return t.enter("tableRow"),S(E)}function S(E){return E===124?(t.enter("tableCellDivider"),t.consume(E),t.exit("tableCellDivider"),S):E===null||Ct(E)?(t.exit("tableRow"),n(E)):Dt(E)?Bt(t,S,"whitespace")(E):(t.enter("data"),k(E))}function k(E){return E===null||E===124||Qt(E)?(t.exit("data"),S(E)):(t.consume(E),E===92?_:k)}function _(E){return E===92||E===124?(t.consume(E),k):k(E)}}function O2(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 $2;for(;++s<t.length;){const p=t[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(d=!1,m!==0&&(Vu(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=Sr(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=Sr(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=Sr(g,n,l,r,s,h)):o[1]!==0&&(h=Sr(g,n,o,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(o[3]=s)}for(m!==0&&Vu(g,n,m,c,u),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=D2(n.events,s))}return t}function Sr(t,n,s,i,r,l){const o=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",d="tableContent";s[0]!==0&&(l.end=Object.assign({},Ui(n.events,s[0])),t.add(s[0],0,[["exit",l,n]]));const m=Ui(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=Ui(n.events,s[2]),u=Ui(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({},Ui(n.events,r)),t.add(r,0,[["exit",l,n]]),l=void 0),l}function Vu(t,n,s,i,r){const l=[],o=Ui(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 Ui(t,n){const s=t[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const B2={name:"tasklistCheck",tokenize:H2};function U2(){return{text:{91:B2}}}function H2(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 Qt(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 Ct(m)?n(m):Dt(m)?t.check({tokenize:q2},n,s)(m):s(m)}}function q2(t,n,s){return Bt(t,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function V2(t){return rp([g2(),C2(),T2(t),L2(),U2()])}const W2={};function ui(t){const n=this,s=t||W2,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),l=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),o=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(V2(s)),l.push(m2()),o.push(h2(s))}const Wu=500,Ku=100;function so(t){return t.length>Wu?t.slice(-Wu):t}function Yp(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),v=a.useRef(s),y=a.useRef(n),M=a.useRef(0);(x.current!==t||v.current!==s||y.current!==n)&&(x.current=t,v.current=s,y.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 _=t,E=s;async function T(){if(!_)return;o(!0),g(!1);try{const Z=await ed(_,E,{limit:Ku});if(f.current||b.current!==S||M.current!==k)return;r(so(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 D=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=Gs(`/api/tasks/${_}/logs/stream${D}`,{events:{"agent:log":Z=>{if(!(f.current||b.current!==S))try{const $=JSON.parse(Z.data);r(R=>so([...R,$])),u(R=>R!==null?R+1:null)}catch{}}}})}return T(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[t,n,s]);const P=a.useCallback(async()=>{if(!t||h)return;const S=b.current,k=i.length,_=t;g(!0);try{const E=await ed(_,s,{limit:Ku,offset:k});if(f.current||b.current!==S)return;r(T=>{const D=[...E.entries,...T];return so(D)}),m(E.hasMore),u(E.total)}catch{}finally{g(!1)}},[t,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:l,clear:w,loadMore:P,hasMore:d,total:c,loadingMore:h}}function K2(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 Gu={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})},G2=50;function Qp(t){return[t.taskId,t.timestamp,t.agent??"",t.type,t.text,t.detail??""].join("|")}function J2(t){const n=new Map;return t.map(s=>{const i=Qp(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function Y2({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),v=a.useMemo(()=>J2(t),[t]);a.useLayoutEffect(()=>{const k=c.current;if(!k)return;const _=t.length,E=u.current,T=h.current,D=v[v.length-1]??null,Z=g.current!==D;if(_>E){const $=k.scrollTop<=G2;if(Z)if($)k.scrollTop=0;else{const R=k.scrollHeight-T;R>0&&(k.scrollTop+=R)}}u.current=_,h.current=k.scrollHeight,g.current=D},[t,v]);const y=a.useCallback(k=>{k.key==="Escape"&&b&&x(!1)},[b]);if(a.useEffect(()=>{if(b)return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[b,y]),n&&t.length===0)return e.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:e.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})});if(t.length===0)return e.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:e.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})});const M=[...t].reverse(),j=[...v].reverse(),P=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:"}),P?e.jsxs("span",{className:"agent-log-model-value",children:[e.jsx(ns,{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(ns,{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(ns,{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(ei,{size:14}):e.jsx(li,{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,_)=>{const E=j[_]??`${Qp(k)}|fallback`,T=M[_-1],D=k.type==="tool"||k.type==="tool_result"||k.type==="tool_error",Z=k.agent?D||_===0||T&&(T.agent!==k.agent||T.type!==k.type):!1,$=Z?e.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:K2(k.timestamp)}):null,R=Z?e.jsxs("span",{className:"agent-log-badge-row",children:[e.jsxs("span",{className:"agent-log-agent-badge",children:["[",k.agent,"]"]}),$]}):null;return k.type==="tool"?e.jsxs("div",{className:"agent-log-tool",children:[R,"⚡ ",k.text,k.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",k.detail]})]},E):k.type==="thinking"?e.jsxs("div",{className:"agent-log-thinking",children:[R,p?e.jsx("div",{className:"markdown-body",children:e.jsx(di,{remarkPlugins:[ui],components:Gu,children:k.text})}):k.text]},E):k.type==="tool_result"?e.jsxs("div",{className:"agent-log-tool-result",children:[R,"✓ ",k.text,k.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",k.detail]})]},E):k.type==="tool_error"?e.jsxs("div",{className:"agent-log-tool-error",children:[R,"✗ ",k.text,k.detail&&e.jsxs("span",{className:"agent-log-tool-detail",children:["— ",k.detail]})]},E):e.jsxs("div",{className:"agent-log-text",children:[R,p?e.jsx("div",{className:"markdown-body",children:e.jsx(di,{remarkPlugins:[ui],components:Gu,children:k.text})}):k.text]},E)}),l&&o&&e.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:e.jsx("button",{className:"agent-log-mode-toggle",onClick:o,disabled:d,"data-testid":"agent-log-load-more-button",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function na(t){return t??void 0}function Cr(t){return{provider:na(t.modelProvider),modelId:na(t.modelId)}}function Er(t){return{provider:na(t.validatorModelProvider),modelId:na(t.validatorModelId)}}function Mr(t){return{provider:na(t.planningModelProvider),modelId:na(t.planningModelId)}}function Q2(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function X2(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 Z2(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 io(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 ao(t){return t.provider&&t.modelId?`${t.provider}/${t.modelId}`:""}function ro(t,n){return t.provider===n.provider&&t.modelId===n.modelId}function eM(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 tM({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(()=>Cr(t)),[x,v]=a.useState(()=>Cr(t)),[y,M]=a.useState(()=>Er(t)),[j,P]=a.useState(()=>Er(t)),[w,S]=a.useState(()=>Mr(t)),[k,_]=a.useState(()=>Mr(t)),[E,T]=a.useState(()=>t.thinkingLevel??null),[D,Z]=a.useState(()=>t.thinkingLevel??null),[$,R]=a.useState(null),N=a.useRef(t.id);a.useEffect(()=>{h(!0),p(null),Vn().then(we=>{l(we.models),d(we.favoriteProviders),c(we.favoriteModels)}).catch(we=>{p(we.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const W=a.useCallback(async we=>{const Ee=o,Pe=Ee.includes(we)?Ee.filter(ze=>ze!==we):[we,...Ee];d(Pe);try{await Jt({favoriteProviders:Pe,favoriteModels:m})}catch{d(Ee),n("Failed to update favorites","error")}},[o,m,n]),Y=a.useCallback(async we=>{const Ee=m,Pe=Ee.includes(we)?Ee.filter(ze=>ze!==we):[we,...Ee];c(Pe);try{await Jt({favoriteProviders:o,favoriteModels:Pe})}catch{c(Ee),n("Failed to update model favorites","error")}},[m,o,n]);a.useEffect(()=>{N.current=t.id;const we=Cr(t),Ee=Er(t),ie=Mr(t);b(we),v(we),M(Ee),P(Ee),S(ie),_(ie);const Pe=t.thinkingLevel??null;T(Pe),Z(Pe),R(null)},[t.id,t.modelProvider,t.modelId,t.validatorModelProvider,t.validatorModelId,t.planningModelProvider,t.planningModelId,t.thinkingLevel]);const H=a.useMemo(()=>ao(f),[f]),A=a.useMemo(()=>ao(y),[y]),z=a.useMemo(()=>ao(w),[w]),J=a.useMemo(()=>Q2(t,i),[t,i]),C=a.useMemo(()=>X2(t,i),[t,i]),q=a.useMemo(()=>Z2(t,i),[t,i]),oe=$!==null,O=a.useCallback(async(we,Ee)=>{const ie=t.id,Pe=x,ze=j,$e=k;R(we);try{const He=s?we==="executor"?{modelProvider:Ee.provider??null,modelId:Ee.modelId??null}:we==="validator"?{validatorModelProvider:Ee.provider??null,validatorModelId:Ee.modelId??null}:{planningModelProvider:Ee.provider??null,planningModelId:Ee.modelId??null}:{modelProvider:(we==="executor"?Ee:x).provider??null,modelId:(we==="executor"?Ee:x).modelId??null,validatorModelProvider:(we==="validator"?Ee:j).provider??null,validatorModelId:(we==="validator"?Ee:j).modelId??null,planningModelProvider:(we==="planning"?Ee:k).provider??null,planningModelId:(we==="planning"?Ee:k).modelId??null},Me=await Zs(ie,He);if(N.current!==ie)return;const Te=Cr(Me),Ve=Er(Me),_e=Mr(Me);v(Te),b(Te),P(Ve),M(Ve),_(_e),S(_e),s?.(Me),n(eM(we,{executor:Te,validator:Ve,planning:_e}[we]),"success")}catch(He){if(N.current!==ie)return;we==="executor"?b(Pe):we==="validator"?M(ze):S($e),n(fe(He)||"Failed to save model settings","error")}finally{N.current===ie&&R(null)}},[t.id,x,j,k,n,s]),V=a.useCallback(we=>{const Ee=io(we);b(Ee),!ro(Ee,x)&&O("executor",Ee)},[x,O]),F=a.useCallback(we=>{const Ee=io(we);M(Ee),!ro(Ee,j)&&O("validator",Ee)},[j,O]),ue=a.useCallback(we=>{const Ee=io(we);S(Ee),!ro(Ee,k)&&O("planning",Ee)},[k,O]),ce=a.useCallback(async we=>{const Ee=t.id,ie=D,Pe=we===""?null:we;T(Pe),R("thinking");try{const ze=await Zs(Ee,{thinkingLevel:Pe});if(N.current!==Ee)return;const $e=ze.thinkingLevel??null;Z($e),T($e),s?.(ze);const He=i?.defaultThinkingLevel??"off";n($e===null?`Thinking level set to default (${He})`:`Thinking level set to ${$e}`,"success")}catch(ze){if(N.current!==Ee)return;T(ie),n(fe(ze)||"Failed to save thinking level","error")}finally{N.current===Ee&&R(null)}},[t.id,D,i,n,s]),K=!x.provider&&!x.modelId,de=!j.provider&&!j.modelId,Fe=!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),Vn().then(we=>{l(we.models),d(we.favoriteProviders),c(we.favoriteModels)}).catch(we=>p(we.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",J.provider&&J.modelId?` (${J.provider}/${J.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[x.provider&&e.jsx(ns,{provider:x.provider,size:"sm"}),x.provider,"/",x.modelId]})}),e.jsx(Yt,{id:"executorModel",label:"Executor Model",value:H,onChange:V,models:r,disabled:oe,placeholder:"Select executor model…",favoriteProviders:o,onToggleFavorite:W,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",C.provider&&C.modelId?` (${C.provider}/${C.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&e.jsx(ns,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),e.jsx(Yt,{id:"validatorModel",label:"Validator Model",value:A,onChange:F,models:r,disabled:oe,placeholder:"Select validator model…",favoriteProviders:o,onToggleFavorite:W,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:Fe?e.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",q.provider&&q.modelId?` (${q.provider}/${q.modelId})`:""]}):e.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&e.jsx(ns,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),e.jsx(Yt,{id:"planningModel",label:"Planning Model",value:z,onChange:ue,models:r,disabled:oe,placeholder:"Select planning model…",favoriteProviders:o,onToggleFavorite:W,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:D===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:D})}),e.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:we=>ce(we.target.value),disabled:oe,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&&Fe&&D===null?"Using global default models.":"Model settings are up to date."})]})]})}const nM={open:e.jsx(sl,{size:16}),closed:e.jsx(Ja,{size:16}),merged:e.jsx(th,{size:16})};function sM({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),[v,y]=a.useState(!1),[M,j]=a.useState(null),P=a.useCallback(async()=>{if(h.trim()){x(!0);try{const _=await fv(t,{title:h.trim(),body:p.trim()||void 0},n);o(_),u(!1),g(""),f(""),m(`Created PR #${_.number}`,"success")}catch(_){m(fe(_)||"Failed to create PR","error")}finally{x(!1)}}},[t,h,p,n,o,m]),w=a.useCallback(async()=>{if(s){y(!0);try{const _=await gv(t,n);j(_),d(_.prInfo),m("PR status refreshed","success")}catch(_){m(fe(_)||"Failed to refresh PR","error")}finally{y(!1)}}},[t,s,n,d,m]);if(!s)return i==="creating-pr"?e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(es,{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(es,{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(es,{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:_=>g(_.target.value),disabled:b,className:"pr-input"}),e.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:_=>f(_.target.value),disabled:b,className:"pr-textarea",rows:3}),e.jsxs("div",{className:"pr-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>u(!1),disabled:b,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:P,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(es,{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=nM[s.status]??e.jsx(sl,{size:16}),k=M?.blockingReasons??[];return e.jsxs("div",{className:"pr-section",children:[e.jsxs("h4",{children:[e.jsx(es,{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:v,title:"Refresh PR status",children:e.jsx(vn,{size:14,style:{verticalAlign:"middle",opacity:v?.5:1}})})]}),e.jsx("div",{className:"pr-title",children:s.title}),e.jsxs("div",{className:"pr-meta",children:[e.jsx("span",{children:s.headBranch}),e.jsx("span",{className:"pr-meta-arrow",children:"→"}),e.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:k.length>0?`Waiting for: ${k.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&e.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),e.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&e.jsxs("span",{className:"pr-comments",children:[e.jsx(oi,{size:14}),s.commentCount]}),e.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[e.jsx(yg,{size:14}),"View on GitHub"]})]})]})]})}const Ju=2e3;function iM(t){const n=t.updatedAt||t.createdAt,s=new Date(n).toLocaleString();return t.updatedAt?`${s} (edited)`:s}function aM(t){return t==="agent"||t==="system"}function rM({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>Ju;async function v(){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(fe(k)||"Failed to add comment","error")}finally{g(!1)}}}async function y(S){const k=c.trim();if(k){g(!0);try{const _=await Gx(t.id,S,k,r);m(null),u(""),n?.(_),s("Comment updated","success")}catch(_){s(fe(_)||"Failed to update comment","error")}finally{g(!1)}}}async function M(S){f(S);try{const k=await Jx(t.id,S,r);n?.(k),s("Comment deleted","success")}catch(k){s(fe(k)||"Failed to delete comment","error")}finally{f(null)}}function j(S){S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),v())}return e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Comments"}),b.length===0?e.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):e.jsx("div",{className:"detail-activity-list",children:b.map(S=>{const k=S.author===i,_=d===S.id,E=aM(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:[E?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:iM(S)})]}),k&&!_?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]}),_?e.jsxs("div",{className:"comments-edit-form",children:[e.jsx("textarea",{value:c,onChange:T=>u(T.target.value),rows:3,className:"spec-editor-feedback"}),e.jsxs("div",{className:"comments-edit-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{m(null),u("")},disabled:h,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(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:j,rows:3,placeholder:"Add a comment",className:"spec-editor-feedback"}),e.jsxs("div",{className:"comments-footer-row",children:[e.jsxs("span",{className:`comments-char-count${x?" comments-char-count--over":""}`,children:[l.length," / ",Ju]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void v(),disabled:h||!l.trim()||x,children:h?"Posting…":"Add Comment"})]})]})]})}function lM(t){return t?t.slice(0,7):"Unknown"}function oM({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:lM(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 Xp(t){return t.split(`
626
+ `).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?e.jsx("span",{className:r,children:`${s}
627
+ `},i):e.jsx(Wm.Fragment,{children:`${s}
628
+ `},i)})}function Yu(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 cM(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function dM({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=v=>{if(v.key==="Escape"){o();return}v.key==="ArrowUp"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),g()),v.key==="ArrowDown"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),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(Rs,{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(sc,{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(on,{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(Br,{size:14})}),d&&e.jsxs("button",{className:"btn btn-sm",onClick:d,children:[e.jsx(vn,{size:14}),"Refresh"]}),e.jsx("button",{className:"modal-close",onClick:o,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"changes-diff-body",children:[e.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Oa,{size:14}),e.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&e.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&e.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),e.jsx("div",{className:"changes-diff-file-list",children:s.map((x,v)=>e.jsxs("button",{className:`changes-diff-file-item ${m===v?"selected":""}`,onClick:()=>c(v),title:x.path,children:[e.jsx("span",{className:`changes-file-status changes-file-status--${x.status}`,children:cM(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:Xp(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(Rs,{size:48,opacity:.3}),e.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Qu(t){switch(t){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function uM({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,v]=a.useState(null),[y,M]=a.useState(!0),[j,P]=a.useState(!1),w=i==="done",S=w&&!!r?.commitSha,k=i==="in-progress"||i==="in-review"||S,_=a.useCallback(async()=>{if(!k){h(!1);return}try{h(!0),p(null);const $=await wh(t,void 0,s),R=$.files.map(N=>({path:N.path,status:N.status,additions:N.additions,deletions:N.deletions,patch:N.patch}));d(R),c($.stats),R.length>0&&(b(new Set([R[0].path])),v(0))}catch($){p(fe($)||"Failed to load diff")}finally{h(!1)}},[t,s,k]);a.useEffect(()=>{_()},[_]);const E=$=>{b(R=>{const N=new Set(R);if(N.has($))N.delete($);else{N.add($);const W=o.findIndex(Y=>Y.path===$);W!==-1&&v(W)}return N})},T=$=>{if($<0||$>=o.length)return;const R=o[$].path;b(new Set([R])),v($)},D=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(ss,{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(Rs,{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 $=r?.filesChanged,R=r?.insertions,N=r?.deletions,W=$!=null||R!=null||N!=null;return e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Rs,{size:24}),e.jsx("p",{children:"Detailed file changes unavailable."}),e.jsx("span",{className:"task-changes-state-hint",children:W?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${R??0} additions, -${N??0} deletions.`:"No merge commit was recorded for this task."})]})})}return o.length===0?w&&l&&l.length>0?e.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&e.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&e.jsxs("div",{className:"commit-diff-sha",children:[e.jsx(Oa,{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(Rs,{size:24}),e.jsxs("p",{children:[l.length," file",l.length===1?"":"s"," modified during execution."]}),e.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),e.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>e.jsx("div",{className:"changes-file-item",children:e.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[e.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Qu("unknown")}),e.jsx("span",{className:"changes-file-path",title:$,children:Yu($)})]})},$))})]}):e.jsx("div",{className:"detail-section",children:e.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[e.jsx(Rs,{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(Oa,{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(Rs,{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:()=>D&&T(x-1),disabled:!D,title:"Previous file","aria-label":"Previous file",children:e.jsx(sc,{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&&T(x+1),disabled:!Z,title:"Next file","aria-label":"Next file",children:e.jsx(on,{size:14})})]}),e.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>M($=>!$),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:e.jsx(Br,{size:14})})]}),e.jsxs("div",{className:"changes-header-actions-secondary",children:[e.jsx("button",{className:"btn btn-sm",onClick:_,disabled:u,children:"Refresh"}),e.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>P(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:e.jsx(li,{size:14})})]})]})]}),e.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>{const R=f.has($.path);return e.jsxs("div",{className:`changes-file-item ${R?"expanded":""}`,children:[e.jsxs("button",{className:"changes-file-header",onClick:()=>E($.path),children:[e.jsx("span",{className:"changes-file-toggle",children:R?e.jsx(Ot,{size:14}):e.jsx(on,{size:14})}),e.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:Qu($.status)}),e.jsx("span",{className:"changes-file-path",title:$.path,children:Yu($.path)}),e.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),R&&$.patch&&e.jsx("div",{className:"changes-file-content",children:e.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:e.jsx("code",{children:Xp($.patch)})})})]},$.path)})}),e.jsx(dM,{isOpen:j,taskId:t,files:o,stats:m,mergeDetails:r,column:i,onClose:()=>P(!1),onRefresh:_})]})}function Yo(t){return{executorValue:t?.executorProvider&&t?.executorModelId?`${t.executorProvider}/${t.executorModelId}`:"",validatorValue:t?.validatorProvider&&t?.validatorModelId?`${t.validatorProvider}/${t.validatorModelId}`:""}}function mM(t){return t.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function hM(t,n){const s=mM(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 Xu=["image/png","image/jpeg","image/gif","image/webp"];function pM(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 Zp({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:v,onPresetModeChange:y,selectedPresetId:M,onSelectedPresetIdChange:j,selectedWorkflowSteps:P,onWorkflowStepsChange:w,onDefaultOnApplied:S,pendingImages:k,onImagesChange:_,tasks:E,projectId:T,disabled:D=!1,addToast:Z,isActive:$=!0,onAutoSaveDescription:R,onPlanningMode:N,onSubtaskBreakdown:W,onClose:Y,renderBelowPrimary:H,hideDependencies:A,autoExpandMoreOptionsOnSelection:z=!0,reviewLevel:J,onReviewLevelChange:C}){const q=(A?!1:l.length>0)||k.length>0||P.length>0||v!=="default"||(d??cs)!==cs||c!==""||h!==""||(p||"")!==""||(b||"")!==""||J!==void 0,[oe,O]=a.useState(!1),[V,F]=a.useState(z?q:!1),[ue,ce]=a.useState(""),[K,de]=a.useState([]),[Fe,we]=a.useState([]),[Ee,ie]=a.useState([]),[Pe,ze]=a.useState(!1),[$e,He]=a.useState(null),[Me,Te]=a.useState([]),[Ve,_e]=a.useState("idle"),[et,le]=a.useState(!1),[X,ke]=a.useState(!1),[se,Le]=a.useState(!1),ve=a.useRef(null),Ye=a.useRef(null),mt=a.useRef(null),ht=a.useRef(null),me=a.useRef(null),te=a.useRef(null),je=a.useRef(null),Ae=a.useRef(!1),Qe=a.useRef(q),be=a.useRef(n.trim()),st=a.useRef(n.trim());a.useEffect(()=>{$&&(ze(!0),Vn().then(ee=>{de(ee.models),we(ee.favoriteProviders),ie(ee.favoriteModels)}).catch(()=>{}).finally(()=>ze(!1)),Xi(T).then(ee=>He(ee)).catch(()=>He(null)),ol(T).then(ee=>Te(ee.filter(Ie=>Ie.enabled))).catch(()=>Te([])))},[$,T]);const Se=$e?.modelPresets||[],Je=Se.find(ee=>ee.id===M),it=(A?!1:l.length>0)||k.length>0||P.length>0||v!=="default"||(d??cs)!==cs||c!==""||h!==""||(p||"")!==""||(b||"")!==""||J!==void 0;a.useEffect(()=>{if(t!=="create"||!$||!$e?.autoSelectModelPreset)return;const ee=($e.defaultPresetBySize,void 0);if(ee){const Ie=Yo(ee);j(ee.id),y("preset"),u(Ie.executorValue),g(Ie.validatorValue)}},[$,$e,Se,t]);const ye=a.useRef(!1);a.useEffect(()=>{if(t!=="create"||!$||ye.current||Me.length===0)return;const ee=Me.filter(xt=>xt.defaultOn);if(ee.length===0)return;ye.current=!0;const Ie=ee.map(xt=>xt.id);w(Ie),S?.(Ie)},[t,$,Me]),a.useEffect(()=>{$||(ye.current=!1)},[$]),a.useEffect(()=>{if(!z){Qe.current=it;return}it&&!Qe.current&&F(!0),Qe.current=it},[it,z]),a.useEffect(()=>{V||(O(!1),ce(""))},[V]),a.useEffect(()=>{t!=="edit"||!$||ht.current&&(ht.current.focus(),ht.current.select())},[t,$]),a.useEffect(()=>{if(!oe)return;const ee=Ie=>{Ye.current&&!Ye.current.contains(Ie.target)&&O(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[oe]),a.useEffect(()=>{(t!=="edit"||D)&&Le(!1)},[t,D]),a.useEffect(()=>{if(t!=="edit"){_e("idle");return}const ee=n.trim();be.current=ee,st.current=ee,_e("idle")},[t]),a.useEffect(()=>{if(t!=="edit"||!R||!$)return;const ee=n.trim(),Ie=be.current;if(ee===Ie||ee===st.current){te.current&&(clearTimeout(te.current),te.current=null),Ae.current||_e("idle");return}return te.current&&clearTimeout(te.current),te.current=setTimeout(async()=>{if(!Ae.current){Ae.current=!0,_e("saving");try{await R(ee),st.current=ee,_e("saved"),je.current&&clearTimeout(je.current),je.current=setTimeout(()=>{_e("idle"),je.current=null},2e3)}catch{_e("idle")}finally{Ae.current=!1,te.current=null}}},1500),()=>{te.current&&(clearTimeout(te.current),te.current=null)}},[t,n,R,$]),a.useEffect(()=>()=>{te.current&&clearTimeout(te.current),je.current&&clearTimeout(je.current)},[]),a.useEffect(()=>{if(!et)return;const ee=Ie=>{ve.current&&!ve.current.contains(Ie.target)&&le(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[et]);const Ge=a.useCallback(ee=>{const Ie=ee.clipboardData?.items;if(Ie)for(let xt=0;xt<Ie.length;xt++){const he=Ie[xt];if(he.type.startsWith("image/")){const Be=he.getAsFile();if(Be&&Xu.includes(Be.type)){ee.preventDefault(),_([...k,{file:Be,previewUrl:URL.createObjectURL(Be)}]);return}}}},[k,_]),Ne=a.useCallback(ee=>{ee.preventDefault();const Ie=ee.dataTransfer.files;for(let xt=0;xt<Ie.length;xt++){const he=Ie[xt];if(Xu.includes(he.type)){_([...k,{file:he,previewUrl:URL.createObjectURL(he)}]);return}}},[k,_]),at=a.useCallback(ee=>{const Ie=k[ee];Ie&&URL.revokeObjectURL(Ie.previewUrl),_(k.filter((xt,he)=>he!==ee))},[k,_]),dt=a.useCallback(ee=>{o(l.includes(ee)?l.filter(Ie=>Ie!==ee):[...l,ee])},[l,o]),vt=(ee,Ie)=>ee.length>Ie?ee.slice(0,Ie)+"…":ee,It=a.useCallback(ee=>{s(ee.target.value);const Ie=ee.target;Ie.style.height="auto",Ie.style.height=Ie.scrollHeight+"px"},[s]),_t=a.useCallback(()=>{Le(ee=>!ee)},[]),Mt=a.useCallback(ee=>{!se||ee.key!=="Escape"||(ee.preventDefault(),ee.stopPropagation(),Le(!1))},[se]),zt=a.useCallback(async ee=>{const Ie=n.trim();if(!(!Ie||X)){ke(!0);try{const xt=await xh(Ie,ee,T);s(xt),le(!1),Z("Description refined with AI","success"),mt.current&&(mt.current.style.height="auto",mt.current.style.height=mt.current.scrollHeight+"px")}catch(xt){const he=vh(xt);Z(he,"error")}finally{ke(!1)}}},[n,X,Z,s,T]),Nt=a.useCallback(async ee=>{const Ie=Fe,he=Ie.includes(ee)?Ie.filter(Be=>Be!==ee):[ee,...Ie];we(he);try{await Jt({favoriteProviders:he,favoriteModels:Ee})}catch{we(Ie)}},[Fe,Ee]),Pt=a.useCallback(async ee=>{const Ie=Ee,he=Ie.includes(ee)?Ie.filter(Be=>Be!==ee):[ee,...Ie];ie(he);try{await Jt({favoriteProviders:Fe,favoriteModels:he})}catch{ie(Ie)}},[Ee,Fe]),tt=a.useCallback(ee=>{if(ee<=0)return;const Ie=[...P];[Ie[ee-1],Ie[ee]]=[Ie[ee],Ie[ee-1]],w(Ie)},[P,w]),bt=a.useCallback(ee=>{if(ee>=P.length-1)return;const Ie=[...P];[Ie[ee],Ie[ee+1]]=[Ie[ee+1],Ie[ee]],w(Ie)},[P,w]),Ue=a.useCallback(ee=>{w(P.filter(Ie=>Ie!==ee))},[P,w]),ot=new Map;for(const ee of Me)ot.set(ee.id,{name:ee.name,description:ee.description});const ge=E.filter(ee=>!l.includes(ee.id)).sort((ee,Ie)=>{const xt=Ie.createdAt.localeCompare(ee.createdAt);if(xt!==0)return xt;const he=parseInt(ee.id.slice(ee.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-he}),Oe=ue?ge.filter(ee=>ee.id.toLowerCase().includes(ue.toLowerCase())||ee.title&&ee.title.toLowerCase().includes(ue.toLowerCase())||ee.description&&ee.description.toLowerCase().includes(ue.toLowerCase())):ge;return e.jsxs("div",{className:"task-form",onDrop:Ne,onDragOver:ee=>ee.preventDefault(),onPaste:Ge,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:ht,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:ee=>r(ee.target.value),disabled:D})]}),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${Ve==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Ve==="saving"?"Saving...":Ve==="saved"?"Saved":""})]}),e.jsxs("div",{className:`description-with-refine${se?" description--fullscreen":""}`,ref:ve,onKeyDown:Mt,children:[se&&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:_t,"aria-label":"Collapse description",title:"Collapse description",children:e.jsx(ei,{size:14})})]}),e.jsx("textarea",{ref:mt,autoFocus:t==="create",id:"task-form-description",value:n,onChange:It,placeholder:"What needs to be done?",rows:t==="edit"?8:5,disabled:D||X}),(()=>{const ee=!!n.trim()&&!D;return e.jsxs(e.Fragment,{children:[!se&&e.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${ee?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:_t,"aria-label":"Expand description",title:"Expand description",children:e.jsx(li,{size:14})}),ee&&e.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${X?"refine-button--loading":""}`,onClick:()=>le(Ie=>!Ie),disabled:X,"data-testid":"refine-button",title:"Refine description with AI",children:[e.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),X?"Refining...":"Refine"]})]})})(),et&&e.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:ee=>ee.preventDefault(),children:[e.jsxs("div",{className:"refine-menu-item",onClick:()=>zt("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:()=>zt("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:()=>zt("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:()=>zt("simplify"),"data-testid":"refine-simplify",children:[e.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),e.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),t==="create"&&(N||W)&&e.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[N&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ee=n.trim();if(!ee){Z("Enter a description first","error");return}Y?.(),N(ee)},disabled:D||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),W&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const ee=n.trim();if(!ee){Z("Enter a description first","error");return}Y?.(),W(ee)},disabled:D||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),H,e.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>F(ee=>!ee),"aria-expanded":V,"aria-controls":"task-form-more-options",disabled:D,"data-testid":"task-form-more-options-toggle",children:[e.jsx("span",{children:"More options"}),V?e.jsx(qs,{size:14}):e.jsx(Ot,{size:14})]}),e.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${V?"":" collapsed"}`,"aria-hidden":!V,hidden:!V,"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((ee,Ie)=>e.jsxs("div",{className:"inline-create-preview",children:[e.jsx("img",{src:ee.previewUrl,alt:ee.file.name}),e.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>at(Ie),disabled:D,title:"Remove image",children:"×"})]},ee.previewUrl))}),e.jsx("input",{ref:me,type:"file",accept:"image/*",onChange:ee=>{const Ie=ee.target.files?.[0];Ie&&(_([...k,{file:Ie,previewUrl:URL.createObjectURL(Ie)}]),ee.target.value="")},style:{display:"none"}}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>me.current?.click(),disabled:D,children:"Attach Screenshot"}),e.jsx("small",{children:"You can also paste images or drag & drop"})]}),!A&&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:()=>O(ee=>!ee),disabled:D,children:l.length>0?`${l.length} selected`:"Add dependencies"}),oe&&e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ue,onChange:ee=>ce(ee.target.value),onClick:ee=>ee.stopPropagation()}),Oe.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Oe.map(ee=>e.jsxs("div",{className:`dep-dropdown-item${l.includes(ee.id)?" selected":""}`,onClick:()=>dt(ee.id),onMouseDown:Ie=>Ie.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:ee.id}),e.jsx("span",{className:"dep-dropdown-title",children:vt(ee.title||ee.description||ee.id,30)})]},ee.id))]})]}),l.length>0&&e.jsx("div",{className:"selected-deps",children:l.map(ee=>e.jsxs("span",{className:"dep-chip",children:[ee,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>dt(ee),disabled:D,children:"×"})]},ee))})]})}),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:ee=>m(ee.target.value),disabled:D,children:cc.map(ee=>e.jsx("option",{value:ee,children:ee[0].toUpperCase()+ee.slice(1)},ee))})]}),Pe?e.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):K.length===0?e.jsx("small",{children:"No models available. Configure authentication in Settings."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),e.jsxs("select",{id:"model-preset",value:v==="preset"?M:v,onChange:ee=>{const Ie=ee.target.value;if(Ie==="default"){y("default"),j(""),u(""),g("");return}if(Ie==="custom"){y("custom"),j("");return}const xt=Se.find(Be=>Be.id===Ie),he=Yo(xt);y("preset"),j(Ie),u(he.executorValue),g(he.validatorValue)},disabled:D,children:[e.jsx("option",{value:"default",children:"Use default"}),Se.length>0?e.jsx("option",{disabled:!0,children:"──────────"}):null,Se.map(ee=>e.jsx("option",{value:ee.id,children:ee.name},ee.id)),e.jsx("option",{value:"custom",children:"Custom"})]})]}),v==="preset"&&Je?e.jsxs("small",{children:["Using preset: ",Je.name]}):null,v==="preset"?e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>y("custom"),disabled:D,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(Yt,{id:"executor-model",label:"Executor Model",value:c,onChange:ee=>{y("custom"),j(""),u(ee)},models:K,disabled:D||v==="preset",favoriteProviders:Fe,onToggleFavorite:Nt,favoriteModels:Ee,onToggleModelFavorite:Pt})]}),e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Validator"}),e.jsx(Yt,{id:"validator-model",label:"Validator Model",value:h,onChange:ee=>{y("custom"),j(""),g(ee)},models:K,disabled:D||v==="preset",favoriteProviders:Fe,onToggleFavorite:Nt,favoriteModels:Ee,onToggleModelFavorite:Pt})]}),f&&e.jsxs("div",{className:"model-select-row",children:[e.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),e.jsx(Yt,{id:"planning-model",label:"Planning Model",value:p||"",onChange:ee=>{y("custom"),j(""),f(ee)},models:K,disabled:D||v==="preset",favoriteProviders:Fe,onToggleFavorite:Nt,favoriteModels:Ee,onToggleModelFavorite:Pt})]}),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:ee=>x(ee.target.value),disabled:D||v==="preset",children:[e.jsxs("option",{value:"",children:["Default (",$e?.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"})]})]}),C&&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:J??"",onChange:ee=>C(ee.target.value===""?0:parseInt(ee.target.value,10)),disabled:D,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:Me.length>0&&Me.map(ee=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${ee.id}`,children:[e.jsx("input",{type:"checkbox",checked:P.includes(ee.id),onChange:Ie=>{w(Ie.target.checked?[...P,ee.id]:P.filter(xt=>xt!==ee.id))},disabled:D}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[ee.name,pM(ee.phase||"pre-merge",ee.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:ee.description})]})]},ee.id))})]}),P.length>1&&e.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[e.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),P.map((ee,Ie)=>{const xt=ot.get(ee);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${ee}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:Ie+1}),e.jsx("span",{className:"workflow-step-order-name",children:xt?.name||ee}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>tt(Ie),disabled:D||Ie===0,"data-testid":`workflow-step-move-up-${ee}`,title:"Move up",children:e.jsx(qs,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>bt(Ie),disabled:D||Ie===P.length-1,"data-testid":`workflow-step-move-down-${ee}`,title:"Move down",children:e.jsx(Ot,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ue(ee),disabled:D,"data-testid":`workflow-step-remove-${ee}`,title:"Remove",children:e.jsx(Lt,{size:14})})]})]},ee)})]})]})]})]})}const Zu={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 fM(t){switch(t){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return t}}function gM(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 bM(t){return t?new Date(t).toLocaleString():null}function xM(t){const n=t.split(`
629
+ `);return n.length<=1?t:`${n.length} lines`}function Ar(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 vM({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 yM({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,v]=a.useState(!1),y=n.some(C=>C.status==="pending"),{entries:M}=Yp(t,!!o&&y,l);a.useEffect(()=>{let C=!1;return ol(l).then(q=>{C||b(q.filter(oe=>oe.enabled))}).catch(()=>{C||b([])}),()=>{C=!0}},[l]);const j=i??[],P=a.useMemo(()=>[...f.map(q=>({id:q.id,name:q.name,description:q.description,phase:q.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(P.map(C=>[C.id,C])),[P]),S=C=>{c(q=>({...q,[C]:!q[C]}))},k=C=>{h(q=>{const oe=q[C]??"markdown";return{...q,[C]:oe==="markdown"?"plain":"markdown"}})},_=C=>{p(C)},E=()=>{p(null)};a.useEffect(()=>{if(!g)return;const C=q=>{q.key==="Escape"&&E()};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[g]);const T=a.useCallback((C,q)=>{if(d){if(q){if(j.includes(C)){d(j);return}d([...j,C]);return}d(j.filter(oe=>oe!==C))}},[d,j]),D=a.useCallback(C=>{if(!d||C<=0)return;const q=[...j];[q[C-1],q[C]]=[q[C],q[C-1]],d(q)},[d,j]),Z=a.useCallback(C=>{if(!d||C>=j.length-1)return;const q=[...j];[q[C],q[C+1]]=[q[C+1],q[C]],d(q)},[d,j]),$=a.useCallback(C=>{d&&d(j.filter(q=>q!==C))},[d,j]),R=n.length>0,N=j.length>0;a.useEffect(()=>{r||v(!1)},[r]);const W=a.useMemo(()=>j.map(C=>{const q=w.get(C);return{id:C,name:q?.name||C,description:q?.description||"Step definition not found.",phase:q?.phase||"pre-merge"}}),[j,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:P.map(C=>e.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":C.id==="browser-verification"?"browser-verification-checkbox":`workflow-step-checkbox-${C.id}`,children:[e.jsx("input",{type:"checkbox",checked:j.includes(C.id),onChange:q=>T(C.id,q.target.checked)}),e.jsxs("div",{children:[e.jsxs("span",{className:"workflow-step-name",children:[C.name,Ar(C.phase,C.id,"workflow-step-phase")]}),e.jsx("div",{className:"workflow-step-description",children:C.description})]})]},C.id))})]}),j.length>1&&e.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[e.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((C,q)=>{const oe=w.get(C);return e.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${C}`,children:[e.jsx("span",{className:"workflow-step-order-number",children:q+1}),e.jsx("span",{className:"workflow-step-order-name",children:oe?.name||C}),e.jsxs("div",{className:"workflow-step-order-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>D(q),disabled:q===0,"data-testid":`workflow-step-move-up-${C}`,title:"Move up",children:e.jsx(qs,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Z(q),disabled:q===j.length-1,"data-testid":`workflow-step-move-down-${C}`,title:"Move down",children:e.jsx(Ot,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(C),"data-testid":`workflow-step-remove-${C}`,title:"Remove",children:e.jsx(Lt,{size:14})})]})]},C)})]})]}),H=()=>{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(!R)return e.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[e.jsx("p",{children:"No workflow steps configured for this task."}),e.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const C=n.filter(F=>F.status==="passed").length,q=n.filter(F=>F.status==="failed").length,oe=n.filter(F=>F.status==="skipped").length,O=n.filter(F=>F.status==="pending").length,V=[`${n.length} step${n.length!==1?"s":""}`];return C>0&&V.push(`${C} passed`),q>0&&V.push(`${q} failed`),oe>0&&V.push(`${oe} skipped`),O>0&&V.push(`${O} 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:V.join(" · ")}),n.map((F,ue)=>{const ce=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,Ar(ce,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:fM(F.status)})]}),e.jsxs("div",{className:"workflow-result-meta",children:[F.startedAt&&e.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",bM(F.startedAt)]}),F.completedAt&&e.jsx("span",{className:"workflow-result-duration",children:gM(F.startedAt,F.completedAt)})]}),F.status==="pending"&&F.startedAt?e.jsx(vM,{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:xM(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:()=>_(F.workflowStepId),"data-testid":`workflow-result-expand-${F.workflowStepId}`,title:"Expand output",children:e.jsx(li,{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(di,{remarkPlugins:[ui],components:Zu,children:F.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:F.output})})]}):null]},`${F.workflowStepId}-${ue}`)})]})},A=r?e.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>v(C=>!C),"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(An,{size:14}),"Done"]}):e.jsxs(e.Fragment,{children:[e.jsx($n,{size:14}),"Edit"]})}):null,z=!s&&!R&&N,J=r&&R;return e.jsxs("div",{className:"workflow-results-tab","data-task-id":t,children:[z?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:[W.length," step",W.length===1?"":"s"]})]}),A]}),e.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:W.map(C=>e.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${C.id}`,children:[e.jsxs("div",{className:"workflow-configured-name",children:[C.name,Ar(C.phase,C.id,"workflow-configured-phase")]}),e.jsx("p",{className:"workflow-configured-description",children:C.description})]},C.id))}),e.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),Y()]}):e.jsxs(e.Fragment,{children:[J&&e.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[e.jsx("h4",{children:"Workflow Steps"}),A]}),H(),Y()]}),g&&(()=>{const C=n.find(O=>O.workflowStepId===g);if(!C)return null;const q=u[C.workflowStepId]??"markdown",oe=C.phase||"pre-merge";return e.jsx("div",{className:"workflow-output-modal-overlay",onClick:O=>{O.target===O.currentTarget&&E()},"data-testid":"workflow-output-modal",children:e.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[e.jsxs("div",{className:"workflow-output-modal-header",children:[e.jsxs("div",{className:"workflow-output-modal-title",children:[e.jsx("span",{className:"workflow-output-modal-name",children:C.workflowStepName}),Ar(oe,C.workflowStepId,"workflow-output-modal-phase")]}),e.jsxs("div",{className:"workflow-output-modal-controls",children:[e.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>k(C.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:q==="markdown"?"Switch to plain text":"Switch to markdown",children:q==="markdown"?"Markdown":"Plain"}),e.jsx("button",{className:"workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:e.jsx(Lt,{size:16})})]})]}),e.jsx("div",{className:"workflow-output-modal-body",children:e.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${q==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:q==="markdown"?e.jsx("div",{className:"markdown-body",children:e.jsx(di,{remarkPlugins:[ui],components:Zu,children:C.output})}):e.jsx("pre",{className:"workflow-result-output-text",children:C.output})})})]})})})()]})}const jM=/^[a-zA-Z0-9_-]{1,64}$/,kM=200;function em(t){return t?new Date(t).toLocaleString():""}function wM(t,n=kM){return t.length<=n?t:t.substring(0,n)+"…"}function NM({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(""),[v,y]=a.useState(null),[M,j]=a.useState([]),[P,w]=a.useState(!1),[S,k]=a.useState(!1),[_,E]=a.useState(""),[T,D]=a.useState(""),[Z,$]=a.useState(!1),[R,N]=a.useState(null),[W,Y]=a.useState(null),[H,A]=a.useState(!1),z=a.useCallback(async()=>{try{const ce=await Yx(t,i);o(ce)}catch(ce){n(fe(ce)||"Failed to load documents","error")}finally{m(!1)}},[t,i,n]);a.useEffect(()=>{z()},[z]);async function J(ce){c===ce.key?(u(null),g(""),f(null),x(""),y(null),j([]),A(!1)):(u(ce.key),g(ce.content),f(null),x(""),y(null),j([]),A(!1))}async function C(ce){if(v===ce)y(null),j([]);else{y(ce),w(!0);try{const K=await Qx(t,ce,i);j(K)}catch(K){n(fe(K)||"Failed to load revisions","error")}finally{w(!1)}}}function q(){c&&(f(c),x(h))}function oe(){f(null),x("")}async function O(){if(!(!p||!b.trim())){$(!0);try{await td(t,p,b,{},i),f(null),x(""),await z();const ce=l.find(K=>K.key===p);ce&&g(ce.content),n("Document saved","success")}catch(ce){n(fe(ce)||"Failed to save document","error")}finally{$(!1)}}}async function V(){const ce=_.trim(),K=T.trim();if(!ce){n("Document key is required","error");return}if(!jM.test(ce)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!K){n("Content is required","error");return}$(!0);try{await td(t,ce,K,{},i),k(!1),E(""),D(""),await z(),n("Document created","success")}catch(de){n(fe(de)||"Failed to create document","error")}finally{$(!1)}}async function F(ce){N(ce);try{await Xx(t,ce,i),Y(null),N(null),c===ce&&(u(null),g("")),v===ce&&(y(null),j([])),await z(),n("Document deleted","success")}catch(K){n(fe(K)||"Failed to delete document","error")}finally{N(null)}}function ue(ce){g(ce.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:_,onChange:ce=>E(ce.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:T,onChange:ce=>D(ce.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),E(""),D("")},disabled:Z,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void V(),disabled:Z||!_.trim()||!T.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(ce=>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(wi,{size:14}),e.jsx("span",{className:"task-document-key",children:ce.key}),e.jsxs("span",{className:"task-document-revision-badge",children:["v",ce.revision]})]}),e.jsxs("div",{className:"task-document-meta",children:[e.jsx("span",{className:"task-document-author",children:ce.author}),e.jsx("span",{className:"task-document-timestamp",children:em(ce.updatedAt||ce.createdAt)})]})]}),c===ce.key&&p!==ce.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:()=>A(K=>!K),"aria-label":H?"Switch to plain text":"Switch to markdown","aria-pressed":H,title:H?"Switch to plain text":"Switch to markdown",children:H?"Markdown":"Plain"})}),e.jsx("div",{className:"task-document-content",children:H?e.jsx("div",{className:"task-document-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(di,{remarkPlugins:[ui],children:h})})}):e.jsx("pre",{className:"task-document-content-text",children:h})}),v===ce.key&&e.jsxs("div",{className:"task-document-revisions",children:[e.jsx("h5",{children:"Revision History"}),P?e.jsx("div",{className:"detail-log-empty",children:"Loading…"}):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<ce.revision).sort((K,de)=>de.revision-K.revision).map(K=>e.jsxs("div",{className:"task-document-revision-item",onClick:()=>ue(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:em(K.createdAt)})]}),e.jsx("div",{className:"revision-preview",children:wM(K.content,100)})]},K.id))})]})]}),p===ce.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:oe,disabled:Z,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void O(),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 J(ce),children:c===ce.key?e.jsxs(e.Fragment,{children:[e.jsx(qs,{size:14})," Collapse"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ot,{size:14})," Expand"]})}),c===ce.key&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void C(ce.key),children:[e.jsx(Ba,{size:14})," History"]}),r&&p!==ce.key&&e.jsx("button",{className:"btn btn-sm",onClick:q,children:"Edit"}),r&&(W===ce.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(ce.key),disabled:R===ce.key,children:R===ce.key?"…":"Yes"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Y(null),disabled:R===ce.key,children:"No"})]}):e.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>Y(ce.key),children:e.jsx(qt,{size:14})}))]})]})]},ce.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 Pr(t){return t.toLocaleString()}function tm(t){const n=new Date(t);return Number.isNaN(n.getTime())?t:n.toLocaleString()}function SM({tokenUsage:t,loading:n}){return!t&&n?e.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task token usage",children:[e.jsx("h4",{children:"Token Usage"}),e.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"})]}):t?e.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task token usage",children:[e.jsx("h4",{children:"Token Usage"}),e.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),e.jsx("span",{className:"task-token-stats-panel__value",children:Pr(t.inputTokens)})]}),e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),e.jsx("span",{className:"task-token-stats-panel__value",children:Pr(t.outputTokens)})]}),e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),e.jsx("span",{className:"task-token-stats-panel__value",children:Pr(t.cachedTokens)})]}),e.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[e.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),e.jsx("span",{className:"task-token-stats-panel__value",children:Pr(t.totalTokens)})]})]}),e.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[e.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[e.jsx("dt",{children:"First used"}),e.jsx("dd",{children:e.jsx("time",{dateTime:t.firstUsedAt,children:tm(t.firstUsedAt)})})]}),e.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[e.jsx("dt",{children:"Last used"}),e.jsx("dd",{children:e.jsx("time",{dateTime:t.lastUsedAt,children:tm(t.lastUsedAt)})})]})]})]}):e.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task token usage",children:[e.jsx("h4",{children:"Token Usage"}),e.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})}function CM(t,n){return t.modelProvider&&t.modelId?{provider:t.modelProvider,modelId:t.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function EM(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 MM(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 AM(t,n,s){if(t.planningModelProvider&&t.planningModelId)return{provider:t.planningModelProvider,modelId:t.planningModelId};const i=MM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function PM(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 IM(t){const n=new Date(t),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),l=Math.floor(r/60),o=Math.floor(l/24);return r<1?"just now":r<60?`${r}m ago`:l<24?`${l}h ago`:o<7?`${o}d ago`:n.toLocaleDateString()}function _M(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function RM(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 nm(t,n){return t.length>n?t.slice(0,n)+"…":t}function sm(t=[],n=[]){return t.length===n.length&&t.every((s,i)=>s===n[i])}function lo(t){const n=t.indexOf("/");return!t||n===-1?null:{provider:t.slice(0,n),modelId:t.slice(n+1)}}function oo(t){return t.trim()}function TM(t){const n=t.trim();return n.length>0?n:void 0}function Sa(t){return typeof t=="string"&&cc.includes(t)?t:cs}const co=200,$M=new Set(["triage","todo"]);function FM({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,v]=a.useState(()=>"prompt"in t?t:null),[y,M]=a.useState(()=>!("prompt"in t));a.useEffect(()=>{if("prompt"in t){v(t),M(!1);return}let ne=!1;return M(!0),v(null),Hr(t.id,n).then(rt=>{ne||(v(rt),M(!1))}).catch(()=>{ne||M(!1)}),()=>{ne=!0}},[t.id,n]);const j=x??{...t,prompt:""},P=t.status==="failed"||t.status==="stuck-killed"||t.status==="specifying"||t.status==="needs-respecify"||(t.stuckKillCount??0)>0||(t.recoveryRetryCount??0)>0||!!t.nextRecoveryAt;a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{_(!1)},[t.id]);const[w,S]=a.useState("activity"),[k,_]=a.useState(!1),[E,T]=a.useState(t.attachments||[]),[D,Z]=a.useState(!1),[$,R]=a.useState(t.dependencies||[]),[N,W]=a.useState(!1),[Y,H]=a.useState(""),[A,z]=a.useState(null),[J,C]=a.useState([]),[q,oe]=a.useState(!1),[O,V]=a.useState(!1),[F,ue]=a.useState(!1),[ce,K]=a.useState(!1),[de,Fe]=a.useState(!1),[we,Ee]=a.useState(j.prompt||""),[ie,Pe]=a.useState(""),[ze,$e]=a.useState(!1),[He,Me]=a.useState(""),[Te,Ve]=a.useState(!1),[_e,et]=a.useState(!1),[le,X]=a.useState(t.title||""),[ke,se]=a.useState(t.description||""),[Le,ve]=a.useState(t.dependencies||[]),[Ye,mt]=a.useState(""),[ht,me]=a.useState(""),[te,je]=a.useState(""),[Ae,Qe]=a.useState(""),[be,st]=a.useState("default"),[Se,Je]=a.useState(void 0),[it,ye]=a.useState(cs),[Ge,Ne]=a.useState(""),[at,dt]=a.useState(t.enabledWorkflowSteps||[]),[vt,It]=a.useState(t.sourceIssue?.provider??""),[_t,Mt]=a.useState(t.sourceIssue?.repository??""),[zt,Nt]=a.useState(t.sourceIssue?.externalIssueId??""),[Pt,tt]=a.useState(t.sourceIssue?.url??""),[bt,Ue]=a.useState([]),[ot,ge]=a.useState(!1),Oe=a.useRef(!1),[ee,Ie]=a.useState(!1),[xt,he]=a.useState(!1),Be=a.useRef(null),gt=a.useRef(null),{getSlotsForId:Kt}=Mh(n),yn=Kt("task-detail-tab");a.useEffect(()=>(Oe.current=!0,()=>{Oe.current=!1}),[]);const[mn,Kn]=a.useState(void 0),[Wt,Cn]=a.useState([]),[Tn,as]=a.useState(!1),[Ut,Xt]=a.useState(t.enabledWorkflowSteps||[]);a.useEffect(()=>{X(t.title||""),se(t.description||""),It(t.sourceIssue?.provider??""),Mt(t.sourceIssue?.repository??""),Nt(t.sourceIssue?.externalIssueId??""),tt(t.sourceIssue?.url??""),et(!1)},[t.id,t.title,t.description,t.sourceIssue]),a.useEffect(()=>{Xt(t.enabledWorkflowSteps||[])},[t.id,t.enabledWorkflowSteps]),a.useEffect(()=>{let ne=!1;return Xi(n).then(rt=>{ne||Kn(rt)}).catch(()=>{}),()=>{ne=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let ne=!1;return as(!0),fy(t.id,n).then(rt=>{ne||Cn(rt)}).catch(rt=>{ne||h(`Failed to load workflow results: ${fe(rt)}`,"error")}).finally(()=>{ne||as(!1)}),()=>{ne=!0}},[f,t.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const ne=n?`?projectId=${encodeURIComponent(n)}`:"",rt=ft=>{try{const At=JSON.parse(ft.data);At.id===t.id&&Array.isArray(At.workflowStepResults)&&Cn(At.workflowStepResults)}catch{}};return Gs(`/api/events${ne}`,{events:{"task:updated":rt}})},[f,t.id,n]),a.useEffect(()=>{N||H("")},[N]),a.useEffect(()=>{if(!t.assignedAgentId){z(null);return}const ne=J.find(ft=>ft.id===t.assignedAgentId);if(ne){z(ne);return}let rt=!1;return jh(t.assignedAgentId,n).then(ft=>{rt||z(ft)}).catch(()=>{rt||z(null)}),()=>{rt=!0}},[t.assignedAgentId,n,J]),a.useEffect(()=>{oe(!1)},[t.id]),a.useEffect(()=>{if(!(ee||xt))return;const rt=ft=>{const At=ft.target,Ms=Be.current?.contains(At),Ys=gt.current?.contains(At);!Ms&&ee&&Ie(!1),!Ys&&xt&&he(!1)};return document.addEventListener("mousedown",rt),()=>document.removeEventListener("mousedown",rt)},[ee,xt]),a.useEffect(()=>{if(!(ee||xt))return;const rt=ft=>{ft.key==="Escape"&&(ft.stopPropagation(),ee&&Ie(!1),xt&&he(!1))};return document.addEventListener("keydown",rt),()=>document.removeEventListener("keydown",rt)},[ee,xt]),a.useEffect(()=>{Fe(!1),Ee(j.prompt||""),Pe("")},[t.id,j.prompt]);const hn=$M.has(t.column)&&!ot,gn=a.useCallback(()=>{if(!hn)return;et(!0),X(t.title||""),se(t.description||""),ve(t.dependencies||[]);const ne=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"",rt=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"",ft=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";mt(ne),me(rt),je(ft),Qe(t.thinkingLevel??""),st(ne||rt||ft?"custom":"default"),Ne(""),dt(t.enabledWorkflowSteps||[]),It(t.sourceIssue?.provider??""),Mt(t.sourceIssue?.repository??""),Nt(t.sourceIssue?.externalIssueId??""),tt(t.sourceIssue?.url??""),Ue([]),Je(t.reviewLevel),ye(Sa(t.priority))},[hn,t]),En=a.useCallback(()=>{et(!1),X(t.title||""),se(t.description||""),ve(t.dependencies||[]),It(t.sourceIssue?.provider??""),Mt(t.sourceIssue?.repository??""),Nt(t.sourceIssue?.externalIssueId??""),tt(t.sourceIssue?.url??""),ye(Sa(t.priority)),bt.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),Ue([])},[t.title,t.description,t.dependencies,t.priority,bt]),an=a.useCallback(async()=>{ge(!0);try{const ne={},rt=le.trim(),ft=ke.trim();rt&&rt!==(t.title??"")&&(ne.title=rt),ft&&ft!==(t.description??"")&&(ne.description=ft),sm(Le,t.dependencies??[])||(ne.dependencies=Le),sm(at,t.enabledWorkflowSteps??[])||(ne.enabledWorkflowSteps=at);const At=lo(Ye),Ms=t.modelProvider&&t.modelId?`${t.modelProvider}/${t.modelId}`:"";Ye!==Ms&&(ne.modelProvider=At?.provider??null,ne.modelId=At?.modelId??null);const Ys=lo(ht),_i=t.validatorModelProvider&&t.validatorModelId?`${t.validatorModelProvider}/${t.validatorModelId}`:"";ht!==_i&&(ne.validatorModelProvider=Ys?.provider??null,ne.validatorModelId=Ys?.modelId??null);const dr=lo(te),Ds=t.planningModelProvider&&t.planningModelId?`${t.planningModelProvider}/${t.planningModelId}`:"";te!==Ds&&(ne.planningModelProvider=dr?.provider??null,ne.planningModelId=dr?.modelId??null);const ur=t.thinkingLevel??"";Ae!==ur&&(ne.thinkingLevel=Ae!==""?Ae:null);const mr=t.reviewLevel;Se!==mr&&(ne.reviewLevel=Se);const vl=Sa(t.priority);it!==vl&&(ne.priority=it);const pa=oo(vt),fa=oo(_t),xs=oo(zt),Ls=TM(Pt);if(pa.length===0&&fa.length===0&&xs.length===0&&!Ls)t.sourceIssue&&(ne.sourceIssue=null);else{if(!pa||!fa||!xs){h("Source issue provider, repository, and issue identifier are required","error"),ge(!1);return}const As=Number.parseInt(xs,10),si=t.sourceIssue?.issueNumber??As;if(!Number.isFinite(si)||si<=0){h("Source issue identifier must be numeric for new metadata","error"),ge(!1);return}const Ps={provider:pa,repository:fa,externalIssueId:xs,issueNumber:si,...Ls?{url:Ls}:{}},Is=t.sourceIssue;(!Is||Is.provider!==Ps.provider||Is.repository!==Ps.repository||Is.externalIssueId!==Ps.externalIssueId||Is.issueNumber!==Ps.issueNumber||(Is.url??void 0)!==Ps.url)&&(ne.sourceIssue=Ps)}if(Object.keys(ne).length>0){const As=await Zs(t.id,ne,n);u?.(As)}if(bt.length>0){const As=[];for(const si of bt)try{const Ps=await Ha(t.id,si.file,n);T(Is=>[...Is,Ps])}catch{As.push(si.file.name)}As.length>0&&h(`Failed to upload: ${As.join(", ")}`,"error")}bt.forEach(As=>URL.revokeObjectURL(As.previewUrl)),Ue([]),h(`Updated ${t.id}`,"success"),et(!1)}catch(ne){h(`Failed to update ${t.id}: ${fe(ne)}`,"error")}finally{Oe.current&&ge(!1)}},[t,le,ke,Le,Ye,ht,te,Ae,Se,it,at,vt,_t,zt,Pt,bt,h,n,u]),Ft=a.useCallback(async ne=>{try{await Zs(t.id,{description:ne},n),h("Description saved","success")}catch(rt){h(`Failed to save: ${fe(rt)}`,"error")}},[t.id,h,n]),pn=a.useCallback(ne=>{_e&&(ne.key==="Escape"?(ne.preventDefault(),En()):ne.key==="Enter"&&(ne.ctrlKey||ne.metaKey)&&(ne.preventDefault(),an()))},[_e,En,an]);a.useEffect(()=>{if(_e)return document.addEventListener("keydown",pn),()=>document.removeEventListener("keydown",pn)},[_e,pn]);const Mn=a.useRef(null),{entries:jn,loading:zn,loadMore:rs,hasMore:Gn,total:Pn,loadingMore:G}=Yp(t.id,f==="logs"&&w==="agent-log",n);a.useEffect(()=>{const ne=rt=>{rt.key==="Escape"&&!_e&&i()};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[i,_e]);const Ke=a.useCallback(ne=>{ne.target===ne.currentTarget&&i()},[i]),I=a.useCallback(async ne=>{try{await l(t.id,ne),i(),h(`Moved to ${ds[ne]}`,"success")}catch(rt){h(fe(rt),"error")}},[t.id,l,i,h]),B=a.useCallback(async()=>{if(confirm(`Delete ${t.id}?`))try{await o(t.id),i(),h(`Deleted ${t.id}`,"info")}catch(ne){const rt=RM(ne);if(!rt||rt.dependentIds.length===0){h(fe(ne),"error");return}const ft=rt.dependentIds.join(", ");if(!confirm(`${t.id} is a dependency of ${ft}.
630
+
631
+ Delete anyway by removing these dependency references first?`))return;try{await o(t.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${t.id} after removing dependency references`,"info")}catch(Ms){h(fe(Ms),"error")}}},[t.id,o,i,h]),re=a.useCallback(()=>{confirm(`Merge ${t.id} into the current branch?`)&&(i(),h(`Merging ${t.id}...`,"info"),d(t.id).then(ne=>{const rt=ne.merged?`Merged ${t.id} (branch: ${ne.branch})`:`Closed ${t.id} (${ne.error||"no branch to merge"})`;h(rt,"success")}).catch(ne=>{h(fe(ne),"error")}))},[t.id,d,i,h]),pe=a.useCallback(()=>{m&&(i(),m(t.id).then(()=>{h(`Retried ${t.id}`,"success")}).catch(ne=>{h(fe(ne),"error")}))},[t.id,m,i,h]),xe=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 ne=await c(t.id);i(),h(`Duplicated ${t.id} → ${ne.id}`,"success")}catch(ne){h(fe(ne),"error")}},[t.id,c,i,h]),Re=a.useCallback(async()=>{try{t.paused?(await _x(t.id,n),h(`Unpaused ${t.id}`,"success")):(await Ix(t.id,n),h(`Paused ${t.id}`,"success")),i()}catch(ne){h(fe(ne),"error")}},[t.id,t.paused,i,h]),pt=a.useCallback(async()=>{try{await Fx(t.id,n),h(`Plan approved — ${t.id} moved to Todo`,"success"),i()}catch(ne){h(fe(ne),"error")}},[t.id,i,h]),kt=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await Dx(t.id,n),h(`Plan rejected — ${t.id} returned to Triage for re-specification`,"info"),i()}catch(ne){h(fe(ne),"error")}},[t.id,i,h]),We=a.useCallback(async()=>{if(confirm("Rebuild the specification for this task? The task will move to triage for re-specification."))try{await tv(t.id,n),i(),h(`Respecifying ${t.id}...`,"info")}catch(ne){h(fe(ne),"error")}},[t.id,n,i,h]),wt=a.useCallback(()=>{$e(!0),Me("")},[]),ae=a.useCallback(()=>{Ie(!1),he(!1)},[]),De=a.useCallback(ne=>{ae(),I(ne)},[ae]),ct=a.useCallback(ne=>{ae(),ne()},[ae]),St=a.useCallback(()=>{ae(),re()},[ae]),Et=a.useCallback(()=>{$e(!1),Me(""),Ve(!1)},[]),cn=a.useCallback(async()=>{if(!He.trim()){h("Please enter feedback describing what needs refinement","error");return}if(He.length>2e3){h("Feedback must be 2000 characters or less","error");return}Ve(!0);try{const ne=await nv(t.id,He.trim(),n);h(`Refinement task created: ${ne.id}`,"success"),i()}catch(ne){h(fe(ne),"error")}finally{Ve(!1)}},[t.id,He,h,i]),Gt=a.useCallback(async ne=>{Z(!0);try{const rt=await Ha(t.id,ne,n);T(ft=>[...ft,rt]),h("Screenshot attached","success")}catch(rt){h(fe(rt),"error")}finally{Z(!1)}},[t.id,h]),un=a.useCallback(async ne=>{const rt=ne.target.files?.[0];rt&&(await Gt(rt),Mn.current&&(Mn.current.value=""))},[Gt]);a.useEffect(()=>{const ne=rt=>{const ft=rt.clipboardData?.items;if(ft)for(let At=0;At<ft.length;At++){const Ms=ft[At];if(Ms.type.startsWith("image/")){const Ys=Ms.getAsFile();if(Ys){rt.preventDefault(),Gt(Ys);return}}}};return document.addEventListener("paste",ne),()=>document.removeEventListener("paste",ne)},[Gt]);const fn=a.useCallback(ne=>{ne.preventDefault()},[]),kn=a.useCallback(ne=>{ne.preventDefault();const rt=ne.dataTransfer.files;for(let ft=0;ft<rt.length;ft++){const At=rt[ft];if(At.type.startsWith("image/")){Gt(At);return}}},[Gt]),In=a.useCallback(async ne=>{try{await Kx(t.id,ne,n),T(rt=>rt.filter(ft=>ft.filename!==ne)),h("Attachment deleted","info")}catch(rt){h(fe(rt),"error")}},[t.id,h]),ps=a.useCallback(async ne=>{const rt=Ut;Xt(ne);try{const ft=await Zs(t.id,{enabledWorkflowSteps:ne},n);h("Workflow steps updated","success"),u?.(ft)}catch(ft){Xt(rt),h(`Failed to update workflow steps: ${fe(ft)}`,"error")}},[t.id,n,Ut,u,h]),On=a.useCallback(async()=>{V(!0);try{const ne=await da(void 0,n);C(ne),oe(!0)}catch(ne){h(`Failed to load agents: ${fe(ne)}`,"error"),oe(!1)}finally{V(!1)}},[n,h]),Jn=a.useCallback(async ne=>{try{const rt=await md(t.id,ne,n),ft=J.find(At=>At.id===ne)??null;z(ft||(At=>At?.id===ne?At:null)),oe(!1),u?.(rt),h("Assigned agent updated","success")}catch(rt){h(`Failed to assign agent: ${fe(rt)}`,"error")}},[t.id,n,J,u,h]),Bn=a.useCallback(async()=>{try{const ne=await md(t.id,null,n);z(null),oe(!1),u?.(ne),h("Agent unassigned","success")}catch(ne){h(`Failed to unassign agent: ${fe(ne)}`,"error")}},[t.id,n,u,h]),Yn=a.useCallback(async ne=>{const rt=[...$,ne];R(rt);try{await Zs(t.id,{dependencies:rt},n)}catch(ft){R($),h(fe(ft),"error")}},[t.id,$,h]),bn=a.useCallback(async(ne,rt)=>{ne.stopPropagation();const ft=$.filter(At=>At!==rt);R(ft);try{await Zs(t.id,{dependencies:ft},n)}catch(At){R($),h(fe(At),"error")}},[t.id,$,h]),Un=a.useCallback(async ne=>{try{const rt=await Hr(ne,n);r(rt)}catch{h(`Failed to load dependency ${ne}`,"error")}},[r,h]),fs=a.useCallback(async ne=>{ue(!0);try{await Zs(j.id,{prompt:ne},n),h("Spec updated","success"),x&&(x.prompt=ne)}catch(rt){throw h(fe(rt),"error"),rt}finally{ue(!1)}},[j,x,h]),Fs=a.useCallback(async ne=>{K(!0);try{await ev(t.id,ne,n),h("AI revision requested. Task moved to triage.","success"),i()}catch(rt){const ft=fe(rt);ft.includes("in-review")||ft.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(ft,"error")}finally{K(!1)}},[t.id,h,i]),gs=a.useCallback(()=>{Fe(!0),Ee(j.prompt||""),Pe("")},[j.prompt]),wn=a.useCallback(()=>{Fe(!1),Ee(j.prompt||""),Pe("")},[j.prompt]),Qn=a.useCallback(async()=>{if(we===(j.prompt||"")){wn();return}await fs(we),Fe(!1)},[we,j.prompt,fs,wn]),bs=a.useCallback(async()=>{ie.trim()&&await Fs(ie.trim())},[ie,Fs]),bl=a.useCallback(ne=>{ne.key==="Escape"?(ne.preventDefault(),wn()):ne.key==="Enter"&&(ne.ctrlKey||ne.metaKey)&&(ne.preventDefault(),Qn())},[wn,Qn]),lr=s.filter(ne=>ne.id!==t.id&&!$.includes(ne.id)).sort((ne,rt)=>{const ft=rt.createdAt.localeCompare(ne.createdAt);if(ft!==0)return ft;const At=parseInt(ne.id.slice(ne.id.lastIndexOf("-")+1),10)||0;return(parseInt(rt.id.slice(rt.id.lastIndexOf("-")+1),10)||0)-At}),or=A?.name??t.assignedAgentId??null,Es=To[t.column]||[],xl={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},cr=t.status?xl[t.status]:void 0;return e.jsx("div",{className:"modal-overlay open",onClick:Ke,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg",onDragOver:fn,onDrop:kn,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:[!_e&&hn&&e.jsx("button",{className:"modal-edit-btn",onClick:gn,title:"Edit task","aria-label":"Edit task",children:e.jsx($n,{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"&&!_e?" detail-body--agent-log":""}`,children:[_e?e.jsx("div",{className:"modal-edit-form",children:e.jsx(Zp,{mode:"edit",title:le,onTitleChange:X,description:ke,onDescriptionChange:se,dependencies:Le,onDependenciesChange:ve,executorModel:Ye,onExecutorModelChange:mt,validatorModel:ht,onValidatorModelChange:me,planningModel:te,onPlanningModelChange:je,thinkingLevel:Ae,onThinkingLevelChange:Qe,presetMode:be,onPresetModeChange:st,selectedPresetId:Ge,onSelectedPresetIdChange:Ne,selectedWorkflowSteps:at,onWorkflowStepsChange:dt,pendingImages:bt,onImagesChange:Ue,tasks:s.filter(ne=>ne.id!==t.id),projectId:n,disabled:ot,addToast:h,isActive:_e,onAutoSaveDescription:Ft,reviewLevel:Se,onReviewLevelChange:Je,priority:it,onPriorityChange:ye,renderBelowPrimary:e.jsxs("div",{className:"form-group detail-source-edit-group",children:[e.jsx("label",{children:"Source Issue"}),e.jsxs("div",{className:"detail-source-edit-grid",children:[e.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:vt,onChange:ne=>It(ne.target.value),disabled:ot,"data-testid":"task-source-provider-input"}),e.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:_t,onChange:ne=>Mt(ne.target.value),disabled:ot,"data-testid":"task-source-repository-input"}),e.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:zt,onChange:ne=>Nt(ne.target.value),disabled:ot,"data-testid":"task-source-external-id-input"}),e.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Pt,onChange:ne=>tt(ne.target.value),disabled:ot,"data-testid":"task-source-url-input"})]}),e.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):e.jsxs(e.Fragment,{children:[(()=>{const ne=t.title||t.description||t.id,rt=!k&&ne.length>co;return e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"detail-title",children:rt?ne.slice(0,co)+"…":ne}),ne.length>co&&e.jsx("button",{className:"detail-description-toggle",onClick:()=>_(!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--${Sa(t.priority)}`,children:["Priority: ",Sa(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})]})]}),!_e&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"detail-tabs",children:[e.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>b("definition"),children:"Definition"}),e.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>b("logs"),children:"Logs"}),(t.column==="in-progress"||t.column==="in-review"||t.column==="done")&&e.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>b("changes"),children:"Changes"}),e.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>b("comments"),children:"Comments"}),e.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>b("documents"),children:"Documents"}),e.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>b("model"),children:"Model"}),e.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>b("workflow"),children:"Workflow"}),e.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>b("stats"),children:"Stats"}),yn.map((ne,rt)=>{const ft=`plugin-${rt}`;return e.jsx("button",{className:`detail-tab${f===ft?" detail-tab-active":""}`,onClick:()=>b(ft),children:ne.slot.label},`plugin-tab-${ne.pluginId}`)})]}),f==="workflow"?e.jsx("div",{className:"detail-section",children:e.jsx(yM,{taskId:t.id,results:Wt,loading:Tn,enabledWorkflowSteps:Ut,canEdit:hn,projectId:n,isTaskInProgress:t.column==="in-progress"&&t.status!=="paused",onWorkflowStepsChange:ps})}):f==="model"?e.jsx("div",{className:"detail-section",children:e.jsx(tM,{task:t,addToast:h,onTaskUpdated:u,settings:mn})}):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(Y2,{entries:jn,loading:zn,executorModel:CM(t,mn),validatorModel:EM(t,mn),planningModel:AM(t,jn,mn),hasMore:Gn,onLoadMore:rs,loadingMore:G,totalCount:Pn}):e.jsxs("div",{className:"detail-activity",children:[e.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?e.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?e.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((ne,rt)=>e.jsxs("div",{className:"detail-log-entry",children:[e.jsxs("div",{className:"detail-log-header",children:[e.jsx("span",{className:"detail-log-timestamp",children:IM(ne.timestamp)}),e.jsx("span",{className:"detail-log-action",children:ne.action})]}),ne.outcome&&e.jsx("div",{className:"detail-log-outcome",children:ne.outcome})]},rt))}):e.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?e.jsx(uM,{taskId:t.id,worktree:t.worktree,projectId:n,column:t.column,mergeDetails:t.mergeDetails,modifiedFiles:t.modifiedFiles}):f==="comments"?e.jsx(rM,{task:t,addToast:h,projectId:n,onTaskUpdated:u}):f==="documents"?e.jsx(NM,{taskId:t.id,addToast:h,projectId:n,onTaskUpdated:u,canEdit:hn}):typeof f=="string"&&f.startsWith("plugin-")?e.jsx("div",{className:"detail-section",children:e.jsx(nr,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?e.jsx("div",{className:"detail-section",children:e.jsx(SM,{tokenUsage:j.tokenUsage,loading:y})}):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(di,{remarkPlugins:[ui],children:t.summary})})]}),e.jsx(oM,{task:t}),e.jsxs("div",{className:"detail-section detail-source-section",children:[e.jsx("h4",{children:"Source Issue"}),t.sourceIssue?e.jsxs("dl",{className:"detail-source-grid",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:t.sourceIssue.provider})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Repository"}),e.jsx("dd",{children:t.sourceIssue.repository})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Issue Identifier"}),e.jsx("dd",{children:t.sourceIssue.externalIssueId})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"URL"}),e.jsx("dd",{children:t.sourceIssue.url?e.jsx("a",{className:"detail-source-link",href:t.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:t.sourceIssue.url}):e.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]}):e.jsx("div",{className:"detail-empty-inline",children:"No source issue metadata recorded."})]}),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(rn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]}),e.jsxs("div",{className:"detail-agent-actions",children:[or?e.jsxs("span",{className:"detail-agent-chip",children:[e.jsx(rn,{size:14}),or,e.jsx("button",{className:"detail-agent-clear",onClick:()=>void Bn(),title:"Unassign agent",children:e.jsx(Lt,{size:12})})]}):e.jsx("button",{className:"btn btn-sm",onClick:()=>{q?oe(!1):On()},children:"Assign Agent"}),q&&e.jsxs("div",{className:"agent-picker-dropdown",children:[O&&e.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!O&&J.filter(ne=>ne.state!=="terminated").map(ne=>e.jsxs("button",{className:`agent-picker-item${t.assignedAgentId===ne.id?" selected":""}`,onClick:()=>void Jn(ne.id),children:[e.jsx(rn,{size:14}),e.jsx("span",{className:"agent-picker-name",children:ne.name}),e.jsx("span",{className:"agent-picker-role",children:ne.role})]},ne.id)),!O&&J.filter(ne=>ne.state!=="terminated").length===0&&e.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),e.jsxs("div",{className:"detail-section detail-step-progress",children:[e.jsx("h4",{children:"Progress"}),j.steps&&j.steps.length>0?e.jsxs("div",{className:"step-progress-wrapper",children:[e.jsx("div",{className:"step-progress-bar",children:j.steps.map((ne,rt)=>e.jsx("div",{className:`step-progress-segment step-progress-segment--${ne.status}`,"data-tooltip":`${ne.name} (${ne.status})`,style:{backgroundColor:PM(ne.status)}},rt))}),e.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(ne=>ne.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):e.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),e.jsxs("div",{className:"detail-section",children:[!de&&e.jsx("div",{className:"detail-spec-edit-trigger",children:e.jsx("button",{className:"btn btn-sm",onClick:gs,children:"Edit"})}),de?e.jsxs("div",{className:"spec-editor-edit-mode",children:[e.jsx("textarea",{className:"spec-editor-textarea",value:we,onChange:ne=>Ee(ne.target.value),onKeyDown:bl,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:wn,disabled:F,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Qn(),disabled:we===(j.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:ie,onChange:ne=>Pe(ne.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ce,rows:4,maxLength:2e3}),e.jsxs("div",{className:"spec-editor-revision-actions",children:[e.jsxs("span",{className:"spec-editor-char-count",children:[ie.length,"/2000"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void bs(),disabled:!ie.trim()||ce,children:ce?"Requesting…":"Request AI Revision"})]})]})]}):y?e.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?e.jsx("div",{className:"markdown-body",children:e.jsx(di,{remarkPlugins:[ui],children:j.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):e.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),e.jsxs("div",{className:"detail-section",children:[e.jsx("h4",{children:"Attachments"}),E.length>0?e.jsx("div",{className:"detail-attachments-grid",children:E.map(ne=>{const rt=$s(`/api/tasks/${t.id}/attachments/${ne.filename}`);return e.jsxs("div",{className:"detail-attachment-card",children:[e.jsx("a",{className:"detail-attachment-link",href:rt,target:"_blank",rel:"noopener noreferrer",children:e.jsx("img",{src:rt,alt:ne.originalName,className:"detail-attachment-image"})}),e.jsxs("div",{className:"detail-attachment-meta",children:[ne.originalName," (",_M(ne.size),")"]}),e.jsx("button",{className:"detail-attachment-delete",onClick:()=>In(ne.filename),title:"Delete attachment",children:"×"})]},ne.filename)})}):e.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),e.jsx("input",{className:"detail-hidden-file-input",ref:Mn,type:"file",accept:"image/*",onChange:un}),e.jsx("button",{className:"btn btn-sm",onClick:()=>Mn.current?.click(),disabled:D,children:D?"Uploading…":"Attach Screenshot"})]}),e.jsxs("div",{className:"detail-deps",children:[e.jsx("h4",{children:"Dependencies"}),$.length>0?e.jsx("ul",{className:"detail-dep-list",children:$.map(ne=>{const rt=s.find(At=>At.id===ne),ft=rt?.title||rt?.description||ne;return e.jsxs("li",{className:"detail-dep-item",children:[e.jsxs("span",{className:"detail-dep-link",onClick:()=>Un(ne),onKeyDown:At=>{(At.key==="Enter"||At.key===" ")&&(At.preventDefault(),Un(ne))},role:"link",tabIndex:0,title:`Click to view ${ne}`,children:[e.jsx("span",{className:"detail-dep-id",children:ne}),e.jsx("span",{className:"detail-dep-label",children:nm(ft,40)})]}),e.jsx("button",{className:"dep-remove-btn",onClick:At=>bn(At,ne),title:`Remove dependency ${ne}`,children:"×"})]},ne)})}):e.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),e.jsxs("div",{className:"dep-trigger-wrap",children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{N&&H(""),W(ne=>!ne)},children:"Add Dependency"}),N&&(()=>{const ne=Y.toLowerCase(),rt=ne?lr.filter(ft=>ft.id.toLowerCase().includes(ne)||ft.title&&ft.title.toLowerCase().includes(ne)||ft.description&&ft.description.toLowerCase().includes(ne)):lr;return e.jsxs("div",{className:"dep-dropdown",children:[e.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Y,onChange:ft=>H(ft.target.value),onClick:ft=>ft.stopPropagation()}),rt.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):rt.map(ft=>e.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Yn(ft.id),W(!1)},children:[e.jsx("span",{className:"dep-dropdown-id",children:ft.id}),e.jsx("span",{className:"dep-dropdown-title",children:nm(ft.title||ft.description||ft.id,30)})]},ft.id))]})})()]})]}),t.column==="in-review"&&e.jsx(sM,{taskId:t.id,projectId:n,prInfo:t.prInfo,automationStatus:t.status??null,autoMerge:mn?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:ne=>{t.prInfo=ne,h(`PR #${ne.number} created`,"success")},onPrUpdated:ne=>{t.prInfo=ne},addToast:h})]})]})]}),e.jsx("div",{className:"modal-actions",children:_e?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:En,disabled:ot,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:an,disabled:ot,children:ot?"Saving…":"Save"})]}):e.jsxs(e.Fragment,{children:[t.column==="triage"&&t.status==="awaiting-approval"&&j.prompt&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-primary btn-sm",onClick:pt,children:"Approve Plan"}),e.jsx("button",{className:"btn btn-danger btn-sm",onClick:kt,children:"Reject Plan"})]}),t.column==="triage"&&t.status!=="awaiting-approval"&&!P&&e.jsx("button",{className:"btn btn-sm btn-danger",onClick:B,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(t.column!=="triage"||t.status==="awaiting-approval"||P)&&e.jsxs("div",{className:"detail-actions-dropdown",ref:gt,children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>{he(ne=>!ne),Ie(!1)},"aria-haspopup":"menu","aria-expanded":xt,children:["Actions",e.jsx(Ot,{size:12})]}),xt&&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:()=>ct(B),children:"Delete"}),c&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ct(xe),children:"Duplicate"}),(t.column==="done"||t.column==="in-review")&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ct(wt),children:"Refine"}),e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ct(We),children:"Respecify"}),P&&m&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ct(pe),children:"Retry"}),t.column!=="done"&&e.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ct(Re),children:t.paused?"Unpause":"Pause"})]})]}),e.jsx("div",{className:"modal-actions-spacer"}),e.jsx("div",{className:"detail-move-dropdown",ref:Be,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:()=>{Ie(ne=>!ne),he(!1)},"aria-haspopup":"menu","aria-expanded":ee,children:["Move",e.jsx(Ot,{size:12})]}),cr?e.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:cr}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:St,children:"Merge & Close"})]}),ee&&e.jsxs("div",{className:"detail-move-menu",role:"menu",children:[e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>De("todo"),children:"Move to Todo"}),e.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>De("in-progress"),children:"Back to In Progress"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>De(Es[0]),disabled:Es.length===0,children:["Move to ",Es.length>0?ds[Es[0]]:""]}),Es.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>{Ie(ne=>!ne),he(!1)},"aria-haspopup":"menu","aria-expanded":ee,children:e.jsx(Ot,{size:12})}),ee&&e.jsx("div",{className:"detail-move-menu",role:"menu",children:Es.map(ne=>e.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>De(ne),children:["Move to ",ds[ne]]},ne))})]})]})})]})}),ze&&e.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Et,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal detail-refine-modal",onClick:ne=>ne.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:Et,"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:He,onChange:ne=>Me(ne.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:[He.length,"/2000 characters"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:cn,disabled:!He.trim()||Te,children:Te?"Creating...":"Create Refinement Task"})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:Et,disabled:Te,children:"Cancel"})})]})})]})})}function DM(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 Ux(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 _=k instanceof Error?k.message:"Failed to fetch memory backend status";c(_),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]),v=r?.currentBackend??null,y=r?.capabilities??null,M=r?.availableBackends??[],j=y?.readable??!1,P=y?.writable??!1,w=y?.supportsAtomicWrite??!1;return{status:r,currentBackend:v,capabilities:y,availableBackends:M,isReadable:j,isWritable:P,supportsAtomicWrite:w,loading:o,error:m,lastUpdated:u,refresh:x}}const LM=[{value:"light",label:"Light",icon:lh},{value:"dark",label:"Dark",icon:ih},{value:"system",label:"System",icon:rl}],im=[{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 zM({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:LM.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(lh,{size:20}):t==="dark"?e.jsx(ih,{size:20}):e.jsx(rl,{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)}`," / ",im.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:im.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 OM(t){if(!t)return!1;const n=t.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function ef({content:t,onChange:n,readOnly:s,filePath:i}){const[r,l]=a.useState(!1),[o,d]=a.useState(!0),m=OM(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(Zm,{size:14}),"Edit"]}),e.jsxs("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:h,disabled:c,"aria-label":"Preview mode",children:[e.jsx(ic,{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(Br,{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(Br,{size:14})})]}),c?e.jsx("div",{className:"file-editor-preview markdown-body",children:e.jsx(di,{remarkPlugins:[ui],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 tf({authenticated:t,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[l,o]=a.useState(null),[d,m]=a.useState(null),c=a.useRef(!0);a.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const u=a.useCallback(async()=>{try{const v=await iv();return c.current&&r(v),v}catch(v){return c.current&&m({kind:"error",message:v instanceof Error?v.message:String(v)}),null}},[]);a.useEffect(()=>{u()},[u]);const h=a.useCallback(async()=>{o("testing"),m(null),await u(),c.current&&o(null)},[u]),g=a.useCallback(async v=>{o(v?"enabling":"disabling"),m(null);try{const y=await av(v);c.current&&m({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await u()}catch(y){c.current&&m({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{c.current&&o(null)}},[n,u]),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(ut,{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(ns,{provider:"claude-cli",size:"sm"}),e.jsx("strong",{children:"Anthropic — via Claude CLI"}),e.jsx(BM,{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(am,{status:i,authenticated:t}),d&&e.jsx(rm,{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(ns,{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(am,{status:i,authenticated:t})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:x}),d&&e.jsx(rm,{action:d})]})}function BM({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 am({status:t,authenticated:n}){if(!t)return e.jsxs("small",{className:"settings-muted",children:[e.jsx(ut,{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 rm({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 Hi=[{id:"default-executor",name:"Default Executor",description:"Standard task execution agent with full tooling and review support.",role:"executor",prompt:`You are a task execution agent for "fn", an AI-orchestrated task board.
632
+
633
+ You are working in a git worktree isolated from the main branch. Your job is to implement the task described in the PROMPT.md specification you're given.`,builtIn:!0},{id:"default-triage",name:"Default Triage",description:"Standard task specification agent producing detailed PROMPT.md files.",role:"triage",prompt:`You are a task specification agent for "fn", an AI-orchestrated task board.
634
+
635
+ Your job: take a rough task description and produce a fully specified PROMPT.md that another AI agent can execute autonomously.`,builtIn:!0},{id:"default-reviewer",name:"Default Reviewer",description:"Standard independent code and plan reviewer with balanced criteria.",role:"reviewer",prompt:`You are an independent code and plan reviewer.
636
+
637
+ You provide quality assessment for task implementations with full read access to the codebase.`,builtIn:!0},{id:"default-merger",name:"Default Merger",description:"Standard merge agent for squash merges with conflict resolution.",role:"merger",prompt:`You are a merge agent for "fn", an AI-orchestrated task board.
638
+
639
+ Your job is to finalize a squash merge: resolve any conflicts and write a good commit message.`,builtIn:!0},{id:"senior-engineer",name:"Senior Engineer",description:"Autonomous executor with architectural awareness, performance focus, and minimal hand-holding.",role:"executor",prompt:`You are a senior engineering agent for "fn", an AI-orchestrated task board.
640
+
641
+ You operate with a high degree of autonomy, making architectural decisions and balancing trade-offs independently.`,builtIn:!0},{id:"strict-reviewer",name:"Strict Reviewer",description:"Rigorous reviewer with stricter criteria for security, edge cases, and type safety.",role:"reviewer",prompt:`You are a strict code and plan reviewer with rigorous standards.
642
+
643
+ You hold all submissions to a high bar for correctness, security, and maintainability.`,builtIn:!0},{id:"concise-triage",name:"Concise Triage",description:"Shorter, more focused specification format with minimal prose.",role:"triage",prompt:`You are a task specification agent for "fn". Produce a concise, actionable PROMPT.md from the given task description.
644
+
645
+ Be brief and precise — avoid verbosity.`,builtIn:!0}],UM={"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..."}},lm=["executor","triage","reviewer","merger"],Ca={executor:"Executor Agent",triage:"Triage Agent",reviewer:"Reviewer Agent",merger:"Merger Agent",scheduler:"Scheduler Agent",engineer:"Engineer Agent",custom:"Custom Agent"},Xs={executor:"#3b82f6",triage:"#f59e0b",reviewer:"#8b5cf6",merger:"#10b981",scheduler:"#06b6d4",engineer:"#ec4899",custom:"#6b7280"},uo={name:"",description:"",role:"executor",prompt:""};function HM(t,n){const s=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"").slice(0,50),i=new Set(Hi.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 qM({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(uo),[g,p]=a.useState(null),[f,b]=a.useState(null),[x,v]=a.useState(new Set),[y,M]=a.useState(null),[j,P]=a.useState(!1),[w,S]=a.useState(null),k=a.useRef(null),_=t?.templates??[],E=t?.roleAssignments??{},T=w===null?null:w.source==="builtin"?Hi.find(O=>O.id===w.id):_.find(O=>O.id===w.id),D=a.useCallback(O=>{const V=Hi.filter(ue=>ue.role===O),F=_.filter(ue=>ue.role===O);return[...V,...F]},[_]);a.useEffect(()=>{w!==null&&k.current?.focus()},[w]);const Z=a.useCallback(()=>{c(!0),d(null),h(uo),p(null),S(null)},[]),$=a.useCallback(O=>{d(O.id),c(!1),h({name:O.name,description:O.description,role:O.role,prompt:O.prompt}),p(null),S(null)},[]),R=a.useCallback(()=>{d(null),c(!1),h(uo),p(null),S(null),P(!1)},[]),N=a.useCallback(()=>{const O=u.name.trim();if(!O){p("Template name is required");return}let V;if(m){if(V=HM(O,_),new Set(Hi.map(de=>de.id)).has(V)){p(`Template ID "${V}" conflicts with a built-in template. Please use a different name.`);return}}else V=o;const F={id:V,name:O,description:u.description.trim(),role:u.role,prompt:u.prompt,builtIn:!1};let ue;m?ue=[..._,F]:ue=_.map(K=>K.id===V?F:K);const ce={...E};for(const[K,de]of Object.entries(ce))de===V&&u.role!==K&&delete ce[K];n({...t,templates:ue,roleAssignments:Object.keys(ce).length>0?ce:void 0}),R()},[u,m,o,_,E,t,n,R]),W=a.useCallback(O=>{const V=_.filter(ce=>ce.id!==O),F={...E};let ue=!1;for(const[ce,K]of Object.entries(F))K===O&&(delete F[ce],ue=!0);n({...t,templates:V.length>0?V:void 0,roleAssignments:Object.keys(F).length>0||ue?Object.keys(F).length>0?F:void 0:E}),b(null),o===O&&R()},[_,E,t,n,o,R]),Y=a.useCallback((O,V)=>{const F={...E};V===""?delete F[O]:F[O]=V,n({...t,roleAssignments:Object.keys(F).length>0?F:void 0})},[E,t,n]),H=a.useCallback((O,V)=>{const F={...s};F[O]=V||null,i(F)},[s,i]),A=a.useCallback(O=>{const V={...s};V[O]=null,i(V)},[s,i]),z=a.useCallback(O=>{v(V=>{const F=new Set(V);return F.has(O)?F.delete(O):F.add(O),F})},[]),J=a.useCallback(O=>{M(V=>V===O?null:O)},[]),C=a.useCallback((O,V)=>{P(!1),S({source:O,id:V})},[]),q=a.useCallback(()=>{S(null),P(O=>!O)},[]),oe=O=>Hi.some(V=>V.id===O);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(Jm,{size:14}),"Templates"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="assignments"?"active":""}`,onClick:()=>l("assignments"),"data-testid":"tab-assignments",children:[e.jsx(ex,{size:14}),"Assignments"]}),e.jsxs("button",{className:`prompt-manager-tab ${r==="overrides"?"active":""}`,onClick:()=>l("overrides"),"data-testid":"tab-overrides",children:[e.jsx(Db,{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:O=>h(V=>({...V,name:O.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:O=>h(V=>({...V,description:O.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:O=>h(V=>({...V,role:O.target.value})),"data-testid":"template-role-select",children:lm.map(O=>e.jsx("option",{value:O,children:Ca[O]},O))})]}),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:q,"aria-label":"Expand prompt to fullscreen","data-testid":"template-prompt-fullscreen",children:e.jsx(li,{size:14})})]}),j?e.jsxs("div",{className:"prompt-override-fullscreen",onKeyDown:O=>{O.key==="Escape"&&(O.preventDefault(),P(!1))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsx("div",{className:"prompt-override-fullscreen-title",children:"Edit Prompt"}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>P(!1),"data-testid":"template-prompt-collapse",children:[e.jsx(ei,{size:14}),"Collapse"]})]}),e.jsx("textarea",{id:"template-prompt-fullscreen","aria-label":"Template prompt - fullscreen",className:"prompt-template-prompt-textarea",value:u.prompt,onChange:O=>h(V=>({...V,prompt:O.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:O=>h(V=>({...V,prompt:O.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:R,"data-testid":"cancel-template-btn",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:N,"data-testid":"save-template-btn",children:m?"Create":"Save"})]})]})]}),e.jsxs("div",{className:"prompt-template-section","data-testid":"builtin-templates",children:[e.jsx("h4",{className:"prompt-template-section-title",children:"Built-in Templates"}),e.jsx("p",{className:"prompt-template-section-desc",children:"These templates are provided by Fusion and cannot be modified."}),e.jsx("div",{className:"prompt-template-list",children:Hi.map(O=>e.jsxs("div",{className:"prompt-template-card","data-testid":`builtin-template-${O.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:O.name}),e.jsx("span",{className:"prompt-template-badge-built-in",style:{borderColor:Xs[O.role]},children:"Built-in"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:Xs[O.role]+"20",color:Xs[O.role]},children:Ca[O.role]})]}),e.jsx("div",{className:"prompt-template-card-actions",children:e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>C("builtin",O.id),title:"View full prompt","aria-label":`View full prompt for ${O.name}`,"data-testid":`expand-view-${O.id}`,children:e.jsx(li,{size:14})})})]}),e.jsx("p",{className:"prompt-template-card-description",children:O.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:O.prompt})})]},O.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."}),_.length===0&&!m&&e.jsx("div",{className:"prompt-template-empty",children:"No custom templates yet. Create one to get started."}),_.length>0&&e.jsx("div",{className:"prompt-template-list",children:_.map(O=>e.jsx("div",{className:"prompt-template-card","data-testid":`custom-template-${O.id}`,children:f===O.id?e.jsxs("div",{className:"prompt-template-delete-confirm",children:[e.jsxs("p",{children:['Delete "',O.name,'"?']}),e.jsxs("div",{className:"prompt-template-delete-actions",children:[e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>W(O.id),"data-testid":`confirm-delete-${O.id}`,children:"Delete"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>b(null),"data-testid":`cancel-delete-${O.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:O.name}),e.jsx("span",{className:"prompt-template-badge-custom",children:"Custom"}),e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:Xs[O.role]+"20",color:Xs[O.role]},children:Ca[O.role]}),oe(O.id)&&e.jsx("span",{className:"prompt-template-badge-override",children:"Overrides built-in"})]}),e.jsxs("div",{className:"prompt-template-card-actions",children:[e.jsx("button",{type:"button",className:"btn-icon prompt-template-fullscreen-btn",onClick:()=>C("custom",O.id),title:"View full prompt","aria-label":`View full prompt for ${O.name}`,"data-testid":`expand-view-${O.id}`,children:e.jsx(li,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>$(O),title:"Edit","aria-label":`Edit ${O.name}`,"data-testid":`edit-${O.id}`,children:e.jsx($n,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>b(O.id),title:"Delete","aria-label":`Delete ${O.name}`,"data-testid":`delete-${O.id}`,children:e.jsx(qt,{size:14})})]})]}),e.jsx("p",{className:"prompt-template-card-description",children:O.description}),e.jsx("div",{className:"prompt-template-card-preview",children:e.jsx("code",{children:O.prompt})})]})},O.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"]})]}),T&&e.jsxs("div",{ref:k,className:"prompt-override-fullscreen",role:"dialog","aria-modal":"true",tabIndex:-1,onKeyDown:O=>{O.key==="Escape"&&(O.preventDefault(),S(null))},children:[e.jsxs("div",{className:"prompt-override-fullscreen-header",children:[e.jsxs("div",{className:"prompt-override-fullscreen-title",children:[T.name,e.jsx("span",{className:"prompt-template-badge-role",style:{backgroundColor:Xs[T.role]+"20",color:Xs[T.role]},children:Ca[T.role]})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>S(null),"data-testid":`collapse-view-${T.id}`,children:[e.jsx(ei,{size:14}),"Collapse"]})]}),e.jsx("pre",{className:"prompt-template-fullscreen-pre",children:T.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:lm.map(O=>{const V=D(O),F=E[O]??"",ue=V.find(K=>K.id===F),ce=!!F;return e.jsxs("div",{className:"prompt-role-assignment-row","data-testid":`assignment-${O}`,children:[e.jsxs("div",{className:"prompt-role-assignment-label",children:[e.jsx("span",{className:"prompt-role-badge",style:{backgroundColor:Xs[O]+"20",color:Xs[O]},children:Ca[O]}),ce&&e.jsxs("span",{className:"prompt-role-assignment-status",children:[ue?.name??"Custom"," (overrides default)"]})]}),e.jsxs("select",{className:"prompt-role-select",value:F,onChange:K=>Y(O,K.target.value),"data-testid":`select-${O}`,children:[e.jsx("option",{value:"",children:"Use default"}),V.map(K=>e.jsxs("option",{value:K.id,children:[K.name,oe(K.id)?" (built-in)":" (custom)"]},K.id))]})]},O)})}),Object.keys(E).length>0&&e.jsxs("div",{className:"prompt-assignments-note",children:[e.jsx("strong",{children:"Note:"})," Role assignments are stored in the agentPrompts configuration. Custom templates override built-ins by ID."]})]}),r==="overrides"&&e.jsxs("div",{className:"prompt-manager-overrides-tab","data-testid":"overrides-tab",children:[e.jsx("p",{className:"prompt-overrides-desc",children:"Customize specific segments of AI agent prompts. Edits override built-in defaults. Use the Reset button to restore the original default for any prompt."}),e.jsx("div",{className:"prompt-overrides-list",children:Object.values(UM).map(O=>{const V=O.key,F=s?.[V]??"",ue=F!=="",ce=x.has(V);return e.jsxs("div",{className:"prompt-override-item","data-testid":`override-${V}`,children:[e.jsxs("div",{className:"prompt-override-header",children:[e.jsxs("div",{className:"prompt-override-info",onClick:()=>z(V),role:"button",tabIndex:0,onKeyDown:K=>{(K.key==="Enter"||K.key===" ")&&z(V)},children:[e.jsx("span",{className:"prompt-override-name",children:O.name}),e.jsx("code",{className:"prompt-override-key",children:V}),ue&&e.jsx("span",{className:"prompt-override-badge",children:"customized"})]}),e.jsxs("div",{className:"prompt-override-header-actions",children:[ce&&e.jsx("button",{className:"prompt-override-fullscreen-btn",onClick:K=>{K.stopPropagation(),J(V)},"aria-label":"Expand to fullscreen","data-testid":`fullscreen-${V}`,children:e.jsx(li,{size:14})}),e.jsx("button",{className:"prompt-override-expand-btn","aria-label":ce?"Collapse":"Expand","data-testid":`expand-${V}`,onClick:K=>{K.stopPropagation(),z(V)},children:ce?e.jsx(qs,{size:16}):e.jsx(Ot,{size:16})})]})]}),e.jsx("p",{className:"prompt-override-description",children:O.description}),ce&&(y===V?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:[O.name,e.jsx("code",{className:"prompt-override-key",children:V})]}),e.jsxs("button",{type:"button",className:"prompt-override-fullscreen-close",onClick:()=>M(null),"data-testid":`collapse-fullscreen-${V}`,children:[e.jsx(ei,{size:14}),"Collapse"]})]}),e.jsx("textarea",{id:`prompt-${V}-fullscreen`,"aria-label":`${O.name} prompt override (${V}) - fullscreen`,className:"prompt-override-textarea",value:F,onChange:K=>{H(V,K.target.value)},placeholder:`Default: ${O.defaultContent.slice(0,100)}${O.defaultContent.length>100?"...":""}`,rows:30,autoFocus:!0,"data-testid":`override-input-fullscreen-${V}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ue&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:()=>A(V),"data-testid":`reset-fullscreen-${V}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:ue?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${O.defaultContent.length} chars).`})]})]}):e.jsxs("div",{className:"prompt-override-editor",children:[e.jsx("textarea",{id:`prompt-${V}`,"aria-label":`${O.name} prompt override (${V})`,className:"prompt-override-textarea",value:F,onChange:K=>{H(V,K.target.value)},placeholder:`Default: ${O.defaultContent.slice(0,100)}${O.defaultContent.length>100?"...":""}`,rows:4,"data-testid":`override-input-${V}`}),e.jsxs("div",{className:"prompt-override-footer",children:[ue&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:K=>{K.stopPropagation(),A(V)},"data-testid":`reset-${V}`,children:"Reset"}),e.jsx("small",{className:"prompt-override-hint",children:ue?"Custom override active. Click Reset to restore default.":`No override set. Using built-in default (${O.defaultContent.length} chars).`})]})]}))]},V)})})]})]})]})}const VM=a.lazy(()=>nn(()=>import("./PluginManager-s6btydh5.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(t=>({default:t.PluginManager}))),WM=a.lazy(()=>nn(()=>import("./PiExtensionsManager-BF5pxrSE.js"),__vite__mapDeps([7,1,4,5,8])).then(t=>({default:t.PiExtensionsManager}))),om="(max-width: 768px)",mo=".fusion/memory/DREAMS.md",Ir=[{id:"__account_header",label:"Account",scope:void 0,isGroupHeader:!0},{id:"authentication",label:"Authentication",scope:void 0,icon:Ni},{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"}],cm=1440*60*1e3,KM=2,Bi=["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],dm={insights:"Insights",roadmap:"Roadmaps",memoryView:"Memory Editor",skillsView:"Skills View",nodesView:"Nodes View",devServer:"Dev Server",devServerView:"Dev Server View"};function GM({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),[v,y]=a.useState(null),M=Ir.find(I=>!I.isGroupHeader),[j,P]=a.useState(()=>i==="pi-extensions"?"plugins":i??M?.id??"authentication"),[w,S]=a.useState(()=>i==="pi-extensions"?"pi-extensions":"fusion-plugins"),[k,_]=a.useState(()=>typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(om)?.matches===!0:!1),[E,T]=a.useState(null),D=Ir.find(I=>I.id===j)?.scope,[Z,$]=a.useState([]),[R,N]=a.useState(!1),[W,Y]=a.useState(null),[H,A]=a.useState({}),[z,J]=a.useState({}),[C,q]=a.useState({}),oe=a.useRef(null),[O,V]=a.useState([]),[F,ue]=a.useState(!1),[ce,K]=a.useState([]),[de,Fe]=a.useState([]),[we,Ee]=a.useState(!1),[ie,Pe]=a.useState(null),[ze,$e]=a.useState(null),[He,Me]=a.useState(null),[Te,Ve]=a.useState(!1),[_e,et]=a.useState(""),[le,X]=a.useState(!1),[ke,se]=a.useState(!1),[Le,ve]=a.useState([]),[Ye,mt]=a.useState([]),[ht,me]=a.useState(mo),[te,je]=a.useState(""),[Ae,Qe]=a.useState(!1),[be,st]=a.useState(null),[Se,Je]=a.useState(!1),[it,ye]=a.useState(!1),Ge=a.useRef(!1),[Ne,at]=a.useState(4),dt=a.useRef(4),[vt,It]=a.useState(!1),[,_t]=a.useState(null),[Mt,zt]=a.useState(null),[Nt,Pt]=a.useState(!1),[tt,bt]=a.useState("both"),[Ue,ot]=a.useState(!0),ge=a.useRef(null),{status:Oe,capabilities:ee,loading:Ie,error:xt,refresh:he}=DM({projectId:s});a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const I=window.matchMedia(om);if(!I)return;const B=re=>{_(re?re.matches:I.matches)};return B(),typeof I.addEventListener=="function"?(I.addEventListener("change",B),()=>I.removeEventListener("change",B)):(I.addListener(B),()=>I.removeListener(B))},[]),a.useEffect(()=>{Promise.all([Xi(s),Vx(s)]).then(([I,B])=>{u(I),f(I),x(B),y(B),g(!1)}).catch(I=>{n(fe(I),"error"),g(!1)})},[n,s]),a.useEffect(()=>{Uy().then(I=>{at(I.globalMaxConcurrent),dt.current=I.globalMaxConcurrent}).catch(()=>{})},[]);const Be=a.useCallback(async()=>{try{const{providers:I}=await Ei();$(I),A(B=>{const re={};for(const[pe,xe]of Object.entries(B)){const Re=I.find(pt=>pt.id===pe);Re&&!Re.authenticated&&(re[pe]=xe)}return Object.keys(re).length===Object.keys(B).length?B:re})}catch{}},[]);a.useEffect(()=>{(j==="global-models"||j==="project-models")&&(ue(!0),Vn().then(I=>{V(I.models),K(I.favoriteProviders),Fe(I.favoriteModels)}).catch(()=>V([])).finally(()=>ue(!1)))},[j]),a.useEffect(()=>{j==="backups"&&(Ve(!0),hd(s).then(I=>Me(I)).catch(()=>Me(null)).finally(()=>Ve(!1)))},[j,s]),a.useEffect(()=>{j==="worktrees"&&fh(s).then(I=>ve(I)).catch(()=>ve([]))},[j,s]),a.useEffect(()=>{if(j!=="memory"||ke)return;if(Ge.current){Ge.current=!1;return}let I=!1;return X(!0),Zc(s).then(async({files:B})=>{if(I)return;mt(B);const re=B.some(xe=>xe.path===ht)?ht:B.find(xe=>xe.path===mo)?.path??B.find(xe=>xe.layer==="dreams")?.path??B[0]?.path??mo;me(re);const{content:pe}=await zx(re,s);I||(et(pe),se(!1))}).catch(B=>{I||(n(fe(B)||"Failed to load project memory","error"),et(""))}).finally(()=>{I||X(!1)}),()=>{I=!0}},[j,ke,ht,s,n]),a.useEffect(()=>(j==="authentication"&&(N(!0),Be().finally(()=>N(!1))),()=>{oe.current&&(clearInterval(oe.current),oe.current=null)}),[j,Be]);const gt=a.useCallback(async I=>{Y(I),A(B=>{if(!(I in B))return B;const re={...B};return delete re[I],re});try{const{url:B,instructions:re}=await uh(I);re?.trim()&&A(pe=>({...pe,[I]:re})),window.open($s(B),"_blank"),oe.current=setInterval(async()=>{try{const{providers:pe}=await Ei();$(pe),pe.find(Re=>Re.id===I)?.authenticated&&(oe.current&&(clearInterval(oe.current),oe.current=null),Y(null),A(Re=>{if(!(I in Re))return Re;const pt={...Re};return delete pt[I],pt}),n("Login successful","success"))}catch{}},2e3)}catch(B){n(fe(B)||"Login failed","error"),Y(null),A(re=>{if(!(I in re))return re;const pe={...re};return delete pe[I],pe})}},[n]),Kt=a.useCallback(async I=>{Y(I);try{await mh(I),await Be(),n("Logged out","success")}catch(B){n(fe(B)||"Logout failed","error")}finally{Y(null)}},[n,Be]),yn=a.useCallback(async I=>{const B=z[I]?.trim();if(!B){q(re=>({...re,[I]:"API key is required"}));return}Y(I),q(re=>{const pe={...re};return delete pe[I],pe});try{await hh(I,B),J(re=>{const pe={...re};return delete pe[I],pe}),await Be(),n("API key saved","success")}catch(re){q(pe=>({...pe,[I]:fe(re)||"Failed to save API key"}))}finally{Y(null)}},[z,n,Be]),mn=a.useCallback(async I=>{Y(I);try{await ph(I),J(B=>{const re={...B};return delete re[I],re}),q(B=>{const re={...B};return delete re[I],re}),await Be(),n("API key cleared","success")}catch(B){n(fe(B)||"Failed to clear API key","error")}finally{Y(null)}},[n,Be]),Kn=a.useCallback(async()=>{if(!(!c.ntfyEnabled||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic))){Ee(!0);try{const I=c.ntfyBaseUrl?.trim();(await Wx({ntfyEnabled:c.ntfyEnabled,ntfyTopic:c.ntfyTopic,...I?{ntfyBaseUrl:I}:{}},s)).success?n("Test notification sent — check your ntfy app!","success"):n("Failed to send test notification","error")}catch(I){n(fe(I)||"Failed to send test notification","error")}finally{Ee(!1)}}},[n,c.ntfyBaseUrl,c.ntfyEnabled,c.ntfyTopic,s]),Wt=a.useCallback(async()=>{Ve(!0);try{const I=await Iy(s);if(I.success){n("Backup created successfully","success");const B=await hd(s);Me(B)}else n(I.error||"Failed to create backup","error")}catch(I){n(fe(I)||"Failed to create backup","error")}finally{Ve(!1)}},[n,s]),Cn=a.useCallback(async()=>{try{const I=D==="global"?"global":D==="project"?"project":"both",B=await _y(I,s),re=new Blob([JSON.stringify(B,null,2)],{type:"application/json"}),pe=URL.createObjectURL(re),xe=document.createElement("a"),Re=`fusion-settings-${new Date().toISOString().replace(/[:.]/g,"-").slice(0,19)}.json`;xe.href=pe,xe.download=Re,document.body.appendChild(xe),xe.click(),document.body.removeChild(xe),URL.revokeObjectURL(pe),n(`Settings exported (${I==="global"?"global":I==="project"?"project":"all"} scope)`,"success")}catch(I){n(fe(I)||"Failed to export settings","error")}},[n,D,s]),Tn=a.useCallback(async I=>{const B=I.target.files?.[0];if(B){_t(B),Pt(!0);try{const re=await B.text(),pe=JSON.parse(re);zt(pe),It(!0)}catch(re){n(`Invalid JSON file: ${fe(re)}`,"error"),_t(null)}finally{Pt(!1)}}},[n]),as=a.useCallback(async()=>{if(Mt){Pt(!0);try{const I=await Ry(Mt,{scope:tt,merge:Ue},s);if(I.success){const B=[];I.globalCount>0&&B.push(`${I.globalCount} global`),I.projectCount>0&&B.push(`${I.projectCount} project`),n(`Imported ${B.join(", ")} setting(s)`,"success"),It(!1),zt(null),_t(null);const re=await Xi(s);u(re)}else n(I.error||"Import failed","error")}catch(I){n(fe(I)||"Failed to import settings","error")}finally{Pt(!1)}}},[n,Mt,tt,Ue,s]),Ut=a.useCallback(async I=>{const B=ce,pe=B.includes(I)?B.filter(xe=>xe!==I):[I,...B];K(pe);try{await Jt({favoriteProviders:pe,favoriteModels:de})}catch{K(B)}},[ce,de]),Xt=a.useCallback(async I=>{const B=de,pe=B.includes(I)?B.filter(xe=>xe!==I):[I,...B];Fe(pe);try{await Jt({favoriteProviders:ce,favoriteModels:pe})}catch{Fe(B)}},[de,ce]);a.useEffect(()=>{const I=B=>{B.key==="Escape"&&t()};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[t]);const hn=a.useCallback(I=>{I.target===I.currentTarget&&t()},[t]),gn=[{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 En(I){if(!b?.project)return"inherited";const B=b.project[I.projectProviderKey],re=b.project[I.projectModelKey];return B!==void 0||re!==void 0?"overridden":"inherited"}function an(I){const B=c[I.projectProviderKey],re=c[I.projectModelKey];return B&&re?`${B}/${re}`:""}function Ft(I,B){if(B){const re=B.indexOf("/");u(pe=>({...pe,[I.projectProviderKey]:B.slice(0,re),[I.projectModelKey]:B.slice(re+1)}))}else{if(En(I)==="inherited")return;u(pe=>({...pe,[I.projectProviderKey]:void 0,[I.projectModelKey]:void 0}))}}function pn(I){En(I)!=="inherited"&&u(re=>({...re,[I.projectProviderKey]:void 0,[I.projectModelKey]:void 0}))}const Mn=a.useCallback(async()=>{if(!(E||ze))try{const I={...c,worktreeInitCommand:c.worktreeInitCommand?.trim()||void 0,taskPrefix:c.taskPrefix?.trim()||void 0},B={};for(const[pe,xe]of Object.entries(I))if(pk(pe)){const Re=p?.[pe];xe===void 0&&Re!==void 0?B[pe]=null:B[pe]=xe}const re={};for(const[pe,xe]of Object.entries(I)){if(pe==="githubTokenConfigured"||pe==="prAuthAvailable"||!fk(pe))continue;const Re=v?.project?.[pe];["planningProvider","planningModelId","validatorProvider","validatorModelId","executionProvider","executionModelId","titleSummarizerProvider","titleSummarizerModelId","defaultProviderOverride","defaultModelIdOverride","planningFallbackProvider","planningFallbackModelId","validatorFallbackProvider","validatorFallbackModelId","titleSummarizerFallbackProvider","titleSummarizerFallbackModelId"].includes(pe)?xe!==Re&&(xe==null&&Re!==void 0&&Re!==null?re[pe]=null:xe!==void 0&&(re[pe]=xe)):re[pe]=xe}await Promise.all([Object.keys(B).length>0?Jt(B):Promise.resolve(),Object.keys(re).length>0?Ta(re,s):Promise.resolve(),Ne!==dt.current?Hy({globalMaxConcurrent:Ne??4}):Promise.resolve()]),n("Settings saved","success"),t()}catch(I){n(fe(I),"error")}},[c,Ne,E,ze,p,v,t,n,s]),jn=a.useCallback(async()=>{try{await Ox(ht,_e,s),se(!1),n("Memory saved","success")}catch(I){n(fe(I)||"Failed to save memory","error")}},[ht,_e,s,n]),zn=a.useCallback(async()=>{Je(!0);try{const{path:I,content:B}=await Bx(ht,s),re=I??ht;ht!==re&&(Ge.current=!0),me(re),et(B),se(!1);const{files:pe}=await Zc(s);mt(pe),n("Memory file compacted","success")}catch(I){n(fe(I)||"Failed to compact memory","error")}finally{Je(!1)}},[ht,s,n]),rs=a.useCallback(async()=>{Qe(!0),st(null);try{const I=await qx(te,s);st(I),n(I.qmdAvailable?"Memory retrieval test complete":"qmd is not installed; local fallback was used",I.qmdAvailable?"success":"warning")}catch(I){n(fe(I)||"Failed to test memory retrieval","error")}finally{Qe(!1)}},[te,s,n]),Gn=a.useCallback(async()=>{ye(!0);try{const I=await Hx(s);await he(),n(I.qmdAvailable?"qmd installed successfully":"qmd install finished, but qmd is still unavailable",I.qmdAvailable?"success":"warning")}catch(I){n(fe(I)||"Failed to install qmd","error")}finally{ye(!1)}},[s,he,n]),Pn=()=>{if(!ze)return;const I=ze.name.trim();if(!I){n("Preset name is required","error");return}const B=c.modelPresets||[];let re;ie?re=ie:re=hM(I,B);const pe={id:re,name:I,executorProvider:ze.executorProvider,executorModelId:ze.executorModelId,validatorProvider:ze.validatorProvider,validatorModelId:ze.validatorModelId};u(xe=>{const Re=xe.modelPresets||[],pt=ie?Re.map(kt=>kt.id===ie?pe:kt):[...Re,pe];return{...xe,modelPresets:pt}}),Pe(null),$e(null)},G=()=>D==="global"?e.jsxs("div",{className:"settings-scope-banner settings-scope-global",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(Ni,{size:14})}),e.jsx("span",{children:"These settings are shared across all your Fusion projects."})]}):D==="project"?e.jsxs("div",{className:"settings-scope-banner settings-scope-project",children:[e.jsx("span",{className:"settings-scope-icon",children:e.jsx(Sn,{size:14})}),e.jsx("span",{children:"These settings only affect this project."})]}):null,Ke=()=>{switch(j){case"general":return e.jsxs(e.Fragment,{children:[G(),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:I=>{const B=I.target.value;u(re=>({...re,taskPrefix:B||void 0})),B&&!/^[A-Z]{1,10}$/.test(B)?T("Prefix must be 1–10 uppercase letters"):T(null)}}),E&&e.jsx("small",{className:"field-error",children:E}),!E&&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:I=>u(B=>({...B,requirePlanApproval:I.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:I=>u(B=>({...B,showQuickChatFAB:I.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 I=c.defaultProvider&&c.defaultModelId?`${c.defaultProvider}/${c.defaultModelId}`:"",B=gn.filter(re=>re.laneId!=="default");return e.jsxs(e.Fragment,{children:[G(),e.jsx("h4",{className:"settings-section-heading",children:"Default Model"}),F?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):O.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(Yt,{id:"defaultModel",label:"Default Model",models:O,value:I,onChange:re=>{if(!re)u(pe=>({...pe,defaultProvider:void 0,defaultModelId:void 0}));else{const pe=re.indexOf("/");u(xe=>({...xe,defaultProvider:re.slice(0,pe),defaultModelId:re.slice(pe+1)}))}},placeholder:"Use default",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt}),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(Yt,{id:"fallbackModel",label:"Fallback Model",models:O,value:c.fallbackProvider&&c.fallbackModelId?`${c.fallbackProvider}/${c.fallbackModelId}`:"",onChange:re=>{if(!re)u(pe=>({...pe,fallbackProvider:void 0,fallbackModelId:void 0}));else{const pe=re.indexOf("/");u(xe=>({...xe,fallbackProvider:re.slice(0,pe),fallbackModelId:re.slice(pe+1)}))}},placeholder:"No fallback",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt}),e.jsx("small",{children:"Used automatically if the primary default model hits a retryable provider error like rate limiting or overload."})]})]}),(()=>{const re=O.find(pe=>pe.provider===c.defaultProvider&&pe.id===c.defaultModelId);return re&&!re.reasoning?null:e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"defaultThinkingLevel",children:"Thinking Effort"}),e.jsxs("select",{id:"defaultThinkingLevel",value:c.defaultThinkingLevel||"",onChange:pe=>{const xe=pe.target.value;u(Re=>({...Re,defaultThinkingLevel:xe||void 0}))},children:[e.jsx("option",{value:"",children:"Default"}),gk.map(pe=>e.jsx("option",{value:pe,children:pe.charAt(0).toUpperCase()+pe.slice(1)},pe))]}),e.jsx("small",{children:"Controls how much reasoning effort the AI model uses. Higher levels produce better results but cost more."})]})})(),O.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Model Lanes"}),e.jsx("p",{className:"settings-description",children:"Global baseline models for each AI role. Project settings can override these per-project."}),B.map(re=>{const pe=c[re.globalProviderKey],xe=c[re.globalModelKey],Re=pe&&xe?`${pe}/${xe}`:"";return e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`global-${re.laneId}-model`,children:re.label}),e.jsx(Yt,{id:`global-${re.laneId}-model`,label:re.label,models:O,value:Re,onChange:pt=>{if(!pt){u(We=>({...We,[re.globalProviderKey]:void 0,[re.globalModelKey]:void 0}));return}const kt=pt.indexOf("/");u(We=>({...We,[re.globalProviderKey]:pt.slice(0,kt),[re.globalModelKey]:pt.slice(kt+1)}))},placeholder:"Use default",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt}),e.jsx("small",{children:re.helperText})]},`global-${re.laneId}`)})]}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"OpenRouter Models"}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"openrouterModelSync",className:"checkbox-label",children:[e.jsx("input",{id:"openrouterModelSync",type:"checkbox",checked:c.openrouterModelSync!==!1,onChange:re=>u(pe=>({...pe,openrouterModelSync:re.target.checked}))}),"Sync OpenRouter model list at dashboard startup"]}),e.jsx("small",{children:"When enabled, the dashboard fetches the latest available models from the OpenRouter API on startup, so the model picker always shows the most up-to-date catalog. Disable to skip the initial API call and use only the built-in model list."})]})]})}case"project-models":{const I=c.modelPresets||[],B=I.map(xe=>({id:xe.id,name:xe.name})),re=new Set(Object.values(c.defaultPresetBySize||{}).filter(Boolean)),pe=gn.filter(xe=>xe.laneId==="execution"||xe.laneId==="planning"||xe.laneId==="validator"||xe.laneId==="summarization");return e.jsxs(e.Fragment,{children:[G(),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:xe=>{const Re=xe.target.value;u(pt=>({...pt,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(xe=>({...xe,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."}),F?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):O.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No models available. Configure authentication first."}):e.jsx(e.Fragment,{children:pe.map(xe=>{const Re=En(xe),pt=an(xe),kt=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:`${xe.laneId}Model`,children:xe.label}),e.jsx("span",{className:`settings-lane-badge ${kt?"settings-lane-badge--override":"settings-lane-badge--inherited"}`,title:kt?"Explicitly set for this project":"Inherited from global settings",children:kt?"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(Yt,{id:`${xe.laneId}Model`,label:xe.label,models:O,value:pt,onChange:We=>Ft(xe,We),placeholder:"Use global",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt})}),kt&&e.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",title:"Reset to inherit from global",onClick:()=>pn(xe),style:{whiteSpace:"nowrap"},children:"Reset"})]}),e.jsxs("small",{children:[xe.helperText," Falls back to: ",xe.fallbackOrder,"."]})]},xe.laneId)})}),e.jsx("h4",{className:"settings-section-heading settings-section-heading--spaced",children:"Fallback Models"}),F?e.jsx("div",{className:"settings-empty-state",children:"Loading available models…"}):O.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(Yt,{id:"planningFallbackModel",label:"Planning Fallback Model",models:O,value:c.planningFallbackProvider&&c.planningFallbackModelId?`${c.planningFallbackProvider}/${c.planningFallbackModelId}`:"",onChange:xe=>{if(!xe)u(Re=>({...Re,planningFallbackProvider:void 0,planningFallbackModelId:void 0}));else{const Re=xe.indexOf("/");u(pt=>({...pt,planningFallbackProvider:xe.slice(0,Re),planningFallbackModelId:xe.slice(Re+1)}))}},placeholder:"Use global fallback",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt}),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(Yt,{id:"validatorFallbackModel",label:"Validator Fallback Model",models:O,value:c.validatorFallbackProvider&&c.validatorFallbackModelId?`${c.validatorFallbackProvider}/${c.validatorFallbackModelId}`:"",onChange:xe=>{if(!xe)u(Re=>({...Re,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0}));else{const Re=xe.indexOf("/");u(pt=>({...pt,validatorFallbackProvider:xe.slice(0,Re),validatorFallbackModelId:xe.slice(Re+1)}))}},placeholder:"Use global fallback",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt}),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"}),I.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No presets configured yet."}):e.jsx("div",{className:"settings-preset-list",children:I.map(xe=>{const Re=Yo(xe),pt=`${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:xe.name}),e.jsx("span",{className:"settings-muted settings-preset-summary",children:pt})]}),e.jsxs("div",{className:"settings-preset-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Pe(xe.id),$e({...xe})},children:"Edit"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{re.has(xe.id)&&!confirm(`Preset "${xe.name}" is used in auto-selection. Delete it anyway?`)||(u(kt=>({...kt,modelPresets:(kt.modelPresets||[]).filter(We=>We.id!==xe.id),defaultPresetBySize:Object.fromEntries(Object.entries(kt.defaultPresetBySize||{}).filter(([,We])=>We!==xe.id))})),ie===xe.id&&(Pe(null),$e(null)))},children:"Delete"})]})]},xe.id)})}),ze?null:e.jsx("div",{className:"settings-preset-actions",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Pe(null),$e({id:"",name:"",executorProvider:void 0,executorModelId:void 0,validatorProvider:void 0,validatorModelId:void 0})},children:"Add Preset"})})]}),ze?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:ze.name,onChange:xe=>{const Re=xe.target.value;$e(pt=>pt&&{...pt,name:Re})}})]}),O.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(Yt,{id:"preset-executor-model",label:"Preset executor model",models:O,value:ze.executorProvider&&ze.executorModelId?`${ze.executorProvider}/${ze.executorModelId}`:"",onChange:xe=>{if(!xe){$e(pt=>pt&&{...pt,executorProvider:void 0,executorModelId:void 0});return}const Re=xe.indexOf("/");$e(pt=>pt&&{...pt,executorProvider:xe.slice(0,Re),executorModelId:xe.slice(Re+1)})},placeholder:"Use default",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"preset-validator-model",children:"Validator model"}),e.jsx(Yt,{id:"preset-validator-model",label:"Preset validator model",models:O,value:ze.validatorProvider&&ze.validatorModelId?`${ze.validatorProvider}/${ze.validatorModelId}`:"",onChange:xe=>{if(!xe){$e(pt=>pt&&{...pt,validatorProvider:void 0,validatorModelId:void 0});return}const Re=xe.indexOf("/");$e(pt=>pt&&{...pt,validatorProvider:xe.slice(0,Re),validatorModelId:xe.slice(Re+1)})},placeholder:"Use default",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt})]})]})]}),e.jsxs("div",{className:"modal-actions settings-preset-editor-actions",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Pn,children:"Save preset"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Pe(null),$e(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:xe=>u(Re=>({...Re,autoSelectModelPreset:xe.target.checked}))}),"Auto-select preset based on task size"]})}),c.autoSelectModelPreset?e.jsx("div",{className:"settings-preset-size-grid",children:["S","M","L"].map(xe=>e.jsxs("div",{className:"form-group settings-preset-size-row",children:[e.jsx("label",{htmlFor:`preset-size-${xe}`,children:xe==="S"?"Small tasks (S):":xe==="M"?"Medium tasks (M):":"Large tasks (L):"}),e.jsxs("select",{id:`preset-size-${xe}`,value:c.defaultPresetBySize?.[xe]||"",onChange:Re=>{const pt=Re.target.value||void 0;u(kt=>({...kt,defaultPresetBySize:{...kt.defaultPresetBySize||{},[xe]:pt}}))},children:[e.jsx("option",{value:"",children:"No preset"}),B.map(Re=>e.jsx("option",{value:Re.id,children:Re.name},Re.id))]})]},xe))}):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:xe=>u(Re=>({...Re,autoSummarizeTitles:xe.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"}),F?e.jsx("small",{children:"Loading available models..."}):O.length===0?e.jsx("small",{children:"No models available. Configure authentication first."}):e.jsx(Yt,{id:"titleSummarizerModel",label:"Title summarization model",models:O,value:c.titleSummarizerProvider&&c.titleSummarizerModelId?`${c.titleSummarizerProvider}/${c.titleSummarizerModelId}`:"",onChange:xe=>{if(!xe){u(pt=>({...pt,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0}));return}const Re=xe.indexOf("/");u(pt=>({...pt,titleSummarizerProvider:xe.slice(0,Re),titleSummarizerModelId:xe.slice(Re+1)}))},placeholder:"Use fallback model",favoriteProviders:ce,onToggleFavorite:Ut,favoriteModels:de,onToggleModelFavorite:Xt}),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(xe=>({...xe,titleSummarizerProvider:xe.planningProvider,titleSummarizerModelId:xe.planningModelId})),disabled:!c.planningProvider||!c.planningModelId,children:"Use planning model"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>u(xe=>({...xe,titleSummarizerProvider:xe.defaultProvider,titleSummarizerModelId:xe.defaultModelId})),disabled:!c.defaultProvider||!c.defaultModelId,children:"Use default model"})]})})]})]})}case"appearance":return e.jsxs(e.Fragment,{children:[G(),e.jsx("h4",{className:"settings-section-heading",children:"Appearance"}),e.jsx(zM,{themeMode:r,colorTheme:l,onThemeModeChange:I=>{u(B=>({...B,themeMode:I})),o?.(I)},onColorThemeChange:I=>{u(B=>({...B,colorTheme:I})),d?.(I)}})]});case"scheduling":return e.jsxs(e.Fragment,{children:[G(),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:Ne??"",onChange:I=>{const B=I.target.value;at(B===""?void 0:Number(B))}}),e.jsx("small",{className:"form-text text-muted",children:"Maximum concurrent agents across all projects"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxConcurrent",children:"Max Concurrent Tasks"}),e.jsx("input",{id:"maxConcurrent",type:"number",min:1,max:10,value:c.maxConcurrent??"",onChange:I=>{const B=I.target.value;u(re=>({...re,maxConcurrent:B===""?void 0:Number(B)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"maxTriageConcurrent",children:"Max Triage Concurrent"}),e.jsx("input",{id:"maxTriageConcurrent",type:"number",min:1,max:10,value:c.maxTriageConcurrent??"",onChange:I=>{const B=I.target.value;u(re=>({...re,maxTriageConcurrent:B===""?void 0:Number(B)}))}}),e.jsx("small",{children:"Maximum concurrent triage/specification agents"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"pollIntervalMs",children:"Poll Interval (ms)"}),e.jsx("input",{id:"pollIntervalMs",type:"number",min:5e3,step:1e3,value:c.pollIntervalMs??"",onChange:I=>{const B=I.target.value;u(re=>({...re,pollIntervalMs:B===""?void 0:Number(B)}))}})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"taskStuckTimeoutMs",children:"Stuck Task Timeout (minutes)"}),e.jsx("input",{id:"taskStuckTimeoutMs",type:"number",min:1,step:1,value:c.taskStuckTimeoutMs?Math.round(c.taskStuckTimeoutMs/6e4):"",onChange:I=>{const B=I.target.value,re=Number(B);u(pe=>({...pe,taskStuckTimeoutMs:B&&re>0?re*6e4:void 0}))}}),e.jsx("small",{children:"Timeout in minutes for detecting stuck tasks. When a task's agent session shows no activity for longer than this duration, the task is terminated and retried. Leave empty to disable. Suggested: 10."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"specStalenessEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"specStalenessEnabled",type:"checkbox",checked:c.specStalenessEnabled||!1,onChange:I=>u(B=>({...B,specStalenessEnabled:I.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:I=>{const B=I.target.value,re=Number(B);u(pe=>({...pe,specStalenessMaxAgeMs:B!==""?re*36e5:void 0}))},disabled:!c.specStalenessEnabled}),e.jsx("small",{children:"Maximum age in hours before a specification is considered stale. Default: 6 hours."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"autoArchiveDoneTasksEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"autoArchiveDoneTasksEnabled",type:"checkbox",checked:c.autoArchiveDoneTasksEnabled??!0,onChange:I=>u(B=>({...B,autoArchiveDoneTasksEnabled:I.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/cm):KM,onChange:I=>{const B=I.target.value,re=Number(B);u(pe=>({...pe,autoArchiveDoneAfterMs:B===""?void 0:re*cm}))},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:I=>u(B=>({...B,archiveAgentLogMode:I.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:I=>{const B=I.target.value,re=Number(B);u(pe=>({...pe,maxStuckKills:B&&re>0?re:void 0}))}}),e.jsx("small",{children:"Maximum stuck-detector retries before a task is marked failed. Default: 6."})]}),e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:"groupOverlappingFiles",className:"checkbox-label",children:[e.jsx("input",{id:"groupOverlappingFiles",type:"checkbox",checked:c.groupOverlappingFiles,onChange:I=>u(B=>({...B,groupOverlappingFiles:I.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:I=>u(B=>({...B,runStepsInNewSessions:I.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:I=>{const B=I.target.value;u(re=>({...re,maxParallelSteps:B===""?void 0:Number(B)}))},disabled:!c.runStepsInNewSessions}),e.jsx("small",{children:"Maximum number of steps to run in parallel when file scopes don't overlap (1-4)"})]})]});case"worktrees":return e.jsxs(e.Fragment,{children:[G(),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:I=>{const B=I.target.value;u(re=>({...re,maxWorktrees:B===""?void 0:Number(B)}))}}),e.jsx("small",{children:"Limits total git worktrees including in-review tasks"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"worktreeInitCommand",children:"Worktree Init Command"}),e.jsx("input",{id:"worktreeInitCommand",type:"text",placeholder:"pnpm install --frozen-lockfile",value:c.worktreeInitCommand||"",onChange:I=>u(B=>({...B,worktreeInitCommand:I.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:I=>u(B=>({...B,recycleWorktrees:I.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:I=>u(B=>({...B,worktreeNaming:I.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:I=>u(B=>({...B,worktreeRebaseBeforeMerge:I.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:I=>u(B=>({...B,worktreeRebaseRemote:I.target.value||void 0})),children:[e.jsx("option",{value:"",children:"Use git default"}),Le.map(I=>e.jsxs("option",{value:I.name,children:[I.name," (",I.fetchUrl,")"]},I.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:[G(),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:I=>u(B=>({...B,testCommand:I.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:I=>u(B=>({...B,buildCommand:I.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:[G(),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:I=>u(B=>({...B,autoMerge:I.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:I=>u(B=>({...B,mergeStrategy:I.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:I=>u(B=>({...B,includeTaskIdInCommit:I.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:I=>u(B=>({...B,commitAuthorEnabled:I.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:I=>u(B=>({...B,commitAuthorName:I.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:I=>u(B=>({...B,commitAuthorEmail:I.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:I=>u(B=>({...B,autoResolveConflicts:I.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:I=>u(B=>({...B,smartConflictResolution:I.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:I=>u(B=>({...B,pushAfterMerge:I.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:I=>u(B=>({...B,pushRemote:I.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:I,status:B,loading:re,error:pe}={capabilities:ee,status:Oe,loading:Ie,error:xt},xe=c.memoryEnabled!==!1,Re=I?.writable??!0,pt=xe&&Re,kt=Ye.find(wt=>wt.path===ht),We={"long-term":"Long-term",daily:"Daily",dreams:"Dreams"};return e.jsxs(e.Fragment,{children:[G(),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:wt=>u(ae=>({...ae,memoryEnabled:wt.target.checked}))}),"Enable memory tools"]}),e.jsx("small",{children:"Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback."})]}),re?e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"settings-muted",children:"Checking memory write access..."})}):pe?e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Failed to load backend status: ",pe]})}):null,B?.qmdAvailable===!1&&e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:["qmd is not installed. Search will use local files. Install indexed retrieval: ",e.jsx("code",{children:B.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Gn,disabled:it,children:it?"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:wt=>u(ae=>({...ae,memoryAutoSummarizeEnabled:wt.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:wt=>u(ae=>({...ae,memoryAutoSummarizeThresholdChars:parseInt(wt.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:wt=>u(ae=>({...ae,memoryAutoSummarizeSchedule:wt.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:wt=>u(ae=>({...ae,memoryDreamsEnabled:wt.target.checked})),disabled:!xe}),"Process dreams from daily memory"]}),e.jsx("small",{children:"Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md."})]}),xe&&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:wt=>u(ae=>({...ae,memoryDreamsSchedule:wt.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:te,onChange:wt=>je(wt.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:rs,disabled:Ae,children:Ae?"Testing…":"Test Retrieval"})}),be&&e.jsxs("div",{className:"memory-test-result",children:[e.jsxs("strong",{children:[be.results.length," result",be.results.length===1?"":"s"," ",'for "',be.query,'"']}),e.jsxs("small",{children:["qmd ",be.qmdAvailable?"available":"missing"," · ",be.usedFallback?"local fallback used":"qmd path used"]}),be.results.length>0?e.jsx("ul",{children:be.results.map((wt,ae)=>e.jsxs("li",{children:[e.jsxs("span",{children:[wt.path,":",wt.lineStart]}),e.jsx("p",{children:wt.snippet})]},`${wt.path}-${wt.lineStart}-${ae}`))}):e.jsx("small",{children:"No matching memory found."})]})]}),!xe&&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."}),xe&&!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."}),le?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:ht,onChange:wt=>{me(wt.target.value),se(!1)},disabled:ke,children:Ye.map(wt=>e.jsxs("option",{value:wt.path,children:[wt.label," - ",wt.path]},wt.path))}),e.jsx("small",{children:ke?"Save or discard the current edits before switching files.":"Choose any project memory file to view or edit. Dreams is selected by default."})]}),kt&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:We[kt.layer]}),e.jsx("strong",{children:kt.path}),e.jsxs("small",{children:[kt.size.toLocaleString()," bytes · updated ",new Date(kt.updatedAt).toLocaleString()]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:kt?.label||"Memory Editor"}),e.jsxs("small",{children:[kt?.layer==="long-term"&&"Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams.",kt?.layer==="daily"&&"Raw daily observations, open loops, and running context for dream processing.",kt?.layer==="dreams"&&"Synthesized patterns and open loops promoted from daily memory.",!kt&&"Edits the selected memory file."]}),e.jsx("div",{className:"memory-editor-frame",children:e.jsx(ef,{content:_e,onChange:wt=>{et(wt),se(!0)},readOnly:!pt,filePath:ht})})]})]}),!le&&e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:zn,disabled:!pt||ke||Se,children:Se?"Compacting…":"Compact Selected File"}),e.jsx("small",{children:ke?"Save or discard edits before compacting this file.":`Compacts ${ht} and writes the result back to the same file.`})]}),ke&&pt&&e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:jn,children:"Save Memory"})}),ke&&!pt&&e.jsx("div",{className:"form-group",children:e.jsxs("small",{className:"field-error",children:["Cannot save: ",xe?"Backend is read-only":"Memory is disabled"]})})]})}case"experimental":{const I=c.experimentalFeatures??{},re=Array.from(new Set([...Object.keys(dm),...Object.keys(I)])).sort((pe,xe)=>pe.localeCompare(xe)).map(pe=>[pe,I[pe]===!0]);return e.jsxs(e.Fragment,{children:[G(),e.jsx("h4",{className:"settings-section-heading",children:"Experimental Features"}),e.jsx("div",{className:"form-group",children:e.jsx("small",{children:"Experimental features are early capabilities that are not yet fully stable. Enable them to test new functionality, but be aware they may change or be removed."})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Feature Flags"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-sm)"},children:re.map(([pe,xe])=>e.jsxs("label",{htmlFor:`experimental-${pe}`,className:"checkbox-label",children:[e.jsx("input",{id:`experimental-${pe}`,type:"checkbox",checked:xe,onChange:Re=>{u(pt=>({...pt,experimentalFeatures:{...pt.experimentalFeatures??{},[pe]:Re.target.checked}}))}}),e.jsx("span",{children:dm[pe]??pe})]},pe))})]})]})}case"backups":return e.jsxs(e.Fragment,{children:[G(),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:I=>u(B=>({...B,autoBackupEnabled:I.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:I=>u(B=>({...B,autoBackupSchedule:I.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:I=>{const B=I.target.value;u(re=>({...re,autoBackupRetention:B===""?void 0:Number(B)}))},disabled:!c.autoBackupEnabled}),e.jsx("small",{children:"Number of backup files to keep (oldest are deleted first). Range: 1-100."}),c.autoBackupRetention!==void 0&&(c.autoBackupRetention<1||c.autoBackupRetention>100)&&e.jsx("small",{className:"field-error",children:"Must be between 1 and 100"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"autoBackupDir",children:"Backup Directory"}),e.jsx("input",{id:"autoBackupDir",type:"text",placeholder:".fusion/backups",value:c.autoBackupDir||".fusion/backups",onChange:I=>u(B=>({...B,autoBackupDir:I.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 (..)"})]}),Te?e.jsx("div",{className:"settings-empty-state",children:"Loading backup info…"}):He?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:He.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:He.totalSize>1024*1024?`${(He.totalSize/(1024*1024)).toFixed(1)} MB`:`${(He.totalSize/1024).toFixed(1)} KB`}),e.jsx("span",{className:"backup-stat-label",children:"total size"})]})]}),He.backups.length>0&&e.jsxs("details",{className:"backup-list",children:[e.jsxs("summary",{children:["View ",He.backups.length," backup(s)"]}),e.jsxs("ul",{children:[He.backups.slice(0,10).map(I=>e.jsxs("li",{children:[e.jsx("code",{children:I.filename}),e.jsx("span",{className:"backup-size",children:I.size>1024*1024?`${(I.size/(1024*1024)).toFixed(1)} MB`:`${(I.size/1024).toFixed(1)} KB`})]},I.filename)),He.backups.length>10&&e.jsx("li",{children:e.jsxs("em",{children:["...and ",He.backups.length-10," more"]})})]})]})]}):null,e.jsx("div",{className:"form-group",children:e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Wt,disabled:Te,children:Te?"Creating…":"Backup Now"})})]});case"notifications":return e.jsxs(e.Fragment,{children:[G(),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:I=>u(B=>({...B,ntfyEnabled:I.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:I=>{const B=I.target.value;u(re=>({...re,ntfyTopic:B||void 0}))}}),e.jsxs("small",{children:["Your ntfy.sh topic name (1–64 alphanumeric/hyphen/underscore characters)."," ",e.jsx("a",{href:"https://ntfy.sh",target:"_blank",rel:"noopener noreferrer",children:"Learn more about ntfy.sh"})]}),c.ntfyTopic&&!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic)&&e.jsx("small",{className:"field-error",children:"Topic must be 1–64 alphanumeric, hyphen, or underscore characters"}),e.jsxs("details",{className:"ntfy-advanced-disclosure",children:[e.jsx("summary",{children:"Advanced"}),e.jsxs("div",{className:"ntfy-advanced-content",children:[e.jsx("label",{htmlFor:"ntfyBaseUrl",children:"Custom ntfy server URL (optional)"}),e.jsx("input",{id:"ntfyBaseUrl",type:"url",placeholder:"https://ntfy.sh",value:c.ntfyBaseUrl||"",onChange:I=>{const B=I.target.value;u(re=>({...re,ntfyBaseUrl:B||void 0}))}}),e.jsx("small",{children:"Leave blank to keep the default server: https://ntfy.sh. Custom servers must use http:// or https://."})]})]}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Kn,disabled:we||!c.ntfyTopic||!/^[a-zA-Z0-9_-]{1,64}$/.test(c.ntfyTopic),children:we?"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:I=>{const B=c.ntfyEvents??[...Bi],re=I.target.checked?B.includes("in-review")?B:[...B,"in-review"]:B.filter(pe=>pe!=="in-review");u(pe=>({...pe,ntfyEvents:re.length>0?re:void 0}))}}),"Task completed (in-review)"]}),e.jsx("small",{children:"When a task moves to In Review (ready for review)"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("merged")??!0,onChange:I=>{const B=c.ntfyEvents??[...Bi],re=I.target.checked?B.includes("merged")?B:[...B,"merged"]:B.filter(pe=>pe!=="merged");u(pe=>({...pe,ntfyEvents:re.length>0?re:void 0}))}}),"Task merged"]}),e.jsx("small",{children:"When a task is successfully merged to main"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("failed")??!0,onChange:I=>{const B=c.ntfyEvents??[...Bi],re=I.target.checked?B.includes("failed")?B:[...B,"failed"]:B.filter(pe=>pe!=="failed");u(pe=>({...pe,ntfyEvents:re.length>0?re:void 0}))}}),"Task failed"]}),e.jsx("small",{children:"When a task fails during execution (high priority)"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("awaiting-approval")??!0,onChange:I=>{const B=c.ntfyEvents??[...Bi],re=I.target.checked?B.includes("awaiting-approval")?B:[...B,"awaiting-approval"]:B.filter(pe=>pe!=="awaiting-approval");u(pe=>({...pe,ntfyEvents:re.length>0?re:void 0}))}}),"Plan needs approval"]}),e.jsx("small",{children:"When a task specification needs manual approval before execution"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("awaiting-user-review")??!0,onChange:I=>{const B=c.ntfyEvents??[...Bi],re=I.target.checked?B.includes("awaiting-user-review")?B:[...B,"awaiting-user-review"]:B.filter(pe=>pe!=="awaiting-user-review");u(pe=>({...pe,ntfyEvents:re.length>0?re:void 0}))}}),"User review needed"]}),e.jsx("small",{children:"When an agent hands off a task for human review (high priority)"}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:c.ntfyEvents?.includes("planning-awaiting-input")??!0,onChange:I=>{const B=c.ntfyEvents??[...Bi],re=I.target.checked?B.includes("planning-awaiting-input")?B:[...B,"planning-awaiting-input"]:B.filter(pe=>pe!=="planning-awaiting-input");u(pe=>({...pe,ntfyEvents:re.length>0?re:void 0}))}}),"Planning needs input"]}),e.jsx("small",{children:"When planning mode is waiting for your response to continue"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"ntfyDashboardHost",children:"Dashboard Hostname"}),e.jsx("input",{id:"ntfyDashboardHost",type:"text",placeholder:"http://localhost:3000",value:c.ntfyDashboardHost||"",onChange:I=>{const B=I.target.value;u(re=>({...re,ntfyDashboardHost:B||void 0}))}}),e.jsx("small",{children:"Base URL for deep links in notifications. When set, clicking a notification opens the dashboard directly to the task."}),c.ntfyDashboardHost&&!/^https?:\/\/.+/.test(c.ntfyDashboardHost)&&e.jsx("small",{className:"field-error",children:"Must be a valid URL starting with http:// or https://"})]})]})]});case"node-sync":return e.jsxs(e.Fragment,{children:[G(),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:I=>u(B=>({...B,settingsSyncEnabled:I.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:I=>u(B=>({...B,settingsSyncAuth:I.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:I=>u(B=>({...B,settingsSyncInterval:parseInt(I.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:I=>u(B=>({...B,settingsSyncConflictResolution:I.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:[G(),e.jsx("h4",{className:"settings-section-heading",children:"Prompts"}),e.jsx(qM,{value:c.agentPrompts,onChange:I=>{u(B=>({...B,agentPrompts:I}))},promptOverrides:c.promptOverrides,onPromptOverridesChange:I=>{u(B=>({...B,promptOverrides:I}))}})]});case"plugins":return e.jsxs(e.Fragment,{children:[G(),e.jsx("h4",{className:"settings-section-heading",children:"Plugins"}),e.jsxs("div",{className:"settings-plugins-subsection-toggle",role:"tablist","aria-label":"Plugin manager type",children:[e.jsx("button",{type:"button",id:"plugins-tab-fusion-plugins",role:"tab","aria-controls":"plugins-panel-fusion-plugins","aria-selected":w==="fusion-plugins",tabIndex:w==="fusion-plugins"?0:-1,className:`settings-plugins-subsection-btn${w==="fusion-plugins"?" active":""}`,onClick:()=>S("fusion-plugins"),children:"Fusion Plugins"}),e.jsx("button",{type:"button",id:"plugins-tab-pi-extensions",role:"tab","aria-controls":"plugins-panel-pi-extensions","aria-selected":w==="pi-extensions",tabIndex:w==="pi-extensions"?0:-1,className:`settings-plugins-subsection-btn${w==="pi-extensions"?" active":""}`,onClick:()=>S("pi-extensions"),children:"Pi Extensions"})]}),e.jsx("div",{id:"plugins-panel-fusion-plugins",role:"tabpanel","aria-labelledby":"plugins-tab-fusion-plugins",className:"settings-plugins-subsection-panel",hidden:w!=="fusion-plugins",children:w==="fusion-plugins"&&e.jsxs(e.Fragment,{children:[e.jsx(a.Suspense,{fallback:null,children:e.jsx(VM,{addToast:n,projectId:s})}),e.jsx(nr,{slotId:"settings-section",projectId:s})]})}),e.jsx("div",{id:"plugins-panel-pi-extensions",role:"tabpanel","aria-labelledby":"plugins-tab-pi-extensions",className:"settings-plugins-subsection-panel",hidden:w!=="pi-extensions",children:w==="pi-extensions"&&e.jsx(a.Suspense,{fallback:null,children:e.jsx(WM,{addToast:n,projectId:s})})})]});case"authentication":{const I=Z.filter(Re=>Re.type==="cli"),re=[...Z.filter(Re=>Re.type!=="cli")].sort((Re,pt)=>Re.authenticated!==pt.authenticated?Re.authenticated?-1:1:Re.name.localeCompare(pt.name)),pe=re.filter(Re=>Re.authenticated),xe=re.filter(Re=>!Re.authenticated);return e.jsxs(e.Fragment,{children:[e.jsx("h4",{className:"settings-section-heading",children:"Authentication"}),R?e.jsx("div",{className:"settings-empty-state",children:"Loading authentication status…"}):Z.length===0?e.jsx("div",{className:"settings-empty-state settings-muted",children:"No providers available"}):e.jsxs(e.Fragment,{children:[I.some(Re=>Re.id==="claude-cli")&&e.jsx(tf,{compact:!0,authenticated:I.find(Re=>Re.id==="claude-cli")?.authenticated??!1,onToggled:()=>{Be()}}),pe.length===0&&e.jsx("div",{className:"auth-section-hint",children:"Sign in to at least one provider to get started with AI models."}),pe.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Authenticated"}),pe.map(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:z[Re.id]??"",onChange:pt=>J(kt=>({...kt,[Re.id]:pt.target.value})),disabled:W===Re.id}),Re.authenticated&&!z[Re.id]?e.jsx("button",{className:"btn btn-sm",onClick:()=>mn(Re.id),disabled:W===Re.id,children:"Clear"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>yn(Re.id),disabled:W===Re.id,children:"Save"})]}),W===Re.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),C[Re.id]&&e.jsx("small",{className:"auth-apikey-error",children:C[Re.id]})]}):e.jsx("div",{children:W===Re.id?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>Kt(Re.id),children:"Logout"})})]})},Re.id))]}),xe.length>0&&e.jsxs("div",{className:"auth-provider-group",children:[e.jsx("div",{className:"auth-group-label",children:"Available"}),xe.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:z[Re.id]??"",onChange:pt=>J(kt=>({...kt,[Re.id]:pt.target.value})),disabled:W===Re.id}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>yn(Re.id),disabled:W===Re.id,children:"Save"})]}),W===Re.id&&e.jsx("small",{className:"auth-apikey-progress",children:"Saving…"}),C[Re.id]&&e.jsx("small",{className:"auth-apikey-error",children:C[Re.id]})]}):e.jsxs("div",{children:[W===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:()=>gt(Re.id),children:"Login"}),H[Re.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`auth-login-instructions-${Re.id}`,children:H[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:hn,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:[k&&e.jsxs("div",{className:"settings-mobile-section-picker",children:[e.jsx("label",{htmlFor:"settings-mobile-section",children:"Settings Section"}),e.jsx("select",{id:"settings-mobile-section",className:"select touch-target",value:j,onChange:I=>P(I.target.value),children:Ir.filter(I=>!I.isGroupHeader).map(I=>e.jsx("option",{value:I.id,children:I.label},I.id))})]}),e.jsx("nav",{className:"settings-sidebar",children:Ir.map(I=>I.isGroupHeader?e.jsx("div",{className:"settings-group-header",children:I.label},I.id):e.jsxs("button",{className:`settings-nav-item${j===I.id?" active":""}`,onClick:()=>P(I.id),title:I.scope==="global"?"Shared across all projects":I.scope==="project"?"Specific to this project":void 0,children:[I.scope==="global"&&e.jsx(Ni,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),I.scope==="project"&&e.jsx(Sn,{className:"settings-scope-icon","aria-label":"Project setting",size:16}),I.icon&&!I.scope&&e.jsx(I.icon,{className:"settings-scope-icon","aria-label":"Global setting",size:16}),I.label]},I.id))}),e.jsx("div",{className:"settings-content",children:Ke()})]}),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:Cn,title:"Export settings to JSON file",children:"Export"}),e.jsx("input",{type:"file",ref:ge,accept:".json,application/json",style:{display:"none"},onChange:Tn}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ge.current?.click(),disabled:Nt,title:"Import settings from JSON file",children:Nt?"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:Mn,disabled:h,children:"Save"})]})]})]}),vt&&Mt&&e.jsx("div",{className:"modal-overlay open",onClick:I=>I.target===I.currentTarget&&It(!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:()=>It(!1),"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[e.jsx("p",{children:"Review the settings to be imported:"}),Mt.global&&Object.keys(Mt.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(Mt.global).filter(([,I])=>I!==void 0).map(([I])=>e.jsx("li",{children:I},I))})]}),Mt.project&&Object.keys(Mt.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(Mt.project).filter(([,I])=>I!==void 0).map(([I])=>e.jsx("li",{children:I},I))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"import-scope",children:"Import Scope:"}),e.jsxs("select",{id:"import-scope",value:tt,onChange:I=>bt(I.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:Ue,onChange:I=>ot(I.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:()=>It(!1),children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:as,disabled:Nt,children:Nt?"Importing…":"Confirm Import"})]})]})})]})}const JM=640;function YM({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([]),[v,y]=a.useState(null),[M,j]=a.useState([]),[P,w]=a.useState(null),[S,k]=a.useState(null),[_,E]=a.useState(!1),[T,D]=a.useState([]),[Z,$]=a.useState(!1),[R,N]=a.useState(""),W=a.useRef(!1),[Y,H]=a.useState(!1),[A,z]=a.useState("list"),J=a.useRef(null),C=new Set;for(const se of i){const Le=se.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Le&&C.add(Le[1]);const ve=se.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);ve&&C.add(ve[1])}a.useEffect(()=>{if(t)return o(""),m(""),u(""),x([]),y(null),j([]),w(null),f("issues"),k(null),E(!1),D([]),$(!0),N(""),J.current=null,W.current=!0,dv().then(se=>{if(W.current)if(D(se),$(!1),se.length===1){const Le=se[0];o(Le.owner),m(Le.repo),N(Le.name)}else se.length>1&&(o(""),m(""),N(""))}).catch(()=>{W.current&&$(!1)}),()=>{W.current=!1}},[t]);const q=a.useCallback(se=>{if(N(se),se==="")o(""),m("");else{const Le=T.find(ve=>ve.name===se);Le&&(o(Le.owner),m(Le.repo))}},[T]),oe=a.useCallback(async()=>{if(!l.trim()||!d.trim()){k("Repository must be selected");return}g(!0),k(null),x([]),y(null);try{const se=c.split(",").map(ve=>ve.trim()).filter(Boolean),Le=await rv(l.trim(),d.trim(),30,se.length>0?se:void 0);x(Le),Le.length===0&&k("No open issues found")}catch(se){k(fe(se)||"Failed to fetch issues")}finally{g(!1)}},[l,d,c]),O=a.useCallback(async()=>{if(!l.trim()||!d.trim()){k("Repository must be selected");return}g(!0),k(null),j([]),w(null);try{const se=await ov(l.trim(),d.trim(),30);j(se),se.length===0&&k("No open pull requests found")}catch(se){k(fe(se)||"Failed to fetch pull requests")}finally{g(!1)}},[l,d]);a.useEffect(()=>{if(!t||!l.trim()||!d.trim()||h||_)return;const se={owner:l.trim(),repo:d.trim(),labels:c.trim(),tab:p};J.current?.owner===se.owner&&J.current?.repo===se.repo&&J.current?.labels===se.labels&&J.current?.tab===se.tab||(J.current=se,p==="issues"?oe():O())},[l,d,c,p,t,h,_,oe,O]),a.useEffect(()=>{if(!t)return;const se=Le=>{Le.key==="Escape"&&n()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[t,n]),a.useEffect(()=>{if(!t)return;const se=()=>{H(window.innerWidth<=JM)};return se(),window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[t]);const V=a.useCallback(se=>{y(se),Y&&z("preview")},[Y]),F=a.useCallback(se=>{w(se),Y&&z("preview")},[Y]),ue=a.useCallback(()=>{z("list")},[]),ce=a.useCallback(async()=>{if(p==="issues"){if(v===null)return;E(!0),k(null);try{const se=await lv(l.trim(),d.trim(),v,r);s(se),n()}catch(se){const Le=fe(se);Le?.includes("already imported")?k(Le):k(Le||"Failed to import issue")}finally{E(!1)}}else{if(P===null)return;E(!0),k(null);try{const se=await cv(l.trim(),d.trim(),P,r);s(se),n()}catch(se){const Le=fe(se);Le?.includes("already imported")?k(Le):k(Le||"Failed to import pull request")}finally{E(!1)}}},[p,v,P,l,d,s,n]),K=b.find(se=>se.number===v),de=M.find(se=>se.number===P);if(!t)return null;const Fe=T.length>0,we=T.length===1,Ee=b.filter(se=>C.has(se.html_url)).length,ie=M.filter(se=>C.has(se.html_url)).length,Pe=S==="No open issues found",ze=S==="No open pull requests found",$e=p==="issues"?Pe:ze,He=!!S&&!Pe&&b.length===0&&!h,Me=!!S&&!ze&&M.length===0&&!h,Te=p==="issues"?He:Me,Ve=h||b.length>0||Pe||He,_e=h||M.length>0||ze||Me,et=p==="issues"?Ve:_e,le=!!S&&b.length>0&&!Pe,X=!!S&&M.length>0&&!ze,ke=p==="issues"?le:X;return e.jsx("div",{className:"modal-overlay open",onClick:se=>se.target===se.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||_,children:[e.jsx(sl,{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"),y(null)},disabled:h||_,children:[e.jsx(es,{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(ut,{size:16,className:"spin"}),e.jsx("span",{children:"Detecting…"})]}):Fe?we?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:T[0].name}),e.jsxs("span",{className:"github-import-remote-pill__repo",children:[T[0].owner,"/",T[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:R,onChange:se=>q(se.target.value),disabled:h||_,"aria-label":"Select Git remote",children:[e.jsx("option",{value:"",children:"Select remote…"}),T.map(se=>e.jsxs("option",{value:se.name,children:[se.name," (",se.owner,"/",se.repo,")"]},se.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:se=>u(se.target.value),onKeyDown:se=>se.key==="Enter"&&oe(),disabled:h||_||!Fe,"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"?oe:O,disabled:h||_||!l.trim()||!d.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?e.jsx(ut,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!Z&&!Fe&&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"})]}),ke&&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":""} ${A==="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:[Ee," 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:[ie," imported"]})]})]}),e.jsxs("div",{className:"github-import-pane-content",children:[!et&&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(ut,{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."})]})]}),Te&&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})]})}),$e&&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(se=>{const Le=C.has(se.html_url);return e.jsxs("div",{className:`issue-item ${v===se.number?"selected":""} ${Le?"imported":""}`,onClick:()=>!Le&&V(se.number),children:[e.jsx("input",{type:"radio",name:"issue",checked:v===se.number,onChange:()=>V(se.number),disabled:Le,"aria-label":`Select issue #${se.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",se.number]}),e.jsx("span",{className:"issue-title",children:se.title})]}),se.labels.length>0&&e.jsx("span",{className:"issue-labels",children:se.labels.map(ve=>e.jsx("span",{className:"label-chip",children:ve.name},ve.name))})]}),Le&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},se.number)})}),p==="pulls"&&M.length>0&&e.jsx("div",{className:"issues-list","aria-live":"polite",children:M.map(se=>{const Le=C.has(se.html_url);return e.jsxs("div",{className:`issue-item ${P===se.number?"selected":""} ${Le?"imported":""}`,onClick:()=>!Le&&F(se.number),children:[e.jsx("input",{type:"radio",name:"pull",checked:P===se.number,onChange:()=>F(se.number),disabled:Le,"aria-label":`Select pull request #${se.number}`}),e.jsxs("div",{className:"issue-main",children:[e.jsxs("div",{className:"issue-heading-row",children:[e.jsxs("span",{className:"issue-number",children:["#",se.number]}),e.jsx("span",{className:"issue-title",children:se.title})]}),e.jsxs("span",{className:"pull-branch-info",children:[se.headBranch," → ",se.baseBranch]})]}),Le&&e.jsx("span",{className:"imported-badge",children:"Imported"})]},se.number)})})]})]}),e.jsxs("section",{className:`github-import-preview-pane ${Y?"mobile":""} ${A==="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:ue,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[e.jsx(oa,{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:_,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:ce,disabled:(p==="issues"?v===null:P===null)||_,children:_?e.jsx(ut,{size:14,className:"spin"}):"Import"})]})]})})}const QM=["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 XM(t,n){return t&&n?`${t}/${n}`:""}function ZM(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 eA({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,v]=a.useState([]),[y,M]=a.useState(null),j=a.useRef(!1),P=a.useRef(!1),[w,S]=a.useState(""),[k,_]=a.useState(!0),[E,T]=a.useState(!1),[D,Z]=a.useState(!1),$=a.useRef(null),R=a.useRef(null),N=a.useRef(null),[W,Y]=a.useState(d??null),H=a.useMemo(()=>Pi(),[]),{isLockedByOther:A,takeControl:z,isLoading:J}=ul(t?W:null),{activeTabMap:C,broadcastUpdate:q,broadcastCompleted:oe,broadcastLock:O,broadcastUnlock:V,broadcastHeartbeat:F}=ua(),[ue,ce]=a.useState(void 0),[K,de]=a.useState(void 0),[Fe,we]=a.useState([]),[Ee,ie]=a.useState(!1),[Pe,ze]=a.useState(null),[$e,He]=a.useState([]),[Me,Te]=a.useState([]),Ve=a.useRef(null),_e=XM(ue,K),et=a.useCallback((ye,Ge)=>{if(!ye||!Ge)return"Using default";const Ne=Fe.find(at=>at.provider===ye&&at.id===Ge);return Ne?`${Ne.provider}/${Ne.id}`:`${ye}/${Ge}`},[Fe]),le=a.useCallback(async()=>{ie(!0),ze(null);try{const ye=await Vn();we(ye.models),He(ye.favoriteProviders),Te(ye.favoriteModels)}catch(ye){ze(fe(ye)||"Failed to load models")}finally{ie(!1)}},[]),X=a.useCallback(ye=>{He(Ge=>{const Ne=Ge,dt=Ne.includes(ye)?Ne.filter(vt=>vt!==ye):[ye,...Ne];return Jt({favoriteProviders:dt,favoriteModels:Me}).catch(()=>{He(Ne)}),dt})},[Me]),ke=a.useCallback(ye=>{Te(Ge=>{const Ne=Ge,dt=Ne.includes(ye)?Ne.filter(vt=>vt!==ye):[ye,...Ne];return Jt({favoriteProviders:$e,favoriteModels:dt}).catch(()=>{Te(Ne)}),dt})},[$e]),se=a.useCallback(ye=>{R.current?.close();const Ge=ly(ye,o,{onThinking:Ne=>{S(at=>at+Ne),q({sessionId:ye,status:"generating",needsInput:!1,owningTabId:H,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onQuestion:Ne=>{T(!1),Z(!1),Di(o),h({type:"question",session:{sessionId:ye,currentQuestion:Ne,summary:null}}),S(""),q({sessionId:ye,status:"awaiting_input",needsInput:!0,owningTabId:H,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onSummary:Ne=>{T(!1),Z(!1),Di(o),h({type:"summary",session:{sessionId:ye,currentQuestion:null,summary:Ne},summary:Ne}),M(Ne),S(""),q({sessionId:ye,status:"complete",needsInput:!1,owningTabId:H,type:"planning",title:m.trim()||"Planning session",projectId:o??null})},onError:Ne=>{const at=Ne||"Session failed while contacting the AI.";T(!0),(async()=>{try{const dt=await ti(ye);if(dt&&(dt.status==="generating"||dt.status==="awaiting_input")){se(ye);return}}catch{}T(!1),Z(!1),p(null),h(dt=>dt.type==="question"||dt.type==="summary"||dt.type==="error"?{type:"error",session:dt.session,errorMessage:at}:{type:"error",session:{sessionId:ye,currentQuestion:null,summary:null},errorMessage:at}),S(""),N.current=ye,q({sessionId:ye,status:"error",needsInput:!1,owningTabId:H,type:"planning",title:m.trim()||"Planning session",projectId:o??null}),oe({sessionId:ye,status:"error"})})()},onComplete:()=>{T(!1),Z(!1),N.current=null,oe({sessionId:ye,status:"complete"})},onConnectionStateChange:Ne=>{T(Ne==="reconnecting")}});R.current=Ge},[oe,q,m,o,H]),Le=a.useCallback(async ye=>{const Ge=ye??m;if(Ge.trim()){p(null),S(""),v([]),b([]),T(!1),h({type:"loading"});try{const Ne=ue&&K?{planningModelProvider:ue,planningModelId:K}:void 0,{sessionId:at}=await Vv(Ge.trim(),o,Ne);N.current=at,Y(at),se(at),b([])}catch(Ne){T(!1),p(fe(Ne)||"Failed to start planning session"),h({type:"initial"}),N.current=null,Y(null)}}},[se,m,K,ue,o]);a.useEffect(()=>{t&&u.type==="initial"&&$.current?.focus()},[t,u.type]),a.useEffect(()=>{t&&le()},[t,le]),a.useEffect(()=>{if(t&&l&&!j.current&&u.type==="initial"){c(l);const ye=setTimeout(()=>{j.current=!0,Le(l)},0);return()=>clearTimeout(ye)}else if(t&&!l&&!j.current&&!P.current&&u.type==="initial"){P.current=!0;const ye=Uw(o);ye&&c(ye)}},[t,l,u.type,Le,o]),a.useEffect(()=>{if(!t||!d||u.type!=="initial")return;let ye=!1;return(async()=>{try{const Ge=await ti(d);if(ye||!Ge)return;N.current=d,Y(d);const Ne=ea(Ge.conversationHistory);if(v(Ne),b(Ne.map(at=>at.response).filter(at=>!!(at&&typeof at=="object"&&!Array.isArray(at)))),Ge.status==="awaiting_input"&&Ge.currentQuestion){Di(o);const at=JSON.parse(Ge.currentQuestion);h({type:"question",session:{sessionId:d,currentQuestion:at,summary:null}}),Ge.thinkingOutput&&S(Ge.thinkingOutput),se(d)}else if(Ge.status==="complete"&&Ge.result){Di(o);const at=JSON.parse(Ge.result);h({type:"summary",session:{sessionId:d,currentQuestion:null,summary:at},summary:at}),M(at)}else Ge.status==="generating"?(h({type:"loading"}),Ge.thinkingOutput&&S(Ge.thinkingOutput),se(d)):Ge.status==="error"&&(p(null),h({type:"error",session:{sessionId:d,currentQuestion:null,summary:null},errorMessage:Ge.error||"Session failed"}))}catch{p("Failed to resume session")}})(),()=>{ye=!0}},[se,t,d,u.type,o]),a.useEffect(()=>{t||(j.current=!1,P.current=!1,T(!1),Z(!1),Y(null))},[t]),a.useEffect(()=>{if(!t){Ve.current&&(V(Ve.current,H),Ve.current=null);return}if(W&&Ve.current!==W){Ve.current&&V(Ve.current,H),O(W,H),Ve.current=W;return}!W&&Ve.current&&(V(Ve.current,H),Ve.current=null)},[O,V,t,W,H]),a.useEffect(()=>{if(!t||!W||Ve.current!==W)return;F(H);const ye=setInterval(()=>{F(H)},3e4);return()=>{clearInterval(ye)}},[F,t,W,H]),a.useEffect(()=>()=>{R.current?.close(),R.current=null,Ve.current&&(V(Ve.current,H),Ve.current=null)},[V,H]),a.useEffect(()=>{if(!t)return;const ye=()=>{R.current?.close(),R.current=null};return window.addEventListener("beforeunload",ye),()=>window.removeEventListener("beforeunload",ye)},[t]);const ve=a.useCallback(()=>{R.current?.close(),R.current=null,n()},[n]),Ye=a.useCallback(()=>{let ye=null;u.type==="question"||u.type==="summary"||u.type==="error"?ye=u.session.sessionId:u.type==="breakdown"?ye=u.sessionId:u.type==="loading"&&(ye=N.current),m&&Bw(m,o),R.current?.close(),R.current=null,ye&&bh(ye,o,H).catch(()=>{}),c(""),h({type:"initial"}),p(null),b([]),v([]),M(null),S(""),T(!1),Z(!1),ce(void 0),de(void 0),N.current=null,Y(null),n()},[m,n,o,H,u]);a.useEffect(()=>{if(!t)return;const ye=Ge=>{Ge.key==="Escape"&&Ye()};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[t,Ye]);const mt=a.useCallback(async ye=>{if(u.type!=="question")return;const{session:Ge}=u,Ne=Ge.sessionId,at=Ge.currentQuestion;if(!at){p("No active question in session");return}p(null),b(dt=>[...dt,ye]),v(dt=>[...dt,{question:at,response:ye}]),h({type:"loading"}),S("");try{await Wv(Ne,ye,o,H)}catch(dt){p(fe(dt)||"Failed to submit response"),h({type:"question",session:Ge})}},[o,H,u]),ht=a.useCallback(async()=>{if(u.type!=="error")return;const ye=u.session;p(null),Z(!0),S(""),h({type:"loading"}),se(ye.sessionId);try{N.current=ye.sessionId,Y(ye.sessionId),await Kv(ye.sessionId,o,H)}catch(Ge){let Ne=Ge;if((fe(Ge)||"").includes("not in an error state"))try{const dt=await ti(ye.sessionId);if(!dt)throw new Error("Failed to refresh planning session.");if(N.current=dt.id,Y(dt.id),dt.status==="generating")S(dt.thinkingOutput??""),h({type:"loading"});else if(dt.status==="awaiting_input"){if(!dt.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const vt=JSON.parse(dt.currentQuestion);Di(o),h({type:"question",session:{sessionId:dt.id,currentQuestion:vt,summary:null}}),R.current?.isConnected()||se(dt.id)}else if(dt.status==="complete"){if(!dt.result)throw new Error("Planning session is complete but has no result.");const vt=JSON.parse(dt.result);Di(o),h({type:"summary",session:{sessionId:dt.id,currentQuestion:null,summary:vt},summary:vt}),M(vt)}else dt.status==="error"&&h({type:"error",session:{sessionId:dt.id,currentQuestion:null,summary:null},errorMessage:dt.error||"Retry failed. Please try again."});T(!1);return}catch(dt){Ne=dt}R.current?.close(),R.current=null,h({type:"error",session:ye,errorMessage:fe(Ne)||"Retry failed. Please try again."}),T(!1)}finally{Z(!1)}},[se,o,H,u]),me=a.useCallback(async()=>{if(u.type==="summary"){p(null),h({type:"loading"});try{const ye=await Gv(u.session.sessionId,y??void 0,o);s(ye),Ye()}catch(ye){p(fe(ye)||"Failed to create task"),h({type:"summary",session:u.session,summary:u.summary})}}},[y,u,o,s,Ye]),te=a.useCallback(async()=>{if(u.type==="summary"){p(null),h({type:"loading"});try{const ye=await Jv(u.session.sessionId,y??void 0,o);Y(ye.sessionId),h({type:"breakdown",sessionId:ye.sessionId,subtasks:ye.subtasks,dirty:!1})}catch(ye){p(fe(ye)||"Failed to start breakdown"),h({type:"summary",session:u.session,summary:u.summary})}}},[y,u,o]),je=a.useCallback(async()=>{if(u.type==="breakdown"){p(null),h({type:"creating"});try{const ye=await Yv(u.sessionId,u.subtasks,o);i(ye.tasks),c(""),h({type:"initial"}),p(null),b([]),v([]),M(null),S(""),ce(void 0),de(void 0),N.current=null,Y(null),n()}catch(ye){p(fe(ye)||"Failed to create tasks"),h({type:"breakdown",sessionId:u.sessionId,subtasks:u.subtasks,dirty:u.dirty})}}},[u,i,n,o]),Ae=a.useCallback(()=>{if(u.type==="question"&&f.length>0){const ye=f.slice(0,-1);b(ye),h({type:"question",session:u.session})}},[u,f]),Qe=()=>u.type==="question"?Math.min(f.length+1,3):3,be=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",st=W?C.get(W):null,Se=st&&st.tabId!==H,Je=!!(Se&&!st.stale),it=A&&(!Se||st.stale);return t?e.jsx("div",{className:"modal-overlay open",onClick:ye=>ye.target===ye.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(Ws,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Planning Mode"})]}),e.jsxs("div",{className:"modal-header-actions",children:[be&&e.jsx("button",{className:"modal-send-to-background",onClick:ve,title:"Send to background","aria-label":"Send to background",children:e.jsx(ei,{size:16})}),e.jsx("button",{className:"modal-close",onClick:Ye,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[g&&e.jsx("div",{className:"form-error planning-error",children:g}),E&&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."}),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(Dn,{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:$,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:ye=>c(ye.target.value),onKeyDown:ye=>{ye.key==="Enter"&&!ye.shiftKey&&m.trim()&&(ye.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:QM.map((ye,Ge)=>e.jsx("button",{className:"planning-example-chip",onClick:()=>c(ye),children:ye.length>40?ye.slice(0,40)+"...":ye},Ge))})]}),e.jsxs("div",{className:"planning-model-select-group",children:[e.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Ee&&e.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),e.jsx(Yt,{id:"planning-modal-model",label:"Planning Model",value:_e,onChange:ye=>{const{provider:Ge,modelId:Ne}=ZM(ye);ce(Ge),de(Ne)},models:Fe,disabled:Ee,favoriteProviders:$e,onToggleFavorite:X,favoriteModels:Me,onToggleModelFavorite:ke}),Pe&&e.jsxs("div",{className:"form-hint form-hint-error",children:[Pe," ",e.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{le()},children:"Retry"})]}),e.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:e.jsx("span",{className:`model-badge ${ue&&K?"model-badge-custom":"model-badge-default"}`,children:et(ue,K)})})]})]}),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(Ws,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),u.type==="loading"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ut,{size:40,className:"spin icon-todo"}),e.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),e.jsxs("div",{className:"planning-thinking-container",children:[e.jsx("button",{className:"planning-thinking-toggle",onClick:()=>_(!k),type:"button",children:k?"Hide thinking":"Show thinking"}),k&&w&&e.jsx("div",{className:"planning-thinking-output",children:e.jsx("pre",{children:w})})]})]}),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(Cs,{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 ht(),disabled:D,children:[D?e.jsx(ut,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:D?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:Ye,disabled:D,children:"Dismiss"})]})]})]})}),u.type==="creating"&&e.jsxs("div",{className:"planning-loading",children:[e.jsx(ut,{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(tA,{question:u.session.currentQuestion,progress:Qe(),historyEntries:x,onSubmit:mt,onBack:f.length>0?Ae:void 0})}),u.type==="summary"&&y&&e.jsx(nA,{summary:y,historyEntries:x,onSummaryChange:M,tasks:r,onCreateTask:me,onBreakIntoTasks:te,onRefine:()=>{h({type:"question",session:u.session})},isLoading:!1}),u.type==="breakdown"&&e.jsx(iA,{subtasks:u.subtasks,dirty:u.dirty,isLoading:!1,onUpdateSubtasks:ye=>h({...u,subtasks:ye,dirty:!0}),onCreateTasks:je,onBack:()=>{const Ge={sessionId:u.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:Ge,summary:y})}}),A&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(al,{size:16}),e.jsx("span",{children:it?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),it&&e.jsx("button",{type:"button",onClick:()=>{z()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}function tA({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(Cs,{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(sn,{size:18}),"Yes"]}),e.jsxs("button",{className:`planning-confirm-btn ${l[t.id]===!1?"selected":""}`,onClick:()=>o({[t.id]:!1}),children:[e.jsx(Lt,{size:18}),"No"]})]})]})]})]})]}),e.jsxs("div",{className:"planning-actions",children:[r&&e.jsxs("button",{className:"btn",onClick:r,children:[e.jsx(oa,{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(Ga,{size:16,className:"icon-ml-4"})]})]})]})}function nA({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(Cs,{entries:n}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(sn,{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(oa,{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(ut,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):e.jsxs(e.Fragment,{children:[e.jsx(il,{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(ut,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function um(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 sA(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function iA({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:um(t),[t]),f=a.useCallback((S,k)=>{i(t.map(_=>_.id===S?{..._,...k}:_))},[t,i]),b=a.useCallback(()=>{i([...t,sA(t.length+1)])},[t,i]),x=a.useCallback(S=>{i(t.filter(k=>k.id!==S).map(k=>({...k,dependsOn:k.dependsOn.filter(_=>_!==S)})))},[t,i]),v=a.useCallback((S,k)=>{if(k<0||k>=t.length)return;const _=[...t],[E]=_.splice(S,1);_.splice(k,0,E),i(_)},[t,i]),y=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)},[]),j=a.useCallback(S=>k=>{if(k.preventDefault(),S===o)return;const _=k.currentTarget.getBoundingClientRect(),E=_.top+_.height/2,T=k.clientY<E?"before":"after";c(S),h(T)},[o]),P=a.useCallback(S=>k=>{k.preventDefault();const _=k.dataTransfer.getData("text/plain");if(!_||_===S){M();return}const E=t.findIndex(R=>R.id===_),T=t.findIndex(R=>R.id===S);if(E===-1||T===-1){M();return}const D=[...t],[Z]=D.splice(E,1);let $=T;u==="after"&&E<T&&$--,u==="after"&&$++,D.splice($,0,Z),i(D),M()},[t,u,i,M]),w=a.useCallback(S=>{const k=S.currentTarget.getBoundingClientRect(),_=S.clientX,E=S.clientY;(_<k.left||_>k.right||E<k.top||E>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(il,{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 _=o===S.id,E=m===S.id,T=["task-detail-section","subtask-item",_?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&u==="before"?"subtask-item-drop-before":"",E&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:T,"data-testid":`subtask-item-${k}`,draggable:!s,onDragStart:y(S.id),onDragEnd:M,onDragOver:j(S.id),onDrop:P(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(ac,{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:()=>v(k,k-1),disabled:s||k===0,title:"Move up","aria-label":"Move subtask up",children:e.jsx(ji,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(k,k+1),disabled:s||k===t.length-1,title:"Move down","aria-label":"Move subtask down",children:e.jsx(Ka,{size:14})}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>x(S.id),disabled:s,children:[e.jsx(qt,{size:14})," Remove"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title"}),e.jsx("input",{ref:D=>{g.current[k]=D},value:S.title,onChange:D=>f(S.id,{title:D.target.value}),onKeyDown:D=>{D.key==="Enter"&&(D.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:D=>f(S.id,{description:D.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:D=>f(S.id,{suggestedSize:D.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(D=>D.id!==S.id).map(D=>{const Z=S.dependsOn.includes(D.id);return e.jsxs("label",{className:`planning-dep-chip ${Z?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:Z,onChange:()=>{const $=Z?S.dependsOn.filter(R=>R!==D.id):[...S.dependsOn,D.id];f(S.id,{dependsOn:$})},disabled:s}),e.jsx("span",{className:"planning-dep-id",children:D.id}),e.jsx("span",{className:"planning-dep-title",children:D.title||"Untitled"})]},D.id)}),k===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),k>0&&t.slice(0,k).filter(D=>D.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"]}),um(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(oa,{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(ut,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):e.jsx(e.Fragment,{children:"Create Tasks"})})]})]})}function aA(t){return{id:`subtask-${t}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function mm(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 rA({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),[v,y]=a.useState(!1),[M,j]=a.useState(!1),[P,w]=a.useState(s),[S,k]=a.useState(null),[_,E]=a.useState(!1),[T,D]=a.useState(null),[Z,$]=a.useState(null),[R,N]=a.useState(null),W=a.useRef(null),Y=a.useRef([]),H=a.useRef(!1),A=a.useRef(null),z=d.type==="generating"||d.type==="editing"||d.type==="creating"||d.type==="error"?d.sessionId:null,J=a.useMemo(()=>Pi(),[]),{isLockedByOther:C,takeControl:q,isLoading:oe}=ul(t?z:null),{activeTabMap:O,broadcastUpdate:V,broadcastCompleted:F,broadcastLock:ue,broadcastUnlock:ce,broadcastHeartbeat:K}=ua(),de=a.useMemo(()=>c.length===0||c.some(me=>!me.title.trim())?!0:mm(c),[c]),Fe=d.type==="generating"||d.type==="editing"||d.type==="error",we=z?O.get(z):null,Ee=we&&we.tabId!==J,ie=!!(Ee&&!we.stale),Pe=C&&(!Ee||we.stale),ze=a.useCallback(()=>{P&&Hw(P,l),W.current?.close(),W.current=null,m({type:"initial"}),u([]),g([]),f(""),x(!0),y(!1),j(!1),k(null),E(!1),H.current=!1},[P,l]),$e=a.useCallback(()=>{W.current?.close(),W.current=null,n()},[n]),He=a.useCallback(async()=>{if(!((_||d.type==="editing"||d.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(z)try{await yh(z,l,J)}catch{}ze(),n()}},[_,n,ze,z,J,d.type,l]),Me=a.useCallback(me=>{W.current?.close(),W.current=wy(me,l,{onThinking:te=>{f(je=>je+te),V({sessionId:me,status:"generating",needsInput:!1,owningTabId:J,type:"subtask",title:P.trim()||"Subtask breakdown",projectId:l??null})},onSubtasks:te=>{y(!1),j(!1),Rl(l),u(te),m({type:"editing",sessionId:me}),E(!1),V({sessionId:me,status:"awaiting_input",needsInput:!0,owningTabId:J,type:"subtask",title:P.trim()||"Subtask breakdown",projectId:l??null})},onError:te=>{const je=te||"Session failed while contacting the AI.";y(!1),j(!1),k(null),m({type:"error",sessionId:me,errorMessage:je}),V({sessionId:me,status:"error",needsInput:!1,owningTabId:J,type:"subtask",title:P.trim()||"Subtask breakdown",projectId:l??null}),F({sessionId:me,status:"error"})},onComplete:()=>{F({sessionId:me,status:"complete"})},onConnectionStateChange:te=>{y(te==="reconnecting")}})},[F,V,P,l,J]),Te=a.useCallback(async()=>{if(P.trim()){k(null),g([]),f(""),y(!1);try{const{sessionId:me}=await yy(P.trim(),l);m({type:"generating",sessionId:me}),Me(me)}catch(me){k(fe(me)||"Failed to start subtask breakdown"),m({type:"initial"})}}},[Me,P,l]);a.useEffect(()=>{if(!t){ze();return}if(t&&s&&!H.current)w(s),H.current=!0,Te();else if(t&&!s&&!H.current){const me=qw(l);me&&w(me)}},[t,s,Te,ze]),a.useEffect(()=>{!t||!o||d.type!=="initial"||(async()=>{try{const me=await ti(o);if(!me)return;const te=ea(me.conversationHistory);if(g(te),me.status==="generating"||me.status==="awaiting_input")f(me.thinkingOutput??""),m({type:"generating",sessionId:o}),Me(o);else if(me.status==="complete"&&me.result){Rl(l);const je=JSON.parse(me.result);u(je),m({type:"editing",sessionId:o})}else me.status==="error"&&(k(null),m({type:"error",sessionId:o,errorMessage:me.error??"Session encountered an error"}))}catch(me){k(fe(me)||"Failed to resume session")}})()},[Me,t,o,d.type,l]),a.useEffect(()=>{if(!t){A.current&&(ce(A.current,J),A.current=null);return}if(z&&A.current!==z){A.current&&ce(A.current,J),ue(z,J),A.current=z;return}!z&&A.current&&(ce(A.current,J),A.current=null)},[ue,ce,t,z,J]),a.useEffect(()=>{if(!t||!z||A.current!==z)return;K(J);const me=setInterval(()=>{K(J)},3e4);return()=>{clearInterval(me)}},[K,t,z,J]),a.useEffect(()=>()=>{W.current?.close(),A.current&&(ce(A.current,J),A.current=null)},[ce,J]),a.useEffect(()=>{if(!t)return;const me=te=>{te.key==="Escape"&&(te.preventDefault(),He())};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[t,He]);const Ve=a.useCallback((me,te)=>{u(je=>je.map(Ae=>Ae.id===me?{...Ae,...te}:Ae)),E(!0)},[]),_e=a.useCallback(()=>{u(me=>[...me,aA(me.length+1)]),E(!0)},[]),et=a.useCallback(me=>{u(te=>te.filter(je=>je.id!==me).map(je=>({...je,dependsOn:je.dependsOn.filter(Ae=>Ae!==me)}))),E(!0)},[]),le=a.useCallback(me=>te=>{D(me),te.dataTransfer.setData("text/plain",me),te.dataTransfer.effectAllowed="move"},[]),X=a.useCallback(()=>{D(null),$(null),N(null)},[]),ke=a.useCallback(me=>te=>{if(te.preventDefault(),me===T)return;const je=te.currentTarget.getBoundingClientRect(),Ae=je.top+je.height/2,Qe=te.clientY<Ae?"before":"after";$(me),N(Qe)},[T]),se=a.useCallback(me=>te=>{te.preventDefault();const je=te.dataTransfer.getData("text/plain");if(!je||je===me){D(null),$(null),N(null);return}u(Ae=>{const Qe=Ae.findIndex(it=>it.id===je),be=Ae.findIndex(it=>it.id===me);if(Qe===-1||be===-1)return Ae;const st=[...Ae],[Se]=st.splice(Qe,1);let Je=be;return R==="after"&&Qe<be&&Je--,R==="after"&&Je++,st.splice(Je,0,Se),st}),E(!0),D(null),$(null),N(null)},[R]),Le=a.useCallback(me=>{const te=me.currentTarget.getBoundingClientRect(),je=me.clientX,Ae=me.clientY;(je<te.left||je>te.right||Ae<te.top||Ae>te.bottom)&&($(null),N(null))},[]),ve=a.useCallback((me,te)=>{te<0||te>=c.length||(u(je=>{const Ae=[...je],[Qe]=Ae.splice(me,1);return Ae.splice(te,0,Qe),Ae}),E(!0))},[c.length]),Ye=a.useCallback(me=>{Y.current[me+1]?.focus()},[]),mt=a.useCallback(async()=>{if(!(!z||de)){k(null),m({type:"creating",sessionId:z});try{const me=await Ny(z,c,r,l);i(me.tasks),ze(),n()}catch(me){k(fe(me)||"Failed to create tasks"),m({type:"editing",sessionId:z})}}},[de,n,i,r,l,ze,z,c]),ht=a.useCallback(async()=>{if(d.type!=="error")return;const me=d.sessionId;k(null),j(!0),f(""),m({type:"generating",sessionId:me}),Me(me);try{await jy(me,l,J)}catch(te){let je=te;if((fe(te)||"").includes("not in an error state"))try{const Qe=await ti(me);if(!Qe)throw new Error("Failed to refresh subtask session.");if(g(ea(Qe.conversationHistory)),Qe.status==="generating"||Qe.status==="awaiting_input")f(Qe.thinkingOutput??""),m({type:"generating",sessionId:Qe.id}),W.current?.isConnected()||Me(Qe.id);else if(Qe.status==="complete"){if(!Qe.result)throw new Error("Subtask session is complete but has no result.");Rl(l);const be=JSON.parse(Qe.result);u(be),m({type:"editing",sessionId:Qe.id}),E(!1)}else Qe.status==="error"&&m({type:"error",sessionId:Qe.id,errorMessage:Qe.error??"Retry failed. Please try again."});y(!1);return}catch(Qe){je=Qe}W.current?.close(),W.current=null,m({type:"error",sessionId:me,errorMessage:fe(je)||"Retry failed. Please try again."}),y(!1)}finally{j(!1)}},[Me,l,J,d]);return t?e.jsx("div",{className:"modal-overlay open",onClick:me=>me.target===me.currentTarget&&void 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(il,{size:20,className:"icon-triage"}),e.jsx("h3",{children:"Subtask Breakdown"})]}),e.jsxs("div",{className:"modal-header-actions",children:[Fe&&e.jsx("button",{className:"modal-send-to-background",onClick:$e,title:"Send to background","aria-label":"Send to background",children:e.jsx(ei,{size:16})}),e.jsx("button",{className:"modal-close",onClick:()=>void He(),"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"planning-modal-body",children:[S&&e.jsx("div",{className:"form-error planning-error",children:S}),v&&e.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ie&&e.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&e.jsx("div",{className:"planning-initial",children:e.jsxs("div",{className:"planning-view-scroll",children:[e.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),e.jsx("pre",{className:"planning-thinking-output",children:P})]})}),d.type==="generating"&&e.jsxs("div",{className:"planning-loading",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Cs,{entries:h,defaultShowThinking:!0}),e.jsx("div",{className:"conversation-separator"})]}),e.jsx(ut,{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(Cs,{entries:h,defaultShowThinking:!0}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"ai-error-panel",role:"alert",children:[e.jsx("div",{className:"ai-error-icon",children:"⚠️"}),e.jsx("div",{className:"ai-error-message",children:d.errorMessage}),e.jsxs("div",{className:"ai-error-actions",children:[e.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:M,children:[M?e.jsx(ut,{size:14,className:"spin"}):e.jsx(vn,{size:14}),e.jsx("span",{className:"icon-ml-6",children:M?"Retrying...":"Retry"})]}),e.jsx("button",{className:"btn",onClick:()=>void He(),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(Cs,{entries:h}),e.jsx("div",{className:"conversation-separator"})]}),e.jsxs("div",{className:"planning-summary-header",children:[e.jsx(sn,{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((me,te)=>{const je=T===me.id,Ae=Z===me.id,Qe=["task-detail-section","subtask-item",je?"subtask-item-dragging":"",Ae?"subtask-item-drop-target":"",Ae&&R==="before"?"subtask-item-drop-before":"",Ae&&R==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return e.jsxs("div",{className:Qe,"data-testid":`subtask-item-${te}`,draggable:d.type!=="creating",onDragStart:le(me.id),onDragEnd:X,onDragOver:ke(me.id),onDrop:se(me.id),onDragLeave:Le,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(ac,{size:16}),e.jsx("strong",{children:me.id})]}),e.jsxs("div",{className:"subtask-item-actions",children:[e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ve(te,te-1),disabled:d.type==="creating"||te===0,title:"Move up","aria-label":"Move subtask up",children:e.jsx(ji,{size:14})}),e.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ve(te,te+1),disabled:d.type==="creating"||te===c.length-1,title:"Move down","aria-label":"Move subtask down",children:e.jsx(Ka,{size:14})}),e.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>et(me.id),disabled:d.type==="creating",children:[e.jsx(qt,{size:14})," Remove"]})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Title"}),e.jsx("input",{ref:be=>{Y.current[te]=be},value:me.title,onChange:be=>Ve(me.id,{title:be.target.value}),onKeyDown:be=>{be.key==="Enter"&&(be.preventDefault(),Ye(te))},disabled:d.type==="creating"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Description"}),e.jsx("textarea",{rows:8,value:me.description,onChange:be=>Ve(me.id,{description:be.target.value}),disabled:d.type==="creating"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Size"}),e.jsxs("select",{className:"planning-size-select",value:me.suggestedSize,onChange:be=>Ve(me.id,{suggestedSize:be.target.value}),disabled:d.type==="creating",children:[e.jsx("option",{value:"S",children:"S"}),e.jsx("option",{value:"M",children:"M"}),e.jsx("option",{value:"L",children:"L"})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Dependencies"}),e.jsxs("div",{className:"planning-deps-list",children:[c.slice(0,te).filter(be=>be.id!==me.id).map(be=>{const st=me.dependsOn.includes(be.id);return e.jsxs("label",{className:`planning-dep-chip ${st?"selected":""}`,children:[e.jsx("input",{type:"checkbox",checked:st,onChange:()=>{const Se=st?me.dependsOn.filter(Je=>Je!==be.id):[...me.dependsOn,be.id];Ve(me.id,{dependsOn:Se})},disabled:d.type==="creating"}),e.jsx("span",{className:"planning-dep-id",children:be.id}),e.jsx("span",{className:"planning-dep-title",children:be.title||"Untitled"})]},be.id)}),te===0&&e.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),te>0&&c.slice(0,te).filter(be=>be.id!==me.id).length===0&&e.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},me.id)}),e.jsxs("button",{type:"button",className:"btn",onClick:_e,disabled:d.type==="creating",children:[e.jsx(Vt,{size:16,className:"icon-mr-6"})," Add subtask"]}),mm(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 He(),disabled:d.type==="creating",children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:()=>void mt(),disabled:d.type==="creating"||de,children:d.type==="creating"?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):e.jsx(e.Fragment,{children:"Create Tasks"})})]})]}),C&&e.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:e.jsxs("div",{className:"session-lock-banner",children:[e.jsx(al,{size:16}),e.jsx("span",{children:Pe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Pe&&e.jsx("button",{type:"button",onClick:()=>{q()},disabled:oe,className:"btn btn-primary session-lock-take-control",children:oe?"Taking control...":"Take Control"})]})})]})]})}):null}const lA=5,oA=1e3,cA=45e3;function _r(){return{scrollback:null,connected:null,data:[]}}function dA(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),v=a.useRef(new Set),y=a.useRef(_r()),M=a.useCallback($=>{p.current.add($);const R=y.current;return R.data.length>0&&(R.data.forEach(N=>$(N)),R.data=[]),()=>p.current.delete($)},[]),j=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),P=a.useCallback($=>{b.current.add($);const R=y.current;return R.connected&&($(R.connected),R.connected=null),()=>b.current.delete($)},[]),w=a.useCallback($=>{x.current.add($);const R=y.current;return R.scrollback&&($(R.scrollback),R.scrollback=null),()=>x.current.delete($)},[]),S=a.useCallback($=>(v.current.add($),()=>v.current.delete($)),[]),k=a.useCallback($=>{const R=m.current;R?.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"input",data:$}))},[]),_=a.useCallback(($,R)=>{const N=m.current;N?.readyState===WebSocket.OPEN&&N.send(JSON.stringify({type:"resize",cols:$,rows:R}))},[]),E=a.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null),h.current&&(clearInterval(h.current),h.current=null),m.current&&(m.current.onopen=null,m.current.onmessage=null,m.current.onclose=null,m.current.onerror=null,m.current.close(),m.current=null),y.current=_r()},[]),T=a.useCallback(()=>{u.current&&(clearTimeout(u.current),u.current=null),h.current&&(clearInterval(h.current),h.current=null),m.current&&(g.current=!0,m.current.close(),m.current=null),y.current=_r()},[]),D=a.useCallback(()=>{if(!t){i("disconnected");return}if(m.current?.readyState===WebSocket.OPEN)return;m.current&&(g.current=!0,m.current.close()),g.current=!1,i("connecting");const $=r.current;let N=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(t)}`;n&&(N+=`&projectId=${encodeURIComponent(n)}`);const W=new WebSocket($s(N));m.current=W,W.onopen=()=>{if(r.current!==$){W.close();return}y.current=_r(),i("connected"),c.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"ping"}))},cA)},W.onmessage=Y=>{if(r.current===$)try{const H=JSON.parse(Y.data),A=y.current;switch(H.type){case"data":H.data&&(p.current.size===0&&A.data.push(H.data),p.current.forEach(z=>z(H.data)));break;case"scrollback":H.data&&(A.scrollback=H.data,x.current.forEach(z=>z(H.data)));break;case"connected":H.shell&&H.cwd&&(A.connected={shell:H.shell,cwd:H.cwd},b.current.forEach(z=>z({shell:H.shell,cwd:H.cwd})));break;case"exit":H.exitCode!==void 0&&f.current.forEach(z=>z(H.exitCode));break;case"ping":W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},W.onclose=Y=>{if(r.current!==$)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&&v.current.forEach(z=>z());return}if(c.current++,c.current>lA){i("disconnected");return}const H=oA*Math.pow(2,c.current-1);i("reconnecting");const A=r.current;u.current=setTimeout(()=>{r.current===A&&(g.current||D())},Math.min(H,16e3))},W.onerror=()=>{}},[t,n]),Z=a.useCallback(()=>{c.current=0,T(),D()},[T,D]);return a.useEffect(()=>(d&&(E(),c.current=0,i("disconnected")),t?D():i("disconnected"),T),[t,n,d,D,T,E]),{connectionStatus:s,sendInput:k,resize:_,onData:M,onExit:j,onConnect:P,onScrollback:w,reconnect:Z,onSessionInvalid:S}}const nf="kb-terminal-tabs",uA=15e3,mA=15e3;function hm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function pm(t){if(typeof window>"u")return[];try{const n=Rn(nf,t);if(n)return JSON.parse(n)}catch{}return[]}function ho(t){const n=t instanceof Error?t.message:typeof t=="string"?t:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function fm(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 hA(t){const[n,s]=a.useState(()=>pm(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(pm(t)),r(!1),o(!0),m(null)},[t]),a.useEffect(()=>{try{us(nf,JSON.stringify(n),t)}catch{}},[t,n]),a.useEffect(()=>{let P=!1;const w=h.current;return(async()=>{if(!P)try{const k=await fm(xv(t),uA,"listTerminalSessions");if(P||w!==h.current)return;const _=new Set(k.map(E=>E.id));o(!0),s(E=>{if(P||w!==h.current)return E;const D=E.map(R=>({...R,_verified:_.has(R.sessionId)})).filter(R=>R._verified);if(D.length===0)return[];const Z=D.map(({_verified:R,...N})=>N);return Z.find(R=>R.isActive)?Z:Z.map((R,N)=>({...R,isActive:N===0}))}),r(!0)}catch(k){if(P||w!==h.current)return;const _=ho(k);_||console.warn("Failed to validate terminal sessions with server:",k),o(!_),r(!0)}})(),()=>{P=!0}},[t]),a.useEffect(()=>{if(n.length===0&&i&&l){const P=h.current,w=setTimeout(()=>{fm(pr(void 0,void 0,void 0,t),mA,"createTerminalSession").then(S=>{if(P!==h.current)return;const k={id:hm(),sessionId:S.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(_=>_.length>0?_:[..._.map(T=>({...T,isActive:!1})),k]),m(null)}).catch(S=>{if(P!==h.current)return;ho(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 P=await pr(void 0,void 0,void 0,t),w={id:hm(),sessionId:P.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(S=>[...S.map(_=>({..._,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(P=>{s(w=>{const S=w.find(T=>T.id===P);if(!S)return w;nd(S.sessionId,t).catch(T=>{console.warn(`Failed to kill terminal session ${S.sessionId}:`,T)});const k=w.findIndex(T=>T.id===P),_=S.isActive,E=w.filter(T=>T.id!==P);if(E.length===0)return[];if(_){const T=Math.min(k,E.length-1);return E.map((D,Z)=>({...D,isActive:Z===T}))}return E})},[]),b=a.useCallback(P=>{s(w=>{let S=!1;const k=w.map(_=>_.id===P?(S=!0,{..._,isActive:!0}):{..._,isActive:!1});return S?k:w})},[]),x=a.useCallback((P,w)=>{s(S=>S.map(k=>k.id===P?{...k,title:w}:k))},[]),v=a.useCallback(async()=>{s(S=>{const k=S.find(_=>_.isActive);return k&&nd(k.sessionId,t).catch(_=>{console.warn(`Failed to kill old session ${k.sessionId}:`,_)}),S});const P=n.find(S=>S.isActive);if(!P)return;const w=await pr(void 0,void 0,void 0,t);s(S=>S.map(k=>k.id===P.id?{...k,sessionId:w.sessionId}:k))},[n]),y=a.useCallback(async()=>{const P=n.find(w=>w.isActive);if(P)try{const w=await pr(void 0,void 0,void 0,t);s(S=>S.map(k=>k.id===P.id?{...k,sessionId:w.sessionId}:k)),m(null)}catch(w){ho(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(P=>P.isActive)??null,j=a.useCallback(()=>{m(null),h.current+=1,u(P=>P+1)},[]);return{tabs:n,activeTab:M,isReady:i,bootstrapError:d,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:x,restartActiveTab:v,retryBootstrap:j,replaceActiveTabSession:y}}const pA=1e4,fA=[500,1500,3e3];function gA(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 bA(t){return new Promise(n=>setTimeout(n,t))}async function xA(t,n=fA){let s;for(let i=0;i<=n.length;i+=1)try{return await t()}catch(r){if(!gA(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 bA(l)}throw s??new Error("Dynamic import failed")}function gm(){if(typeof window>"u")return!1;const t="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return t&&n}function vA(){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=yA()-t.offsetTop-t.height;return i>=30&&i>80?i:0}let po=null;function yA(){return po===null&&(po=window.innerHeight),po}function jA({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,v]=a.useState(null),y=a.useRef(null),M=a.useRef(null),j=a.useRef(null),P=a.useRef(null),w=a.useRef(!1),S=a.useRef(!1),k=a.useRef(null),_=a.useRef(0),E=a.useRef(null),T=a.useRef(i);_.current=f;const D=a.useCallback(Me=>{if(Me&&S.current!==Me)return;const Te=P.current,Ve=j.current,_e=k.current;if(!(!Te||!Ve)&&!(Me&&S.current!==Me))try{Te.fit(),_e&&_e(Ve.cols,Ve.rows)}catch{}},[]);a.useEffect(()=>{t&&p(Me=>Me+1)},[t]),a.useEffect(()=>{if(!t||!gm())return;const Me=window.visualViewport;if(!Me)return;const Te=()=>{const Ve=vA();b(Ve),v(Me.height),Ve>0&&M.current?.scrollIntoView&&M.current.scrollIntoView({block:"end",behavior:"smooth"}),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const _e=typeof S.current=="string"?S.current:void 0;E.current=requestAnimationFrame(()=>{E.current=null,D(_e)})};return Te(),Me.addEventListener("resize",Te),Me.addEventListener("scroll",Te),()=>{Me.removeEventListener("resize",Te),Me.removeEventListener("scroll",Te),E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),b(0),v(null)}},[D,t]);const{tabs:Z,activeTab:$,isReady:R,bootstrapError:N,createTab:W,closeTab:Y,setActiveTab:H,updateTabTitle:A,restartActiveTab:z,retryBootstrap:J,replaceActiveTabSession:C}=hA(i),{connectionStatus:q,sendInput:oe,resize:O,onData:V,onConnect:F,onExit:ue,onScrollback:ce,reconnect:K,onSessionInvalid:de}=dA($?.sessionId??null,i);k.current=O,a.useEffect(()=>{if(!t||!R||!$)return;const Me=$.sessionId,Te=T.current!==i;if(Te&&(T.current=i),S.current===Me&&j.current&&!Te)return;j.current&&(S.current!==Me||Te)&&(j.current.dispose(),j.current=null,P.current=null,S.current=!1,c(!1),h(null));let Ve=!0,_e;const le=(async()=>{const X=xA(()=>Promise.all([nn(()=>import("./vendor-xterm-DzcZoU0P.js").then(ve=>ve.x),__vite__mapDeps([4,1,5])),nn(()=>import("./addon-fit-C7jRorKK.js").then(ve=>ve.a),__vite__mapDeps([9,1])),nn(()=>import("./addon-web-links-CkJwd4cQ.js").then(ve=>ve.a),__vite__mapDeps([10,1]))])),ke=new Promise((ve,Ye)=>{_e=setTimeout(()=>{Ye(new Error("xterm initialization timed out"))},pA)});let se,Le;try{const[{Terminal:ve},{FitAddon:Ye},{WebLinksAddon:mt}]=await Promise.race([X,ke]);if(!Ve||!y.current||j.current)return;se=new ve({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,se.loadAddon(Le);const ht=new mt;if(se.loadAddon(ht),!gm())try{const{WebglAddon:Ae}=await nn(async()=>{const{WebglAddon:be}=await import("./addon-webgl-BjvOw43o.js").then(st=>st.a);return{WebglAddon:be}},__vite__mapDeps([11,1])),Qe=new Ae;Qe.onContextLoss(()=>{Qe.dispose()}),se.loadAddon(Qe)}catch{}se.open(y.current),clearTimeout(_e);const me=y.current?.querySelector(".xterm-helper-textarea");if(me&&me.focus(),y.current)try{y.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Le.fit();const Ae=y.current?.querySelector(".xterm-helper-textarea");Ae&&Ae.focus()},50),j.current=se,P.current=Le,S.current=Me,_.current>0&&(E.current!==null&&(cancelAnimationFrame(E.current),E.current=null),E.current=requestAnimationFrame(()=>{E.current=null,D(Me)})),c(!0),h(null);const te=se.onData(Ae=>{oe(Ae)}),je=()=>{if(P.current&&j.current)try{P.current.fit();const{cols:Ae,rows:Qe}=j.current;O(Ae,Qe)}catch{}};return window.addEventListener("resize",je),()=>{te.dispose(),window.removeEventListener("resize",je)}}catch(ve){if(clearTimeout(_e),!Ve)return;const Ye=ve instanceof Error?ve.message:"xterm initialization failed";h(Ye)}})();return()=>{Ve=!1,clearTimeout(_e),le.then(X=>X?.())}},[D,t,R,$,$?.sessionId,oe,O]),a.useEffect(()=>{t||(j.current&&(j.current.dispose(),j.current=null),P.current=null,S.current=!1,c(!1),h(null),w.current=!1,l(null),d(null))},[t]),a.useEffect(()=>{if(!m||!j.current||!$)return;const Me=$.sessionId,Te=X=>{S.current===Me&&j.current?.write(X)},Ve=V(X=>{Te(X)}),_e=ce(X=>{Te(X)}),et=F(X=>{A($.id,X.shell.split("/").pop()||X.shell)}),le=ue(X=>{S.current===Me&&(d(X),j.current?.write(`\r
646
+ \x1B[33m[Process exited with code ${X}]\x1B[0m\r
647
+ `))});return()=>{Ve(),_e(),et(),le()}},[m,$?.sessionId,$?.id,$,q,V,ce,F,ue,A]),a.useEffect(()=>{q==="connected"&&s&&w.current!==s&&$&&(w.current=s,setTimeout(()=>{oe(s+`
648
+ `)},500))},[q,s,oe,$,g]),a.useEffect(()=>{if(!t)return;const Me=Te=>{if(!(!Te.ctrlKey&&!Te.metaKey)){if(Te.code==="Equal"||Te.code==="NumpadAdd"){if(Te.preventDefault(),j.current){const Ve=j.current.options.fontSize||14;j.current.options.fontSize=Math.min(Ve+1,32),P.current?.fit()}return}if(Te.code==="Minus"||Te.code==="NumpadSubtract"){if(Te.preventDefault(),j.current){const Ve=j.current.options.fontSize||14;j.current.options.fontSize=Math.max(Ve-1,8),P.current?.fit()}return}if(Te.code==="Digit0"||Te.code==="Numpad0"){Te.preventDefault(),j.current&&(j.current.options.fontSize=14,P.current?.fit());return}}};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[t]),a.useEffect(()=>{if(!t)return;const Me=Te=>{Te.key==="Escape"&&n()};return document.addEventListener("keydown",Me),()=>document.removeEventListener("keydown",Me)},[t,n]),a.useEffect(()=>{q==="connected"&&j.current&&setTimeout(()=>{if(!j.current||!y.current)return;const Me=y.current.querySelector(".xterm-helper-textarea");Me&&Me.focus();try{y.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[q]);const Fe=a.useCallback(()=>{if(!y.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;j.current?.focus();const Te=y.current.querySelector(".xterm-helper-textarea");if(!Te)return;Te.autocapitalize="off",Te.autocomplete="off",Te.autocorrect="off",Te.spellcheck=!1,Te.setAttribute("inputmode","text");try{Te.focus({preventScroll:!0})}catch{Te.focus()}const Ve=Te.value.length;Te.setSelectionRange(Ve,Ve)},[]);a.useEffect(()=>de(()=>{j.current?.clear(),d(null),w.current=!1,j.current&&(j.current.dispose(),j.current=null),P.current=null,S.current=!1,c(!1),h(null),C().catch(Te=>{console.error("Failed to replace invalid terminal session:",Te)})}),[de,C]);const we=a.useCallback(Me=>{Me.target===Me.currentTarget&&n()},[n]),Ee=a.useCallback(()=>{j.current?.clear()},[]),ie=a.useCallback(async()=>{j.current?.clear(),d(null),w.current=!1;try{await z()}catch(Me){l(fe(Me)||"Failed to restart terminal session")}},[z]),Pe=a.useCallback(()=>{j.current&&(j.current.dispose(),j.current=null),P.current=null,S.current=!1,h(null),c(!1)},[]),ze=a.useCallback(()=>{window.location.reload()},[]);if(!t)return null;const $e=()=>{switch(q){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}},He=!R||!$&&!N||!m&&!u;return e.jsx("div",{className:"modal-overlay open",onClick:we,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(Me=>e.jsxs("div",{className:`terminal-tab ${Me.isActive?"terminal-tab--active":""}`,onClick:()=>H(Me.id),title:Me.title,role:"tab","aria-selected":Me.isActive,children:[e.jsx("span",{className:"terminal-tab-label",children:Me.title}),Z.length>1&&e.jsx("button",{className:"terminal-tab-close",onClick:Te=>{Te.stopPropagation(),Y(Me.id)},title:"Close tab",children:"×"})]},Me.id)),e.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:W,title:"New terminal",children:"+"})]}),e.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[e.jsx(Ks,{size:16}),$e()]}),e.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[q==="disconnected"&&$&&e.jsxs("button",{className:"terminal-reconnect-btn",onClick:K,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[e.jsx(vn,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),o!==null&&e.jsxs("button",{className:"terminal-restart-btn",onClick:ie,title:"New Session","data-testid":"terminal-restart-btn",children:[e.jsx(vn,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),e.jsxs("button",{className:"terminal-clear-btn",onClick:Ee,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[e.jsx(qt,{size:14}),e.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),e.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:e.jsx(Lt,{size:20})})]})]}),r&&e.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),e.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[He&&!N&&e.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[e.jsx("div",{className:"terminal-spinner"}),e.jsx("span",{children:"Starting terminal..."})]}),N&&!$&&e.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:e.jsxs("div",{className:"terminal-error-content",children:[e.jsxs("span",{children:["Failed to start terminal: ",N]}),e.jsxs("div",{className:"terminal-error-actions",children:[e.jsxs("button",{className:"terminal-retry-btn",onClick:J,"data-testid":"terminal-retry-btn",children:[e.jsx(vn,{size:14}),"Retry"]}),e.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-bootstrap-refresh-btn",children:[e.jsx(vn,{size:14}),"Refresh page"]})]})]})}),u&&$&&e.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:e.jsxs("div",{className:"terminal-error-content",children:[e.jsxs("span",{children:["Terminal UI failed to initialize: ",u]}),e.jsxs("div",{className:"terminal-error-actions",children:[e.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-reinit-btn",children:[e.jsx(vn,{size:14}),"Reinitialize"]}),e.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-xterm-refresh-btn",children:[e.jsx(vn,{size:14}),"Refresh page"]})]})]})}),e.jsx("div",{ref:y,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Fe,onTouchStart:Fe},$?.sessionId)]}),e.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[e.jsxs("span",{className:`terminal-connection-status ${q}`,children:[q==="connected"&&"Connected",q==="connecting"&&"Connecting...",q==="reconnecting"&&"Reconnecting...",q==="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 Ea={name:"",command:""};function bm(t){return/^[a-zA-Z0-9_-]+$/.test(t)}function kA(t,n=60){return t.length<=n?t:t.slice(0,n-3)+"..."}function wA({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(Ea),[b,x]=a.useState(!1),[v,y]=a.useState(null),[M,j]=a.useState(null),P=a.useCallback(async()=>{try{m(!0);const R=await Za(i);o(R)}catch(R){s(fe(R)||"Failed to load scripts","error")}finally{m(!1)}},[s,i]);a.useEffect(()=>{t&&P()},[t,P]);const w=a.useCallback(()=>{u(!0),g(null),f(Ea),j(null)},[]),S=a.useCallback((R,N)=>{g(R),u(!1),f({name:R,command:N}),j(null)},[]),k=a.useCallback(()=>{g(null),u(!1),f(Ea),j(null)},[]),_=a.useCallback(R=>{f(N=>({...N,name:R})),R&&!bm(R)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),E=a.useCallback(async()=>{const R=p.name.trim(),N=p.command.trim();if(!R){s("Script name is required","error");return}if(!bm(R)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!N){s("Script command is required","error");return}x(!0);try{await xy(R,N,i),s(h?"Script updated":"Script created","success"),g(null),u(!1),f(Ea),j(null),await P()}catch(W){const Y=fe(W);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,P,i]),T=a.useCallback(async R=>{try{await vy(R,i),s("Script deleted","success"),y(null),h===R&&(g(null),f(Ea)),await P()}catch(N){s(fe(N)||"Failed to delete script","error")}},[h,s,P,i]),D=a.useCallback((R,N)=>{r&&r(R,N)},[r]);if(!t)return null;const Z=c||h!==null,$=Object.entries(l).map(([R,N])=>({name:R,command:N}));return e.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:e.jsxs("div",{className:"modal scripts-modal",onClick:R=>R.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{children:[e.jsx(Ks,{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(ut,{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:R=>_(R.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:R=>f(N=>({...N,command:R.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:E,disabled:b||!!M,"data-testid":"script-save-btn",children:b?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[e.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),e.jsxs("button",{className:"btn btn-primary",onClick:w,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[e.jsx(Vt,{size:14}),"Add Script"]})]}),$.length===0?e.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[e.jsx(Ks,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),e.jsx("div",{children:"No scripts defined yet."}),e.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):e.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:$.map(R=>e.jsx("div",{className:"script-card","data-testid":`script-${R.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:R.name})}),e.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:R.command,children:kA(R.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:()=>D(R.name,R.command),title:"Run script","aria-label":`Run ${R.name}`,"data-testid":`run-script-${R.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[e.jsx(ln,{size:12}),"Run"]}),e.jsx("button",{className:"btn-icon",onClick:()=>S(R.name,R.command),title:"Edit","aria-label":`Edit ${R.name}`,"data-testid":`edit-script-${R.name}`,children:e.jsx(Vt,{size:14,style:{transform:"rotate(45deg)"}})}),v===R.name?e.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[e.jsx("button",{className:"btn-icon",onClick:()=>T(R.name),title:"Confirm delete","aria-label":`Confirm delete ${R.name}`,"data-testid":`confirm-delete-script-${R.name}`,style:{color:"var(--color-error)"},children:e.jsx(qt,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${R.name}`,children:e.jsx(Lt,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>y(R.name),title:"Delete","aria-label":`Delete ${R.name}`,"data-testid":`delete-script-${R.name}`,children:e.jsx(qt,{size:14})})]})]})},R.name))})]})})]})})}function NA(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 v=await Fv(t,l==="."?void 0:l,s);b||r(v.entries)}catch(v){b||(u(fe(v)||"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 SA(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 j(){h(!0),b(null);try{const P=await Dv(t,n,i);M||(l(P.content),d(P.content),c(P.mtime))}catch(P){M||(b(fe(P)||"Failed to load file"),l(""),d(""),c(null))}finally{M||h(!1)}}return j(),()=>{M=!0}},[t,n,s,i]);const v=r!==o,y=a.useCallback(async()=>{if(!(!t||!n||!v)){p(!0),b(null);try{const M=await Lv(t,n,r,i);d(r),c(M.mtime)}catch(M){throw b(fe(M)||"Failed to save file"),M}finally{p(!1)}}},[t,n,r,v,i]);return{content:r,setContent:x,originalContent:o,loading:u,saving:g,error:f,save:y,hasChanges:v,mtime:m}}const CA=1e4;function EA(t){const s=t.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||t||"Project Root"}function MA(t){return{id:t.id,label:t.id,title:t.title,worktree:t.worktree,kind:"task"}}function AA(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 $v(t);if(c)return;s(EA(g.project)),r(g.tasks.map(MA)),m(null)}catch(g){c||m(fe(g)||"Failed to load workspaces")}finally{c||o(!1)}}u();const h=window.setInterval(()=>{u()},CA);return()=>{c=!0,window.clearInterval(h)}},[t]),{projectName:n,workspaces:i,loading:l,error:d}}function PA(t){return t===void 0?"":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function IA(t){return t?new Date(t).toLocaleDateString():""}function xm(t,n){return t==="."?n:`${t}/${n}`}const Ma={visible:!1,x:0,y:0,entry:null,entryFullPath:""},fo={type:null,entry:null,entryFullPath:""},_A=200,RA=500,vm=10;function TA({x:t,y:n,entry:s,onAction:i,onClose:r}){const l=a.useRef(null),[o,d]=a.useState({x:t,y:n});a.useEffect(()=>{const u=l.current;if(!u)return;const h=u.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,x=g?.offsetTop??0,v=8;let y=t-b,M=n-x;y+h.width>p-v&&(y=p-v-h.width),M+h.height>f-v&&(M=f-v-h.height),y<v&&(y=v),M<v&&(M=v),d({x:y+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:Gi,disabled:!1},{id:"move",label:"Move",icon:vb,disabled:!1},{id:"rename",label:"Rename",icon:$n,disabled:!1},...m?[{id:"download-zip",label:"Download as ZIP",icon:nl,disabled:!1}]:[{id:"download",label:"Download",icon:fg,disabled:!1}],{id:"divider",label:"",icon:Gi,disabled:!0},{id:"delete",label:"Delete",icon:qt,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 $A({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 FA({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(Ma),[g,p]=a.useState(fo),[f,b]=a.useState(!1),[x,v]=a.useState(null),[y,M]=a.useState(!1),[j,P]=a.useState(null),w=a.useRef(null),S=a.useRef(null),k=a.useRef(null),_=a.useRef(!1),E=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]),T=a.useCallback(()=>{E(),k.current=null,M(!1),P(null)},[E]);a.useEffect(()=>()=>{E()},[E]);const D=a.useCallback((z,J,C,q)=>{h({visible:!0,x:z,y:J,entry:C,entryFullPath:q})},[]),Z=a.useCallback((z,J,C)=>{if(z.touches.length!==1)return;const q=z.touches[0];q&&(T(),k.current={x:q.clientX,y:q.clientY},S.current=window.setTimeout(()=>{M(!0),P(C)},_A),w.current=window.setTimeout(()=>{const oe=k.current;oe&&(_.current=!0,M(!1),P(null),E(),D(oe.x,oe.y,J,C))},RA))},[T,E,D]),$=a.useCallback(z=>{const J=k.current,C=z.touches[0];!J||!C||(Math.abs(C.clientX-J.x)>vm||Math.abs(C.clientY-J.y)>vm)&&T()},[T]),R=a.useCallback(()=>{T()},[T]);a.useEffect(()=>{if(!u.visible)return;const z=document.querySelector(".file-browser-list"),J=()=>{_.current=!1,T(),h(Ma)};return z?.addEventListener("scroll",J),()=>z?.removeEventListener("scroll",J)},[T,u.visible]),a.useEffect(()=>{if(!u.visible)return;const z=J=>{J.key==="Escape"&&(_.current=!1,h(Ma))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[u.visible]);const N=a.useCallback((z,J)=>{z.preventDefault(),z.stopPropagation(),T(),_.current=!1,D(z.clientX,z.clientY,J,xm(n,J.name))},[T,n,D]),W=a.useCallback(z=>{if(!u.entry)return;_.current=!1;const J=u.entry,C=u.entryFullPath;if(h(Ma),z==="download"){if(!d)return;const q=gh(d,C,c);window.open($s(q),"_blank");return}if(z==="download-zip"){if(!d)return;const q=qv(d,C,c);window.open($s(q),"_blank");return}p({type:z,entry:J,entryFullPath:C}),v(null)},[u,d,c]),Y=a.useCallback(async z=>{if(!(!g.type||!g.entry||!d)){b(!0),v(null);try{switch(g.type){case"copy":await Ov(d,g.entryFullPath,z,c);break;case"move":await Bv(d,g.entryFullPath,z,c);break;case"rename":await Hv(d,g.entryFullPath,z,c);break;case"delete":await Uv(d,g.entryFullPath,c);break}p(fo),m?.()}catch(J){v(fe(J)||"Operation failed")}finally{b(!1)}}},[g,d,m,c]),H=a.useCallback(()=>{p(fo),v(null)},[]),A=a.useCallback((z,J)=>{if(_.current){_.current=!1;return}u.visible||(z.type==="directory"?i(J):s(J))},[u.visible,i,s]);return r?e.jsxs("div",{className:"file-browser-loading",children:[e.jsx(ut,{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 z=n.split("/").filter(Boolean);z.pop(),i(z.length===0?".":z.join("/"))},children:[e.jsx(on,{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(z=>{const J=xm(n,z.name),C=y&&j===J;return e.jsxs("div",{className:`file-node file-node--${z.type} ${C?"file-node--long-pressing":""}`,onClick:()=>A(z,J),onContextMenu:q=>N(q,z),onTouchStart:q=>Z(q,z,J),onTouchMove:$,onTouchEnd:R,onTouchCancel:R,children:[e.jsx("div",{className:"file-node-icon",children:z.type==="directory"?e.jsx(Sn,{size:16}):e.jsx(eh,{size:16})}),e.jsx("div",{className:"file-node-name",children:z.name}),z.type==="file"&&z.size!==void 0&&e.jsx("div",{className:"file-node-size",children:PA(z.size)}),z.mtime&&e.jsx("div",{className:"file-node-time",children:IA(z.mtime)})]},z.name)})}),u.visible&&u.entry&&e.jsx(TA,{x:u.x,y:u.y,entry:u.entry,onAction:W,onClose:()=>{_.current=!1,h(Ma)}}),g.type&&g.entry&&e.jsx($A,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:Y,onCancel:H,loading:f,error:x})]})}function DA(t,n=44){if(t)return t.length<=n?t:`${t.slice(0,n-1)}…`}function LA({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(Wc,{size:14}):e.jsx(Eo,{size:14}),e.jsx("span",{className:"workspace-selector-trigger-label",children:o}),e.jsx(Ot,{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(Wc,{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(Eo,{size:14}),e.jsx("span",{children:d.id})]}),d.title&&e.jsx("span",{className:"workspace-selector-option-meta",title:d.title,children:DA(d.title)})]},d.id))]})]})]})}const zA=768,sf=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),OA=new Set([...sf,".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 ym(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return OA.has(n)}function BA(t){const n=t.slice(t.lastIndexOf(".")).toLowerCase();return sf.has(n)}function UA({initialWorkspace:t="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:l}=AA(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:v,error:y,refresh:M}=NA(o,!0,i),{content:j,setContent:P,originalContent:w,loading:S,saving:k,error:_,save:E,hasChanges:T,mtime:D}=SA(o,m,!0,i);a.useEffect(()=>{d(t)},[t]),a.useEffect(()=>{const z=()=>{h(window.innerWidth<=zA)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{m||p("list")},[m]),a.useEffect(()=>{const z=J=>{J.key==="Escape"&&n(),(J.metaKey||J.ctrlKey)&&J.key==="s"&&(J.preventDefault(),T&&!k&&E())};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[n,T,k,E]);const Z=a.useCallback(z=>{c(z),u&&p("editor")},[u]),$=a.useCallback(()=>{p("list")},[]),R=a.useCallback(()=>{P(w)},[w,P]),N=a.useCallback(z=>{d(z),c(null),p("list"),s?.(z)},[s]),Y=`Files — ${a.useMemo(()=>o==="project"?"Project":l.find(z=>z.id===o)?.id??o,[o,l])}`,H=a.useMemo(()=>!m||!BA(m)?null:gh(o,m,i),[m,o,i]),A=z=>{const J=new Blob([z]).size;return J<1024?`${J} B`:`${(J/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:z=>z.stopPropagation(),children:[e.jsxs("div",{className:"modal-header file-browser-modal-header",children:[e.jsxs("div",{className:"file-browser-header-title",children:[e.jsx(Sn,{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(LA,{currentWorkspace:o,projectName:r,workspaces:l,onSelect:N}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsxs("div",{className:"file-browser-body",children:[e.jsx("div",{className:`file-browser-sidebar ${u?"mobile":""} ${g==="list"?"active":""}`,children:e.jsx(FA,{entries:f,currentPath:b,onSelectFile:Z,onNavigate:x,loading:v,error:y,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:$,"aria-label":"Back to file list",children:[e.jsx(oa,{size:16}),e.jsx("span",{children:"Back"})]}),m,ym(m)&&e.jsxs("span",{className:"file-browser-binary-indicator",children:[e.jsx($g,{size:12}),"Binary file — read only"]}),D&&e.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(D).toLocaleString()]}),S&&e.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),e.jsx("div",{className:"file-browser-actions",children:!H&&T&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:R,disabled:k,children:[e.jsx(Ib,{size:14}),"Discard"]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void E(),disabled:k,children:[e.jsx(rh,{size:14}),k?"Saving...":"Save"]})]})})]}),_&&!H&&e.jsx("div",{className:"file-browser-error-banner",children:_}),H?e.jsx("div",{className:"file-browser-image-preview",children:e.jsx("img",{src:H,alt:m??"",className:"file-browser-image"})}):e.jsx("div",{className:"file-editor-wrapper",children:e.jsx(ef,{content:j,onChange:P,filePath:m,readOnly:ym(m)})}),!H&&e.jsxs("div",{className:"file-browser-footer",children:[e.jsx("span",{children:A(j)}),T&&e.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):e.jsxs("div",{className:"file-browser-placeholder",children:[e.jsx(Sn,{size:48,opacity:.3}),e.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function HA(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 sv();r({providers:u,loading:!1,error:null,lastUpdated:new Date})}catch(u){if(u instanceof Error&&u.name==="AbortError")return;r(h=>({...h,loading:!1,error:fe(u)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{d()},[d]),a.useEffect(()=>{if(s)return l.current=setInterval(()=>{d(!1)},n),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,n,d]),a.useEffect(()=>()=>{o.current&&o.current.abort(),l.current&&clearInterval(l.current)},[]);const m=a.useCallback(()=>d(!0),[d]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:m}}function qA(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 VA(t){return t>90?"usage-progress-fill--high":t>70?"usage-progress-fill--medium":"usage-progress-fill--low"}function WA({window:t,viewMode:n,providerName:s}){const i=VA(t.percentUsed),r=n==="remaining",l=Math.round(r?t.percentLeft:t.percentUsed),o=r?`${Math.round(t.percentLeft)}% remaining`:`${Math.round(t.percentUsed)}% used`,d=r?`${Math.round(t.percentUsed)}% used`:`${Math.round(t.percentLeft)}% left`;let m=t.resetText;if(!m&&t.resetAt){const b=new Date(t.resetAt).getTime()-Date.now();if(b>0){const x=Math.floor(b/36e5),v=Math.floor(x/24),y=x%24;v>0&&y>0?m=`resets in ${v}d ${y}h`:v>0?m=`resets in ${v}d`:x>0?m=`resets in ${x}h`:m=`resets in ${Math.floor(b/6e4)}m`}}const c=t.pace,u=c!==void 0;let h=0;u&&(h=r?100-c.percentElapsed:c.percentElapsed);const g=c?.status==="ahead",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:qA(t.resetAt)})]})]}),u&&e.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[g&&e.jsxs(e.Fragment,{children:[e.jsx(rc,{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(Jb,{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(sn,{size:14,className:"pace-icon pace-ontrack"}),e.jsx("span",{className:"pace-text pace-ontrack",children:c.message})]})]})]})}function KA(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 GA({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(ns,{provider:KA(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(WA,{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 JA(){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 YA({isOpen:t,onClose:n,projectId:s}){const{providers:i,loading:r,error:l,lastUpdated:o,refresh:d}=HA({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 y=Rn("kb-usage-view-mode",s);if(y==="used"||y==="remaining"){h(y);return}h("used")},[s]);const b=a.useCallback(y=>{h(y),us("kb-usage-view-mode",y,s)},[s]),x=a.useCallback(async()=>{c(!0),await d(),c(!1)},[d]);a.useEffect(()=>{if(!t)return;const y=M=>{M.key==="Escape"&&n()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,n]);const v=a.useCallback(y=>{y.target===y.currentTarget&&n()},[n]);return t?e.jsx("div",{className:"modal-overlay open",onClick:v,"data-testid":"usage-modal-overlay",children:e.jsxs("div",{className:"modal usage-modal","data-testid":"usage-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{className:"usage-header",children:[e.jsx(Ss,{size:18,className:"usage-header-icon"}),e.jsx("h3",{children:"Usage"})]}),e.jsxs("div",{className:"usage-header-actions",children:[e.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[e.jsx("button",{className:`usage-view-toggle-btn ${u==="used"?"active":""}`,onClick:()=>b("used"),"aria-pressed":u==="used","data-testid":"usage-view-toggle-used",children:"Used"}),e.jsx("button",{className:`usage-view-toggle-btn ${u==="remaining"?"active":""}`,onClick:()=>b("remaining"),"aria-pressed":u==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:e.jsx(Lt,{size:20})})]})]}),e.jsx("div",{className:"usage-content",ref:g,children:(r||!f.current&&!l)&&i.length===0?e.jsx(JA,{}):l&&i.length===0?e.jsxs("div",{className:"usage-error",children:[e.jsx("p",{children:"Failed to load usage data"}),e.jsx("p",{className:"usage-error-message",children:l}),e.jsx("button",{className:"btn btn-sm",onClick:x,children:"Retry"})]}):i.length===0?e.jsxs("div",{className:"usage-empty",children:[e.jsx("p",{children:"No AI providers configured"}),e.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):e.jsx("div",{className:"usage-providers",children:i.map(y=>e.jsx(GA,{provider:y,viewMode:u},y.name))})}),e.jsxs("div",{className:"modal-actions usage-actions",children:[e.jsx("div",{className:"modal-actions-left usage-actions-left",children:e.jsx("div",{className:"usage-last-updated",children:o&&e.jsxs("span",{children:["Last updated: ",o.toLocaleTimeString()]})})}),e.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[e.jsxs("button",{className:"btn btn-sm",onClick:x,disabled:r||m,"data-testid":"usage-refresh-btn",children:[e.jsx(vn,{size:14,className:m?"spin":"",style:{marginRight:6}}),"Refresh"]}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function af(t){if(t<1e3)return`${t}ms`;const n=Math.floor(t/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),l=s%60;return l>0?`${r}h ${l}m`:`${r}h`}function Zr(t){const n=Date.now(),s=new Date(t).getTime(),i=n-s;if(i<0){const r=Math.abs(i);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const QA={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},rf={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},XA={cron:Ym,webhook:oh,api:Qm,manual:Nn},ZA={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},eP={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function tP({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(sn,{size:12}):e.jsx(Ja,{size:12}),e.jsx("span",{children:t.success?"Success":"Failed"}),n>0&&e.jsx("span",{className:"schedule-run-duration",children:af(n)})]})}function nP({result:t,index:n}){const[s,i]=a.useState(!1),r=t.completedAt&&t.startedAt?new Date(t.completedAt).getTime()-new Date(t.startedAt).getTime():0;return e.jsxs("div",{className:"schedule-history-item",children:[e.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${t.success?"succeeded":"failed"} ${Zr(t.startedAt)}`,children:[e.jsx("span",{className:`schedule-history-status ${t.success?"success":"failure"}`,children:t.success?e.jsx(sn,{size:12}):e.jsx(Ja,{size:12})}),e.jsx("span",{className:"schedule-history-time",children:Zr(t.startedAt)}),t.triggerType&&e.jsx("span",{className:"routine-history-trigger-type",children:rf[t.triggerType]}),e.jsx("span",{className:"schedule-history-duration",children:af(r)}),s?e.jsx(qs,{size:12}):e.jsx(Ot,{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 sP({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=QA[t.trigger.type],u=XA[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}),rf[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(Ni,{size:10}):e.jsx(Sn,{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(ln,{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(Hs,{size:14}):e.jsx(ln,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>n(t),title:"Edit","aria-label":`Edit ${t.name}`,children:e.jsx($n,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${t.name}`,children:e.jsx(qt,{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(Si,{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(Ki,{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:ZA[t.executionPolicy]})}),e.jsx("div",{className:"routine-meta-item",children:e.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${t.catchUpPolicy}`,children:eP[t.catchUpPolicy]})}),t.nextRunAt&&t.enabled&&e.jsxs("div",{className:"routine-meta-item",children:[e.jsx("span",{className:"routine-meta-label",children:"Next:"}),e.jsx("span",{title:t.nextRunAt,children:Zr(t.nextRunAt)})]}),t.lastRunAt&&e.jsxs("div",{className:"routine-meta-item",children:[e.jsx("span",{className:"routine-meta-label",children:"Last:"}),e.jsx("span",{title:t.lastRunAt,children:Zr(t.lastRunAt)})]}),t.lastRunResult&&e.jsx(tP,{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(qs,{size:12}):e.jsx(Ot,{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(nP,{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 iP({type:t,size:n=12}){return t==="command"?e.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[e.jsx(Ks,{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(rb,{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(Dn,{size:n}),e.jsx("span",{children:"AI Prompt"})]})}function go(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function aP(t){return t==="command"?{id:go(),type:t,name:"New Command Step",command:"",continueOnFailure:!1}:t==="ai-prompt"?{id:go(),type:t,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:go(),type:t,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function rP({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??""),[v,y]=a.useState(t.taskDescription??""),[M,j]=a.useState(t.taskColumn??"triage"),[P,w]=a.useState(t.timeoutMs),[S,k]=a.useState(t.continueOnFailure??!1),[_,E]=a.useState({}),[T,D]=a.useState([]),[Z,$]=a.useState(!1),[R,N]=a.useState(null);a.useEffect(()=>{let z=!1;return $(!0),N(null),Vn().then(J=>{z||D(J.models)}).catch(J=>{z||N(J instanceof Error?J.message:"Failed to load models")}).finally(()=>{z||$(!1)}),()=>{z=!0}},[]);const W=a.useCallback(()=>{const z={};return i.trim()||(z.name="Step name is required"),l==="command"&&!d.trim()&&(z.command="Command is required"),l==="ai-prompt"&&!c.trim()&&(z.prompt="Prompt is required"),l==="create-task"&&!v.trim()&&(z.taskDescription="Task description is required"),(l==="ai-prompt"||l==="create-task")&&(h||p)&&(!h||!p)&&(z.modelProvider="Both model provider and model ID must be set together"),P!==void 0&&P<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(z),Object.keys(z).length===0},[i,l,d,c,v,h,p,P]),Y=h&&p?`${h}/${p}`:"",H=a.useCallback(z=>{if(!z)g(""),f("");else{const J=z.indexOf("/");J!==-1&&(g(z.slice(0,J)),f(z.slice(J+1)))}},[]),A=a.useCallback(()=>{if(!W())return;const z={...t,name:i.trim(),type:l,command:l==="command"?d.trim():void 0,prompt:l==="ai-prompt"?c.trim():void 0,taskTitle:l==="create-task"&&b.trim()?b.trim():void 0,taskDescription:l==="create-task"&&v.trim()?v.trim():void 0,taskColumn:l==="create-task"?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:P||void 0,continueOnFailure:S};l!=="ai-prompt"&&delete z.prompt,l!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[W,n,t,i,l,d,c,b,v,M,h,p,P,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:z=>r(z.target.value),"aria-invalid":!!_.name}),_.name&&e.jsx("small",{className:"field-error",children:_.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:z=>o(z.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:z=>m(z.target.value),rows:2,"aria-invalid":!!_.command}),_.command&&e.jsx("small",{className:"field-error",children:_.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:z=>u(z.target.value),rows:3,"aria-invalid":!!_.prompt}),_.prompt&&e.jsx("small",{className:"field-error",children:_.prompt})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-model-${t.id}`,children:"Model (optional)"}),e.jsx(Yt,{id:`step-model-${t.id}`,label:"Model",models:T,value:Y,onChange:H,placeholder:"Use default",disabled:Z}),R&&e.jsx("small",{className:"field-error",children:R}),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:z=>x(z.target.value)}),e.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-task-description-${t.id}`,children:"Task Description *"}),e.jsx("textarea",{id:`step-task-description-${t.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:v,onChange:z=>y(z.target.value),rows:4,"aria-invalid":!!_.taskDescription}),_.taskDescription&&e.jsx("small",{className:"field-error",children:_.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:z=>j(z.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(Yt,{id:`step-task-model-${t.id}`,label:"Model",models:T,value:Y,onChange:H,placeholder:"Use default",disabled:Z}),R&&e.jsx("small",{className:"field-error",children:R}),_.modelProvider&&e.jsx("small",{className:"field-error",children:_.modelProvider}),e.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:`step-timeout-${t.id}`,children:"Timeout (ms, optional)"}),e.jsx("input",{id:`step-timeout-${t.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:P??"",onChange:z=>w(z.target.value?Number(z.target.value):void 0),"aria-invalid":!!_.timeoutMs}),_.timeoutMs&&e.jsx("small",{className:"field-error",children:_.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:z=>k(z.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:A,children:"Save Step"})]})]})}function lP({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=aP(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(rP,{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(ac,{size:14})}),e.jsx("span",{className:"step-card-index",children:u+1}),e.jsx(iP,{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(qs,{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(Ot,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(c.id),title:"Edit","aria-label":`Edit ${c.name}`,children:e.jsx($n,{size:14})}),e.jsx("button",{type:"button",className:"btn-icon",onClick:()=>o(c.id),title:"Delete","aria-label":`Delete ${c.name}`,children:e.jsx(qt,{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 lf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},oP={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function cP(t){const n=t.trim();for(const[s,i]of Object.entries(lf))if(i===n)return s;return"custom"}function dP(t){const n=t.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function uP(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 mP(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 hP=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],pP=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function jm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function km({routine:t,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:l}){const o=!!t,d=t?mP(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,v]=a.useState(()=>d.triggerType!=="cron"?"custom":cP(d.cronExpression)),[y,M]=a.useState(d.webhookPath),[j,P]=a.useState(d.webhookSecret),[w,S]=a.useState(d.endpoint),[k,_]=a.useState(t?.executionPolicy??"queue"),[E,T]=a.useState(t?.catchUpPolicy??"run_one"),[D,Z]=a.useState(t?.enabled??!0),$=t?.steps&&t.steps.length===1&&t.steps[0].type==="ai-prompt"&&!t.command,R=t?.steps&&t.steps.length===1&&t.steps[0].type==="create-task"&&!t.command,[N,W]=a.useState(t?.steps&&t.steps.length>0&&!$&&!R?"advanced":"simple"),[Y,H]=a.useState(()=>$?"ai-prompt":R?"create-task":"command"),[A,z]=a.useState(t?.command??""),[J,C]=a.useState(t?.steps??[]),[q,oe]=a.useState(!1),[O,V]=a.useState(t?.timeoutMs??3e5),[F,ue]=a.useState($?t.steps?.[0]?.prompt??"":""),[ce,K]=a.useState(R?t.steps?.[0]?.taskTitle??"":""),[de,Fe]=a.useState(R?t.steps?.[0]?.taskDescription??"":""),[we,Ee]=a.useState(R?t.steps?.[0]?.taskColumn??"triage":"triage"),[ie,Pe]=a.useState($||R?t.steps?.[0]?.modelProvider??"":""),[ze,$e]=a.useState($||R?t.steps?.[0]?.modelId??"":""),[He,Me]=a.useState([]),[Te,Ve]=a.useState(!1),[_e,et]=a.useState(null),[le,X]=a.useState(i??"global"),[ke,se]=a.useState({}),[Le,ve]=a.useState(!1),Ye=a.useRef(!0);a.useEffect(()=>()=>{Ye.current=!1},[]),a.useEffect(()=>{i&&X(i)},[i]),a.useEffect(()=>{let Ne=!1;return Ve(!0),et(null),Vn().then(at=>{Ne||Me(at.models)}).catch(at=>{Ne||et(at instanceof Error?at.message:"Failed to load models")}).finally(()=>{Ne||Ve(!1)}),()=>{Ne=!0}},[]);const mt=ie&&ze?`${ie}/${ze}`:"",ht=a.useCallback(Ne=>{if(!Ne){Pe(""),$e("");return}const at=Ne.indexOf("/");at!==-1&&(Pe(Ne.slice(0,at)),$e(Ne.slice(at+1)))},[]),me=a.useCallback(()=>{const Ne={};if(m.trim()||(Ne.name="Name is required"),le==="project"&&!r&&(Ne.scope="Project-specific entries require an active project."),g==="cron"&&x==="custom"&&(f.trim()?dP(f)||(Ne.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Ne.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(Ne.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(Ne.endpoint="API endpoint is required"),N==="simple")Y==="command"&&!A.trim()&&(Ne.command="Command is required"),Y==="ai-prompt"&&!F.trim()&&(Ne.prompt="Prompt is required"),Y==="create-task"&&!de.trim()&&(Ne.taskDescription="Task description is required"),(ie.trim()&&!ze.trim()||!ie.trim()&&ze.trim())&&(Ne.model="Both model provider and model ID must be set, or both must be empty");else{J.length===0&&(Ne.steps="At least one step is required"),q&&(Ne.stepsEditing="Please save or cancel all step edits before saving the routine");const at=[];J.forEach((dt,vt)=>{dt.name?.trim()||at.push(`Step ${vt+1}: Name is required`),dt.type==="command"&&!dt.command?.trim()&&at.push(`Step ${vt+1}: Command is required`),dt.type==="ai-prompt"&&!dt.prompt?.trim()&&at.push(`Step ${vt+1}: Prompt is required`),dt.type==="create-task"&&!dt.taskDescription?.trim()&&at.push(`Step ${vt+1}: Task description is required`)}),at.length>0&&(Ne.steps=at.join("; "))}return O<1e3&&(Ne.timeoutMs="Timeout must be at least 1 second (1000ms)"),se(Ne),Object.keys(Ne).length===0},[m,g,f,x,y,w,le,r,N,Y,A,F,de,ie,ze,J,q,O]),te=a.useCallback(async Ne=>{if(Ne.preventDefault(),!!me()){ve(!0);try{let at=t?.scope??le??(r?"project":"global");at==="project"&&!r&&(at="global");const dt=uP(g,f,y,j,w);let vt,It;N==="simple"?Y==="command"?vt=A.trim()||void 0:Y==="ai-prompt"?It=[{id:jm(),type:"ai-prompt",name:m.trim(),prompt:F.trim(),modelProvider:ie.trim()||void 0,modelId:ze.trim()||void 0}]:It=[{id:jm(),type:"create-task",name:m.trim(),taskTitle:ce.trim()||void 0,taskDescription:de.trim(),taskColumn:we,modelProvider:ie.trim()||void 0,modelId:ze.trim()||void 0}]:It=J;const _t={name:m.trim(),agentId:t?.agentId??"",description:u.trim()||void 0,trigger:dt,command:vt,steps:It,timeoutMs:O,executionPolicy:k,catchUpPolicy:E,enabled:D,scope:at};await n(_t)}finally{Ye.current&&ve(!1)}}},[me,n,m,u,g,f,y,j,w,N,Y,A,F,ie,ze,ce,de,we,J,O,k,E,D,le,r,t?.scope,t?.agentId]),je="routine-name-error",Ae="routine-cron-error",Qe="routine-webhook-error",be="routine-endpoint-error",st="routine-command-error",Se="routine-prompt-error",Je="routine-task-description-error",it="routine-model-error",ye="routine-timeout-error",Ge=a.useCallback(Ne=>{v(Ne),Ne!=="custom"&&b(lf[Ne])},[]);return e.jsxs("form",{className:"routine-form",onSubmit:te,noValidate:!0,children:[e.jsx("h4",{className:"settings-section-heading",children:o?"Edit Routine":"New Routine"}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-name",children:"Name"}),e.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:m,onChange:Ne=>c(Ne.target.value),"aria-invalid":!!ke.name,"aria-describedby":ke.name?je:void 0}),ke.name&&e.jsx("small",{id:je,className:"field-error",children:ke.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:Ne=>h(Ne.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${le==="global"?" active":""}`,onClick:()=>{X("global"),l?.("global")},role:"radio","aria-checked":le==="global"?"true":"false",disabled:!!t?.scope,title:t?.scope?`Scope is locked to ${t.scope} for existing routines`:"Global scope",children:[e.jsx(Ni,{size:12}),"Global"]}),e.jsxs("button",{type:"button",className:`routine-scope-btn${le==="project"?" active":""}`,onClick:()=>{X("project"),l?.("project")},role:"radio","aria-checked":le==="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(Sn,{size:12}),"Project"]})]}),e.jsx("small",{children:!r&&!t?.scope?"No active project. Routines will be created at global scope.":le==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ke.scope&&e.jsx("small",{className:"field-error",children:ke.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(Ym,{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(oh,{size:14}),"Webhook"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[e.jsx(Qm,{size:14}),"API"]}),e.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[e.jsx(Nn,{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:Ne=>Ge(Ne.target.value),children:Object.entries(oP).map(([Ne,at])=>e.jsx("option",{value:Ne,children:at},Ne))}),e.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),e.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:Ne=>b(Ne.target.value),disabled:x!=="custom","aria-invalid":!!ke.cronExpression,"aria-describedby":ke.cronExpression?Ae:void 0}),ke.cronExpression?e.jsx("small",{id:Ae,className:"field-error",children:ke.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:y,onChange:Ne=>M(Ne.target.value),"aria-invalid":!!ke.webhookPath,"aria-describedby":ke.webhookPath?Qe:void 0}),ke.webhookPath?e.jsx("small",{id:Qe,className:"field-error",children:ke.webhookPath}):e.jsx("small",{children:"URL path for the webhook endpoint"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),e.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:Ne=>P(Ne.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:Ne=>S(Ne.target.value),"aria-invalid":!!ke.endpoint,"aria-describedby":ke.endpoint?be:void 0}),ke.endpoint?e.jsx("small",{id:be,className:"field-error",children:ke.endpoint}):e.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&e.jsx("div",{className:"form-group",children:e.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Action Mode"}),e.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[e.jsx("button",{type:"button",className:`schedule-mode-btn${N==="simple"?" active":""}`,onClick:()=>W("simple"),role:"radio","aria-checked":N==="simple",children:"Simple"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${N==="advanced"?" active":""}`,onClick:()=>W("advanced"),role:"radio","aria-checked":N==="advanced",children:"Multi-Step"})]}),e.jsx("small",{children:N==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),N==="simple"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Action Type"}),e.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[e.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="command"?" active":""}`,onClick:()=>H("command"),role:"radio","aria-checked":Y==="command",children:"Command"}),e.jsx("button",{type:"button",className:`schedule-mode-btn${Y==="ai-prompt"?" active":""}`,onClick:()=>H("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:()=>H("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:A,onChange:Ne=>z(Ne.target.value),"aria-invalid":!!ke.command,"aria-describedby":ke.command?st:void 0}),ke.command?e.jsx("small",{id:st,className:"field-error",children:ke.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:Ne=>ue(Ne.target.value),rows:3,"aria-invalid":!!ke.prompt,"aria-describedby":ke.prompt?Se:void 0}),ke.prompt?e.jsx("small",{id:Se,className:"field-error",children:ke.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(Yt,{id:"routine-model",label:"Model",models:He,value:mt,onChange:ht,placeholder:"Use default",disabled:Te}),_e&&e.jsx("small",{className:"field-error",children:_e}),ke.model&&e.jsx("small",{id:it,className:"field-error",children:ke.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:ce,onChange:Ne=>K(Ne.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:Ne=>Fe(Ne.target.value),rows:4,"aria-invalid":!!ke.taskDescription,"aria-describedby":ke.taskDescription?Je:void 0}),ke.taskDescription?e.jsx("small",{id:Je,className:"field-error",children:ke.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:we,onChange:Ne=>Ee(Ne.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(Yt,{id:"routine-task-model",label:"Executor Model",models:He,value:mt,onChange:ht,placeholder:"Use default",disabled:Te}),_e&&e.jsx("small",{className:"field-error",children:_e}),ke.model&&e.jsx("small",{id:it,className:"field-error",children:ke.model})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(lP,{steps:J,onChange:C,onEditingChange:oe}),ke.steps&&e.jsx("small",{className:"field-error",children:ke.steps}),ke.stepsEditing&&e.jsx("small",{className:"field-error",children:ke.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:O,onChange:Ne=>V(Number(Ne.target.value)),"aria-invalid":!!ke.timeoutMs,"aria-describedby":ke.timeoutMs?ye:void 0}),ke.timeoutMs?e.jsx("small",{id:ye,className:"field-error",children:ke.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:Ne=>_(Ne.target.value),children:hP.map(Ne=>e.jsx("option",{value:Ne.value,children:Ne.label},Ne.value))}),e.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),e.jsx("select",{id:"routine-catchup-policy",value:E,onChange:Ne=>T(Ne.target.value),children:pP.map(Ne=>e.jsx("option",{value:Ne.value,children:Ne.label},Ne.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:D,onChange:Ne=>Z(Ne.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:Le,children:"Cancel"}),e.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Le,children:Le?"Saving…":o?"Save Changes":"Create Routine"})]})]})}const fP=3e4;function gP({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 T=await oy(p);o(T)}catch(T){n(fe(T)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const T=setInterval(()=>{f()},fP);return()=>clearInterval(T)},[f]),a.useEffect(()=>{const T=D=>{D.key==="Escape"&&(d!=="list"?(m("list"),u(void 0)):t())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[t,d]);const b=a.useCallback(T=>{T.target===T.currentTarget&&t()},[t]),x=a.useCallback(async T=>{try{await cy(T,p),n("Routine created","success"),m("list"),await f()}catch(D){n(fe(D)||"Failed to create routine","error")}},[n,f,p]),v=a.useCallback(T=>{u(T),m("edit")},[]),y=a.useCallback(async T=>{if(c)try{await od(c.id,T,p),n("Routine updated","success"),m("list"),u(void 0),await f()}catch(D){n(fe(D)||"Failed to update routine","error")}},[c,n,f,p]),M=a.useCallback(async T=>{try{await dy(T.id,p),n(`Deleted "${T.name}"`,"success"),await f()}catch(D){n(fe(D)||"Failed to delete routine","error")}},[n,f,p]),j=a.useCallback(async T=>{g(T.id);try{const{result:D}=await uy(T.id,p);D.success?n(`"${T.name}" completed successfully`,"success"):n(`"${T.name}" failed: ${D.error||"Unknown error"}`,"error"),await f()}catch(D){n(fe(D)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),P=a.useCallback(async T=>{try{await od(T.id,{enabled:!T.enabled},p),n(`"${T.name}" ${T.enabled?"disabled":"enabled"}`,"success"),await f()}catch(D){n(fe(D)||"Failed to toggle routine","error")}},[n,f,p]),w=a.useCallback(()=>{m("list"),u(void 0)},[]),S=a.useCallback(T=>{r(T),m("list"),u(void 0)},[]),k=()=>d==="create"?e.jsx(km,{onSubmit:x,onCancel:w,scope:i,projectId:s}):d==="edit"&&c?e.jsx(km,{routine:c,onSubmit:y,onCancel:w,scope:i,projectId:s}):l.length===0?e.jsxs("div",{className:"routine-empty-state",children:[e.jsx(Nn,{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(T=>e.jsx(sP,{routine:T,onEdit:v,onDelete:M,onRun:j,onToggle:P,running:h===T.id},T.id))}),_=()=>k(),E=d==="list"&&l.length>0;return e.jsx("div",{className:"modal-overlay open",onClick:b,children:e.jsxs("div",{className:"modal modal-lg",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[e.jsxs("div",{className:"modal-header scheduling-modal-header",children:[e.jsxs("div",{className:"scheduling-header-main-row",children:[e.jsxs("div",{className:"detail-title-row",children:[e.jsx(Nn,{size:20,className:"icon-triage"}),e.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),e.jsxs("div",{className:"modal-header-actions",children:[E&&e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),"aria-label":"Create new automation",children:[e.jsx(Vt,{size:14}),"New Automation"]}),e.jsx("button",{className:"modal-close",onClick:t,"aria-label":"Close",children:e.jsx(Lt,{size:20})})]})]}),e.jsx("div",{className:"scheduling-header-scope-row",role:"group","aria-label":"Scheduling scope",children:e.jsxs("div",{className:"scheduling-scope-selector",children:[e.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>S("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[e.jsx(Ni,{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(Sn,{size:14}),"Project"]})]})})]}),e.jsxs("div",{className:"scheduling-summary","aria-live":"polite",children:[e.jsx(Nn,{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(Nn,{size:14})," Routines"]})}),e.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:_()})]})})}const bP=3e4,Qo=new Map,bo=new Map;function wm(t){return t??"default"}function Nm(t){const n=Qo.get(t);return n?Date.now()>=n.expiresAt?(Qo.delete(t),null):n:null}function xP(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 vP(t){const n=bo.get(t);if(n)return n;const s=Ei().then(({providers:i,ghCli:r})=>{const o={...xP(i,r),ghCli:r,expiresAt:Date.now()+bP};return Qo.set(t,o),o}).finally(()=>{bo.delete(t)});return bo.set(t,s),s}function of(t){const n=wm(t),s=Nm(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=wm(t),p=Nm(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 vP(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 cf({hasAiProvider:t,hasGithub:n,compact:s=!1,onDismiss:i}){if(t&&n)return null;const r=i?e.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:e.jsx(Lt,{size:16,"aria-hidden":"true"})}):null;if(s)return e.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[e.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const l=[];return t||l.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||l.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),e.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,l.map(o=>e.jsxs("div",{className:"setup-warning-banner__item",children:[e.jsx("strong",{className:"setup-warning-banner__title",children:o.title}),e.jsx("p",{className:"setup-warning-banner__description",children:o.description})]},o.key))]})}function yP({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,v]=a.useState(""),[y,M]=a.useState(""),[j,P]=a.useState(""),[w,S]=a.useState(""),[k,_]=a.useState(""),[E,T]=a.useState("default"),[D,Z]=a.useState(!1),[$,R]=a.useState([]),[N,W]=a.useState(!1),[Y,H]=a.useState(void 0),[A,z]=a.useState(cs),[J,C]=a.useState(null),[q,oe]=a.useState([]),[O,V]=a.useState(!1),[F,ue]=a.useState(!1),ce=a.useRef(null),[K,de]=a.useState(!1),[Fe,we]=a.useState(""),Ee=a.useRef(null),{hasAiProvider:ie,hasGithub:Pe,loading:ze}=of(s),$e=a.useCallback(ve=>{W(!0),R(ve)},[]),He=a.useCallback(()=>{W(!1)},[]),Me=a.useCallback(async()=>{if(q.length>0){V(!0);return}ue(!0);try{const ve=await da(void 0,s);oe(ve),V(!0)}catch(ve){const Ye=fe(ve);l(Ye?`Failed to load agents: ${Ye}`:"Failed to load agents","error"),V(!1)}finally{ue(!1)}},[q.length,s,l]);a.useEffect(()=>{if(!O)return;const ve=Ye=>{ce.current&&!ce.current.contains(Ye.target)&&V(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[O]),a.useEffect(()=>{if(!K)return;const ve=Ye=>{Ee.current&&!Ee.current.contains(Ye.target)&&(de(!1),we(""))};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[K]);const Te=i.filter(ve=>!u.includes(ve.id)).sort((ve,Ye)=>{const mt=Ye.createdAt.localeCompare(ve.createdAt);if(mt!==0)return mt;const ht=parseInt(ve.id.slice(ve.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ye.id.slice(Ye.id.lastIndexOf("-")+1),10)||0)-ht}),Ve=Fe?Te.filter(ve=>ve.id.toLowerCase().includes(Fe.toLowerCase())||ve.title&&ve.title.toLowerCase().includes(Fe.toLowerCase())||ve.description&&ve.description.toLowerCase().includes(Fe.toLowerCase())):Te,_e=(ve,Ye)=>ve.length>Ye?ve.slice(0,Ye)+"…":ve;a.useEffect(()=>{const ve=m.trim()!==""||u.length>0||g.length>0||x!==""||y!==""||j!==""||w!==""||$.length>0||J!==null||Y!==void 0||A!==cs;Z(ve)},[m,u,g,x,y,j,w,$,J,Y,A]);const et=a.useCallback(()=>{D&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(ve=>URL.revokeObjectURL(ve.previewUrl)),p([]),c(""),h([]),v(""),M(""),P(""),S(""),_(""),T("default"),R([]),W(!1),C(null),V(!1),H(void 0),z(cs),Z(!1),n())},[D,n,g]),le=a.useCallback(async()=>{const ve=m.trim();if(!(!ve||f)){b(!0);try{const Ye=x.indexOf("/"),mt=y.indexOf("/"),ht=j.indexOf("/"),me=await r({title:void 0,description:ve,column:"triage",dependencies:u.length?u:void 0,enabledWorkflowSteps:N?$.length>0?$:[]:void 0,...J?{assignedAgentId:J}:{},modelPresetId:E==="preset"&&k||void 0,modelProvider:x&&Ye!==-1?x.slice(0,Ye):void 0,modelId:x&&Ye!==-1?x.slice(Ye+1):void 0,validatorModelProvider:y&&mt!==-1?y.slice(0,mt):void 0,validatorModelId:y&&mt!==-1?y.slice(mt+1):void 0,planningModelProvider:j&&ht!==-1?j.slice(0,ht):void 0,planningModelId:j&&ht!==-1?j.slice(ht+1):void 0,thinkingLevel:w!==""?w:void 0,reviewLevel:Y,priority:A});if(g.length>0){const te=[];for(const je of g)try{await Ha(me.id,je.file,s)}catch{te.push(je.file.name)}te.length>0&&l(`Failed to upload: ${te.join(", ")}`,"error")}g.forEach(te=>URL.revokeObjectURL(te.previewUrl)),p([]),c(""),h([]),v(""),M(""),P(""),S(""),_(""),T("default"),R([]),W(!1),C(null),V(!1),H(void 0),z(cs),l(`Created ${me.id}`,"success"),n()}catch(Ye){l(fe(Ye)||"Failed to create task","error")}finally{b(!1)}}},[m,u,g,x,y,j,w,f,r,l,n,s,E,k,$,N,J,Y,A]),X=a.useCallback(ve=>{ve.key==="Escape"&&(ve.preventDefault(),et())},[et]),se=(J?q.find(ve=>ve.id===J):void 0)?.name??J,Le=e.jsxs("div",{className:"new-task-quick-fields",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Dependencies"}),e.jsxs("div",{className:"dep-trigger-wrap",ref:Ee,children:[e.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(ve=>!ve),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:Fe,onChange:ve=>we(ve.target.value),onClick:ve=>ve.stopPropagation()}),Ve.length===0?e.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ve.map(ve=>e.jsxs("div",{className:`dep-dropdown-item${u.includes(ve.id)?" selected":""}`,onClick:()=>{h(u.includes(ve.id)?u.filter(Ye=>Ye!==ve.id):[...u,ve.id]),de(!1),we("")},onMouseDown:Ye=>Ye.preventDefault(),children:[e.jsx("span",{className:"dep-dropdown-id",children:ve.id}),e.jsx("span",{className:"dep-dropdown-title",children:_e(ve.title||ve.description||ve.id,30)})]},ve.id))]})]}),u.length>0&&e.jsx("div",{className:"selected-deps",children:u.map(ve=>e.jsxs("span",{className:"dep-chip",children:[ve,e.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(u.filter(Ye=>Ye!==ve)),disabled:f,children:"×"})]},ve))})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{children:"Assign Agent"}),e.jsxs("div",{className:"agent-trigger-wrap",ref:ce,children:[e.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{O?V(!1):Me()},disabled:f,"data-testid":"new-task-agent-button",children:[e.jsx(rn,{size:12,style:{verticalAlign:"middle"}}),se?` ${se}`:" Assign agent"]}),O&&e.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ve=>ve.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&&q.filter(ve=>ve.state!=="terminated").map(ve=>e.jsxs("div",{className:`dep-dropdown-item${J===ve.id?" selected":""}`,onMouseDown:Ye=>Ye.preventDefault(),onClick:()=>{C(ve.id===J?null:ve.id),V(!1)},"data-testid":`agent-option-${ve.id}`,children:[e.jsx(rn,{size:12,style:{marginRight:6}}),e.jsx("span",{className:"dep-dropdown-id",children:ve.role}),e.jsx("span",{className:"dep-dropdown-title",children:ve.name})]},ve.id)),!F&&q.filter(ve=>ve.state!=="terminated").length===0&&e.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),J&&e.jsx("div",{className:"dep-dropdown-item",onMouseDown:ve=>ve.preventDefault(),onClick:()=>{C(null),V(!1)},children:e.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return t?e.jsx("div",{className:"modal-overlay open",onClick:et,onKeyDown:X,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ve=>ve.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:"New Task"}),e.jsx("button",{className:"modal-close",onClick:et,disabled:f,"aria-label":"Close",children:"×"})]}),e.jsxs("div",{className:"modal-body",children:[!ze&&e.jsx(cf,{hasAiProvider:ie,hasGithub:Pe}),e.jsx(Zp,{mode:"create",description:m,onDescriptionChange:c,dependencies:u,onDependenciesChange:h,executorModel:x,onExecutorModelChange:v,validatorModel:y,onValidatorModelChange:M,presetMode:E,onPresetModeChange:T,selectedPresetId:k,onSelectedPresetIdChange:_,selectedWorkflowSteps:$,onWorkflowStepsChange:$e,onDefaultOnApplied:He,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:l,isActive:t,onPlanningMode:o,onSubtaskBreakdown:d,onClose:et,planningModel:j,onPlanningModelChange:P,thinkingLevel:w,onThinkingLevelChange:S,reviewLevel:Y,onReviewLevelChange:H,priority:A,onPriorityChange:z,renderBelowPrimary:Le,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:et,disabled:f,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary btn-sm",onClick:le,disabled:!m.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const jP=5e3;function kP(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 bd({limit:i,projectId:n,type:s}):M=(await cd({limit:i,type:s,projectId:n})).map(P=>({...P,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]),v=a.useCallback(async()=>{if(b.current)try{c(!0);let M;l?M=await bd({limit:i,projectId:n,type:s,since:b.current}):M=(await cd({limit:i,type:s,since:b.current,projectId:n})).map(P=>({...P,projectId:n??"",projectName:""})),d(j=>[...j,...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]),y=a.useCallback(()=>{d([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{x()},[x]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{x()},jP),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,x]),{entries:o,loading:m,error:u,refresh:x,clear:y,hasMore:g,loadMore:v}}const xo={"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"},wP={"task:created":e.jsx(Vt,{size:14,className:"activity-icon created"}),"task:moved":e.jsx(Ga,{size:14,className:"activity-icon moved"}),"task:updated":e.jsx(vn,{size:14,className:"activity-icon updated"}),"task:deleted":e.jsx(Lt,{size:14,className:"activity-icon deleted"}),"task:merged":e.jsx(sn,{size:14,className:"activity-icon merged"}),"task:failed":e.jsx(Ja,{size:14,className:"activity-icon failed"}),"settings:updated":e.jsx(Ua,{size:14,className:"activity-icon settings"})};function NP(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 SP({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:v,loading:y,error:M,refresh:j,hasMore:P}=kP({projectId:b,type:f,limit:100,autoRefresh:t,useCentralFeed:x}),w=v.map(T=>({id:T.id,timestamp:T.timestamp,type:T.type,taskId:T.taskId,taskTitle:T.taskTitle,details:T.details,metadata:T.metadata,projectId:T.projectId,projectName:T.projectName})),S=async()=>{try{await my(),j(),p(!1)}catch{p(!1)}},k=T=>{i&&i(T)},_=T=>{h(T),o?.(T==="all"?void 0:T)};a.useEffect(()=>{if(!t)return;const T=D=>{D.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[t,n,g]);const E=m!=="all"||u!=="all";return t?e.jsx("div",{className:"modal-overlay open",onClick:T=>{T.target===T.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(Ba,{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(Sn,{size:14}),e.jsxs("select",{value:u,onChange:T=>_(T.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[e.jsx("option",{value:"all",children:"All Projects"}),l.map(T=>e.jsx("option",{value:T.id,children:T.name},T.id))]})]}),e.jsxs("div",{className:"activity-log-filter",children:[e.jsx(zr,{size:14}),e.jsxs("select",{value:m,onChange:T=>c(T.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[e.jsx("option",{value:"all",children:"All Events"}),Object.entries(xo).map(([T,D])=>e.jsx("option",{value:T,children:D},T))]})]}),e.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?e.jsx(ut,{size:14,className:"spin"}):e.jsx(vn,{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(qt,{size:14})})]}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&e.jsxs("div",{className:"activity-log-active-filters",children:[e.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),u!=="all"&&e.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",l.find(T=>T.id===u)?.name||u]}),m!=="all"&&e.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",xo[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(ss,{size:16}),e.jsx("span",{children:M})]}),w.length===0&&!y&&!M&&e.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[e.jsx(Ba,{size:48,className:"activity-log-empty-icon"}),e.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&e.jsx("button",{className:"btn btn-secondary",onClick:()=>{c("all"),h("all"),o?.(void 0)},children:"Clear Filters"})]}),e.jsx("div",{className:"activity-log-list",children:w.map(T=>e.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[e.jsx("div",{className:"activity-log-entry-icon",children:wP[T.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:xo[T.type]}),e.jsx("span",{className:"activity-log-entry-time",children:NP(T.timestamp)})]}),e.jsxs("div",{className:"activity-log-entry-details",children:[T.taskId&&e.jsx("button",{className:"activity-log-task-link",onClick:()=>k(T.taskId),"data-testid":"activity-task-link",children:T.taskId}),T.taskTitle&&e.jsx("span",{className:"activity-log-task-title",children:T.taskTitle}),e.jsx("span",{className:"activity-log-entry-text",children:T.details})]}),T.metadata&&Object.keys(T.metadata).length>0&&e.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof T.metadata.from=="string"&&typeof T.metadata.to=="string"&&e.jsxs("span",{className:"activity-log-metadata-item",children:[T.metadata.from," → ",T.metadata.to]}),typeof T.metadata.merged=="boolean"&&e.jsx("span",{className:`activity-log-metadata-item ${T.metadata.merged?"success":"error"}`,children:T.metadata.merged?"Merged":"Not merged"})]})]})]},T.id))}),P&&!y&&e.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&e.jsx("div",{className:"activity-log-loading",children:e.jsx(ut,{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 Aa=[{id:"status",label:"Status",icon:ah},{id:"changes",label:"Changes",icon:Xm},{id:"commits",label:"Commits",icon:Oa},{id:"branches",label:"Branches",icon:Vs},{id:"worktrees",label:"Worktrees",icon:Jg},{id:"stashes",label:"Stashes",icon:nl},{id:"remotes",label:"Remotes",icon:th}];function Sm({status:t}){switch(t){case"added":case"untracked":return e.jsx(Pg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return e.jsx(Zm,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return e.jsx(Eg,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return e.jsx(wi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return e.jsx(_g,{size:14,className:"gm-file-icon"})}}function Cm({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 CP(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 sa(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 EP({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=CP(i),[p,f]=a.useState(null),[b,x]=a.useState([]),[v,y]=a.useState(new Set),[M,j]=a.useState(""),[P,w]=a.useState(!1),[S,k]=a.useState(null),[_,E]=a.useState(!1),[T,D]=a.useState(null),[Z,$]=a.useState(null),R=a.useRef(0),[N,W]=a.useState([]),[Y,H]=a.useState(null),[A,z]=a.useState(null),[J,C]=a.useState(!1),[q,oe]=a.useState(20),[O,V]=a.useState(""),[F,ue]=a.useState([]),[ce,K]=a.useState(""),[de,Fe]=a.useState(""),[we,Ee]=a.useState(""),[ie,Pe]=a.useState(null),[ze,$e]=a.useState([]),[He,Me]=a.useState(!1),[Te,Ve]=a.useState(null),[_e,et]=a.useState(null),[le,X]=a.useState(!1),[ke,se]=a.useState([]),[Le,ve]=a.useState([]),[Ye,mt]=a.useState(""),[ht,me]=a.useState(null),[te,je]=a.useState(null),[Ae,Qe]=a.useState(null),be=a.useCallback(async()=>{if(t){m(!0),u(null);try{switch(l){case"status":{const he=await _s(r);f(he);break}case"changes":{const[he,Be]=await Promise.all([_s(r),$i(r)]);f(he),x(Be),y(new Set),$(null),k(null),D(null);break}case"commits":{const he=await vv(q,r);W(he);break}case"branches":{const[he,Be]=await Promise.all([ba(r),_s(r)]);ue(he),f(Be);break}case"worktrees":{const he=await wv(r);se(he);break}case"stashes":{const he=await fr(r);ve(he);break}case"remotes":{const he=await _s(r);f(he);break}}}catch(he){u(fe(he)||"Failed to fetch git data"),i(fe(he)||"Failed to fetch git data","error")}finally{m(!1)}}},[l,t,q,i,r]);a.useEffect(()=>{t&&be()},[be,t]),a.useEffect(()=>{if(!t)return;const he=Be=>{if(Be.key==="Escape"){n();return}if((Be.key==="ArrowUp"||Be.key==="ArrowDown")&&Be.altKey){Be.preventDefault();const gt=Aa.findIndex(Kt=>Kt.id===l);Be.key==="ArrowUp"&&gt>0?o(Aa[gt-1].id):Be.key==="ArrowDown"&&gt<Aa.length-1&&o(Aa[gt+1].id)}};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[t,n,l]);const st=a.useCallback(async he=>{try{await id(he,r),i(`Staged ${he.length} file(s)`,"success");const Be=await $i(r);x(Be),y(new Set),$(null),k(null),D(null)}catch(Be){i(fe(Be)||"Failed to stage files","error")}},[i,r]),Se=a.useCallback(async he=>{try{await Rv(he,r),i(`Unstaged ${he.length} file(s)`,"success");const Be=await $i(r);x(Be),y(new Set),$(null),k(null),D(null)}catch(Be){i(fe(Be)||"Failed to unstage files","error")}},[i,r]),Je=a.useCallback(async he=>{if(confirm(`Discard changes to ${he.length} file(s)? This cannot be undone.`))try{await Tv(he,r),i(`Discarded changes to ${he.length} file(s)`,"success");const[Be,gt]=await Promise.all([$i(r),_s(r)]);x(Be),f(gt),y(new Set),$(null),k(null),D(null)}catch(Be){i(fe(Be)||"Failed to discard changes","error")}},[i,r]),it=a.useCallback(async he=>{if(he.preventDefault(),!!M.trim()){w(!0);try{const Be=await ad(M.trim(),r);i(`Committed: ${Be.hash}`,"success"),j("");const[gt,Kt]=await Promise.all([$i(r),_s(r)]);x(gt),f(Kt),$(null),k(null),D(null)}catch(Be){i(fe(Be)||"Failed to commit","error")}finally{w(!1)}}},[M,i,r]),ye=a.useCallback(async()=>{if(M.trim()){w(!0);try{const he=b.filter(yn=>!yn.staged).map(yn=>yn.file);he.length>0&&await id(he,r);const Be=await ad(M.trim(),r);i(`Committed: ${Be.hash}`,"success"),j("");const[gt,Kt]=await Promise.all([$i(r),_s(r)]);x(gt),f(Kt),$(null),k(null),D(null)}catch(he){i(fe(he)||"Failed to commit","error")}finally{w(!1)}}},[M,b,i,r]),Ge=a.useCallback(async(he,Be)=>{$({file:he,staged:Be}),E(!0),D(null);const gt=R.current+1;R.current=gt;try{const Kt=await _v(he,Be,r);if(R.current!==gt)return;k(Kt)}catch(Kt){if(R.current!==gt)return;const yn=fe(Kt)||"Failed to load file diff";k(null),D(yn),i(yn,"error")}finally{R.current===gt&&E(!1)}},[i,r]),Ne=a.useCallback(he=>{y(Be=>{const gt=new Set(Be);return gt.has(he)?gt.delete(he):gt.add(he),gt})},[]),at=a.useCallback(async he=>{if(Y===he){H(null),z(null);return}H(he),C(!0);try{const Be=await qr(he,r);z(Be)}catch(Be){i(fe(Be)||"Failed to load diff","error"),z(null)}finally{C(!1)}},[Y,i,r]),dt=a.useCallback(()=>{oe(he=>Math.min(he+20,100))},[]),vt=a.useMemo(()=>{if(!O.trim())return N;const he=O.toLowerCase();return N.filter(Be=>Be.message.toLowerCase().includes(he)||Be.author.toLowerCase().includes(he)||Be.shortHash.toLowerCase().includes(he))},[N,O]),It=a.useCallback(async he=>{if(he.preventDefault(),!!ce.trim()){m(!0);try{await Nv(ce.trim(),de.trim()||void 0,r),i(`Created branch ${ce}`,"success"),K(""),Fe("");const Be=await ba(r);ue(Be)}catch(Be){i(fe(Be)||"Failed to create branch","error")}finally{m(!1)}}},[ce,de,i,r]),_t=a.useCallback(async he=>{m(!0);try{await Sv(he,r),i(`Switched to ${he}`,"success");const[Be,gt]=await Promise.all([_s(r),ba(r)]);f(Be),ue(gt)}catch(Be){i(fe(Be)||"Failed to checkout branch","error")}finally{m(!1)}},[i,r]),Mt=a.useCallback(async he=>{if(confirm(`Delete branch "${he}"?`)){m(!0);try{await sd(he,void 0,r),i(`Deleted branch ${he}`,"success");const Be=await ba(r);ue(Be)}catch(Be){if(fe(Be).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await sd(he,!0,r),i(`Force deleted branch ${he}`,"success");const gt=await ba(r);ue(gt)}catch(gt){i(fe(gt)||"Failed to delete branch","error")}}else i(fe(Be)||"Failed to delete branch","error")}finally{m(!1)}}},[i,r]),zt=a.useMemo(()=>{if(!we.trim())return F;const he=we.toLowerCase();return F.filter(Be=>Be.name.toLowerCase().includes(he))},[F,we]),Nt=a.useCallback(async he=>{if(ie===he){Pe(null),$e([]),Ve(null),et(null);return}Pe(he),$e([]),Ve(null),et(null),Me(!0);try{const Be=await kv(he,10,r);$e(Be)}catch{$e([])}finally{Me(!1)}},[ie,r]),Pt=a.useCallback(async he=>{if(Te===he){Ve(null),et(null);return}Ve(he),et(null),X(!0);try{const Be=await qr(he,r);et(Be)}catch{et(null)}finally{X(!1)}},[Te,r]),tt=a.useCallback(()=>{Pe(null),$e([]),Ve(null),et(null)},[]),bt=a.useCallback(async he=>{he.preventDefault(),me("create");try{await Av(Ye.trim()||void 0,r),i("Changes stashed","success"),mt("");const Be=await fr(r);ve(Be)}catch(Be){i(fe(Be)||"Failed to stash changes","error")}finally{me(null)}},[Ye,i,r]),Ue=a.useCallback(async(he,Be=!1)=>{me(`apply-${he}`);try{await Pv(he,Be,r),i(Be?"Stash popped":"Stash applied","success");const gt=await fr(r);ve(gt)}catch(gt){i(fe(gt)||"Failed to apply stash","error")}finally{me(null)}},[i,r]),ot=a.useCallback(async he=>{if(confirm(`Drop stash@{${he}}? This cannot be undone.`)){me(`drop-${he}`);try{await Iv(he,r),i("Stash dropped","success");const Be=await fr(r);ve(Be)}catch(Be){i(fe(Be)||"Failed to drop stash","error")}finally{me(null)}}},[i,r]),ge=a.useCallback(async()=>{je("fetch");try{const he=await Cv(void 0,r);Qe(he),i(he.message||"Fetch completed",he.fetched?"success":"info");const Be=await _s(r);f(Be)}catch(he){i(fe(he)||"Fetch failed","error")}finally{je(null)}},[i,r]),Oe=a.useCallback(async()=>{je("pull");try{const he=await Ev(r);Qe(he),he.conflict?i("Merge conflict detected. Resolve manually.","error"):i(he.message||"Pull completed","success");const Be=await _s(r);f(Be)}catch(he){i(fe(he)||"Pull failed","error")}finally{je(null)}},[i,r]),ee=a.useCallback(async()=>{je("push");try{const he=await Mv(r);Qe(he),i(he.message||"Push completed","success");const Be=await _s(r);f(Be)}catch(he){i(fe(he)||"Push failed","error")}finally{je(null)}},[i,r]),Ie=a.useMemo(()=>b.filter(he=>he.staged),[b]),xt=a.useMemo(()=>b.filter(he=>!he.staged),[b]);return t?e.jsx("div",{className:"modal-overlay open",onClick:he=>he.target===he.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(Eo,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),e.jsxs("div",{className:"gm-header-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:be,disabled:d,title:"Refresh",children:e.jsx(vn,{size:14,className:d?"spin":""})}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:e.jsx(Lt,{size:18})})]})]}),e.jsxs("div",{className:"gm-layout",children:[e.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Aa.map(he=>{const Be=he.icon;return e.jsxs("button",{role:"tab","aria-selected":l===he.id,className:`gm-nav-item${l===he.id?" active":""}`,onClick:()=>o(he.id),children:[e.jsx(Be,{size:16}),e.jsx("span",{className:"gm-nav-label",children:he.label})]},he.id)})}),e.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&e.jsxs("div",{className:"gm-loading",children:[e.jsx(ut,{size:24,className:"spin"}),e.jsx("span",{children:"Loading..."})]}),c&&!d&&e.jsxs("div",{className:"gm-error",children:[e.jsx(ss,{size:18}),e.jsx("span",{children:c}),e.jsx("button",{className:"btn btn-sm",onClick:be,children:"Retry"})]}),l==="status"&&!d&&p&&e.jsx(MP,{status:p,copyToClipboard:g}),l==="changes"&&!d&&e.jsx(AP,{status:p,stagedFiles:Ie,unstagedFiles:xt,selectedFiles:v,toggleFileSelection:Ne,onStageFiles:st,onUnstageFiles:Se,onDiscardChanges:Je,onSelectDiffFile:Ge,selectedDiffTarget:Z,changeDiff:S,loadingChangeDiff:_,changeDiffError:T,commitMessage:M,setCommitMessage:j,onCommit:it,onStageAllAndCommit:ye,committing:P}),l==="commits"&&!d&&e.jsx(PP,{commits:vt,commitSearch:O,setCommitSearch:V,selectedCommit:Y,commitDiff:A,loadingDiff:J,onCommitClick:at,onLoadMore:dt,canLoadMore:N.length>=q&&q<100,copyToClipboard:g}),l==="branches"&&!d&&e.jsx(IP,{branches:zt,branchSearch:we,setBranchSearch:Ee,newBranchName:ce,setNewBranchName:K,branchBase:de,setBranchBase:Fe,onCreateBranch:It,onCheckoutBranch:_t,onDeleteBranch:Mt,loading:d,allBranches:F,selectedBranch:ie,branchCommits:ze,loadingBranchCommits:He,expandedBranchCommit:Te,branchCommitDiff:_e,loadingBranchCommitDiff:le,onSelectBranch:Nt,onBranchCommitClick:Pt,onCloseBranchDetails:tt}),l==="worktrees"&&!d&&e.jsx(_P,{worktrees:ke}),l==="stashes"&&!d&&e.jsx(RP,{stashes:Le,stashMessage:Ye,setStashMessage:mt,onCreateStash:bt,onApplyStash:Ue,onDropStash:ot,stashLoading:ht}),l==="remotes"&&!d&&e.jsx(TP,{status:p,remoteLoading:te,lastRemoteResult:Ae,onFetch:ge,onPull:Oe,onPush:ee,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function MP({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(Vs,{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(Gi,{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(ss,{size:12}),"Modified"]}):e.jsxs(e.Fragment,{children:[e.jsx(sn,{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(ji,{size:12}),t.ahead]}),t.behind>0&&e.jsxs("span",{className:"gm-behind",title:`${t.behind} commit(s) behind`,children:[e.jsx(Ka,{size:12}),t.behind]}),t.ahead===0&&t.behind===0&&e.jsxs("span",{className:"gm-in-sync",children:[e.jsx(sn,{size:12}),"Up to date"]})]})]})]})]})}function AP({status:t,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:l,onUnstageFiles:o,onDiscardChanges:d,onSelectDiffFile:m,selectedDiffTarget:c,changeDiff:u,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:b,onStageAllAndCommit:x,committing:v}){const y=s.filter(j=>i.has(`unstaged:${j.file}`)),M=n.filter(j=>i.has(`staged:${j.file}`));return e.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[t&&e.jsxs("div",{className:"gm-changes-header",children:[e.jsxs("span",{className:"gm-branch-indicator",children:[e.jsx(Vs,{size:14}),t.branch]}),t.isDirty&&e.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),e.jsxs("div",{className:"gm-file-section",children:[e.jsxs("div",{className:"gm-file-section-header",children:[e.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),e.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>l(y.map(j=>j.file)),title:"Stage selected",children:[e.jsx(Vt,{size:12})," Stage (",y.length,")"]}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>d(y.map(j=>j.file)),title:"Discard selected",children:e.jsx(Ja,{size:12})})]}),s.length>0&&e.jsx("button",{className:"btn btn-sm",onClick:()=>l(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),e.jsx("div",{className:"gm-file-list",children:s.length===0?e.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const P=c?.file===j.file&&c.staged===!1;return e.jsxs("div",{className:`gm-file-item${P?" active":""}`,onClick:()=>m(j.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),m(j.file,!1))},children:[e.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),e.jsx(Sm,{status:j.status}),e.jsx("span",{className:"gm-file-name",title:j.file,children:j.file}),e.jsx(Cm,{status:j.status}),e.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([j.file])},title:"Stage file",children:e.jsx(Vt,{size:12})})]},`unstaged:${j.file}`)})})]}),e.jsxs("div",{className:"gm-file-section",children:[e.jsxs("div",{className:"gm-file-section-header",children:[e.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),e.jsxs("div",{className:"gm-file-section-actions",children:[M.length>0&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>o(M.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",M.length,")"]}),n.length>0&&e.jsx("button",{className:"btn btn-sm",onClick:()=>o(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),e.jsx("div",{className:"gm-file-list",children:n.length===0?e.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const P=c?.file===j.file&&c.staged===!0;return e.jsxs("div",{className:`gm-file-item staged${P?" active":""}`,onClick:()=>m(j.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),m(j.file,!0))},children:[e.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:e.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),e.jsx(Sm,{status:j.status}),e.jsx("span",{className:"gm-file-name",title:j.file,children:j.file}),e.jsx(Cm,{status:j.status}),e.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([j.file])},title:"Unstage file",children:e.jsx(Lt,{size:12})})]},`staged:${j.file}`)})})]}),(c||h||u||g)&&e.jsxs("div",{className:"gm-diff-section",children:[c&&e.jsxs("div",{className:"gm-diff-target",children:[e.jsx(Xm,{size:14}),e.jsxs("span",{children:[c.staged?"Staged":"Unstaged"," diff: "]}),e.jsx("code",{children:c.file})]}),h&&e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ut,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&e.jsx("div",{className:"gm-diff-error",children:g}),u&&!h&&e.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&e.jsx("pre",{className:"gm-diff-stat",children:u.stat}),e.jsx("pre",{className:"gm-diff-patch",children:u.patch})]})]}),e.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[e.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>f(j.target.value),rows:3,disabled:v}),e.jsxs("div",{className:"gm-commit-actions",children:[e.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:v||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[v?e.jsx(ut,{size:14,className:"spin"}):e.jsx(yi,{size:14}),"Commit"]}),s.length>0&&e.jsx("button",{type:"button",className:"btn btn-sm",onClick:x,disabled:v||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function PP({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(qi,{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:sa(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(Gi,{size:12})})}),i===u.hash&&e.jsx("div",{className:"gm-commit-diff",children:l?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ut,{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 IP({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:v,onSelectBranch:y,onBranchCommitClick:M,onCloseBranchDetails:j}){return e.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[e.jsxs("div",{className:"gm-panel-header",children:[e.jsx("h4",{children:"Branches"}),e.jsxs("div",{className:"gm-search-box",children:[e.jsx(qi,{size:14}),e.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:P=>s(P.target.value)})]})]}),e.jsxs("form",{className:"gm-create-form",onSubmit:d,children:[e.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:P=>r(P.target.value),disabled:u}),e.jsxs("select",{value:l,onChange:P=>o(P.target.value),disabled:u,className:"gm-branch-select",children:[e.jsx("option",{value:"",children:"Base: HEAD"}),h.map(P=>e.jsx("option",{value:P.name,children:P.name},P.name))]}),e.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:u||!i.trim(),children:[e.jsx(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(P=>e.jsxs("div",{children:[e.jsxs("div",{className:`gm-branch-item${P.isCurrent?" current":""}${g===P.name?" selected":""}`,onClick:()=>y(P.name),children:[e.jsxs("div",{className:"gm-branch-info",children:[e.jsxs("span",{className:"gm-branch-name",children:[P.isCurrent&&e.jsx(An,{size:14,className:"gm-current-icon"}),P.name]}),P.remote&&e.jsxs("span",{className:"gm-branch-remote",children:["→ ",P.remote]}),P.lastCommitDate&&e.jsx("span",{className:"gm-branch-date",children:sa(P.lastCommitDate)})]}),e.jsx("div",{className:"gm-branch-actions",children:!P.isCurrent&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),m(P.name)},disabled:u,title:"Checkout",children:e.jsx(Vs,{size:14})}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),c(P.name)},disabled:u,title:"Delete",children:e.jsx(qt,{size:14})})]})})]}),g===P.name&&e.jsxs("div",{className:"gm-branch-details",children:[e.jsxs("div",{className:"gm-branch-details-header",children:[e.jsxs("span",{className:"gm-branch-details-title",children:[e.jsx(Oa,{size:14}),"Commits on ",P.name]}),e.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:e.jsx(Lt,{size:14})})]}),f?e.jsxs("div",{className:"gm-branch-details-loading",children:[e.jsx(ut,{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:sa(w.date)}),w.parents.length>1&&e.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===w.hash&&e.jsx("div",{className:"gm-commit-diff",children:v?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ut,{size:16,className:"spin"}),"Loading diff..."]}):x?e.jsxs(e.Fragment,{children:[x.stat&&e.jsx("pre",{className:"gm-diff-stat",children:x.stat}),e.jsx("pre",{className:"gm-diff-patch",children:x.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},P.name))})]})}function _P({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(Vs,{size:12}),n.branch]}),n.taskId&&e.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function RP({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(ut,{size:14,className:"spin"}):e.jsx(nl,{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(Vs,{size:12}),d.branch]}),e.jsx("span",{children:sa(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(ut,{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(ut,{size:14,className:"spin"}):e.jsx(qt,{size:14})})]})]},d.index))})]})}function TP({status:t,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:l,addToast:o,projectId:d,copyToClipboard:m}){const c=X=>{try{return new URL(X).hostname}catch{return X.replace(/^git@/,"").split(":")[0]||X}},[u,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[x,v]=a.useState(""),[y,M]=a.useState(""),[j,P]=a.useState(null),[w,S]=a.useState(""),[k,_]=a.useState(""),[E,T]=a.useState(!1),[D,Z]=a.useState([]),[$,R]=a.useState(!1),[N,W]=a.useState(null),[Y,H]=a.useState([]),[A,z]=a.useState(!1),[J,C]=a.useState(null),q=u.find(X=>X.name===N),[oe,O]=a.useState(null),[V,F]=a.useState(null),[ue,ce]=a.useState(!1),[K,de]=a.useState(null),[Fe,we]=a.useState(null),[Ee,ie]=a.useState(!1);a.useEffect(()=>{Pe()},[]),a.useEffect(()=>{t&&t.ahead>0?ze():t&&t.ahead===0&&Z([])},[t?.ahead]),a.useEffect(()=>{u.length>0&&!N&&W(u[0].name)},[u]),a.useEffect(()=>{N?$e(N):(H([]),C(null))},[N]),a.useEffect(()=>{N&&!u.find(X=>X.name===N)&&W(u.length>0?u[0].name:null)},[u,N]);const Pe=async()=>{p(!0);try{const X=await fh(d);h(X)}catch(X){o(fe(X)||"Failed to load remotes","error")}finally{p(!1)}},ze=async()=>{R(!0);try{const X=await yv(d);Z(X)}catch{Z([])}finally{R(!1)}},$e=async X=>{z(!0),C(null);try{const ke=await jv(X,void 0,10,d);H(ke)}catch(ke){C(fe(ke)||"Failed to load remote commits"),H([])}finally{z(!1)}},He=async X=>{if(X.preventDefault(),!(!x.trim()||!y.trim())){b("add");try{await uv(x.trim(),y.trim(),d),o(`Remote '${x}' added successfully`,"success"),v(""),M(""),T(!1),await Pe()}catch(ke){o(fe(ke)||"Failed to add remote","error")}finally{b(null)}}},Me=async X=>{if(confirm(`Are you sure you want to remove remote '${X}'?`)){b(`remove-${X}`);try{await mv(X,d),o(`Remote '${X}' removed`,"success"),await Pe()}catch(ke){o(fe(ke)||"Failed to remove remote","error")}finally{b(null)}}},Te=async X=>{if(k.trim()){b(`rename-${X}`);try{await hv(X,k.trim(),d),o(`Remote renamed to '${k.trim()}'`,"success"),P(null),_(""),await Pe()}catch(ke){o(fe(ke)||"Failed to rename remote","error")}finally{b(null)}}},Ve=async X=>{if(w.trim()){b(`url-${X}`);try{await pv(X,w.trim(),d),o("Remote URL updated","success"),P(null),S(""),await Pe()}catch(ke){o(fe(ke)||"Failed to update remote URL","error")}finally{b(null)}}},_e=a.useCallback(async(X,ke)=>{if(ke==="ahead"){if(oe===X){O(null),F(null);return}O(X),F(null),ce(!0);try{const se=await qr(X);F(se)}catch{F(null)}finally{ce(!1)}}else{if(K===X){de(null),we(null);return}de(X),we(null),ie(!0);try{const se=await qr(X);we(se)}catch{we(null)}finally{ie(!1)}}},[oe,K]),et=X=>{P(`url-${X.name}`),S(X.pushUrl||X.fetchUrl)},le=X=>{P(`name-${X.name}`),_(X.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:()=>T(!E),disabled:f!==null,title:E?"Cancel":"Add Remote",children:E?e.jsx(Lt,{size:14}):e.jsx(Vt,{size:14})})]}),E&&e.jsxs("form",{className:"gm-remote-form",onSubmit:He,children:[e.jsx("input",{type:"text",placeholder:"Remote name",value:x,onChange:X=>v(X.target.value),disabled:f==="add",className:"gm-input"}),e.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:X=>M(X.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()||!y.trim()||f==="add",children:[f==="add"?e.jsx(ut,{size:12,className:"spin"}):e.jsx(Vt,{size:12}),"Add"]})]}),g?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ut,{size:16,className:"spin"}),"Loading..."]}):u.length===0?e.jsx("div",{className:"gm-empty",children:"No remotes"}):u.map(X=>e.jsxs("div",{className:`gm-remote-selector-item${N===X.name?" selected":""}`,onClick:()=>W(X.name),role:"button",tabIndex:0,children:[e.jsxs("div",{className:"gm-remote-selector-info",children:[e.jsxs("span",{className:"gm-remote-selector-name",children:[X.name,X.name==="origin"&&e.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),e.jsx("span",{className:"gm-remote-selector-host",children:c(X.fetchUrl)})]}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:ke=>{ke.stopPropagation(),Me(X.name)},disabled:f!==null,title:"Remove remote",children:e.jsx(qt,{size:14})})]},X.name))]}),e.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[N&&q?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[e.jsxs("div",{className:"gm-remote-sync-card-header",children:[e.jsx("span",{className:"gm-remote-sync-card-title",children:N}),t&&(t.ahead>0||t.behind>0)&&e.jsxs("div",{className:"gm-remote-status",children:[t.ahead>0&&e.jsxs("div",{className:"gm-remote-indicator ahead",children:[e.jsx(ji,{size:14}),t.ahead," to push"]}),t.behind>0&&e.jsxs("div",{className:"gm-remote-indicator behind",children:[e.jsx(Ka,{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(ut,{size:14,className:"spin"}):e.jsx(vn,{size:14}),"Fetch"]}),e.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?e.jsx(ut,{size:14,className:"spin"}):e.jsx(es,{size:14}),"Pull"]}),e.jsxs("button",{className:"btn btn-primary",onClick:l,disabled:n!==null||g,children:[n==="push"?e.jsx(ut,{size:14,className:"spin"}):e.jsx(ji,{size:14}),"Push"]})]})]}),e.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[e.jsxs("div",{className:"gm-remote-detail-urls",children:[e.jsxs("div",{className:"gm-remote-detail-url-row",children:[e.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${N}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:w,onChange:X=>S(X.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ve(N),disabled:f===`url-${N}`,children:f===`url-${N}`?e.jsx(ut,{size:12,className:"spin"}):e.jsx(An,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{P(null),S("")},title:"Cancel",children:e.jsx(Lt,{size:12})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"gm-url-value",title:q.fetchUrl,children:q.fetchUrl}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>m(q.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:e.jsx(Gi,{size:14})}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>et(q),disabled:f!==null,title:"Edit remote URL",children:e.jsx($n,{size:14})})]})]}),q.pushUrl&&q.pushUrl!==q.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:q.pushUrl,children:q.pushUrl}),e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>m(q.pushUrl,"push URL"),title:"Copy push URL",children:e.jsx(Gi,{size:14})})]})]}),e.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${N}`?e.jsxs("div",{className:"gm-remote-edit",children:[e.jsx("input",{type:"text",value:k,onChange:X=>_(X.target.value),className:"gm-input",autoFocus:!0}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Te(N),disabled:f===`rename-${N}`,children:f===`rename-${N}`?e.jsx(ut,{size:12,className:"spin"}):e.jsx(An,{size:12})}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{P(null),_("")},title:"Cancel",children:e.jsx(Lt,{size:12})})]}):e.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>le(q),disabled:f!==null,title:"Edit remote name",children:e.jsx($n,{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(ji,{size:14}),"Commits to Push (",t.ahead,")"]})}),$?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ut,{size:14,className:"spin"}),"Loading..."]}):D.length>0?e.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:D.map(X=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>_e(X.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:X.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:X.message,children:X.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:X.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:sa(X.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:oe===X.hash?e.jsx(Ot,{size:14}):e.jsx(on,{size:14})})]}),oe===X.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ue?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ut,{size:16,className:"spin"}),"Loading diff..."]}):V?e.jsxs(e.Fragment,{children:[X.message&&e.jsx("div",{className:"gm-commit-message-full",children:X.message}),V.stat&&e.jsx("pre",{className:"gm-diff-stat",children:V.stat}),e.jsx("pre",{className:"gm-diff-patch",children:V.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},X.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(ah,{size:14}),"Recent commits on ",N]})}),A?e.jsxs("div",{className:"gm-loading",children:[e.jsx(ut,{size:14,className:"spin"}),"Loading commits..."]}):J?e.jsxs("div",{className:"gm-error",children:[e.jsx(ss,{size:14}),J]}):Y.length===0?e.jsxs("div",{className:"gm-empty",children:["No commits found on ",N,". Try fetching first."]}):e.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:Y.map(X=>e.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[e.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>_e(X.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:X.shortHash})}),e.jsxs("div",{className:"gm-commit-compact-info",children:[e.jsx("span",{className:"gm-commit-message",title:X.message,children:X.message}),e.jsxs("span",{className:"gm-commit-meta",children:[e.jsx("span",{children:X.author}),e.jsx("span",{children:"•"}),e.jsx("span",{children:sa(X.date)})]})]}),e.jsx("span",{className:"gm-commit-expand-icon",children:K===X.hash?e.jsx(Ot,{size:14}):e.jsx(on,{size:14})})]}),K===X.hash&&e.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Ee?e.jsxs("div",{className:"gm-diff-loading",children:[e.jsx(ut,{size:16,className:"spin"}),"Loading diff..."]}):Fe?e.jsxs(e.Fragment,{children:[X.message&&e.jsx("div",{className:"gm-commit-message-full",children:X.message}),Fe.stat&&e.jsx("pre",{className:"gm-diff-stat",children:Fe.stat}),e.jsx("pre",{className:"gm-diff-patch",children:Fe.patch})]}):e.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},X.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 Pa={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function $P(t,n){return t&&n?`${t}/${n}`:""}function FP(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 DP(t){switch(t){case"file-text":return wi;case"check-circle":return sn;case"shield":return Ob;case"zap":return Nn;case"eye":return ic;case"globe":return Ni;case"layout-grid":return Ci;default:return sn}}function LP(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 zP({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,v]=a.useState(!1),[y,M]=a.useState(Pa),[j,P]=a.useState(!1),[w,S]=a.useState(!1),[k,_]=a.useState(null),[E,T]=a.useState(null),[D,Z]=a.useState({}),[$,R]=a.useState([]),N=a.useCallback(async()=>{try{c(!0);const F=await ol(i);l(F)}catch(F){s(fe(F)||"Failed to load workflow steps","error")}finally{c(!1)}},[s,i]),W=a.useCallback(async()=>{try{const F=await Za(i);Z(F||{})}catch{}},[i]),Y=a.useCallback(async()=>{try{const F=await Vn();R(F.models||[])}catch{}},[]),H=a.useCallback(async()=>{try{h(!0);const F=await gy();d(F.templates)}catch(F){s(fe(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{t&&(N(),H(),W(),Y())},[t,N,H,W,Y]);const A=a.useCallback(()=>{v(!0),b(null),M(Pa)},[]),z=a.useCallback(F=>{b(F.id),v(!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||""})},[]),J=a.useCallback(()=>{b(null),v(!1),M(Pa)},[]),C=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}P(!0);try{const F=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(x){const ue={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...F};await dd(ue,i),s("Workflow step created","success")}else f&&(await hy(f,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...F},i),s("Workflow step updated","success"));v(!1),b(null),M(Pa),await N()}catch(F){s(fe(F)||"Failed to save workflow step","error")}finally{P(!1)}},[y,x,f,s,N]),q=a.useCallback(async F=>{try{await py(F,i),s("Workflow step deleted","success"),_(null),f===F&&(b(null),M(Pa)),await N()}catch(ue){s(fe(ue)||"Failed to delete workflow step","error")}},[f,s,N]),oe=a.useCallback(async()=>{if(!(!f&&!x)&&y.mode==="prompt"){if(x){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}P(!0);try{const F=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},ue={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...F},ce=await dd(ue,i);v(!1),b(ce.id),S(!0);const K=await ud(ce.id,i);M(de=>({...de,prompt:K.prompt})),s("Prompt refined with AI","success"),await N()}catch(F){s(fe(F)||"Failed to refine prompt","error")}finally{P(!1),S(!1)}return}if(f){S(!0);try{const F=await ud(f,i);M(ue=>({...ue,prompt:F.prompt})),s("Prompt refined with AI","success"),await N()}catch(F){s(fe(F)||"Failed to refine prompt","error")}finally{S(!1)}}}},[f,x,y,s,N]),O=a.useCallback(async F=>{T(F.id);try{await by(F.id,i),s(`Added ${F.name} workflow step`,"success"),await N(),p("my-steps")}catch(ue){const ce=fe(ue);ce?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(ce||"Failed to add workflow step from template","error")}finally{T(null)}},[s,N]);if(!t)return null;const V=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:[!V&&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(Jm,{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(Ci,{size:14}),"Templates (",o.length,")"]})]}),g==="my-steps"&&!V&&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:()=>z(F),title:"Edit","aria-label":`Edit ${F.name}`,children:e.jsx($n,{size:14})}),k===F.id?e.jsxs("div",{className:"wfm-delete-confirm",children:[e.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>q(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:e.jsx(An,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>_(null),title:"Cancel delete","aria-label":"Cancel delete",children:e.jsx(Lt,{size:14})})]}):e.jsx("button",{className:"btn-icon",onClick:()=>_(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:e.jsx(qt,{size:14})})]})]})},F.id))})]}),g==="templates"&&!V&&e.jsx(e.Fragment,{children:u?e.jsxs("div",{className:"wfm-loading",children:[e.jsx(ut,{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 ue=DP(F.icon),ce=LP(F.category),K=E===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(ue,{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:ce,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:()=>O(F),disabled:K,"data-testid":`add-template-${F.id}`,children:K?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:12,className:"spin"}),"Adding..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Vt,{size:12}),"Add"]})})]})]})},F.id)})})}),V&&e.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[e.jsx("h3",{className:"wfm-form-title",children:x?"New Workflow Step":"Edit Workflow Step"}),e.jsxs("div",{className:"wfm-form-fields",children:[e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Name"}),e.jsx("input",{type:"text",value:y.name,onChange:F=>M(ue=>({...ue,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:y.description,onChange:F=>M(ue=>({...ue,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 ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[e.jsx(oi,{size:14}),"AI Prompt"]}),e.jsxs("button",{className:`btn ${y.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(Ks,{size:14}),"Run Script"]})]})]}),e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Execution Phase"}),e.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[e.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),e.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),e.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&e.jsxs("div",{className:"wfm-field",children:[e.jsxs("div",{className:"wfm-prompt-header",children:[e.jsx("label",{children:"Agent Prompt"}),e.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:oe,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?e.jsx(ut,{size:12,className:"spin"}):e.jsx(Dn,{size:12}),e.jsx("span",{children:"Refine with AI"})]})]}),e.jsx("textarea",{value:y.prompt,onChange:F=>M(ue=>({...ue,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&e.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[e.jsxs("div",{className:"wfm-model-header",children:[e.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&e.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>M(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[e.jsx(Lt,{size:12}),e.jsx("span",{children:"Use default"})]})]}),e.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),e.jsx("div",{"data-testid":"workflow-step-model-select",children:e.jsx(Yt,{models:$,value:$P(y.modelProvider,y.modelId),onChange:F=>{const ue=FP(F);M(ce=>({...ce,modelProvider:ue.provider,modelId:ue.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&e.jsxs("div",{className:"wfm-field",children:[e.jsx("label",{children:"Script"}),Object.keys(D).length===0?e.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):e.jsxs("select",{value:y.scriptName,onChange:F=>M(ue=>({...ue,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[e.jsx("option",{value:"",children:"Select a script…"}),Object.entries(D).map(([F,ue])=>e.jsxs("option",{value:F,children:[F," (",ue,")"]},F))]})]}),e.jsxs("label",{className:"wfm-checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:y.enabled,onChange:F=>M(ue=>({...ue,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:y.defaultOn,onChange:F=>M(ue=>({...ue,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:J,disabled:j,children:"Cancel"}),e.jsx("button",{className:"btn btn-primary",onClick:C,disabled:j||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:j?"Saving...":x?"Create":"Save"})]})]})]})]})}),!V&&e.jsx("div",{className:"wfm-footer",children:e.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:A,"data-testid":"add-workflow-step",children:[e.jsx(Vt,{size:14}),"Add Workflow Step"]})})]})})}const OP=36e5,BP=3e5,vo=[{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 UP(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 HP(t){return typeof t!="number"||!Number.isFinite(t)?OP:Math.max(BP,Math.round(t))}function WT(t){if(vo.some(s=>s.value===t))return[...vo];const n={value:t,label:`${UP(t)} (custom)`};return[...vo,n].sort((s,i)=>s.value-i.value)}const qP=4,VP=5*6e4;function WP(t){const n=HP(t?.heartbeatIntervalMs);return Math.max(n*qP,VP)}function KP(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 GP(t){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:l}=t,o=KP(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(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:e.jsx(Hs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||o&&n==="active")return{label:"Running",icon:e.jsx(Ss,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:e.jsx(rn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),m=Date.now()-d,c=WP(l);return m>c?{label:"Unresponsive",icon:e.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:e.jsx(Qg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ia=[{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 JP({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,v]=a.useState(()=>{if(typeof window>"u")return"list";const N=Rn("fn-agent-view",i);return N==="board"||N==="list"?N:"list"});a.useEffect(()=>{const N=Rn("fn-agent-view",i);if(N==="board"||N==="list"){v(N);return}v("list")},[i]),a.useEffect(()=>{us("fn-agent-view",x,i)},[i,x]);const[y,M]=a.useState(null),j=a.useRef(null),P=a.useMemo(()=>f==="all"?r.filter(N=>N.state!=="terminated"):r,[r,f]),w=a.useCallback(async()=>{d(!0);try{const W=await da(f!=="all"?{state:f}:void 0,i);l(W)}catch(N){s(`Failed to load agents: ${fe(N)}`,"error")}finally{d(!1)}},[f,s,i]);a.useEffect(()=>{t&&w()},[t,w]),a.useEffect(()=>{if(!t)return;const N=setInterval(()=>{w()},3e4);return()=>{clearInterval(N)}},[t,w]);const S=async()=>{if(u.trim())try{await Cy({name:u.trim(),role:g},i),s(`Agent "${u}" created`,"success"),h(""),c(!1),w()}catch(N){s(`Failed to create agent: ${fe(N)}`,"error")}},k=async(N,W)=>{try{await My(N,W,i),s(`Agent state updated to ${W}`,"success"),w()}catch(Y){s(`Failed to update state: ${fe(Y)}`,"error")}},_=async(N,W)=>{if(confirm(`Delete agent "${W}"? This cannot be undone.`))try{await Ay(N,i),s(`Agent "${W}" deleted`,"success"),w()}catch(Y){s(`Failed to delete agent: ${fe(Y)}`,"error")}},E=async(N,W)=>{const Y=r.find(H=>H.id===N);if(Y){if(Y.role===W){M(null);return}try{await Ey(N,{role:W},i),s(`Agent role updated to ${Ia.find(H=>H.value===W)?.label??W}`,"success"),M(null),w()}catch(H){s(`Failed to update role: ${fe(H)}`,"error")}}},T=(N,W)=>{N.key==="Escape"&&M(null)},D=N=>Ia.find(W=>W.value===N)?.label??N,Z=N=>Ia.find(W=>W.value===N)?.icon??"◆",$=N=>GP(N),R=N=>N.color==="var(--state-active-text)"?"active":N.color==="var(--state-paused-text)"?"paused":N.color==="var(--state-error-text)"?"error":"muted";return t?e.jsx("div",{className:"modal-overlay open",onClick:N=>N.target===N.currentTarget&&n(),role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("h2",{className:"modal-title",children:[e.jsx(rn,{size:20}),"Agents"]}),e.jsxs("div",{className:"modal-actions",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${x==="board"?" active":""}`,onClick:()=>v("board"),title:"Board view","aria-label":"Board view","aria-pressed":x==="board",children:e.jsx(Ci,{size:16})}),e.jsx("button",{className:`view-toggle-btn${x==="list"?" active":""}`,onClick:()=>v("list"),title:"List view","aria-label":"List view","aria-pressed":x==="list",children:e.jsx(Mo,{size:16})})]}),e.jsx("button",{className:"btn-icon",onClick:()=>void w(),title:"Refresh",disabled:o,children:e.jsx(vn,{size:16,className:o?"spin":""})}),e.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]})]}),e.jsxs("div",{className:"modal-content agent-modal-content",children:[e.jsxs("div",{className:"agent-controls",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(zr,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:N=>b(N.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"}),e.jsx("option",{value:"terminated",children:"Terminated"})]})]}),e.jsxs("button",{className:"btn btn--primary",onClick:()=>c(!m),children:[e.jsx(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:N=>h(N.target.value),onKeyDown:N=>N.key==="Enter"&&S(),className:"input",autoFocus:!0}),e.jsx("select",{className:"select",value:g,onChange:N=>p(N.target.value),children:Ia.map(N=>e.jsxs("option",{value:N.value,children:[N.icon," ",N.label]},N.value))}),e.jsx("button",{className:"btn btn--primary",onClick:()=>void S(),children:"Create"})]}),e.jsx("div",{className:x==="board"?"agent-board":"agent-list",children:P.length===0?e.jsxs("div",{className:"agent-empty",children:[e.jsx(rn,{size:48,opacity:.3}),e.jsx("p",{children:"No agents found"}),e.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):x==="board"?P.map(N=>{const W=$(N),Y=R(W);return e.jsxs("div",{className:"agent-board-card","data-state":N.state,children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:Z(N.role)}),e.jsx("span",{className:"agent-board-badge","data-state":N.state,children:N.state}),e.jsx("span",{className:"agent-board-health","data-health":Y,title:W.label,children:W.icon})]}),e.jsx("div",{className:"agent-board-name",title:N.name,children:N.name}),e.jsx("div",{className:"agent-board-id",children:N.id}),e.jsxs("div",{className:"agent-board-actions",children:[N.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Activate",children:e.jsx(ln,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(N.id,N.name),title:"Delete",children:e.jsx(qt,{size:14})})]}),N.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:e.jsx(Hs,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),N.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Resume",children:e.jsx(ln,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),N.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:e.jsx(Hs,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),N.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Retry",children:e.jsx(ln,{size:14})}),e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:e.jsx(os,{size:14})})]}),N.state==="terminated"&&e.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(N.id,N.name),title:"Delete",children:e.jsx(qt,{size:14})})]})]},N.id)}):P.map(N=>{const W=$(N),Y=R(W);return e.jsxs("div",{className:"agent-card","data-state":N.state,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[y===N.id?e.jsx("select",{ref:j,className:"select agent-role-select",value:N.role,onChange:H=>void E(N.id,H.target.value),onKeyDown:H=>T(H,N.id),onBlur:()=>M(null),autoFocus:!0,children:Ia.map(H=>e.jsxs("option",{value:H.value,children:[H.icon," ",H.label]},H.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>M(N.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:H=>{(H.key==="Enter"||H.key===" ")&&M(N.id)},children:Z(N.role)}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:N.name}),e.jsx("span",{className:"agent-id text-secondary",children:N.id})]})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:"badge agent-list-state-badge","data-state":N.state,children:N.state}),e.jsxs("span",{className:"badge agent-list-health-badge","data-health":Y,title:W.label,children:[W.icon,!W.stateDerived&&` ${W.label}`]}),e.jsx("span",{className:"badge text-secondary",children:D(N.role)})]})]}),e.jsxs("div",{className:"agent-card-body",children:[N.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:N.taskId})]}),N.lastHeartbeatAt&&e.jsxs("div",{className:"agent-heartbeat",children:[e.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),e.jsx("span",{children:new Date(N.lastHeartbeatAt).toLocaleString()})]})]}),e.jsxs("div",{className:"agent-card-actions",children:[N.state==="idle"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Activate",children:[e.jsx(ln,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(N.id,N.name),title:"Delete",children:[e.jsx(qt,{size:14})," Delete"]})]}),N.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:[e.jsx(Hs,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),N.state==="paused"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Resume",children:[e.jsx(ln,{size:14})," Resume"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),N.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"paused"),title:"Pause",children:[e.jsx(Hs,{size:14})," Pause"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),N.state==="error"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm",onClick:()=>void k(N.id,"active"),title:"Retry",children:[e.jsx(ln,{size:14})," Retry"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void k(N.id,"terminated"),title:"Stop",children:[e.jsx(os,{size:14})," Stop"]})]}),N.state==="terminated"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void k(N.id,"active"),title:"Start",children:[e.jsx(ln,{size:14})," Start"]}),e.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(N.id,N.name),title:"Delete",children:[e.jsx(qt,{size:14})," Delete"]})]})]})]},N.id)})})]})]})}):null}const Ai="fusion_model_onboarding_state",ia=[],aa=[],el=!1,tl=!1,ra={},YP=void 0,ri=["ai-setup","github","project-setup","first-task"],QP={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function hs(){if(typeof window>"u")return null;try{const t=localStorage.getItem(Ai);if(!t)return null;const n=JSON.parse(t);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?XP(n):null}catch{return null}}function XP(t){const n=t.postOnboardingDismissedAt??YP;return{...t,completedSteps:t.completedSteps??ia,skippedSteps:t.skippedSteps??aa,dismissed:t.dismissed??el,completed:t.completed??tl,stepData:t.stepData??ra,...n?{postOnboardingDismissedAt:n}:{}}}function Rr(t,n){if(!(typeof window>"u")){if(!n){const s={currentStep:t,updatedAt:new Date().toISOString(),completedSteps:ia,skippedSteps:aa,dismissed:el,completed:tl,stepData:ra};try{localStorage.setItem(Ai,JSON.stringify(s))}catch{}return}try{const s=hs(),i=new Date().toISOString(),r=n.completed??tl;let l=n.dismissed??el;r&&(l=!1);const o=n.completedSteps??s?.completedSteps??ia,d=n.skippedSteps??s?.skippedSteps??aa,m={...s?.stepData??ra};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(Ai,JSON.stringify(c))}catch{}}}function ZP(t){if(!(typeof window>"u"))try{const n=hs(),s=new Date().toISOString();if(!n){const l={currentStep:t,updatedAt:s,completedSteps:ia,skippedSteps:[t],dismissed:el,completed:tl,stepData:ra};localStorage.setItem(Ai,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(Ai,JSON.stringify(r))}catch{}}function Em(){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:ia,skippedSteps:aa,dismissed:!1,completed:!0,stepData:ra};localStorage.setItem(Ai,JSON.stringify(s))}catch{}}function la(){const t=hs();return t?t.completed===!0?!0:typeof t.completedAt=="string"&&t.completedAt.length>0:!1}function eI(){if(!(typeof window>"u"))try{const t=hs(),n=new Date().toISOString(),s=t?{...t,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ia,skippedSteps:aa,dismissed:!1,completed:!1,stepData:ra,postOnboardingDismissedAt:n};localStorage.setItem(Ai,JSON.stringify(s))}catch{}}function df(){const t=hs();return t?typeof t.postOnboardingDismissedAt=="string"&&t.postOnboardingDismissedAt.length>0:!1}function tI(){const t=hs();return!t||la()?!1:t.currentStep!=="complete"}function nI(){const t=hs();if(!t||la()||t.currentStep==="complete")return null;const n=t.currentStep,s=QP[n]??aI(t.currentStep);return{currentStep:t.currentStep,label:s,completedSteps:t.completedSteps}}function sI(){const t=hs();return t?t.skippedSteps:aa}function iI(t){const n=hs();return!n||!n.stepData?null:n.stepData[t]??null}function aI(t){return t.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const uf="fusion_onboarding_events",Mm="fusion_onboarding_session_id",rI=200,lI=50;function ks(t,n={}){if(!(typeof window>"u"))try{const s=cI(),i=mI(n.step),r={type:t,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:oI()},l=uI([...s,r]);dI(l)}catch{}}function oI(){if(typeof window>"u")return"server-session";try{const t=sessionStorage.getItem(Mm);if(t)return t;const n=Am();return sessionStorage.setItem(Mm,n),n}catch{return Am()}}function Am(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function cI(){try{const t=localStorage.getItem(uf);if(!t)return[];const n=JSON.parse(t);return Array.isArray(n)?n.filter(hI):[]}catch{return[]}}function dI(t){try{localStorage.setItem(uf,JSON.stringify(t))}catch{}}function uI(t){const n=[...t];for(;n.length>rI;)n.splice(0,lI);return n}function mI(t){if(t==="ai-setup"||t==="github"||t==="first-task"||t==="complete")return t}function hI(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 pI=1e4,fI=1e3;function gI(){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 fd();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 fd();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<fI||(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()},pI),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async p=>{const f=await Ty(p);return n(b=>[...b,f]),f},[]),u=a.useCallback(async(p,f)=>{const b=await $y(p,f);return n(x=>x.map(v=>v.id===p?b:v)),b},[]),h=a.useCallback(async p=>{await Fy(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await Dy(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 mf({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 bI={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"}}},hf={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:"..."}},xI={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Pm={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 Xo(t){if(Pm[t])return Pm[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 yo=["anthropic","openai","google","gemini","ollama"],vI=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],yI={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"},jI={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Zo(t){return yI[t]??t}function Im(t){const n=Zo(t),s=vI.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function _m(t,n){if(t.authenticated!==n.authenticated)return t.authenticated?-1:1;const s=Im(t.id),i=Im(n.id);if(s!==i)return s-i;const r=Zo(t.id),l=Zo(n.id);if(r!==l)return r.localeCompare(l);const o=jI[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 kI(t,n){const s=n.trim();if(!s)return"API key is required";const i=hf[t]??xI;return i.pattern.test(s)?null:`${Xo(t)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const pf={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"},wI={description:"AI provider — connect to start using AI models",apiKeyInfo:pf};function ec(t){return bI[t]??wI}function NI(t){return ec(t.id).apiKeyInfo??pf}function Us({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(on,{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 SI({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 CI({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=hf[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(Us,{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(Us,{summary:"Advanced setup details",children:f})]})}const EI=150;function MI({onComplete:t,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:l,firstCreatedTask:o,onViewTask:d}){const m=hs(),c=m?.currentStep,u=c==="complete"?"ai-setup":ri.includes(c)?c:"ai-setup",h=m?.completedSteps??[],g=m?.skippedSteps??sI(),[p,f]=a.useState(!0),[b,x]=a.useState(u),[v,y]=a.useState(h),[M,j]=a.useState(g),[P,w]=a.useState(!1),[S,k]=a.useState(""),[_,E]=a.useState(!1),[T,D]=a.useState(null),[Z,$]=a.useState(null),[R,N]=a.useState([]),[W,Y]=a.useState(void 0),[H,A]=a.useState(!0),[z,J]=a.useState(null),[C,q]=a.useState({}),[oe,O]=a.useState([]),[V,F]=a.useState(""),[ue,ce]=a.useState(!1),[K,de]=a.useState({}),[Fe,we]=a.useState({}),[Ee,ie]=a.useState({}),Pe=a.useRef({}),ze=a.useRef(null),$e=a.useRef(null),[He,Me]=a.useState({}),[Te,Ve]=a.useState(()=>hs()?.stepData?.github?.skipped===!0),_e=a.useRef(0),et=a.useRef(o),le=a.useRef(!1),X=m?.currentStep,ke=!!m&&m.currentStep!=="complete",[se,Le]=a.useState(()=>hs()?.stepData?.["ai-setup"]?.skippedProviders??{}),ve=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Ye=ve.findIndex(G=>G.key===b),mt=b==="complete"?ve.length:Ye;a.useEffect(()=>{b!=="complete"&&Rr(b,{completedSteps:v,skippedSteps:M})},[b,v,M]),a.useEffect(()=>{le.current||(le.current=!0,ks("onboarding:wizard-opened",{source:ke?"resume":"initial",resumedFromStep:X}))},[ke,X]),a.useEffect(()=>{const G=et.current!=null,Ke=o!=null;!G&&Ke&&w(!0),Ke||w(!1),et.current=o},[o]);const ht=a.useRef(u);a.useEffect(()=>{if(ht.current==="ai-setup"&&b!=="ai-setup"&&!R.some(Ke=>Ke.id!=="github"&&Ke.authenticated)){const Ke={};for(const I of R)I.id!=="github"&&!I.authenticated&&!se[I.id]&&(Ke[I.id]=!0);if(Object.keys(Ke).length>0){const I={...se,...Ke};Le(I),Rr(b,{stepData:{"ai-setup":{skippedProviders:I}}})}}ht.current=b},[b,R,se]);const me=a.useCallback(async()=>{try{const{providers:G,ghCli:Ke}=await Ei();N(G),Y(Ke),q(I=>{const B={};for(const[re,pe]of Object.entries(I)){const xe=G.find(Re=>Re.id===re);xe&&!xe.authenticated&&(B[re]=pe)}return Object.keys(B).length===Object.keys(I).length?I:B}),Le(I=>{const B={...I};for(const re of G)re.authenticated&&B[re.id]&&delete B[re.id];return Object.keys(B).length===Object.keys(I).length?I:B})}catch{}},[]),te=a.useRef(!1);a.useEffect(()=>{te.current&&me(),te.current=b!=="ai-setup"},[b,me]);const je=R.find(G=>G.id==="github"),Ae=!!je,Qe=je?.authenticated??!1,be=W?.authenticated??!1,st=Qe||be,Se=!Qe&&be,Je=a.useCallback(G=>{if(G.authenticated)return"connected";const Ke=He?.[G.id];return Ke==="timeout"||Ke==="failed"?"retry":se[G.id]?"skipped":"not-connected"},[He,se]);function it({status:G}){const Ke={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:I,className:B}=Ke[G];return e.jsx("span",{"data-testid":"provider-status-badge",className:B,"data-status":G,children:I})}const ye=a.useCallback(()=>{if(st)return"connected";const G=He.github;return G==="pending"?"pending":G==="failed"||G==="timeout"?"failed":Te?"skipped":"not-connected"},[st,He,Te]);function Ge({status:G}){const Ke={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:I,className:B}=Ke[G];return e.jsx("span",{"data-testid":"github-status-badge",className:B,"data-status":G,children:I})}const Ne=a.useCallback(async()=>{try{const G=await Vn();O(G.models)}catch{}},[]),at=a.useCallback(async()=>{try{const G=await ca();if(G.defaultProvider&&G.defaultModelId){const Ke=`${G.defaultProvider}/${G.defaultModelId}`;F(Ke)}}catch{}},[]);a.useEffect(()=>{Promise.all([me(),Ne(),at()]).finally(()=>A(!1))},[me,Ne,at]),a.useEffect(()=>{const G=iI("ai-setup");if(G?.loginOutcomes){const Ke=G.loginOutcomes,I={};for(const[B,re]of Object.entries(Ke))re!=="pending"&&(I[B]=re);Object.keys(I).length>0&&Me(I)}},[]);const dt=a.useCallback((G,Ke)=>{Rr(b,{completedSteps:v,stepData:{"ai-setup":{loginOutcomes:{[G]:Ke}}}})},[b,v]);a.useEffect(()=>{const G=Object.entries(He).filter(([Ke,I])=>I!=="pending");for(const[Ke,I]of G)dt(Ke,I)},[He,dt]),a.useEffect(()=>()=>{$e.current&&clearInterval($e.current),Object.values(Pe.current).forEach(clearTimeout),Pe.current={}},[]);const vt=a.useCallback(G=>{Ve(G),Rr(b,{completedSteps:v,stepData:{github:{skipped:G}}})},[b,v]),It=a.useCallback(G=>G==="complete"?-1:ri.indexOf(G),[]),_t=a.useCallback(()=>{y(Ke=>[...new Set([...Ke,b])]),j(Ke=>Ke.filter(I=>I!==b)),ks("onboarding:step-completed",{step:b}),b==="github"&&!Qe&&vt(!1);const G=It(b);G>=0&&G<ri.length-1&&x(ri[G+1])},[b,Qe,vt,It]),Mt=a.useCallback(()=>{j(Ke=>[...new Set([...Ke,b])]),ZP(b),ks("onboarding:step-skipped",{step:b}),b==="github"&&!Qe&&vt(!0);const G=It(b);G>=0&&G<ri.length-1&&x(ri[G+1])},[b,Qe,vt,It]),zt=a.useCallback(()=>{const G=b;y(I=>I.filter(B=>B!==G)),j(I=>I.filter(B=>B!==G)),G==="github"&&!Qe&&vt(!1);const Ke=It(b);Ke>0&&x(ri[Ke-1])},[b,Qe,vt,It]),Nt=a.useCallback(()=>{Mt()},[Mt]),Pt=a.useCallback(async G=>{Me(Ke=>{const I=Ke[G];if(I&&I!=="pending"){const{[G]:B,...re}=Ke;return re}return Ke}),q(Ke=>{if(!(G in Ke))return Ke;const I={...Ke};return delete I[G],I}),Me(Ke=>({...Ke,[G]:"pending"})),J(G),_e.current=0;try{const{url:Ke,instructions:I}=await uh(G);I?.trim()&&q(B=>({...B,[G]:I})),window.open($s(Ke),"_blank"),$e.current=setInterval(async()=>{if(_e.current++,_e.current>=EI){$e.current&&(clearInterval($e.current),$e.current=null),J(null),Me(B=>({...B,[G]:"timeout"})),q(B=>{if(!(G in B))return B;const re={...B};return delete re[G],re}),n("Login timed out. Please try again.","warning");return}try{const{providers:B,ghCli:re}=await Ei();N(B),Y(re),B.find(xe=>xe.id===G)?.authenticated&&($e.current&&(clearInterval($e.current),$e.current=null),J(null),Me(xe=>({...xe,[G]:"success"})),q(xe=>{if(!(G in xe))return xe;const Re={...xe};return delete Re[G],Re}),G==="github"&&vt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Ke){Ke instanceof Error&&Ke.message.includes("already in progress")||Ke&&typeof Ke=="object"&&"status"in Ke&&Ke.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Me(B=>({...B,[G]:"failed"}))):(n(Ke instanceof Error?Ke.message:"Login failed","error"),Me(B=>({...B,[G]:"failed"}))),J(null),q(B=>{if(!(G in B))return B;const re={...B};return delete re[G],re})}},[n,vt]),tt=a.useCallback(G=>{$e.current&&(clearInterval($e.current),$e.current=null),J(null),_e.current=0,Me(Ke=>({...Ke,[G]:"cancelled"})),q(Ke=>{if(!(G in Ke))return Ke;const I={...Ke};return delete I[G],I})},[]),bt=a.useCallback((G,Ke)=>{de(B=>({...B,[G]:Ke}));const I=Pe.current[G];I&&(clearTimeout(I),delete Pe.current[G]),we(B=>{if(!B[G])return B;const re={...B};return delete re[G],re}),ie(B=>{if(!B[G])return B;const re={...B};return delete re[G],re})},[]),Ue=a.useCallback(()=>{const G=ze.current;if(!G)return;const Ke=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof G.scrollTo=="function"){G.scrollTo({top:0,behavior:Ke?"auto":"smooth"});return}}catch{}G.scrollTop=0},[]),ot=a.useCallback(async(G,Ke)=>{const I=(Ke??K[G]??"").trim(),B=kI(G,I);if(B){we(pe=>({...pe,[G]:B}));return}const re=Pe.current[G];re&&(clearTimeout(re),delete Pe.current[G]),J(G),we(pe=>{const xe={...pe};return delete xe[G],xe}),ie(pe=>{if(!pe[G])return pe;const xe={...pe};return delete xe[G],xe});try{await hh(G,I),await me(),Ue(),de(pe=>{const xe={...pe};return delete xe[G],xe}),we(pe=>{if(!pe[G])return pe;const xe={...pe};return delete xe[G],xe}),ie(pe=>({...pe,[G]:"✓ Key saved"})),Pe.current[G]=setTimeout(()=>{ie(pe=>{if(!pe[G])return pe;const xe={...pe};return delete xe[G],xe}),delete Pe.current[G]},3e3),n("API key saved","success")}catch(pe){const xe=pe instanceof TypeError&&pe.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":pe instanceof Error?pe.message:"Failed to save API key";we(Re=>({...Re,[G]:xe})),ie(Re=>{if(!Re[G])return Re;const pt={...Re};return delete pt[G],pt}),n(xe,"error")}finally{J(null)}},[K,n,me,Ue]),ge=a.useCallback(async G=>{J(G);try{await ph(G),await me(),n("API key removed","success")}catch(Ke){n(Ke instanceof Error?Ke.message:"Failed to clear API key","error")}finally{J(null)}},[n,me]),Oe=a.useCallback(async G=>{J(G);try{await mh(G),await me(),n("Logged out","success")}catch(Ke){n(Ke instanceof Error?Ke.message:"Logout failed","error")}finally{J(null)}},[n,me]),ee=a.useCallback(G=>{F(G)},[]),Ie=a.useCallback(async()=>{try{const G={modelOnboardingComplete:!0};if(V){const Ke=V.indexOf("/"),I=Ke!==-1?V.slice(0,Ke):void 0,B=Ke!==-1?V.slice(Ke+1):V,re=oe.find(pe=>pe.id===B);re?(G.defaultProvider=re.provider,G.defaultModelId=re.id):I&&B&&(G.defaultProvider=I,G.defaultModelId=B)}await Jt(G),Em()}catch{}},[V,oe,Jt,Em]),xt=a.useCallback(async()=>{const G=[...new Set([...v,"first-task"])];ce(!0);try{await Ie(),ks("onboarding:completed",{completedSteps:G,skippedSteps:M}),y(G),j(Ke=>Ke.filter(I=>I!=="first-task")),x("complete")}finally{ce(!1)}},[Ie,v,M]),he=a.useCallback(async()=>{if(!s)return;const G=S.trim();if(!G){D("Please enter a task description.");return}D(null),E(!0);let Ke=!1;try{const I=await dh({description:G},s);$(I),w(!0),ks("onboarding:first-task-created",{taskId:I?.id}),n("Task created","success"),Ke=!0}catch(I){const B=I instanceof Error?I.message:"Something went wrong creating your task. Please try again.";D(B),n(B,"error")}finally{E(!1)}Ke&&Ie()},[s,S,n,Ie]),Be=a.useCallback(async()=>{ce(!0);try{await Ie()}finally{ce(!1)}ks("onboarding:open-new-task",{}),r?.()},[Ie,r]),gt=a.useCallback(async()=>{if(st){ce(!0);try{await Ie()}finally{ce(!1)}f(!1),t(),ks("onboarding:open-github-import",{}),l?.()}},[Ie,st,t,l]),Kt=a.useCallback(async()=>{ks("onboarding:dismissed",{currentStep:b,completedSteps:v,skippedSteps:M}),ce(!0);try{await Jt({modelOnboardingComplete:!0})}catch{}f(!1),t()},[b,v,M,t]),yn=a.useCallback(()=>{ks("onboarding:finished",{}),f(!1),t()},[t]),mn=a.useCallback(()=>{const G=o??Z;G&&(Ie(),d?.(G),t())},[o,Z,Ie,d,t]),Kn=a.useCallback(()=>{Ie(),t()},[Ie,t]);if(!p)return null;const Wt=ye(),Cn=R.filter(G=>G.id!=="github"),Tn=[...Cn].sort(_m),as=Tn.some(G=>!G.type||G.type==="oauth"),Ut=Tn.some(G=>G.type==="api_key"),Xt=Cn.filter(G=>G.authenticated),hn=Xt.length>0,gn=!!s,En=b==="github"&&!hn,an=(()=>{if(!V)return"";const G=V.indexOf("/"),Ke=G===-1?void 0:V.slice(0,G),I=G===-1?V:V.slice(G+1),B=oe.find(re=>re.id===I&&(!Ke||re.provider===Ke));return B?.name?B.name:Ke?`${Xo(Ke)} ${I}`:V})(),Ft=[];if(gn?Ft.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Ft.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),hn){const G=Xo(Xt[0]?.id??"");Ft.push({label:"AI Provider",status:"connected",detail:`${G} connected — AI agents can work on tasks`})}else Cn.length>0&&Cn.some(G=>se[G.id])?Ft.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Ft.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});st?Ft.push({label:"GitHub",status:"connected",detail:Se?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Ae||Te?Ft.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Ft.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),an&&Ft.push({label:"Default Model",status:"connected",detail:an});const pn=o??Z,Mn=pn?.description?.split(`
649
+ `)[0]?.trim()||pn?.title||"",jn=new Set(yo),zn=Tn.filter(G=>jn.has(G.id)).sort((G,Ke)=>{const I=yo.indexOf(G.id),B=yo.indexOf(Ke.id);return I!==B?I-B:_m(G,Ke)}),rs=Tn.filter(G=>G.authenticated&&!jn.has(G.id)),Gn=Tn.filter(G=>!G.authenticated&&!jn.has(G.id)),Pn=G=>{if(G.id==="claude-cli"&&G.type==="cli")return e.jsx(tf,{authenticated:G.authenticated,onToggled:()=>{me()}},G.id);if(G.type==="api_key"){const Ke=ec(G.id),I=NI(G);return e.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ns,{provider:G.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsxs("strong",{className:"onboarding-provider-card__name",children:[e.jsx(sh,{size:14,className:"onboarding-provider-key-icon"}),G.name]}),e.jsx("span",{className:"onboarding-provider-card__description",children:Ke.description}),e.jsx(it,{status:Je(G)}),G.authenticated&&G.keyHint&&e.jsxs("span",{className:"auth-key-hint",children:["Key: ",G.keyHint]})]}),e.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:e.jsx(CI,{provider:G,apiKeyInfo:I,inputValue:K[G.id]??"",isSaving:z===G.id,error:Fe[G.id],success:Ee[G.id],isConnected:G.authenticated,onInputChange:bt,onSave:ot,onClear:ge})})]},G.id)}return e.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[e.jsx("div",{className:"onboarding-provider-card__icon",children:e.jsx(ns,{provider:G.id,size:"md"})}),e.jsxs("div",{className:"onboarding-provider-card__body",children:[e.jsx("strong",{className:"onboarding-provider-card__name",children:G.name}),e.jsx("span",{className:"onboarding-provider-card__description",children:ec(G.id).description}),e.jsx(it,{status:Je(G)})]}),e.jsx("div",{className:"onboarding-provider-card__actions",children:z===G.id?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",disabled:!0,children:G.authenticated?"Logging out…":"Waiting for login…"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>tt(G.id),children:"Cancel"})]}):G.authenticated?e.jsx("button",{className:"btn btn-sm",onClick:()=>Oe(G.id),children:"Logout"}):e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Pt(G.id),children:"Login"})}),z===G.id&&C[G.id]&&e.jsx("p",{className:"auth-login-instructions","data-testid":`onboarding-login-instructions-${G.id}`,children:C[G.id]}),He[G.id]==="timeout"&&z!==G.id&&e.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),He[G.id]==="failed"&&z!==G.id&&e.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},G.id)};return e.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:e.jsxs("div",{className:"modal model-onboarding-modal",children:[e.jsxs("div",{className:"model-onboarding-header",children:[e.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx(Nn,{size:24})," Set Up AI ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&e.jsxs(e.Fragment,{children:[e.jsx(es,{size:24})," Connect GitHub ",e.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&e.jsxs(e.Fragment,{children:[e.jsx(Kc,{size:24})," Set Up Your Project"]}),b==="first-task"&&e.jsxs(e.Fragment,{children:[e.jsx(Kc,{size:24})," Create Your First Task"]}),b==="complete"&&e.jsxs(e.Fragment,{children:[e.jsx(sn,{size:24})," All Set!"]})]}),b!=="complete"&&e.jsx("button",{className:"modal-close",onClick:Kt,"aria-label":"Skip onboarding",title:"Skip for now",children:e.jsx(Lt,{size:20})})]}),e.jsx("div",{className:"model-onboarding-steps",children:ve.map((G,Ke)=>{const I=mt>Ke,B=v.includes(G.key)&&I,re=M.includes(G.key)&&!v.includes(G.key)&&I,pe=B||re;return e.jsxs("div",{className:"onboarding-step-wrapper",children:[Ke>0&&e.jsx("div",{className:`model-onboarding-step-connector ${Ke<=mt?"done":""}`}),pe?e.jsxs("button",{className:`model-onboarding-step-indicator ${b===G.key?"active":""} ${B?"done":""} ${re?"skipped":""}`,onClick:()=>x(G.key),"aria-label":`Go back to ${G.label}`,title:`Review ${G.label}`,children:[e.jsx("span",{className:"step-number",children:B?e.jsx(sn,{size:14}):re?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ke+1}),e.jsx("span",{className:"step-label",children:G.label})]}):e.jsxs("div",{className:`model-onboarding-step-indicator ${b===G.key?"active":""} ${B?"done":""} ${re?"skipped":""}`,children:[e.jsx("span",{className:"step-number",children:B?e.jsx(sn,{size:14}):re?e.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ke+1}),e.jsx("span",{className:"step-label",children:G.label})]})]},G.key)})}),e.jsxs("div",{className:"model-onboarding-content",ref:ze,children:[b==="ai-setup"&&e.jsxs("div",{className:"model-onboarding-ai-setup",children:[e.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),e.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!H&&R.length>0&&(()=>{const G=R.filter(pe=>pe.id!=="github"&&pe.authenticated).length,Ke=R.filter(pe=>pe.id!=="github").length,I=Object.keys(se).filter(pe=>!R.find(xe=>xe.id===pe)?.authenticated).length;if(Ke===0)return null;let B="onboarding-provider-summary",re="";return G>0?(B+=" onboarding-provider-summary--connected",re=`✓ ${G} of ${Ke} provider${Ke!==1?"s":""} connected`):I>0?(B+=" onboarding-provider-summary--skipped",re=`${I} provider${I!==1?"s":""} skipped`):(B+=" onboarding-provider-summary--none",re="No providers connected yet"),e.jsx("div",{className:B,"data-testid":"provider-summary",children:re})})(),e.jsx(Us,{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."})}),R.length>0&&!R.some(G=>G.authenticated)&&e.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),H?e.jsxs("div",{className:"model-onboarding-loading",children:[e.jsx(ut,{size:24,className:"animate-spin"}),e.jsx("span",{children:"Loading providers…"})]}):R.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"}),zn.length>0?e.jsx("div",{className:"model-onboarding-providers",children:zn.map(G=>Pn(G))}):e.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),rs.length>0&&e.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[e.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),e.jsx("div",{className:"model-onboarding-providers",children:rs.map(G=>Pn(G))})]}),e.jsx(Us,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:e.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Gn.length>0?e.jsx("div",{className:"model-onboarding-providers",children:Gn.map(G=>Pn(G))}):e.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),as&&e.jsx(Us,{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."})}),Ut&&e.jsx(Us,{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(Us,{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."})}),oe.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(Yt,{models:oe,value:V,onChange:ee,placeholder:"Select a default model…",label:"Default model"})}),V&&e.jsx("div",{className:"onboarding-model-preview",children:e.jsxs("small",{className:"settings-muted",children:["Selected:"," ",oe.find(G=>G.id===V)?.name??V]})})]})]}),b==="github"&&e.jsxs("div",{className:"model-onboarding-github",children:[e.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),e.jsx("div",{className:"onboarding-feature-list",children:e.jsxs("ul",{children:[e.jsx("li",{className:"onboarding-feature-list-heading",children:e.jsx("strong",{children:"Without GitHub (available now):"})}),e.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),e.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),e.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),e.jsx("li",{className:"onboarding-feature-list-heading",children:e.jsx("strong",{children:"With GitHub (after connecting):"})}),e.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),e.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),e.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),En&&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(Us,{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."})}),Ae?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(es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),e.jsx("span",{"data-testid":"onboarding-auth-status-github",children:e.jsx(Ge,{status:Wt})})]}),Qe&&(z==="github"?e.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):e.jsx("button",{className:"btn btn-sm",onClick:()=>Oe("github"),children:"Disconnect"}))]}),(Wt==="not-connected"||Wt==="pending")&&e.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="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:()=>tt("github"),children:"Cancel"})]}):e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Pt("github"),children:[e.jsx(es,{size:16}),"Connect"]}),z==="github"&&C.github&&e.jsx("p",{className:"auth-login-instructions","data-testid":"onboarding-login-instructions-github",children:C.github})]}),Wt==="connected"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Se?"GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls.":"GitHub OAuth is connected. You can import issues and track pull requests."}),Wt==="failed"&&e.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[e.jsx("p",{children:"Connection failed or timed out."}),e.jsxs("div",{className:"onboarding-github-feedback-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>Pt("github"),children:"Retry"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Nt,children:"Skip for now"})]})]}),Wt==="pending"&&e.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Wt==="skipped"&&e.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[e.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),e.jsx("div",{className:"onboarding-github-feedback-actions",children:e.jsx("button",{className:"btn btn-sm",onClick:()=>Pt("github"),children:"Connect anyway"})})]}),Wt==="not-connected"&&e.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):e.jsxs("div",{className:"model-onboarding-github-optional",children:[e.jsx(es,{size:48,className:"optional-icon"}),Se?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:()=>x("project-setup"),children:"Continue without GitHub →"})]})]}),b==="project-setup"&&e.jsxs("div",{className:"model-onboarding-project-setup",children:[e.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),gn?e.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:e.jsx("p",{children:"Project selected — task creation and imports are available."})}):e.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[e.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),e.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),e.jsx(Us,{summary:"What does project setup do?",children:e.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&e.jsxs("div",{className:"model-onboarding-first-task",children:[e.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),P&&pn?e.jsxs("div",{className:"onboarding-task-created",children:[e.jsx(sn,{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:pn.id}),Mn&&e.jsx("p",{className:"onboarding-task-created__description",children:Mn}),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:mn,children:"View Task"}),e.jsx("button",{type:"button",className:"btn",onClick:Kn,children:"Go to Dashboard"})]})]}):e.jsxs(e.Fragment,{children:[gn?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:S,onChange:G=>{k(G.target.value),D(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:he,disabled:_,"data-testid":"onboarding-first-task-submit",children:_?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),T&&e.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[e.jsx("p",{className:"field-error",children:T}),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(SI,{items:Ft}),gn&&e.jsxs(e.Fragment,{children:[e.jsx(Us,{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:Be,disabled:ue,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${st?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:gt,disabled:ue||!st,children:[e.jsx("div",{className:"cta-icon",children:e.jsx(es,{size:24})}),e.jsxs("div",{className:"cta-content",children:[e.jsx("strong",{children:"Import from GitHub"}),e.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!st&&e.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),e.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",e.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&e.jsxs("div",{className:"model-onboarding-complete",children:[e.jsx(sn,{size:48,className:"success-icon"}),e.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),e.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Kt,disabled:ue,children:"Skip for now"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip setup →"}),e.jsx("button",{className:"btn btn-primary",onClick:_t,children:"Next →"})]}),b==="github"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:zt,children:"← Back"}),e.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip GitHub →"}),e.jsx("button",{className:"btn btn-primary",onClick:_t,children:"Next →"})]}),b==="project-setup"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:zt,children:"← Back"}),e.jsx("button",{className:"btn btn-primary",onClick:_t,disabled:!gn,children:"Next →"})]}),b==="first-task"&&!P&&e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:zt,children:"← Back"}),e.jsx("button",{className:"btn btn-primary",onClick:xt,disabled:ue,children:ue?e.jsxs(e.Fragment,{children:[e.jsx(ut,{size:16,className:"animate-spin"}),e.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&e.jsxs("button",{className:"btn btn-primary",onClick:yn,children:[e.jsx(sn,{size:16}),e.jsx("span",{children:"Get Started"})]})]})]})})}const AI=a.lazy(()=>nn(()=>import("./SetupWizardModal-CQc1uGSq.js"),__vite__mapDeps([12,1,2,3,4,5])).then(t=>({default:t.SetupWizardModal})));function PI({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),v=p??d.closeSettings,y=a.useCallback(()=>{d.openNewTask()},[d]),M=a.useCallback(()=>{d.openGitHubImport()},[d]),j=a.useCallback(w=>{x(null),d.closeModelOnboarding(),d.openDetailTask(w)},[d]),P=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(gi,{children:e.jsx(FM,{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(gi,{children:e.jsx(GM,{onClose:v,addToast:r,initialSection:d.settingsInitialSection,projectId:t,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})}),e.jsx(YM,{isOpen:d.githubImportOpen,onClose:d.closeGitHubImport,onImport:c.handleGitHubImport,tasks:n,projectId:t}),e.jsx(gi,{children:e.jsx(eA,{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(gi,{children:e.jsx(rA,{isOpen:d.isSubtaskOpen,onClose:d.closeSubtask,initialDescription:d.subtaskInitialDescription??"",onTasksCreated:c.handleSubtaskTasksCreated,projectId:t,resumeSessionId:d.subtaskResumeSessionId})}),e.jsx(jA,{isOpen:d.terminalOpen,onClose:d.closeTerminal,initialCommand:d.terminalInitialCommand,projectId:t}),e.jsx(wA,{isOpen:d.scriptsOpen,onClose:d.closeScripts,addToast:r,onRunScript:d.runScript,projectId:t}),d.filesOpen&&e.jsx(UA,{initialWorkspace:d.fileBrowserWorkspace,isOpen:!0,onClose:d.closeFiles,onWorkspaceChange:d.setFileWorkspace,projectId:t}),e.jsx(YA,{isOpen:d.usageOpen,onClose:d.closeUsage,projectId:t}),d.schedulesOpen&&e.jsx(gP,{onClose:d.closeSchedules,addToast:r,projectId:t}),e.jsx(gi,{children:e.jsx(yP,{isOpen:d.newTaskModalOpen,onClose:d.closeNewTask,tasks:n,onCreateTask:P,addToast:r,projectId:t,onPlanningMode:d.openPlanningWithInitialPlan,onSubtaskBreakdown:d.openSubtaskBreakdown})}),e.jsx(SP,{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(gi,{children:e.jsx(EP,{isOpen:d.gitManagerOpen,onClose:d.closeGitManager,tasks:n,addToast:r,projectId:t})}),e.jsx(gi,{children:e.jsx(zP,{isOpen:d.workflowStepsOpen,onClose:d.closeWorkflowSteps,addToast:r,projectId:t})}),e.jsx(JP,{isOpen:d.agentsOpen,onClose:d.closeAgents,addToast:r,projectId:t}),d.setupWizardOpen&&e.jsx(a.Suspense,{fallback:null,children:e.jsx(AI,{onProjectRegistered:m.handleSetupComplete,onClose:d.closeSetupWizard})}),d.modelOnboardingOpen&&e.jsx(MI,{onComplete:m.handleModelOnboardingComplete,addToast:r,projectId:t??"",onOpenSetupWizard:m.handleAddProject,onOpenNewTask:y,onOpenGitHubImport:M,firstCreatedTask:b,onViewTask:j}),e.jsx(mf,{toasts:l,onRemove:o})]})}function II({errorMessage:t,isRetrying:n,onRetry:s}){return e.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[e.jsx("h2",{children:"Can't reach the Fusion backend"}),e.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),e.jsxs("p",{className:"settings-muted",children:["Error: ",t]}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const tc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function _I(t,n){if(n==="ready")return"done";const s=tc.findIndex(r=>r.id===n),i=tc.findIndex(r=>r.id===t);return i<s?"done":i===s?"active":"pending"}function RI({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:tc.map(n=>{const s=_I(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(ut,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),e.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const TI=5e3;function $I(t,n,s){return t||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function FI(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++,Wr(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 DI(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 zy(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()},TI),()=>{u.current&&(clearInterval(u.current),u.current=null)}),[g]);const p=FI(t,s,i),f=$I(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:o,error:m,refresh:g}}const LI={planning:Ws,subtask:Si,mission_interview:ts,milestone_interview:ts,slice_interview:ts},zI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function OI({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}=ua(),p=a.useMemo(()=>Pi(),[]);if(a.useEffect(()=>{if(!l)return;const x=v=>{c.current&&!c.current.contains(v.target)&&o(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,v=new Map;for(const y of t){const M=g.get(y.id),j=[y.status,y.updatedAt,M?.tabId??y.lockedByTab??"",M?.stale?"stale":"fresh"].join("|"),P=u.current.get(y.id);P&&P!==j&&x.add(y.id),v.set(y.id,j)}if(u.current=v,x.size!==0)return m(x),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{m(new Set),h.current=null},500),()=>{h.current&&(clearTimeout(h.current),h.current=null)}},[g,t]),t.length===0)return null;const 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(ut,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&e.jsx(Vc,{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 v=LI[x.type],y=x.status==="generating",M=x.status==="awaiting_input",j=x.status==="error",P=g.get(x.id),w=P?.tabId??x.lockedByTab??null,S=!!(w&&w!==p&&!P?.stale),k=d.has(x.id);return e.jsxs("div",{className:`background-tasks-indicator__item${k?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:k?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:k?"translateY(-1px)":void 0},onClick:()=>{S&&!window.confirm("This session is active in another tab. Open anyway?")||(i(x),o(!1))},children:[j?e.jsx(ss,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):e.jsx(v,{size:14,className:"background-tasks-indicator__session-icon"}),e.jsxs("div",{className:"background-tasks-indicator__session-content",children:[e.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),e.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[j?"Failed":zI[x.type],y&&" — generating...",M&&!S&&" — needs input",M&&S&&" — active in another tab"]})]}),y&&e.jsx(ut,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),M&&!S&&e.jsx(Vc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),M&&S&&e.jsx(al,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),e.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(x.id)},title:"Dismiss",children:e.jsx(Lt,{size:12})})]},x.id)})})]})]})}function BI(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 UI(t){switch(t){case"running":return{label:"Running",color:"var(--color-success)",icon:ln};case"paused":return{label:"Paused",color:"var(--triage)",icon:Hs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Nn}}}function HI({tasks:t,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:l,onOpenBackgroundSession:o,onDismissBackgroundSession:d,lastFetchTimeMs:m,currentProjectPath:c,onOpenProjectDirectory:u}){const{stats:h,loading:g,error:p}=DI(t,n,s,m),[f,b]=a.useState(!1),x=a.useMemo(()=>UI(h.executorState),[h.executorState]),v=a.useMemo(()=>BI(h.lastActivityAt),[h.lastActivityAt]),y=x.icon;return p?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(rc,{size:14}),p]})}):g&&h.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 ${h.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(OI,{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:h.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 ${h.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:h.runningTaskCount}),e.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),e.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.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:h.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 ${h.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 ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.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:h.inReviewCount})]}),c&&u&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[e.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(M=>!M),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:e.jsx(Sn,{size:12,"aria-hidden":"true"})}),f&&e.jsx("button",{className:"executor-status-bar__project-path",onClick:u,title:c,"data-testid":"executor-project-path-link",children:c})]})]}),e.jsx("div",{className:"executor-status-bar__spacer"}),e.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[e.jsx(Ki,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__time",children:v})]}),e.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),e.jsxs("div",{className:"executor-status-bar__segment",children:[e.jsx(y,{size:12,style:{color:x.color},"aria-hidden":"true"}),e.jsx("span",{className:"executor-status-bar__state",style:{color:x.color},children:x.label})]})]})}const qI={planning:Ws,subtask:Si,mission_interview:ts,milestone_interview:ts,slice_interview:ts},VI={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},vi=new Set;function WI({sessions:t,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,l]=a.useState(0),o=()=>l(f=>f+1);a.useEffect(()=>{if(vi.size===0)return;const f=new Map(t.map(x=>[x.id,x]));let b=!1;for(const x of vi){const v=f.get(x);v&&v.status!=="awaiting_input"&&v.status!=="error"&&(vi.delete(x),b=!0)}b&&o()},[t]);const d=a.useMemo(()=>t.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!vi.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=>{vi.add(f),o()},g=f=>{vi.delete(f.id),o(),n(f)},p=()=>{for(const f of d)vi.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(ss,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:u})]}),e.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[e.jsx(Lt,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Dismiss all"})]})]}),e.jsx("div",{className:"session-notification-banner__list",children:d.map(f=>{const b=qI[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(ss,{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":VI[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(Lt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function KI({onResume:t}){const n=nI();if(!n)return null;const s=n.completedSteps.length,i=ri.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return e.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[e.jsxs("div",{className:"onboarding-resume-card__main",children:[e.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:e.jsx(Dn,{size:20})}),e.jsxs("div",{className:"onboarding-resume-card__content",children:[e.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),e.jsxs("p",{className:"onboarding-resume-card__description",children:[r,e.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),e.jsx("div",{className:"onboarding-resume-card__actions",children:e.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{ks("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),t()},children:[e.jsx(ln,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:"Continue onboarding"})]})})]})}function GI({onOpenSettings:t,onOpenModelOnboarding:n}){const s=la(),i=df(),[r,l]=a.useState(!0),[o,d]=a.useState(!1),[m,c]=a.useState(!1),[u,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){l(!1);return}let v=!1;return(async()=>{try{l(!0),d(!1);const[M,j]=await Promise.all([Ei(),ca()]);if(v)return;const P=M.providers??[],w=P.find(T=>T.id==="github"),k=!P.some(T=>T.id!=="github"&&T.authenticated),_=!j.defaultProvider&&!j.defaultModelId,E=w?!w.authenticated:!1;h({needsAiProvider:k,needsDefaultModel:_,needsGitHub:E})}catch{v||d(!0)}finally{v||l(!1)}})(),()=>{v=!0}},[s,i]);const g=a.useCallback(()=>{eI(),c(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{t("global-models")},[t]),b=a.useCallback(()=>{t("authentication")},[t]),x=a.useMemo(()=>{const v=[];return u.needsAiProvider&&v.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Nn}),u.needsDefaultModel&&v.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:sh}),u.needsGitHub&&v.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:es}),v},[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(Ws,{size:18,"aria-hidden":!0})}),e.jsxs("div",{className:"post-onboarding-recommendations__content",children:[e.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),e.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),e.jsx("ul",{className:"post-onboarding-recommendations__list",children:x.map(v=>{const y=v.icon;return e.jsxs("li",{className:"post-onboarding-recommendations__item",children:[e.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[e.jsx(ss,{size:14,"aria-hidden":!0}),e.jsx(y,{size:14,"aria-hidden":!0})]}),e.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[e.jsx("strong",{children:v.title}),e.jsx("span",{children:v.description})]}),e.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:v.onAction,children:v.actionLabel})]},v.id)})})]})]}),e.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:e.jsx(Lt,{size:16,"aria-hidden":!0})})]})}function JI({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 jo(t){return t>99?"99+":String(t)}function YI({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:v=0,onOpenUsage:y,onRunScript:M,projectId:j,onViewAllProjects:P,showSkillsTab:w,experimentalFeatures:S}){const k=sr(),[_,E]=a.useState(!1),[T,D]=a.useState(!1),[Z,$]=a.useState({}),[R,N]=a.useState(!1),W=a.useMemo(()=>Object.entries(Z).sort(([V],[F])=>V.localeCompare(F)),[Z]);a.useEffect(()=>{if(!T)return;let V=!1;return N(!0),Za(j).then(F=>{V||$(F)}).catch(()=>{V||$({})}).finally(()=>{V||N(!1)}),()=>{V=!0}},[T,j]);const Y=a.useCallback(()=>E(!1),[]),H=a.useCallback(V=>{Y(),V?.()},[Y]);if(a.useEffect(()=>{if(!_)return;const V=F=>{F.key==="Escape"&&E(!1)};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[_]),k!=="mobile"||i)return null;const A=v>0&&x?x:b,z=!!S?.roadmap,J=!!w,C=z&&(!J||t==="roadmaps"),q=J&&(!z||t!=="roadmaps"),oe=J&&!q,O=t==="documents"||t==="insights"||t==="memory"||t==="devserver"||t==="dev-server"||t==="roadmaps"&&!C||t==="skills"&&!q;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(Ci,{}),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(rn,{}),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(ts,{}),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(oi,{}),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(Yi,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-nav-tab-badge",children:jo(d)})]}),q&&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(Nn,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),C&&e.jsxs("button",{type:"button",className:`mobile-nav-tab${t==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":t==="roadmaps",onClick:()=>n("roadmaps"),children:[e.jsx(Ao,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),e.jsxs("button",{type:"button",className:`mobile-nav-tab${O?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>E(V=>!V),children:[e.jsx(Co,{}),e.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),_&&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:()=>H(o),children:[e.jsx(Yi,{}),e.jsx("span",{children:"Mailbox"}),d>0&&e.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:jo(d)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>H(l),children:[e.jsx(Ss,{}),e.jsx("span",{children:"Activity Log"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>H(m),children:[e.jsx(Vs,{}),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:()=>H(g),children:[e.jsx(Ks,{}),e.jsx("span",{children:"Terminal"})]}),e.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>D(V=>!V),"aria-expanded":T,"aria-haspopup":"menu","aria-label":"Show scripts",children:e.jsx(on,{size:14,className:`mobile-more-chevron${T?" mobile-more-chevron--open":""}`})})]}),T&&e.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:R?e.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[e.jsx(ut,{size:14,className:"animate-spin"}),e.jsx("span",{children:"Loading scripts…"})]}):W.length>0?e.jsxs(e.Fragment,{children:[W.map(([V,F])=>e.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${V}`,onClick:()=>{M&&M(V,F),Y(),D(!1)},children:[e.jsx(ln,{size:14}),e.jsx("span",{children:V})]},V)),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(),D(!1),h()},children:[e.jsx(Rs,{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(),D(!1),h()},children:[e.jsx(Rs,{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:()=>H(p),children:[e.jsx(Sn,{}),e.jsx("span",{children:"Files"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>H(A),children:[e.jsx(Ws,{}),e.jsx("span",{children:"Planning"}),v>0&&e.jsx("span",{className:"mobile-more-item-badge",children:jo(v)})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>H(c),children:[e.jsx(Io,{}),e.jsx("span",{children:"Workflow Steps"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>H(u),children:[e.jsx(Ki,{}),e.jsx("span",{children:"Automation"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>H(f),children:[e.jsx(JI,{}),e.jsx("span",{children:"Import from GitHub"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>H(y),children:[e.jsx(Ss,{}),e.jsx("span",{children:"Usage"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>H(P),children:[e.jsx(nh,{}),e.jsx("span",{children:"Projects"})]}),e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>H(()=>n("documents")),children:[e.jsx(wi,{}),e.jsx("span",{children:"Documents"})]}),oe&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>H(()=>n("skills")),children:[e.jsx(Nn,{}),e.jsx("span",{children:"Skills"})]}),z&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>H(()=>n("roadmaps")),children:[e.jsx(Ao,{}),e.jsx("span",{children:"Roadmaps"})]}),S?.insights&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>H(()=>n("insights")),children:[e.jsx(Dn,{}),e.jsx("span",{children:"Insights"})]}),S?.memoryView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>H(()=>n("memory")),children:[e.jsx(Lr,{}),e.jsx("span",{children:"Memory"})]}),S?.devServerView&&e.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{H(()=>n("dev-server"))},children:[e.jsx(rl,{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:()=>H(r),children:[e.jsx(Ua,{}),e.jsx("span",{children:"Settings"})]})]})]})]})}function QI({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(rn,{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 Tc="__fn_agent__";function ff(t,n){const s=typeof t=="string"?t.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Rm(t,n,s){const i=typeof t=="string"?t.trim():"",r=ff(n,s),l=i||(r.modelProvider&&r.modelId?Tc:"");return l?{agentId:l,...r}:null}function ko(t,n,s){const i=ff(n,s),r=i.modelProvider??"",l=i.modelId??"";return`${t}::${r}/${l}`}function XI(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 Tm(t){return{id:t.id,sessionId:t.sessionId,role:t.role,content:t.content,thinkingOutput:t.thinkingOutput,toolCalls:XI(t.metadata),createdAt:t.createdAt}}function ZI(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,v]=a.useState([]),[y,M]=a.useState(""),j=a.useRef(null),P=a.useRef(!1),w=a.useRef(""),S=a.useRef(""),k=a.useRef(null);a.useEffect(()=>{w.current=y},[y]);const _=a.useCallback(async H=>{const A={agentId:H.agentId};return H.modelProvider&&H.modelId&&(A.modelProvider=H.modelProvider,A.modelId=H.modelId),(await ek(A,t)).session},[t]),E=a.useCallback(async(H,A,z)=>{const J=Rm(H,A,z);if(!J)return;const C=ko(J.agentId,J.modelProvider,J.modelId);l(!0);try{const{session:q}=await Zj({agentId:J.agentId,modelProvider:J.modelProvider,modelId:J.modelId},t);if(q)i(q),S.current=C;else{const oe=await _(J);i(oe),S.current=C}}catch(q){console.error("[useQuickChat] Failed to initialize session:",q),n?.("Failed to initialize chat","error")}finally{l(!1)}},[t,n,_]),T=a.useCallback(async()=>{if(s){c(!0);try{const H=await yd(s.id,{limit:50},t);d(H.messages.map(Tm))}catch(H){console.error("[useQuickChat] Failed to load messages:",H)}finally{c(!1)}}},[s,t]);a.useEffect(()=>{s?T():d([])},[s,T]);const D=a.useCallback(async()=>{if(s){c(!0);try{const H=await yd(s.id,{limit:50},t);d(H.messages.map(Tm))}catch(H){console.error("[useQuickChat] Failed to reload messages:",H)}finally{c(!1)}}},[s,t]),Z=a.useCallback(async(H,A,z)=>{const J=Rm(H,A,z);if(!J)return;const C=ko(J.agentId,J.modelProvider,J.modelId);if(k.current=J,j.current&&(j.current.close(),j.current=null),p(""),b(""),v([]),h(!1),C===S.current&&s){await D();return}d([]),S.current=C,await E(J.agentId,J.modelProvider,J.modelId)},[E,D,s]),$=a.useCallback(async(H,A)=>{await Z(Tc,H,A)},[Z]),R=a.useCallback(async()=>{const H=k.current;if(!H)return;const A=ko(H.agentId,H.modelProvider,H.modelId);j.current&&(j.current.close(),j.current=null),p(""),b(""),v([]),h(!1),d([]),l(!0);try{const z=await _(H);i(z),S.current=A}catch(z){console.error("[useQuickChat] Failed to start a fresh session:",z),n?.("Failed to start a new chat","error")}finally{l(!1)}},[n,_]),N=a.useCallback(()=>{s&&(P.current=!0,j.current?.close(),j.current=null,tk(s.id,t).catch(()=>{}),h(!1),p(""),b(""),v([]))},[s,t]),W=a.useCallback(()=>{w.current="",M("")},[]),Y=a.useCallback(H=>{if(!s||!H.trim())return;if(u){w.current=H,M(H);return}P.current=!1,j.current&&(j.current.close(),j.current=null);const z={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:H,createdAt:new Date().toISOString()};d(O=>[...O,z]),p(""),b(""),v([]),h(!0);let J="",C="",q=[];const oe={onThinking:O=>{C+=O,b(C)},onText:O=>{J+=O,p(J)},onToolStart:O=>{q=[...q,{toolName:O.toolName,args:O.args,isError:!1,status:"running"}],v(q)},onToolEnd:O=>{const V=[...q];for(let F=V.length-1;F>=0;F--){const ue=V[F];if(ue?.toolName===O.toolName&&ue.status==="running"){V[F]={...ue,status:"completed",isError:O.isError,result:O.result},q=V,v(V);return}}q=[...V,{toolName:O.toolName,isError:O.isError,result:O.result,status:"completed"}],v(q)},onDone:O=>{const V={id:O.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:J,thinkingOutput:C||void 0,toolCalls:q.length>0?q:void 0,createdAt:new Date().toISOString()};d(ue=>[...ue,V]),p(""),b(""),v([]),h(!1),j.current=null;const F=w.current.trim();F&&(w.current="",M(""),Y(F))},onError:O=>{if(p(""),b(""),v([]),h(!1),j.current=null,console.error("[useQuickChat] Stream error:",O),n?.("Failed to get response","error"),!P.current){const V=w.current.trim();V&&(w.current="",M(""),Y(V))}D()}};j.current=nk(s.id,H,oe,t)},[s,u,t,n,D]);return a.useEffect(()=>()=>{j.current&&(j.current.close(),j.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:o,messagesLoading:m,isStreaming:u,streamingText:g,streamingThinking:f,streamingToolCalls:x,pendingMessage:y,sendMessage:Y,stopStreaming:N,clearPendingMessage:W,switchSession:Z,startModelChat:$,startFreshSession:R,loadMessages:T,reloadMessages:D}),[s,r,o,m,u,g,f,x,y,Y,N,W,Z,$,R,T,D])}function e_(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 da({...f,...g,includeEphemeral:g?.includeEphemeral??b},t),v=Array.from(new Map(x.map(y=>[y.id,y])).values());i(v)}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 Py(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 Gs(`/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||!vk(g));return{agents:s,activeAgents:h,stats:r,isLoading:o,loadAgents:m,loadStats:c}}function t_({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(eh,{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 n_=200;function s_(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 v=a.useCallback((w,S)=>{if(S<0||S>w.length){r(!1);return}const k=_=>/[a-zA-Z0-9/_.-]/.test(_);for(let _=S-1;_>=0;_--){if(w[_]==="#")if(_===0){const E=w.slice(_+1,S);m(_),o(E),f(0),r(!0);return}else{const E=w[_-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const T=w.slice(_+1,S);m(_),o(T),f(0),r(!0);return}r(!1);return}if(!k(w[_])){r(!1);return}}r(!1)},[]),y=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 zv(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)},n_),()=>{b.current&&clearTimeout(b.current)}},[l,i,M]);const j=a.useCallback((w,S)=>{if(!i||d<0)return S;const k=S.slice(0,d),_=S.slice(d+1),E=_.match(/[\s]|$/),T=E?E.index:_.length,D=_.slice(T);return`${k}#${w.path}${D}`},[i,d]),P=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(),y(),!0;default:return!1}},[i,c,p,y]);return{mentionActive:i,files:c,loading:h,mentionQuery:l,selectedIndex:p,setSelectedIndex:f,detectMention:v,selectFile:j,dismissMention:y,handleKeyDown:P}}const i_={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"},a_={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function r_(t){return`${t.name?.trim()||t.id} (${t.role})`}function l_(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 o_(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 Dr(t,n){return t.length>n?`${t.slice(0,n)}…`:t}function c_(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}=${Dr(r,50)}`}).join(", ")}function d_(t){if(t===void 0)return null;if(typeof t=="string")return Dr(t,200);try{return Dr(JSON.stringify(t),200)}catch{return Dr(String(t),200)}}function $m(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(ix,{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=c_(s.args),d=d_(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 u_(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 m_(t,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,l]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${t||"default"}`;try{const x=localStorage.getItem(b);if(x){const v=JSON.parse(x);if(typeof v.x=="number"&&typeof v.y=="number"&&!isNaN(v.x)&&!isNaN(v.y))return v}}catch{}return i()}),[o,d]=a.useState(!1),m=a.useRef(null),c=n??a.useRef(!1),u=a.useCallback(b=>{if(typeof window>"u")return b;const x=48,v=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,j=window.innerWidth-x-v,P=window.innerHeight-x-v-y-M;return{x:Math.max(v,Math.min(j,b.x)),y:Math.max(v,Math.min(P,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const x=`fusion-quick-chat-position-${t||"default"}`;try{localStorage.setItem(x,JSON.stringify(b))}catch{}},[t]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const v=b.target.closest(".quick-chat-fab");v&&(b.preventDefault(),typeof v.setPointerCapture=="function"&&v.setPointerCapture(b.pointerId),m.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},c.current=!1,d(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!m.current||!o)return;const x=b.clientX-m.current.pointerX,v=b.clientY-m.current.pointerY;if((Math.abs(x)>=5||Math.abs(v)>=5)&&(c.current=!0),c.current){const y=m.current.x-x,M=m.current.y-v,j=u({x:y,y:M});l(j)}},[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 h_({projectId:t,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:l=[],favoriteModels:o=[],onToggleFavorite:d,onToggleModelFavorite:m}){const{agents:c}=e_(t),[u,h]=a.useState(!1),g=i!==void 0,p=g?i:u,f=g?Ue=>{r?.(typeof Ue=="function"?Ue(p):Ue)}:h,[b,x]=a.useState("agent"),[v,y]=a.useState(""),[M,j]=a.useState([]),[P,w]=a.useState(!1),[S,k]=a.useState(""),[_,E]=a.useState(""),[T,D]=a.useState(""),[Z,$]=a.useState(!1),[R,N]=a.useState(0),[W,Y]=a.useState(-1),[,H]=a.useState(!1),[A,z]=a.useState({top:0,left:0}),J=s_({projectId:t}),C=a.useCallback(Ue=>{if(!Ue||!J.mentionActive)return;const ot=Ue.getBoundingClientRect();z({top:ot.top-260,left:ot.left+8})},[J.mentionActive]),q=a.useRef(!1),oe=a.useRef(!1),O=a.useRef(""),V=a.useRef(0),F=a.useRef(null),{position:ue,isDragging:ce,handlePointerDown:K,handlePointerMove:de,handlePointerUp:Fe}=m_(t,q),{activeSession:we,messages:Ee,isStreaming:ie,streamingText:Pe,streamingThinking:ze,streamingToolCalls:$e,sessionsLoading:He,messagesLoading:Me,sendMessage:Te,stopStreaming:Ve,pendingMessage:_e,clearPendingMessage:et,switchSession:le,startModelChat:X,startFreshSession:ke}=ZI(t,n),se=a.useRef(null),Le=a.useRef(null),ve=a.useRef(null),Ye=a.useRef(null),mt=a.useMemo(()=>l_(S),[S]),ht=a.useMemo(()=>M.find(Ue=>`${Ue.provider}/${Ue.id}`===S)??null,[M,S]),me=a.useMemo(()=>o_(ht,mt),[ht,mt]),te=a.useMemo(()=>b==="model"?mt?`${Tc}::${mt.modelProvider}/${mt.modelId}`:"":v?`${v}::`:"",[b,mt,v]),je=b==="agent"?!!v:!!mt;a.useEffect(()=>{if(c.length===0){y(""),x("model");return}c.some(ot=>ot.id===v)||y(c[0]?.id??"")},[c,v]),a.useEffect(()=>{!p||oe.current||(oe.current=!0,w(!0),Vn().then(Ue=>{const ot=Ue.models??[];if(j(ot),c.length===0&&ot.length>0&&!S){const ge=ot[0];ge&&k(`${ge.provider}/${ge.id}`)}}).catch(Ue=>{console.error("[QuickChatFAB] Failed to load models:",Ue),j([])}).finally(()=>{w(!1)}))},[p,c.length,S]),a.useEffect(()=>{if(!p){O.current="";return}if(!te){O.current="";return}if(te!==O.current){if(O.current=te,b==="model"&&mt){X(mt.modelProvider,mt.modelId);return}b==="agent"&&v&&le(v)}},[p,b,mt,v,te,X,le]),a.useEffect(()=>{p||($(!1),D(""),Y(-1))},[p]);const Ae=a.useCallback(Ue=>{y(Ue)},[]),Qe=a.useCallback(Ue=>{k(Ue)},[]),be=a.useCallback(()=>{!je||He||ke()},[je,He,ke]),st=a.useMemo(()=>c.find(Ue=>Ue.id===v)??null,[c,v]),Se=a.useMemo(()=>{const Ue=T.trim().toLowerCase();return Ue?c.filter(ot=>ot.name.toLowerCase().includes(Ue)):c},[c,T]),Je=a.useMemo(()=>{const Ue=new Map;for(const ot of c)Ue.set(ot.name.toLowerCase(),ot);return Ue},[c]);a.useEffect(()=>{N(0)},[T,Z]),a.useEffect(()=>()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),a.useEffect(()=>{if(!p)return;const Ue=ge=>{const Oe=ge.target;se.current?.contains(Oe)||Le.current?.contains(Oe)||Oe.closest(".model-combobox-dropdown--portal")||f(!1)},ot=ge=>{ge.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Ue),document.addEventListener("keydown",ot),()=>{document.removeEventListener("mousedown",Ue),document.removeEventListener("keydown",ot)}},[p,f]),a.useEffect(()=>{if(!p)return;const Ue=ve.current;Ue&&(Ue.scrollTop=Ue.scrollHeight)},[Ee,Pe,ze,p]);const it=a.useMemo(()=>b==="agent"?st?`Message ${st.name||st.id}`:"Select an agent to start chatting":me?`Message ${me}`:"Select a model to start chatting",[b,st,me]),ye=!je||!we||He,Ge=_e.length>50?`${_e.slice(0,50)}…`:_e,Ne=a.useCallback(()=>{const Ue=_.trim();!Ue||ye||(E(""),$(!1),D(""),Y(-1),Te(Ue))},[Te,ye,_]),at=a.useCallback((Ue,ot)=>{const ge=u_(Ue,ot);if(ge){$(!0),D(ge.filter),Y(ge.start);return}$(!1),D(""),Y(-1)},[]),dt=a.useCallback(Ue=>{const ot=Ye.current;if(!ot||W<0)return;const ge=ot.selectionStart??V.current,Oe=ot.selectionEnd??ge,ee=Math.max(ge,Oe),Ie=Math.min(W,ee),he=`${`@${Ue.name.replace(/\s+/g,"_")}`} `,Be=_.slice(0,Ie)+he+_.slice(ee),gt=Ie+he.length;E(Be),$(!1),D(""),N(0),Y(-1),window.requestAnimationFrame(()=>{Ye.current&&(Ye.current.focus(),Ye.current.setSelectionRange(gt,gt))})},[W,_]),vt=a.useCallback(Ue=>{const ot=Ue.target.value,ge=Ue.target.selectionStart??ot.length;V.current=ge,E(ot),at(ot,ge),J.detectMention(ot,ge),H(J.mentionActive),J.mentionActive&&C(Ue.target)},[at,J,C]),It=a.useCallback(()=>{F.current!==null&&window.clearTimeout(F.current),F.current=window.setTimeout(()=>{$(!1),D(""),Y(-1),H(!1),J.dismissMention(),F.current=null},120)},[J]),_t=a.useCallback(()=>{F.current!==null&&(window.clearTimeout(F.current),F.current=null)},[]),Mt=a.useCallback(Ue=>{const ot=Ue.currentTarget,ge=ot.selectionStart??ot.value.length;V.current=ge,at(ot.value,ge),J.detectMention(ot.value,ge),H(J.mentionActive),J.mentionActive&&C(ot)},[at,J,C]),zt=a.useCallback(Ue=>{Ue.key!=="Escape"&&Mt(Ue)},[Mt]),Nt=a.useCallback(Ue=>{const ot=/@([\w-]+)/g,ge=[];let Oe=0,ee=ot.exec(Ue);for(;ee;){const[Ie,xt=""]=ee,he=ee.index;he>Oe&&ge.push(Ue.slice(Oe,he));const Be=xt.replace(/_/g," ").toLowerCase(),gt=Je.get(Be);gt?ge.push(e.jsxs("span",{className:"chat-mention-chip",children:["@",gt.name.replace(/\s+/g,"_")]},`${gt.id}-${he}`)):ge.push(Ie),Oe=he+Ie.length,ee=ot.exec(Ue)}return Oe<Ue.length&&ge.push(Ue.slice(Oe)),ge.length===0?Ue:ge},[Je]),Pt=a.useCallback(Ue=>{if(V.current=Ue.currentTarget.selectionStart??V.current,J.mentionActive&&J.files.length>0){if(J.handleKeyDown(Ue,_),Ue.key==="Enter"||Ue.key==="Tab"){const ot=J.files[J.selectedIndex];if(ot){const ge=J.selectFile(ot,_);E(ge),J.dismissMention(),H(!1)}}return}if(Z&&Ue.key==="ArrowDown"){Ue.preventDefault(),Se.length>0&&N(ot=>(ot+1)%Se.length);return}if(Z&&Ue.key==="ArrowUp"){Ue.preventDefault(),Se.length>0&&N(ot=>ot===0?Se.length-1:ot-1);return}if(Z&&Ue.key==="Enter"){Ue.preventDefault();const ot=Se[R]??Se[0];ot&&dt(ot);return}if(Z&&Ue.key==="Escape"){Ue.preventDefault(),Ue.stopPropagation(),$(!1),D(""),Y(-1);return}Ue.key!=="Enter"||Ue.shiftKey||(Ue.preventDefault(),Ne())},[Z,Se,R,dt,Ne,J,_]),tt=a.useCallback(()=>{if(q.current){q.current=!1;return}f(Ue=>!Ue)},[f]),bt=ue.y+60;return e.jsxs(e.Fragment,{children:[s&&e.jsx("button",{ref:Le,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ce?"true":"false",style:{right:ue.x,bottom:ue.y},onPointerDown:K,onPointerMove:de,onPointerUp:Fe,onClick:tt,children:e.jsx(oi,{size:24})}),p&&e.jsxs("div",{className:"quick-chat-panel",ref:se,"data-testid":"quick-chat-panel",style:{right:ue.x,bottom:bt},children:[e.jsxs("div",{className:"quick-chat-panel-header",children:[e.jsxs("div",{style:a_,children:[e.jsx("h3",{children:"Quick Chat"}),me&&e.jsx("span",{style:i_,"data-testid":"quick-chat-model-tag",title:me,children:me})]}),e.jsxs("div",{className:"quick-chat-panel-header-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:be,disabled:!je||He,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(Lt,{size:16})})]})]}),c.length>0&&e.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[e.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{x("agent"),k("")},children:"Agent"}),e.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{x("model"),y("")},children:"Model"})]}),b==="agent"&&c.length>0&&e.jsxs("div",{className:"quick-chat-panel-agent-select",children:[e.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),e.jsx("select",{id:"quick-chat-agent-select",value:v,onChange:Ue=>Ae(Ue.target.value),"data-testid":"quick-chat-agent-select",children:c.map(Ue=>e.jsx("option",{value:Ue.id,children:r_(Ue)},Ue.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(Yt,{id:"quick-chat-model-override",models:M,value:S,onChange:Qe,label:"Select model override",placeholder:P?"Loading models…":"Select a model",disabled:P||M.length===0,favoriteProviders:l,favoriteModels:o,onToggleFavorite:d,onToggleModelFavorite:m})]}),e.jsx("div",{className:"quick-chat-panel-messages",ref:ve,"data-testid":"quick-chat-messages",children:He||Me?e.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ee.length===0&&!Pe&&!ze&&!ie?e.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):e.jsxs(e.Fragment,{children:[Ee.map(Ue=>{const ot=Ue.role==="user";return e.jsxs("div",{className:`quick-chat-panel-message ${ot?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${Ue.id}`,children:[e.jsx("p",{children:Nt(Ue.content)}),$m(Ue.toolCalls,!0)]},Ue.id)}),ie&&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:[Pe?e.jsx("p",{"data-testid":"quick-chat-streaming-text",children:Nt(Pe)}):e.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:ze?"Thinking…":"Connecting…"}),$m($e,!0),ze&&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:ze})]})]})]})}),e.jsxs("div",{className:"quick-chat-panel-input",children:[e.jsxs("div",{className:"quick-chat-input-wrapper",children:[e.jsx("input",{ref:Ye,type:"text",value:_,onChange:vt,onKeyDown:Pt,onKeyUp:zt,onClick:Mt,onBlur:It,onFocus:_t,placeholder:it,disabled:ye,"data-testid":"quick-chat-input"}),e.jsx(QI,{agents:c,filter:T,highlightedIndex:R,visible:Z,onSelect:dt,position:"above"}),e.jsx(t_,{visible:J.mentionActive&&!Z,position:A,files:J.files,selectedIndex:J.selectedIndex,onSelect:Ue=>{const ot=J.selectFile(Ue,_);E(ot),J.dismissMention(),H(!1),Ye.current?.focus()},loading:J.loading}),_e&&e.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[e.jsx("span",{children:`Queued: ${Ge}`}),e.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:et,children:"×"})]})]}),ie?e.jsx("button",{type:"button",className:"chat-input-stop",onClick:Ve,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:e.jsx(os,{size:14})}):e.jsx("button",{type:"button",onClick:()=>void Ne(),disabled:ye||_.trim().length===0,"data-testid":"quick-chat-send",children:e.jsx(yi,{size:16})})]})]})]})}function Tr(t){if(!t)return 0;const n=Date.parse(t);return Number.isFinite(n)?n:0}function Fm(t){return t.status==="generating"||t.status==="awaiting_input"}function p_(t){const[n,s]=a.useState([]),i=a.useRef(new Map),{sessions:r,broadcastUpdate:l,broadcastCompleted:o,requestSync:d}=ua(),m=a.useCallback(()=>{Ch(t).then(g=>{const p=new Map;for(const f of g)p.set(f.id,Tr(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,v=i.current.get(b.sessionId)??0;if(x<v)continue;const y=f.get(b.sessionId),M=b.type??y?.type,j=b.title??y?.title;if(!y&&(!M||!j))continue;const P={id:b.sessionId,type:M??"planning",status:b.status,title:j??"AI Session",projectId:b.projectId??y?.projectId??t??null,lockedByTab:b.owningTabId??y?.lockedByTab??null,updatedAt:b.updatedAt??y?.updatedAt??new Date(x).toISOString()},w=f.get(b.sessionId);(!w||w.status!==P.status||w.title!==P.title||w.type!==P.type||w.projectId!==P.projectId||w.lockedByTab!==P.lockedByTab||w.updatedAt!==P.updatedAt)&&(f.set(b.sessionId,P),i.current.set(b.sessionId,x),p=!0)}return p?[...f.values()].sort((b,x)=>Tr(x.updatedAt)-Tr(b.updatedAt)):g})},[t,r]),a.useEffect(()=>{const g=t?`?projectId=${encodeURIComponent(t)}`:"",p=b=>{try{const x=JSON.parse(b.data),v=Tr(x.updatedAt)||Date.now();s(y=>{const M=i.current.get(x.id)??0;if(v<M)return y;if(i.current.set(x.id,v),x.status==="complete"||x.status==="error")return y.filter(P=>P.id!==x.id);const j=y.findIndex(P=>P.id===x.id);if(j>=0){const P=[...y];return P[j]=x,P}return Fm(x)?[x,...y]:y}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:v}),(x.status==="complete"||x.status==="error")&&o({sessionId:x.id,status:x.status,timestamp:v})}catch{}},f=b=>{try{const x=JSON.parse(b.data);s(v=>v.filter(y=>y.id!==x)),i.current.delete(x)}catch{}};return Gs(`/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(y=>y.id===g)?.type,b=Pi();let x=!1,v=!1;if(f==="planning")try{await bh(g,t,b)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(v=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${g}: locked by another tab`))}else if(f==="subtask")try{await yh(g,t,b)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(v=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${g}: locked by another tab`))}else if(f==="mission_interview")try{await Sh(g,t,b)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(v=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${g}: locked by another tab`))}x&&!v&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${g}, attempting delete anyway`);try{await Uj(g)}catch{}s(y=>y.filter(M=>M.id!==g)),i.current.delete(g)},[t,n]),u=a.useMemo(()=>n.filter(g=>Fm(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 Hn(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 Dm(t,n){return!t&&!n?0:t?n?t.localeCompare(n):1:-1}function f_(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 v=1e3,y=a.useCallback(async $=>{const R=++u.current,N=n,W=$?.searchQueryOverride??s,Y=$?.includeArchivedOverride??m.current;try{const H=await Nx(void 0,void 0,N,W,Y);if(u.current!==R||n!==N)return;l(H.map(Hn)),f.current=Date.now()}catch{if(u.current!==R||n!==N)return;if($?.clearOnError){l([]);return}l(H=>H)}},[n,s]);p.current=y;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 $=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout($)},[s]),a.useEffect(()=>{y({clearOnError:!0});const $=()=>{if(document.visibilityState!=="visible")return;const R=Date.now();R-h.current<v||(h.current=R,y())};return document.addEventListener("visibilitychange",$),()=>{document.removeEventListener("visibilitychange",$)}},[y]),a.useEffect(()=>{if(i===!1)return;const $=b.current,R=n?`?projectId=${encodeURIComponent(n)}`:"",N=()=>b.current!==$;let W=!0;const Y=q=>{if(N())return;const oe=Hn(JSON.parse(q.data));if(g.current){p.current({searchQueryOverride:g.current});return}l(O=>O.some(V=>V.id===oe.id)?O:[...O,oe])},H=q=>{if(N())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:oe,to:O}=JSON.parse(q.data),V=Hn(oe);l(F=>F.map(ue=>ue.id===V.id?{...V,column:O}:ue)),f.current=Date.now()},A=q=>{if(N())return;if(g.current){p.current({searchQueryOverride:g.current});return}const oe=Hn(JSON.parse(q.data));l(O=>O.map(V=>{if(V.id!==oe.id||Dm(oe.updatedAt,V.updatedAt)<0)return V;if(V.column===oe.column)return oe;const ue=Dm(V.columnMovedAt,oe.columnMovedAt);return V.columnMovedAt&&!oe.columnMovedAt?{...oe,column:V.column,columnMovedAt:V.columnMovedAt}:ue>0?{...oe,column:V.column,columnMovedAt:V.columnMovedAt}:oe})),f.current=Date.now()},z=q=>{if(N())return;if(g.current){p.current({searchQueryOverride:g.current});return}const oe=Hn(JSON.parse(q.data));l(O=>O.filter(V=>V.id!==oe.id))},J=q=>{if(N())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:oe}=JSON.parse(q.data),O=Hn(oe);l(V=>V.map(F=>F.id===O.id?{...O,column:"done"}:F))},C=Gs(`/api/events${R}`,{events:{"task:created":Y,"task:moved":H,"task:updated":A,"task:deleted":z,"task:merged":J},onReconnect:()=>{W&&(N()||p.current())}});return()=>{W=!1,C()}},[n,i]);const j=a.useCallback(async $=>{const R=Hn(await dh($,n));return l(N=>N.some(W=>W.id===R.id)?N:[...N,R]),R},[n]),P=a.useCallback(async($,R)=>Hn(await Cx($,R,n)),[n]),w=a.useCallback(async $=>Hn(await Ex($,n)),[n]),S=a.useCallback(async $=>Mx($,n),[n]),k=a.useCallback(async $=>Hn(await Ax($,n)),[n]),_=a.useCallback(async $=>{const R=Hn(await Px($,n));return l(N=>N.some(W=>W.id===R.id)?N:[...N,R]),R},[n]),E=a.useCallback(async($,R)=>{const N=c.current.find(Y=>Y.id===$),W=N?{...N,...R,updatedAt:new Date().toISOString()}:void 0;W&&l(Y=>Y.map(H=>H.id===$?W:H));try{const Y=Hn(await Zs($,R,n));return l(H=>H.map(A=>A.id===$?Y:A)),Y}catch(Y){throw N&&l(H=>H.map(A=>A.id===$?N:A)),Y}},[n]),T=a.useCallback(async $=>{const R=Hn(await Rx($,n));return l(N=>N.map(W=>W.id===$?R:W)),R},[n]),D=a.useCallback(async $=>{const R=Hn(await Tx($,n));return l(N=>N.map(W=>W.id===$?R:W)),R},[n]),Z=a.useCallback(async()=>{const R=(await $x(n)).map(Hn);return l(N=>N.map(W=>R.find(H=>H.id===W.id)||W)),R},[n]);return{tasks:r,createTask:j,moveTask:P,deleteTask:w,mergeTask:S,retryTask:k,duplicateTask:_,updateTask:E,archiveTask:T,unarchiveTask:D,archiveAllDone:Z,loadArchivedTasks:M,includeArchived:o,lastFetchTimeMs:f.current}}const g_=5e3,b_=1e3;function x_(){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 pd();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 pd(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${x.length} projects)`;console.log(`[useProjects] ${y}`),Fa("[useProjects]",y),g||(n(x),l(null))}catch(x){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${x instanceof Error?x.message:String(x)}`;console.warn(`[useProjects] ${y}`),Fa("[useProjects]",y),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<b_||(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()},g_),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,m]);const c=a.useCallback(async g=>{const p=await Ly(g);return n(f=>[...f,p]),p},[]),u=a.useCallback(async(g,p)=>{const f=await qy(g,p);return n(b=>b.map(x=>x.id===g?f:x)),f},[]),h=a.useCallback(async g=>{await kh(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 v_="kb-dashboard-current-project";function y_(t){return t??"local"}function j_(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=y_(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ca();if(p)return;c.current=b.dashboardCurrentProjectIdByNode??{};const x=c.current[u];if(x){const v=t.find(y=>y.id===x);v&&(r(v),d.current=!0)}if(!x)try{const v=localStorage.getItem(v_);if(v){const y=JSON.parse(v);y?.id&&t.some(j=>j.id===y.id)&&(r(y),d.current=!0,c.current={...c.current,[u]:y.id},await Jt({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,Jt({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,Jt({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[u]),g=a.useCallback(()=>{m.current=!0,r(null);const p={...c.current};delete p[u],c.current=p,Jt({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[u]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:l}}const gf=a.createContext(null);function k_({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()},[]),Wm.createElement(gf.Provider,{value:{toasts:n,addToast:o,removeToast:l}},t)}function w_(){const t=a.useContext(gf);if(!t)throw new Error("useToast must be used within ToastProvider");return t}const bf="kb-dashboard-theme-mode",xf="kb-dashboard-color-theme",vf=[...bk],nc="theme-data",wo="theme-data.css";function N_(){const t=document.baseURI||(typeof document.location<"u"?document.location.href:"");return t?t.endsWith("/")?t.slice(0,-1)+`/${wo}`:t.replace(/\/[^/]+$/,`/${wo}`):`/${wo}`}const Ns=typeof window<"u",S_=Ns?a.useLayoutEffect:a.useEffect;function yf(t){return t==="dark"||t==="light"||t==="system"}function Lm(){if(!Ns)return"dark";try{const t=localStorage.getItem(bf);if(yf(t))return t}catch{}return"dark"}function zm(){if(!Ns)return"default";try{const t=localStorage.getItem(xf);if(t&&vf.includes(t))return t}catch{}return"default"}function Om(t){if(Ns)try{localStorage.setItem(bf,t)}catch{}}function Bm(t){if(Ns)try{localStorage.setItem(xf,t)}catch{}}function C_(t,n){return t==="system"?n?"dark":"light":t}function E_(t,n,s){if(!Ns)return;const i=C_(t,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Um(){if(!Ns)return;const t=N_(),n=document.getElementById(nc);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=nc,document.head.appendChild(s)}function Hm(){if(!Ns)return;const t=document.getElementById(nc);t&&t.remove()}function M_(){const[t,n]=a.useState(()=>Lm()),[s,i]=a.useState(()=>zm()),[r,l]=a.useState(!0),[o,d]=a.useState(()=>Ns?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(!Ns||!r)return;let f=!1;return ca().then(b=>{f||(yf(b.themeMode)&&!u.current&&(m.current!==b.themeMode&&(m.current=b.themeMode,n(b.themeMode)),Lm()!==b.themeMode&&Om(b.themeMode)),b.colorTheme&&vf.includes(b.colorTheme)&&!h.current&&(c.current!==b.colorTheme&&(c.current=b.colorTheme,i(b.colorTheme)),zm()!==b.colorTheme&&Bm(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(!Ns)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=x=>{d(x.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),S_(()=>{E_(t,s,o)},[t,s,o]),a.useEffect(()=>{!Ns||r||(s!=="default"?Um():Hm())},[s,r]);const g=a.useCallback(f=>{u.current=!0,m.current=f,n(f),Om(f),Jt({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),Bm(f),f!=="default"?Um():Hm(),Jt({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 A_(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,v]=a.useState(null),[y,M]=a.useState("definition"),[j,P]=a.useState(!1),[w,S]=a.useState(void 0),[k,_]=a.useState(!1),[E,T]=a.useState(!1),[D,Z]=a.useState(!1),[$,R]=a.useState(!1),[N,W]=a.useState(void 0),[Y,H]=a.useState(!1),[A,z]=a.useState("project"),[J,C]=a.useState(!1),[q,oe]=a.useState(!1),[O,V]=a.useState(!1),[F,ue]=a.useState(!1),[ce,K]=a.useState(!1),[de,Fe]=a.useState(!1),[we,Ee]=a.useState(!1),ie=!!(x||j||s||r||u||$||Y||J||q||O||ce||F||D||k||E||de||we),Pe=a.useCallback(()=>i(!0),[]),ze=a.useCallback(()=>i(!1),[]),$e=a.useCallback(()=>l(!0),[]),He=a.useCallback(Oe=>{d(Oe),l(!0)},[]),Me=a.useCallback(()=>{const Oe=n[0];Oe&&(c(Oe.id),l(!0))},[n]),Te=a.useCallback(Oe=>{c(Oe),l(!0)},[]),Ve=a.useCallback(()=>{l(!1),d(null),c(void 0)},[]),_e=a.useCallback(Oe=>{p(Oe),h(!0)},[]),et=a.useCallback(Oe=>{b(Oe),h(!0)},[]),le=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),X=a.useCallback((Oe,ee="definition")=>{v(Oe),M(ee)},[]),ke=a.useCallback(Oe=>{v(Oe),M("changes")},[]),se=a.useCallback(Oe=>{v(ee=>ee&&{...ee,...Oe})},[]),Le=a.useCallback(()=>{v(null)},[]),ve=a.useCallback(Oe=>{S(Oe),P(!0)},[]),Ye=a.useCallback(()=>{P(!1),S(void 0)},[]),mt=a.useCallback(()=>_(!0),[]),ht=a.useCallback(()=>_(!1),[]),me=a.useCallback(()=>T(!0),[]),te=a.useCallback(()=>T(!1),[]),je=a.useCallback(()=>Z(!0),[]),Ae=a.useCallback(()=>Z(!1),[]),Qe=a.useCallback(()=>{R(Oe=>!Oe)},[]),be=a.useCallback(()=>{R(!1),W(void 0)},[]),st=a.useCallback(()=>H(!0),[]),Se=a.useCallback(()=>H(!1),[]),Je=a.useCallback(Oe=>{z(Oe)},[]),it=a.useCallback(()=>C(!0),[]),ye=a.useCallback(()=>C(!1),[]),Ge=a.useCallback(()=>oe(!0),[]),Ne=a.useCallback(()=>oe(!1),[]),at=a.useCallback(()=>V(!0),[]),dt=a.useCallback(()=>V(!1),[]),vt=a.useCallback(()=>ue(!0),[]),It=a.useCallback(()=>ue(!1),[]),_t=a.useCallback(()=>K(!0),[]),Mt=a.useCallback(()=>K(!1),[]),zt=a.useCallback(async(Oe,ee)=>{K(!1),W(ee),R(!0)},[]),Nt=a.useCallback(()=>Fe(!0),[]),Pt=a.useCallback(()=>Fe(!1),[]),tt=a.useCallback(()=>Ee(!0),[]),bt=a.useCallback(()=>Ee(!1),[]),Ue=a.useCallback((Oe,ee)=>{ee(`Created ${Oe.id} from planning mode`,"success"),l(!1),d(null)},[]),ot=a.useCallback((Oe,ee)=>{const Ie=Oe.map(xt=>xt.id).join(", ");ee(`Created ${Ie} from planning mode`,"success"),l(!1),d(null)},[]),ge=a.useCallback((Oe,ee)=>{const Ie=Oe.map(xt=>xt.id).join(", ");ee(`Created ${Ie} 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:y,settingsOpen:j,settingsInitialSection:w,schedulesOpen:k,githubImportOpen:E,usageOpen:D,terminalOpen:$,terminalInitialCommand:N,filesOpen:Y,fileBrowserWorkspace:A,activityLogOpen:J,gitManagerOpen:q,workflowStepsOpen:O,agentsOpen:F,scriptsOpen:ce,setupWizardOpen:de,modelOnboardingOpen:we,anyModalOpen:ie,openNewTask:Pe,closeNewTask:ze,openPlanning:$e,openPlanningWithInitialPlan:He,resumePlanning:Me,openPlanningWithSession:Te,closePlanning:Ve,openSubtaskBreakdown:_e,openSubtaskWithSession:et,closeSubtask:le,openDetailTask:X,openDetailWithChangesTab:ke,updateDetailTask:se,closeDetailTask:Le,openSettings:ve,closeSettings:Ye,openSchedules:mt,closeSchedules:ht,openGitHubImport:me,closeGitHubImport:te,openUsage:je,closeUsage:Ae,toggleTerminal:Qe,closeTerminal:be,openFiles:st,closeFiles:Se,setFileWorkspace:Je,openActivityLog:it,closeActivityLog:ye,openGitManager:Ge,closeGitManager:Ne,openWorkflowSteps:at,closeWorkflowSteps:dt,openAgents:vt,closeAgents:It,openScripts:_t,closeScripts:Mt,runScript:zt,openSetupWizard:Nt,closeSetupWizard:Pt,openModelOnboarding:tt,closeModelOnboarding:bt,onPlanningTaskCreated:Ue,onPlanningTasksCreated:ot,onSubtaskTasksCreated:ge}}function P_(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),[v,y]=a.useState({}),[M,j]=a.useState(!1),[P,w]=a.useState(!1),[S,k]=a.useState(!1),[_,E]=a.useState(!1),T=a.useCallback(async()=>{const[N,W]=await Promise.allSettled([Lx(t),Xi(t)]);if(N.status==="fulfilled"&&(s(N.value.maxConcurrent),r(N.value.rootDir)),W.status==="fulfilled"){const Y=W.value;o(!!Y.autoMerge),m(!!Y.globalPause),u(!!Y.enginePaused),x(!!Y.prAuthAvailable),g(Y.taskStuckTimeoutMs),f(Y.showQuickChatFAB===!0),y(Y.experimentalFeatures??{});const H=Y.experimentalFeatures??{};j(H.insights===!0),w(H.roadmap===!0),k(H.memoryView===!0),E(H.devServerView===!0)}},[t]);a.useEffect(()=>{T()},[T]);const D=a.useCallback(async()=>{const N=!l;o(N);try{await Ta({autoMerge:N},t)}catch{o(!N)}},[l,t]),Z=a.useCallback(async()=>{const N=!d;m(N);try{await Ta({globalPause:N,globalPauseReason:N?"manual":void 0},t)}catch{m(!N)}},[d,t]),$=a.useCallback(async()=>{const N=!c;u(N);try{await Ta({enginePaused:N},t)}catch{u(!N)}},[c,t]),R=a.useCallback(async()=>{const N=!p;f(N);try{await Ta({showQuickChatFAB:N},t)}catch{f(!N)}},[p,t]);return{maxConcurrent:n,rootDir:i,autoMerge:l,globalPaused:d,enginePaused:c,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:v,insightsEnabled:M,roadmapEnabled:P,memoryEnabled:S,devServerEnabled:_,toggleAutoMerge:D,toggleGlobalPause:Z,toggleEnginePause:$,toggleShowQuickChatFAB:R,refresh:T}}function I_(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(v=>v.id===p);if(!x){o(`Project '${p}' not found`,"error");return}r?.id!==x.id&&l(x)}if(c.current)return;c.current=!0,Hr(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 __(){const[t,n]=a.useState([]),[s,i]=a.useState([]),[r,l]=a.useState([]);a.useEffect(()=>{Vn().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 Jt({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 Jt({favoriteProviders:s,favoriteModels:h})}catch(g){throw l(c),g}},[r,s]);return{availableModels:t,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:o,toggleFavoriteModel:d}}function R_({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;Ei().then(({providers:o})=>{const d=o.some(c=>c.authenticated);if(o.length>0&&!d||o.length>0&&d)return ca().then(c=>{const u=!!(c.defaultProvider&&c.defaultModelId);(c.modelOnboardingComplete===!1||c.modelOnboardingComplete===void 0)&&(!d||!u)&&!la()?r=!0:!d&&!la()&&(l=!0)})}).then(()=>{r?(ks("onboarding:auto-triggered",{trigger:"first-run"}),n()):l&&(ks("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[t,n,s])}const T_=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function qm(t){return t!==null&&T_.includes(t)}function $_(t){return t==="devserver"?"dev-server":t}function F_(t){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:l,setupWizardOpen:o,openSetupWizard:d,themeMode:m,setThemeMode:c}=t,[u,h]=a.useState(()=>{if(typeof window<"u"){const v=window.localStorage.getItem("kb-dashboard-view-mode");if(v==="overview"||v==="project")return v}return"overview"}),[g,p]=a.useState(()=>{const v=Rn("kb-dashboard-task-view");return qm(v)?v:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",u)},[u]),a.useEffect(()=>{const v=Rn("kb-dashboard-task-view",r?.id);if(qm(v)){const y=!f.current&&v==="devserver";p(y?"devserver":$_(v))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{us("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&u==="overview"&&h("project")},[n,i,r,u]),a.useEffect(()=>{if(n||i||o||s||l>0||r)return;const v=window.setTimeout(()=>{d()},500);return()=>window.clearTimeout(v)},[n,s,l,i,r,o,d]);const b=a.useCallback(v=>{p(v)},[]),x=a.useCallback(()=>{const v=["dark","light","system"],y=v.indexOf(m),M=v[(y+1)%v.length];c(M)},[m,c]);return{viewMode:u,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:x}}function D_(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]),v=a.useCallback(k=>{h(),n(k),i("project"),m(`Project ${k.name} registered successfully`,"success"),l()},[h,n,i,m,l]),y=a.useCallback(()=>{g()},[g]),M=a.useCallback(async k=>{try{await Oy(k.id),m(`Project ${k.name} paused`,"success"),await l()}catch{m(`Failed to pause project ${k.name}`,"error")}},[m,l]),j=a.useCallback(async k=>{try{await By(k.id),m(`Project ${k.name} resumed`,"success"),await l()}catch{m(`Failed to resume project ${k.name}`,"error")}},[m,l]),P=a.useCallback(async k=>{try{await kh(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:v,handleModelOnboardingComplete:y,handlePauseProject:M,handleResumeProject:j,handleRemoveProject:P,handleToggleFavorite:w,handleToggleModelFavorite:S}}function L_(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 z_(t){return cl("/health",{nodeId:t})}async function O_(t){return cl("/projects",{nodeId:t})}async function B_(t,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),cl(`/tasks?${i.toString()}`,{nodeId:t})}async function U_(t,n){return cl(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:t})}async function KT(t){return L(`/nodes/${encodeURIComponent(t)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function GT(t){return L(`/nodes/${encodeURIComponent(t)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function JT(t){return L(`/nodes/${encodeURIComponent(t)}/settings/sync-status`)}async function YT(t){return L(`/nodes/${encodeURIComponent(t)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function H_(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 v=new AbortController;f.current=v,h(!0),p(null);try{const y=[z_(t),O_(t)];s&&(y.push(B_(t,s,i)),y.push(U_(t,s)));const M=await Promise.allSettled(y);if(v.signal.aborted)return;const j=M[0],P=M[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(c(j.value),P.status==="rejected"){p(`Failed to fetch projects: ${P.reason}`),h(!1);return}if(l(P.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(y){v.signal.aborted||(p(y instanceof Error?y.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 q_(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 Gs(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 V_="fusion-dashboard-current-node",jf=a.createContext(null);function W_({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 ca();if(u)return;o.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(l.current=!0),!p)try{const f=localStorage.getItem(V_);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(o.current=b.id,await Jt({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,Jt({dashboardCurrentNodeId:u}).catch(()=>{}))}else n===null&&o.current!==void 0&&(o.current=void 0,Jt({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const d=a.useCallback(u=>{s(u)},[]),m=a.useCallback(()=>{s(null),o.current=void 0,Jt({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),c={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:d,clearCurrentNode:m};return e.jsx(jf.Provider,{value:c,children:t})}function K_(){const t=a.useContext(jf);if(t===null)throw new Error("useNodeContext must be used within a NodeProvider");return t}function G_({open:t}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{t&&i.current?.focus()},[t]);const r=a.useCallback(()=>{const o=n.trim();o&&(hx(o),window.location.reload())},[n]),l=a.useCallback(()=>{px(),window.location.reload()},[]);return t?e.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:o=>{o.key==="Escape"&&(o.preventDefault(),o.stopPropagation())},children:e.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[e.jsx("div",{className:"modal-header auth-token-recovery-header",children:e.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),e.jsxs("div",{className:"auth-token-recovery-content",children:[e.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),e.jsxs("div",{className:"auth-token-recovery-field",children:[e.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),e.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:o=>s(o.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),e.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:l,children:"Clear token and retry"}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const J_=a.lazy(()=>nn(()=>import("./AgentsView-yCYBY2km.js").then(t=>t.A),__vite__mapDeps([13,1,14,3,15])).then(t=>({default:t.AgentsView}))),Y_=a.lazy(()=>nn(()=>import("./DocumentsView-DkkoHRwL.js"),__vite__mapDeps([16,1,4,5,17])).then(t=>({default:t.DocumentsView}))),Q_=a.lazy(()=>nn(()=>import("./InsightsView-DaRtUPHX.js"),__vite__mapDeps([18,1,4,5,19])).then(t=>({default:t.InsightsView}))),X_=a.lazy(()=>nn(()=>import("./NodesView-BsUk_oiU.js"),__vite__mapDeps([20,1,14,4,5,21])).then(t=>({default:t.NodesView}))),Z_=a.lazy(()=>nn(()=>import("./ChatView-CH9T0dDs.js"),__vite__mapDeps([22,1,4,5])).then(t=>({default:t.ChatView}))),eR=a.lazy(()=>nn(()=>import("./RoadmapsView-SQol126Y.js"),__vite__mapDeps([23,1,4,5,24])).then(t=>({default:t.RoadmapsView}))),tR=a.lazy(()=>nn(()=>import("./SkillsView-BtUhs_QW.js"),__vite__mapDeps([25,1,4,5,26])).then(t=>({default:t.SkillsView}))),nR=a.lazy(()=>nn(()=>import("./MemoryView-85NKuU3h.js"),__vite__mapDeps([27,1,4,5,28])).then(t=>({default:t.MemoryView}))),sR=a.lazy(()=>nn(()=>import("./DevServerView-jXXtoQUx.js"),__vite__mapDeps([29,1,4,5,30])).then(t=>({default:t.DevServerView})));function iR(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{nn(()=>import("./AgentsView-yCYBY2km.js").then(n=>n.A),__vite__mapDeps([13,1,14,3,15])),nn(()=>import("./DocumentsView-DkkoHRwL.js"),__vite__mapDeps([16,1,4,5,17])),nn(()=>import("./InsightsView-DaRtUPHX.js"),__vite__mapDeps([18,1,4,5,19])),nn(()=>import("./NodesView-BsUk_oiU.js"),__vite__mapDeps([20,1,14,4,5,21])),nn(()=>import("./ChatView-CH9T0dDs.js"),__vite__mapDeps([22,1,4,5])),nn(()=>import("./RoadmapsView-SQol126Y.js"),__vite__mapDeps([23,1,4,5,24])),nn(()=>import("./SkillsView-BtUhs_QW.js"),__vite__mapDeps([25,1,4,5,26])),nn(()=>import("./MemoryView-85NKuU3h.js"),__vite__mapDeps([27,1,4,5,28])),nn(()=>import("./DevServerView-jXXtoQUx.js"),__vite__mapDeps([29,1,4,5,30]))})}const No="kb-setup-warning-dismissed";function aR(){const{toasts:t,addToast:n,removeToast:s}=w_(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{iR()},[]);const{projects:r,loading:l,error:o,refresh:d}=x_(),{nodes:m}=gI(),{currentNode:c,currentNodeId:u,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=K_(),{currentProject:f,setCurrentProject:b,clearCurrentProject:x,loading:v}=j_(r,{nodeId:u}),{hasAiProvider:y,hasGithub:M,loading:j,hasWarnings:P}=of(f?.id);a.useEffect(()=>{if(u&&!c&&m.length>0){const We=m.find(wt=>wt.id===u);if(We){g(We);return}}u&&m.length>0&&(m.some(wt=>wt.id===u)||p())},[u,c,m,g,p]);const[w,S]=a.useState(""),k=H_(u,{projectId:f?.id,searchQuery:w||void 0});q_(u);const _=h&&k.projects.length>0?k.projects:r,{themeMode:E,colorTheme:T,setThemeMode:D,setColorTheme:Z}=M_(),{sessions:$,generating:R,needsInput:N,planningSessions:W,dismissSession:Y}=p_(f?.id),H=$.filter(We=>We.status==="awaiting_input"||We.status==="error"),A=A_({projectId:f?.id,planningSessions:W}),{viewMode:z,setViewMode:J,taskView:C,handleChangeTaskView:q}=F_({projectsLoading:l,projectsError:o,currentProjectLoading:v,currentProject:f,projectsLength:r.length,setupWizardOpen:A.setupWizardOpen,openSetupWizard:A.openSetupWizard,themeMode:E,setThemeMode:D}),oe=a.useCallback(We=>{We==="missions"&&(te(void 0),Ae(void 0),be(void 0)),q(We)},[q]),O=C==="board"||C==="list",{tasks:V,createTask:F,moveTask:ue,deleteTask:ce,mergeTask:K,retryTask:de,updateTask:Fe,duplicateTask:we,archiveTask:Ee,unarchiveTask:ie,archiveAllDone:Pe,loadArchivedTasks:ze,lastFetchTimeMs:$e}=f_({...f?{projectId:f.id}:{},searchQuery:w||void 0,sseEnabled:O}),[He,Me]=a.useState(!1),Te=a.useRef(performance.now()),Ve=a.useRef(!1),_e=a.useRef(!1),et=a.useMemo(()=>l?"projects":v?"project":"tasks",[l,v]);a.useEffect(()=>{if(!l&&!Ve.current){Ve.current=!0;const We=`projects loaded at ${Math.round(performance.now()-Te.current)}ms from mount`;console.log(`[App] ${We}`),Fa("[App]",We)}if(!v&&!_e.current){_e.current=!0;const We=`current-project resolved at ${Math.round(performance.now()-Te.current)}ms from mount`;console.log(`[App] ${We}`),Fa("[App]",We)}},[l,v]),a.useEffect(()=>{if(He||l||v)return;const We=performance.now(),wt=window.setTimeout(()=>{const ae=`dashboard ready at ${Math.round(performance.now()-Te.current)}ms from mount (settle delay=${Math.round(performance.now()-We)}ms)`;console.log(`[App] ${ae}`),Fa("[App]",ae),Me(!0)},200);return()=>{window.clearTimeout(wt)}},[He,l,v]);const X=sr()==="mobile",[ke,se]=a.useState(0),Le=a.useCallback(()=>{Eh(f?.id).then(We=>{se(We.unreadCount)}).catch(We=>{console.warn("[App] Failed to fetch mailbox unread count:",We)})},[f?.id]);a.useEffect(()=>{Le();const We=new URLSearchParams;f?.id&&We.set("projectId",f.id);const wt=We.size>0?`?${We.toString()}`:"";return Gs(`/api/events${wt}`,{events:{"message:sent":Le,"message:received":Le,"message:read":Le,"message:deleted":Le}})},[f?.id,Le]);const[ve,Ye]=a.useState(!1),[mt,ht]=a.useState(!1),[me,te]=a.useState(void 0),[je,Ae]=a.useState(void 0),[Qe,be]=a.useState(void 0),[st,Se]=a.useState(!1),[Je,it]=a.useState(!1),[ye,Ge]=a.useState(()=>Rn(No,f?.id)==="true");a.useEffect(()=>{Ge(Rn(No,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const We=()=>{it(!0)};return window.addEventListener(_o,We),()=>{window.removeEventListener(_o,We)}},[]);const Ne=a.useCallback(()=>{us(No,"true",f?.id),Ge(!0)},[f?.id]),{maxConcurrent:at,autoMerge:dt,globalPaused:vt,enginePaused:It,taskStuckTimeoutMs:_t,showQuickChatFAB:Mt,prAuthAvailable:zt,experimentalFeatures:Nt,insightsEnabled:Pt,roadmapEnabled:tt,memoryEnabled:bt,devServerEnabled:Ue,toggleAutoMerge:ot,toggleGlobalPause:ge,toggleEnginePause:Oe,refresh:ee}=P_(f?.id),Ie=Nt.skillsView===!0,xt=Nt.nodesView===!0,he=!0;a.useEffect(()=>{Object.keys(Nt).length!==0&&(C==="insights"&&!Pt&&q("board"),C==="roadmaps"&&!tt&&q("board"),C==="memory"&&!bt&&q("board"),(C==="devserver"||C==="dev-server")&&!Ue&&q("board"))},[C,Pt,tt,Nt,q,he,bt,Ue]),a.useEffect(()=>{ve&&!xt&&Ye(!1)},[ve,xt]);const{availableModels:Be,favoriteProviders:gt,favoriteModels:Kt,toggleFavoriteProvider:yn,toggleFavoriteModel:mn}=__();R_({projectId:f?.id,openModelOnboarding:A.openModelOnboarding,openSettings:A.openSettings});const{handleSelectProject:Kn,handleViewAllProjects:Wt,handleOpenSettings:Cn,handleAddProject:Tn,handleSetupComplete:as,handleModelOnboardingComplete:Ut,handlePauseProject:Xt,handleResumeProject:hn,handleRemoveProject:gn,handleToggleFavorite:En,handleToggleModelFavorite:an}=D_({setCurrentProject:b,clearCurrentProject:x,setViewMode:J,currentProject:f,refreshProjects:d,toggleFavoriteProvider:yn,toggleFavoriteModel:mn,addToast:n,openSettings:A.openSettings,openSetupWizard:A.openSetupWizard,closeSetupWizard:A.closeSetupWizard,closeModelOnboarding:A.closeModelOnboarding}),{handleDetailClose:Ft}=I_({projectId:f?.id,projects:r,projectsLoading:l,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:A.openDetailTask,closeTaskDetail:A.closeDetailTask}),{handleBoardQuickCreate:pn,handleModalCreate:Mn,handlePlanningTaskCreated:jn,handlePlanningTasksCreated:zn,handleSubtaskTasksCreated:rs,handleGitHubImport:Gn}=L_({createTask:F,onPlanningTaskCreated:A.onPlanningTaskCreated,onPlanningTasksCreated:A.onPlanningTasksCreated,onSubtaskTasksCreated:A.onSubtaskTasksCreated,addToast:n}),Pn=a.useCallback((We,wt)=>{if(wt==="changes"){A.openDetailWithChangesTab(We);return}A.openDetailTask(We,wt)},[A]),G=a.useCallback(()=>{xt&&Ye(We=>!We)},[xt]),Ke=a.useCallback(()=>{A.setFileWorkspace("project"),A.openFiles()},[A]),I=a.useCallback(async()=>{ht(!0);try{await d()}finally{ht(!1)}},[d]),B=a.useCallback(We=>{Ae(We),te(void 0),q("missions")},[q]),re=a.useCallback(We=>{We.type==="planning"?A.openPlanningWithSession(We.id):We.type==="subtask"?A.openSubtaskWithSession(We.id):We.type==="mission_interview"?(Ae(void 0),te(We.id),be(void 0),q("missions")):(We.type==="milestone_interview"||We.type==="slice_interview")&&(te(void 0),Ae(void 0),be(We.id),q("missions"))},[q,A]),pe=a.useCallback(()=>{for(const We of H)Y(We.id)},[Y,H]),xe=!l&&!v&&r.length===0&&!f&&!!o,Re=()=>xe?e.jsx(II,{errorMessage:o??"Failed to fetch projects",isRetrying:mt,onRetry:I}):ve?e.jsx("div",{className:"nodes-management-overlay",children:e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(X_,{addToast:n,onClose:()=>Ye(!1)})})})}):z==="overview"?e.jsx(Xn,{children:e.jsx(_w,{projects:r,loading:l,onSelectProject:Kn,onAddProject:Tn,onPauseProject:Xt,onResumeProject:hn,onRemoveProject:gn,nodes:m})}):C==="skills"?Ie?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(tR,{addToast:n,projectId:f?.id,onClose:()=>q("board")})})}):(q("board"),null):C==="chat"?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(Z_,{addToast:n,projectId:f?.id})})}):C==="mailbox"?e.jsx(Xn,{children:e.jsx(NN,{projectId:f?.id,addToast:n,onUnreadCountChange:se})}):C==="roadmaps"?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(eR,{addToast:n,projectId:f?.id})})}):C==="missions"?e.jsx(Xn,{children:e.jsx(yN,{isInline:!0,isOpen:!0,onClose:()=>{Ae(void 0),te(void 0),be(void 0),q("board")},addToast:n,projectId:f?.id,onSelectTask:We=>{const wt=V.find(ae=>ae.id===We);wt&&A.openDetailTask(wt)},availableTasks:V.map(We=>({id:We.id,title:We.title})),resumeSessionId:me,targetMissionId:je,milestoneSliceResumeSessionId:Qe,onMilestoneSliceResumeFetchError:()=>be(void 0)})}):C==="agents"&&he?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(J_,{addToast:n,projectId:f?.id})})}):C==="documents"?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(Y_,{projectId:f?.id,addToast:n,onOpenDetail:A.openDetailTask})})}):C==="insights"?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(Q_,{projectId:f?.id,addToast:n,onClose:()=>q("board")})})}):C==="memory"?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(nR,{addToast:n,projectId:f?.id})})}):C==="devserver"||C==="dev-server"?e.jsx(Xn,{children:e.jsx(a.Suspense,{fallback:null,children:e.jsx(sR,{addToast:n,projectId:f?.id})})}):C==="board"?e.jsx(Xn,{children:e.jsx(yw,{tasks:h&&k.tasks.length>0?k.tasks:V,projectId:f?.id,maxConcurrent:at,onMoveTask:ue,onOpenDetail:A.openDetailTask,addToast:n,onQuickCreate:pn,onNewTask:A.openNewTask,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,autoMerge:dt,onToggleAutoMerge:ot,globalPaused:vt,onUpdateTask:Fe,onArchiveTask:Ee,onUnarchiveTask:ie,onDeleteTask:ce,onArchiveAllDone:Pe,onLoadArchivedTasks:ze,searchQuery:w,availableModels:Be,onOpenDetailWithTab:Pn,favoriteProviders:gt,favoriteModels:Kt,onToggleFavorite:En,onToggleModelFavorite:an,taskStuckTimeoutMs:_t,onOpenMission:B,lastFetchTimeMs:$e})}):e.jsx(Xn,{children:e.jsx(kw,{tasks:h&&k.tasks.length>0?k.tasks:V,projectId:f?.id,onMoveTask:ue,onOpenDetail:A.openDetailTask,addToast:n,globalPaused:vt,onNewTask:A.openNewTask,onQuickCreate:pn,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,availableModels:Be,favoriteProviders:gt,favoriteModels:Kt,onToggleFavorite:En,onToggleModelFavorite:an,taskStuckTimeoutMs:_t,searchQuery:w,lastFetchTimeMs:$e})});if(!He)return e.jsxs(e.Fragment,{children:[e.jsx(RI,{stage:et}),e.jsx(mf,{toasts:t,onRemove:s})]});const pt=!A.modelOnboardingOpen&&tI(),kt=!A.modelOnboardingOpen&&!pt&&la()&&!df();return e.jsxs(e.Fragment,{children:[e.jsx(ck,{isElectron:i,onOpenSettings:Cn,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:W.length,onOpenUsage:A.openUsage,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>oe("mailbox"),mailboxUnreadCount:ke,onOpenSchedules:A.openSchedules,onOpenGitManager:A.openGitManager,onOpenNodes:G,showNodesButton:xt,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenScripts:A.openScripts,onRunScript:A.runScript,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,filesOpen:A.filesOpen,globalPaused:vt,enginePaused:It,onToggleGlobalPause:ge,onToggleEnginePause:Oe,view:C,onChangeView:z==="project"&&f?oe:void 0,showSkillsTab:Ie,showAgentsTab:he,searchQuery:w,onSearchChange:S,projects:_,currentProject:f,onSelectProject:Kn,onViewAllProjects:Wt,projectId:f?.id,mobileNavEnabled:X,availableNodes:m,currentNode:c,onSelectNode:We=>{We===null?p():g(We)},isRemote:h,experimentalFeatures:{insights:Pt,roadmap:tt,memoryView:bt,devServer:Ue,devServerView:Ue}}),z==="project"&&f&&!ve&&C!=="missions"&&!A.isPlanningOpen&&e.jsx(WI,{sessions:H,onResumeSession:re,onDismissSession:Y,onDismissAll:pe}),z==="project"&&f&&pt&&e.jsx(KI,{onResume:A.openModelOnboarding}),z==="project"&&f&&kt&&e.jsx(GI,{onOpenModelOnboarding:A.openModelOnboarding,onOpenSettings:We=>A.openSettings(We)}),z==="project"&&f&&!j&&P&&!ye&&e.jsx(cf,{hasAiProvider:y,hasGithub:M,onDismiss:Ne}),e.jsx("div",{className:`project-content${z==="project"&&f?" project-content--with-footer":""}${X?" project-content--with-mobile-nav":""}`,children:Re()}),z==="project"&&f&&!ve&&e.jsx(HI,{tasks:h&&k.tasks.length>0?k.tasks:V,projectId:f.id,taskStuckTimeoutMs:_t,backgroundSessions:$,backgroundGenerating:R,backgroundNeedsInput:N,onOpenBackgroundSession:re,onDismissBackgroundSession:Y,lastFetchTimeMs:$e,currentProjectPath:f.path,onOpenProjectDirectory:Ke}),e.jsx(YI,{view:C,onChangeView:z==="project"&&f?oe:()=>{},footerVisible:z==="project"&&!!f,modalOpen:A.anyModalOpen,onOpenSettings:Cn,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>oe("mailbox"),mailboxUnreadCount:ke,onOpenGitManager:A.openGitManager,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenSchedules:A.openSchedules,onOpenScripts:A.openScripts,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:W.length,onOpenUsage:A.openUsage,onViewAllProjects:Wt,onRunScript:A.runScript,projectId:f?.id,showSkillsTab:Ie,experimentalFeatures:{insights:Pt,roadmap:tt,memoryView:bt,devServer:Ue,devServerView:Ue}}),z==="project"&&f&&C!=="chat"&&C!=="mailbox"&&C!=="insights"&&C!=="devserver"&&C!=="dev-server"&&e.jsx(h_,{projectId:f.id,addToast:n,showFAB:Mt,open:st,onOpenChange:Se,favoriteProviders:gt,favoriteModels:Kt,onToggleFavorite:En,onToggleModelFavorite:an}),e.jsx(PI,{projectId:f?.id,tasks:V,projects:r,currentProject:f,addToast:n,toasts:t,removeToast:s,modalManager:A,projectActions:{handleAddProject:Tn,handleSetupComplete:as,handleModelOnboardingComplete:Ut},taskHandlers:{handleModalCreate:Mn,handlePlanningTaskCreated:jn,handlePlanningTasksCreated:zn,handleSubtaskTasksCreated:rs,handleGitHubImport:Gn},taskOperations:{moveTask:ue,deleteTask:ce,mergeTask:K,retryTask:de,duplicateTask:we},deepLink:{handleDetailClose:Ft},settings:{prAuthAvailable:zt,themeMode:E,colorTheme:T,setThemeMode:D,setColorTheme:Z},onSettingsClose:()=>{A.closeSettings(),ee()},onReopenOnboarding:()=>{A.closeSettings(),A.openModelOnboarding()}}),e.jsx(G_,{open:Je})]})}function rR(){return e.jsx(k_,{children:e.jsx(W_,{children:e.jsx(aR,{})})})}jx();Mf.createRoot(document.getElementById("root")).render(e.jsx(a.StrictMode,{children:e.jsx(lx,{children:e.jsx(rR,{})})}));"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{wR as $,Ss as A,rn as B,sn as C,on as D,ln as E,wi as F,Ni as G,vo as H,qt as I,Hs as J,Ot as K,ut as L,GP as M,Ey as N,BP as O,ns as P,UP as Q,vn as R,qi as S,rc as T,My as U,HR as V,Ay as W,Lt as X,kR as Y,Nn as Z,nn as _,us as a,hT as a$,Hr as a0,Dv as a1,kg as a2,ic as a3,oa as a4,di as a5,ui as a6,qs as a7,BT as a8,qT as a9,ek as aA,zT as aB,OT as aC,tk as aD,nk as aE,s_ as aF,sr as aG,sc as aH,QI as aI,t_ as aJ,os as aK,yi as aL,oi as aM,ix as aN,eT as aO,nT as aP,tT as aQ,sT as aR,iT as aS,aT,rT as aU,lT as aV,oT as aW,cT as aX,dT as aY,uT as aZ,mT as a_,HT as aa,UT as ab,VT as ac,Dn as ad,ss as ae,Jb as af,ex as ag,Ws as ah,yg as ai,nl as aj,Ki as ak,JT as al,KT as am,GT as an,YT as ao,Or as ap,Ob as aq,Ua as ar,fg as as,$n as at,rh as au,gI as av,x_ as aw,LT as ax,yd as ay,qa as az,XR as b,yR as b$,fT as b0,gT as b1,pT as b2,An as b3,ac as b4,Gi as b5,FT as b6,$T as b7,DT as b8,DM as b9,sy as bA,iy as bB,ty as bC,NR as bD,ei as bE,li as bF,rl as bG,Qi as bH,Ly as bI,hx as bJ,px as bK,CT as bL,Ib as bM,Po as bN,_T as bO,RT as bP,AT as bQ,MT as bR,PT as bS,ET as bT,IT as bU,ZR as bV,Sn as bW,xR as bX,gR as bY,bR as bZ,Jm as b_,zx as ba,Zc as bb,dR as bc,Ox as bd,Hx as be,qx as bf,pR as bg,uR as bh,mR as bi,hR as bj,Bx as bk,cR as bl,fR as bm,ef as bn,ER as bo,CR as bp,RR as bq,SR as br,MR as bs,AR as bt,PR as bu,IR as bv,ay as bw,_R as bx,oc as by,ny as bz,Ze as c,jR as c0,vR as c1,bT as c2,vT as c3,kT as c4,yT as c5,xT as c6,jT as c7,wT as c8,jh as c9,ed as ca,Qg as cb,NT as cc,VR as cd,OR as ce,UR as cf,BR as cg,GR as ch,KR as ci,Zm as cj,LR as ck,DR as cl,OP as cm,qR as cn,Ja as co,Y2 as cp,$R as cq,TR as cr,Lv as cs,FR as ct,zR as cu,ST as cv,YR as d,QR as e,TT as f,Rn as g,Vn as h,da as i,Yt as j,Cy as k,JR as l,e_ as m,Xi as n,Ta as o,fe as p,vk as q,WR as r,Gs as s,Mo as t,Jt as u,Vs as v,Vt as w,zr as x,HP as y,WT as z};