@runfusion/fusion 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/bin.js +67600 -65202
  2. package/dist/client/assets/{AgentDetailView-CJIxNRq-.js → AgentDetailView-sy6Hg1Xr.js} +3 -3
  3. package/dist/client/assets/{AgentsView-BS17exn3.js → AgentsView-DpEpW88a.js} +3 -3
  4. package/dist/client/assets/ChatView-BUt3C4cf.js +1 -0
  5. package/dist/client/assets/{DevServerView-qMPpnXRb.js → DevServerView-BOyWtQJM.js} +1 -1
  6. package/dist/client/assets/{DirectoryPicker-CTwgv9LY.js → DirectoryPicker-BJyEEso5.js} +1 -1
  7. package/dist/client/assets/{DocumentsView-DOz1KFGN.js → DocumentsView-Dx0M1YHw.js} +1 -1
  8. package/dist/client/assets/{InsightsView-CHZTJUic.js → InsightsView-BtXdAo7D.js} +1 -1
  9. package/dist/client/assets/MemoryView-DiajLXby.css +1 -0
  10. package/dist/client/assets/MemoryView-kKPuqmwf.js +2 -0
  11. package/dist/client/assets/{NodesView-BtGNRj2z.js → NodesView-B_ZwUORz.js} +1 -1
  12. package/dist/client/assets/{PiExtensionsManager-D9Ye2Vak.js → PiExtensionsManager-Db0EGr0Q.js} +3 -3
  13. package/dist/client/assets/{PluginManager-LeHp0jJ_.js → PluginManager-mOwWndfg.js} +1 -1
  14. package/dist/client/assets/{RoadmapsView-C413ISVU.js → RoadmapsView-DbUzBLeF.js} +1 -1
  15. package/dist/client/assets/SettingsModal-Bs_lNs5B.js +31 -0
  16. package/dist/client/assets/SettingsModal-G0ESQXRD.css +1 -0
  17. package/dist/client/assets/{SettingsModal-olTBmYJs.js → SettingsModal-TRJu_mTn.js} +1 -1
  18. package/dist/client/assets/{SetupWizardModal-WdaR2eQQ.js → SetupWizardModal-D1bmCQrf.js} +1 -1
  19. package/dist/client/assets/{SkillsView-BcE57w8i.js → SkillsView-Dzzpd5Md.js} +1 -1
  20. package/dist/client/assets/{folder-open-Ec4hU1xL.js → folder-open-BcuByk6U.js} +1 -1
  21. package/dist/client/assets/index-BipedNj4.css +1 -0
  22. package/dist/client/assets/index-k2c4LrUr.js +616 -0
  23. package/dist/client/assets/{upload-BksRDuGJ.js → upload-BzNbXYEj.js} +1 -1
  24. package/dist/client/assets/{users-EFU4n9Qr.js → users-BvIqhSXp.js} +1 -1
  25. package/dist/client/index.html +2 -2
  26. package/dist/client/version.json +1 -0
  27. package/dist/extension.js +2165 -885
  28. package/dist/pi-claude-cli/package.json +1 -1
  29. package/dist/pi-claude-cli/src/provider.ts +0 -1
  30. package/package.json +5 -5
  31. package/dist/client/assets/ChatView-BUlq3WNJ.js +0 -1
  32. package/dist/client/assets/MemoryView-DhinauGs.css +0 -1
  33. package/dist/client/assets/MemoryView-V0QdeO3e.js +0 -2
  34. package/dist/client/assets/SettingsModal--vWmKBpT.css +0 -1
  35. package/dist/client/assets/SettingsModal-BZLL2xAP.js +0 -31
  36. package/dist/client/assets/index-CCYdhck-.js +0 -616
  37. package/dist/client/assets/index-lJ5WOmO9.css +0 -1
@@ -1,616 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-WdaR2eQQ.js","assets/DirectoryPicker-CTwgv9LY.js","assets/folder-open-Ec4hU1xL.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-BMa6p24b.css","assets/SettingsModal-BZLL2xAP.js","assets/SettingsModal-olTBmYJs.js","assets/SettingsModal--vWmKBpT.css","assets/users-EFU4n9Qr.js","assets/SettingsModal-CDWvhvrd.css","assets/AgentsView-BS17exn3.js","assets/upload-BksRDuGJ.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-DOz1KFGN.js","assets/DocumentsView-DV2DrCZb.css","assets/InsightsView-CHZTJUic.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-BtGNRj2z.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-BUlq3WNJ.js","assets/RoadmapsView-C413ISVU.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-BcE57w8i.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-V0QdeO3e.js","assets/MemoryView-DhinauGs.css","assets/DevServerView-qMPpnXRb.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
2
- import{r as a,j as t,a as _a,g as Om,R as Um,c as hf}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
3
- * @license lucide-react v1.7.0 - ISC
4
- *
5
- * This source code is licensed under the ISC license.
6
- * See the LICENSE file in the root directory of this source tree.
7
- */const Bm=(...e)=>e.filter((n,s,i)=>!!n&&n.trim()!==""&&i.indexOf(n)===s).join(" ").trim();/**
8
- * @license lucide-react v1.7.0 - ISC
9
- *
10
- * This source code is licensed under the ISC license.
11
- * See the LICENSE file in the root directory of this source tree.
12
- */const pf=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
13
- * @license lucide-react v1.7.0 - ISC
14
- *
15
- * This source code is licensed under the ISC license.
16
- * See the LICENSE file in the root directory of this source tree.
17
- */const ff=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,i)=>i?i.toUpperCase():s.toLowerCase());/**
18
- * @license lucide-react v1.7.0 - ISC
19
- *
20
- * This source code is licensed under the ISC license.
21
- * See the LICENSE file in the root directory of this source tree.
22
- */const Bc=e=>{const n=ff(e);return n.charAt(0).toUpperCase()+n.slice(1)};/**
23
- * @license lucide-react v1.7.0 - ISC
24
- *
25
- * This source code is licensed under the ISC license.
26
- * See the LICENSE file in the root directory of this source tree.
27
- */var So={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 gf=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},bf=a.createContext({}),xf=()=>a.useContext(bf),vf=a.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:i,className:r="",children:o,iconNode:l,...c},u)=>{const{size:d=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:g="currentColor",className:p=""}=xf()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...So,width:n??d??So.width,height:n??d??So.height,stroke:e??g,strokeWidth:f,className:Bm("lucide",p,r),...!o&&!gf(c)&&{"aria-hidden":"true"},...c},[...l.map(([b,v])=>a.createElement(b,v)),...Array.isArray(o)?o:[o]])});/**
33
- * @license lucide-react v1.7.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const qe=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(vf,{ref:o,iconNode:n,className:Bm(`lucide-${pf(Bc(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Bc(e),s};/**
38
- * @license lucide-react v1.7.0 - ISC
39
- *
40
- * This source code is licensed under the ISC license.
41
- * See the LICENSE file in the root directory of this source tree.
42
- */const yf=[["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=qe("activity",yf);/**
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 kf=[["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"}]],Jr=qe("archive",kf);/**
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 jf=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],qa=qe("arrow-down",jf);/**
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 wf=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],na=qe("arrow-left",wf);/**
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 Nf=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Va=qe("arrow-right",Nf);/**
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 Sf=[["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"}]],Hm=qe("arrow-up-down",Sf);/**
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 Cf=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ki=qe("arrow-up",Cf);/**
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 Ef=[["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"}]],Mf=qe("book-open",Ef);/**
78
- * @license lucide-react v1.7.0 - ISC
79
- *
80
- * This source code is licensed under the ISC license.
81
- * See the LICENSE file in the root directory of this source tree.
82
- */const _f=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],nn=qe("bot",_f);/**
83
- * @license lucide-react v1.7.0 - ISC
84
- *
85
- * This source code is licensed under the ISC license.
86
- * See the LICENSE file in the root directory of this source tree.
87
- */const Af=[["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"}]],jl=qe("box",Af);/**
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 Rf=[["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"}]],Rr=qe("brain",Rf);/**
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 Tf=[["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"}]],qm=qe("calendar",Tf);/**
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 If=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Pf=qe("check-check",If);/**
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 $f=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],yn=qe("check",$f);/**
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 Df=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],zt=qe("chevron-down",Df);/**
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 Lf=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Zl=qe("chevron-left",Lf);/**
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 zf=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],an=qe("chevron-right",zf);/**
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 Ff=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Zs=qe("chevron-up",Ff);/**
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 Of=[["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"}]],ns=qe("circle-alert",Of);/**
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 Uf=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],en=qe("circle-check-big",Uf);/**
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 Bf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Yr=qe("circle-dot",Bf);/**
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 Hf=[["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"}]],Hc=qe("circle-question-mark",Hf);/**
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 qf=[["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"}]],Wa=qe("circle-x",qf);/**
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 Vf=[["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"}]],Wf=qe("clipboard-list",Vf);/**
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 Gf=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],wi=qe("clock",Gf);/**
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 Kf=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Vm=qe("code",Kf);/**
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 Jf=[["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"}]],Yf=qe("columns-3",Jf);/**
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 Qf=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Hi=qe("copy",Qf);/**
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 Xf=[["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"}]],Zf=qe("cpu",Xf);/**
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 eg=[["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"}]],tg=qe("download",eg);/**
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 ng=[["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"}]],sg=qe("ellipsis-vertical",ng);/**
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 ig=[["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"}]],wl=qe("ellipsis",ig);/**
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 ag=[["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"}]],rg=qe("external-link",ag);/**
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 og=[["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"}]],lg=qe("eye-off",og);/**
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 cg=[["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"}]],ec=qe("eye",cg);/**
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 dg=[["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"}]],As=qe("file-code",dg);/**
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 ug=[["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"}]],Wm=qe("file-diff",ug);/**
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 mg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],hg=qe("file-minus",mg);/**
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 pg=[["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"}]],Gm=qe("file-pen",pg);/**
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 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"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],gg=qe("file-plus",fg);/**
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 bg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],xg=qe("file-question-mark",bg);/**
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 vg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Ni=qe("file-text",vg);/**
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 yg=[["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"}]],kg=qe("file-type",yg);/**
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 jg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],Km=qe("file",jg);/**
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 wg=[["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"}]],Nl=qe("folder-git-2",wg);/**
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 Ng=[["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"}]],qc=qe("folder-root",Ng);/**
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 Sg=[["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"}]],kn=qe("folder",Sg);/**
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 Cg=[["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"}]],Tr=qe("funnel",Cg);/**
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 Eg=[["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"}]],Us=qe("git-branch",Eg);/**
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 Mg=[["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"}]],Da=qe("git-commit-horizontal",Mg);/**
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 _g=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]],Jm=qe("git-merge",_g);/**
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 Ag=[["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"}]],Zn=qe("git-pull-request",Ag);/**
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 Rg=[["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"}]],Qr=qe("globe",Rg);/**
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 Tg=[["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"}]],Ym=qe("grid-3x3",Tg);/**
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 Ig=[["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"}]],tc=qe("grip-vertical",Ig);/**
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 Pg=[["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"}]],$g=qe("hard-drive",Pg);/**
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 Dg=[["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"}]],Lg=qe("heart",Dg);/**
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 zg=[["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"}]],La=qe("history",zg);/**
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 Fg=[["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"}]],Aa=qe("inbox",Fg);/**
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 Og=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]],Qm=qe("key",Og);/**
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 Ug=[["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=qe("layers",Ug);/**
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 Bg=[["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=qe("layout-grid",Bg);/**
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 Hg=[["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"}]],Bs=qe("lightbulb",Hg);/**
353
- * @license lucide-react v1.7.0 - ISC
354
- *
355
- * This source code is licensed under the ISC license.
356
- * See the LICENSE file in the root directory of this source tree.
357
- */const qg=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]],qi=qe("link",qg);/**
358
- * @license lucide-react v1.7.0 - ISC
359
- *
360
- * This source code is licensed under the ISC license.
361
- * See the LICENSE file in the root directory of this source tree.
362
- */const Vg=[["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"}]],Wg=qe("list-plus",Vg);/**
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 Gg=[["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"}]],Xr=qe("list-tree",Gg);/**
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 Kg=[["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"}]],Sl=qe("list",Kg);/**
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 Jg=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],at=qe("loader-circle",Jg);/**
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 Yg=[["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"}]],Zr=qe("lock",Yg);/**
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 Qg=[["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"}]],Vi=qe("mail",Qg);/**
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 Xg=[["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"}]],Cl=qe("map",Xg);/**
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 Zg=[["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"}]],eo=qe("maximize-2",Zg);/**
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 eb=[["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"}]],li=qe("message-square",eb);/**
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 tb=[["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"}]],sa=qe("minimize-2",tb);/**
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 nb=[["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"}]],Xm=qe("monitor",nb);/**
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 sb=[["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"}]],ib=qe("move",sb);/**
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 ab=[["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"}]],El=qe("package",ab);/**
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 rb=[["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"}]],ob=qe("paperclip",rb);/**
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 lb=[["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"}]],Os=qe("pause",lb);/**
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 cb=[["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"}]],Un=qe("pencil",cb);/**
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 db=[["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"}]],sn=qe("play",db);/**
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 ub=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ht=qe("plus",ub);/**
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 mb=[["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"}]],Zm=qe("radio",mb);/**
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 hb=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]],mn=qe("refresh-cw",hb);/**
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 pb=[["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"}]],Vc=qe("rocket",pb);/**
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 fb=[["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"}]],gb=qe("rotate-ccw",fb);/**
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 bb=[["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"}]],eh=qe("save",bb);/**
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 xb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Oi=qe("search",xb);/**
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 vb=[["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=qe("send",vb);/**
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 yb=[["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"}]],Ir=qe("server",yb);/**
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 kb=[["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"}]],za=qe("settings",kb);/**
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 jb=[["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"}]],wb=qe("shield",jb);/**
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 Nb=[["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"}]],Pn=qe("sparkles",Nb);/**
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 Sb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],os=qe("square",Sb);/**
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 Cb=[["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"}]],es=qe("target",Cb);/**
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 Eb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Hs=qe("terminal",Eb);/**
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 Mb=[["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"}]],Pr=qe("text-wrap",Mb);/**
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 _b=[["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"}]],Bt=qe("trash-2",_b);/**
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 Ab=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Rb=qe("trending-up",Ab);/**
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 Tb=[["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"}]],nc=qe("triangle-alert",Tb);/**
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 Ib=[["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"}]],Wc=qe("unlink",Ib);/**
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 Pb=[["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=qe("user",Pb);/**
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 $b=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],th=qe("webhook",$b);/**
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 Db=[["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"}]],Ml=qe("workflow",Db);/**
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 Lb=[["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"}]],zb=qe("wrench",Lb);/**
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 Fb=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Tt=qe("x",Fb);/**
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 Ob=[["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"}]],bn=qe("zap",Ob);class to 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 t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(nc,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Qn({children:e,onError:n}){return t.jsx(to,{level:"page",onError:n,children:e})}function gi({children:e,onError:n}){return t.jsx(to,{level:"modal",onError:n,children:e})}function Ub({children:e,onError:n}){return t.jsx(to,{level:"root",onError:n,children:e})}const Bb="modulepreload",Hb=function(e){return"/"+e},Gc={},Zt=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=Hb(d),d in Gc)return;Gc[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":Bb,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},sc="fn.authToken",Kc="token",qb="fn_token";let Ui,Jc=!1,$r=!1;const _l="fn:auth-token-recovery-required";function Vb(){try{const e=window.localStorage.getItem(sc);return e&&e.length>0?e:void 0}catch{return}}function nh(e){try{window.localStorage.setItem(sc,e)}catch{}}function Wb(){if(!(Jc||typeof window>"u")){Jc=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Kc);if(!n)return;nh(n),e.searchParams.delete(Kc);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Wi(){if(Ui!==void 0)return Ui;const e=Wb();if(e)return Ui=e,e;const n=Vb();if(n)return Ui=n,n}function Gb(e){Ui=e,$r=!1,nh(e)}function Kb(){Ui=void 0,$r=!1;try{window.localStorage.removeItem(sc)}catch{}}function Yc(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Jb(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Yb(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Jb(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Yc(e.protocol)===Yc(n.protocol);return s&&i&&r}function Qb(e){if(!(typeof window>"u"))try{const n=new URL(e,window.location.origin),s=e.startsWith("/");return{parsed:n,preserveRelativePath:s}}catch{return}}function qs(e){const n=Wi();if(!n||typeof window>"u")return e;const s=Qb(e);return!s||!Yb(s.parsed)?e:(s.parsed.searchParams.set(qb,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function di(e){const n=Wi();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Xb(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Zb(){typeof window>"u"||$r||($r=!0,window.dispatchEvent(new CustomEvent(_l)))}async function ex(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();Xb(i)&&Zb()}catch{}}function tx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Wi();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Wi(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const u=new URL(o,window.location.origin);return u.origin!==window.location.origin?!1:u.pathname.startsWith("/api/")||u.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const c=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:c}).then(u=>(ex(u),u))}}class nx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function sx(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Hn(e){return`/api${e}`}async function L(e,n={}){const s=Hn(e),i=Wi(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),di(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||sx(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!u){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new nx(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function TT(){return L("/health")}function ix(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return L(`/tasks${l}`)}async function Dr(e,n){const i=Hn(q(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:di({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function sh(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:E,priority:k}=e;return L(q("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:E,priority:k})})}function Qs(e,n,s){return L(q(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ax(e,n,s,i,r,o,l,c){return L(q("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l})})}function rx(e,n,s){return L(q(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function ox(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(q(`/tasks/${e}${r}`,n),{method:"DELETE"})}function lx(e,n){return L(q(`/tasks/${e}/merge`,n),{method:"POST"})}function cx(e,n){return L(q(`/tasks/${e}/retry`,n),{method:"POST"})}function dx(e,n){return L(q(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ih(e,n){return L(q(`/tasks/${e}/pause`,n),{method:"POST"})}function ux(e,n){return L(q(`/tasks/${e}/unpause`,n),{method:"POST"})}function mx(e,n){return L(q(`/tasks/${e}/archive`,n),{method:"POST"})}function hx(e,n){return L(q(`/tasks/${e}/unarchive`,n),{method:"POST"})}function px(e){return L(q("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function fx(e,n){return L(q(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function gx(e,n){return L(q(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function bx(e){return L(q("/config",e))}function no(e){return L(q("/settings",e))}function or(e,n){return L(q("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function IT(e){return L(q("/memory",e))}function PT(e,n){return L(q("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function $T(e){return L(q("/memory/files",e))}function DT(e,n){const s=`path=${encodeURIComponent(e)}`;return L(q(`/memory/file?${s}`,n))}function LT(e,n,s){return L(q("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function zT(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return L(q("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function FT(e){return L(q("/memory/insights",e))}function OT(e,n){return L(q("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function UT(e){return L(q("/memory/extract",e),{method:"POST"})}function BT(e){return L(q("/memory/audit",e))}function HT(e){return L(q("/memory/stats",e))}function qT(e){return L(q("/memory/backend",e))}function VT(e){return L(q("/memory/install-qmd",e),{method:"POST"})}function WT(e,n){return L(q("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ia(){return L("/settings/global")}function tn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function GT(e){return L(q("/settings/scopes",e))}function KT(e){return L(q("/settings/pi-extensions",e))}function JT(e,n){return L(q("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function YT(e,n){return L(q("/settings/test-ntfy",n),{method:"POST",body:e?JSON.stringify(e):void 0})}function QT(){return L("/pi-settings")}async function XT(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function ZT(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function eI(e){return L(q("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Fa(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Hn(q(`/tasks/${e}/attachments`,s)),{method:"POST",headers:di(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function xx(e,n,s){return L(q(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Qc(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=q(`/tasks/${e}/logs${r}`,n),l=await fetch(Hn(o),{headers:di()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),u=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,d=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:u,hasMore:d}}function vx(e,n,s,i){return L(q(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function yx(e,n,s){return L(q(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function kx(e,n){return L(q(`/tasks/${e}/documents`,n))}function jx(e,n,s){return L(q(`/tasks/${e}/documents/${n}/revisions`,s))}async function tI(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return L(q(r,n))}function nI(e,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,e))}function Xc(e,n,s,i,r){return L(q(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function wx(e,n,s){return L(q(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Nx(e,n,s){return L(q(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Sx(e,n,s){return L(q(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Cx(e,n){return L(q(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Ex(e,n,s){return L(q(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ss(){return L("/models")}function Mx(){return L("/usage")}function _x(){return L("/providers/claude-cli/status")}function Ax(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Oa(){return L("/auth/status")}function Rx(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Tx(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Ix(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Px(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function $x(e,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function Dx(e,n,s,i){return L(q("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Lx(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function zx(e,n,s,i){return L(q("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Fx(e){return L(q("/git/remotes",e))}function Ox(e){return L(q("/git/remotes/detailed",e))}function Ux(e,n,s){return L(q("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Bx(e,n){return L(q(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hx(e,n,s){return L(q(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function qx(e,n,s){return L(q(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Vx(e,n,s){return L(q(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Wx(e,n){return L(q(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Gx(e,n){return(await L(q("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function lr(e,n,s,i){return L(q("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Zc(e,n){return L(q(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Kx(e){return L(q("/terminal/sessions",e))}function _s(e){return L(q("/git/status",e))}function Jx(e,n){const s=e?`?limit=${e}`:"";return L(q(`/git/commits${s}`,n))}function Lr(e,n){return L(q(`/git/commits/${e}/diff`,n))}function Yx(e){return L(q("/git/commits/ahead",e))}function Qx(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(q(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function ma(e){return L(q("/git/branches",e))}function Xx(e,n,s){const i=`?limit=${n}`;return L(q(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Zx(e){return L(q("/git/worktrees",e))}function ev(e,n,s){return L(q("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function tv(e,n){return L(q(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function ed(e,n,s){const i=n?"?force=true":"";return L(q(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function nv(e,n){return L(q("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function sv(e){return L(q("/git/pull",e),{method:"POST"})}function iv(e){return L(q("/git/push",e),{method:"POST"})}function cr(e){return L(q("/git/stashes",e))}function av(e,n){return L(q("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function rv(e,n,s){return L(q(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function ov(e,n){return L(q(`/git/stashes/${e}`,n),{method:"DELETE"})}function lv(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),L(q(`/git/diff/file?${i.toString()}`,s))}function Ii(e){return L(q("/git/changes",e))}function td(e,n){return L(q("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function cv(e,n){return L(q("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function nd(e,n){return L(q("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function dv(e,n){return L(q("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function uv(e){return L(q("/workspaces",e))}function mv(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),L(`/files?${i.toString()}`)}function hv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function pv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function fv(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),L(`/files/search?${i.toString()}`)}function gv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function bv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function xv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function vv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function ah(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function yv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function kv(e,n,s){return L(q("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function jv(e,n,s,i){return L(q("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function wv(e,n,s){return L(q(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function rh(e,n,s){return L(q("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Nv(e,n,s){return L(q("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Sv(e,n,s){return L(q("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Cv(e,n,s){return L(q("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Al=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Al))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Ev(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ga(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const b=Number.parseInt(f,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Ev(e,u),f=new EventSource(qs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))f.addEventListener(b,x=>{const y=x;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Al.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Al.add(g),g}function sd(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function Gi(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Mv(e,n){return{id:typeof e.id=="number"&&Number.isFinite(e.id)?e.id:n,text:typeof e.text=="string"?e.text:typeof e.line=="string"?e.line:"",stream:e.stream==="stderr"?"stderr":"stdout",timestamp:typeof e.timestamp=="string"?e.timestamp:""}}function _v(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Mv(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Av(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((d,m)=>({id:m+1,text:d,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(d=>d.id>r).slice(0,s),totalLines:o};const c=Math.max(o-i,0),u=Math.max(c-s,0);return{lines:l.slice(u,c),totalLines:o}}function id(e){return Array.isArray(e)?e.map(sd):(e.candidates??[]).map(sd)}async function Rv(e){try{const n=await L(q("/dev-server/candidates",e));return id(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(q("/dev-server/detect",e));return id(s)}throw n}}function ic(e){return L(q("/dev-server/status",e)).then(Gi)}async function sI(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await L(q(`/dev-server/logs/history${i}`,n));return _v(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await ic(n);return Av(o.logs,e)}throw r}}function Tv(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return L(q("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Gi)}function Iv(e){return L(q("/dev-server/stop",e),{method:"POST"}).then(Gi)}function Pv(e){return L(q("/dev-server/restart",e),{method:"POST"}).then(Gi)}async function $v(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await L(q("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Gi(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(q("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Gi(r)}throw i}}function iI(e){return Hn(q("/dev-server/logs/stream",e))}async function aI(e){try{return(await L(q("/devserver",e))).sessions??[]}catch{try{const n=await ic(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function rI(e,n){try{return await L(q(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await ic(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function oI(e,n){try{return await L(q(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Tv({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function lI(e,n){try{return await L(q(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Iv(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function cI(e,n){try{return await L(q(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Pv(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function dI(e,n,s){try{const i=await L(q(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await $v({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function uI(e){try{return(await L(q("/devserver/detect",e))).candidates??[]}catch{try{return(await Rv(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function mI(e,n){return Hn(q(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Ka(e,n,s=25e3){const i=setInterval(()=>{pk(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Dv(e,n){return Hn(q(`/planning/${encodeURIComponent(e)}/stream`,n))}function Lv(e,n,s,i){const r=Dv(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ga(r,{onOpen:()=>{c(),o=Ka(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Ja(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function zv(e){return L(Ja("/routines",e))}function Fv(e,n){return L(Ja("/routines",n),{method:"POST",body:JSON.stringify(e)})}function ad(e,n,s){return L(Ja(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Ov(e,n){await L(Ja(`/routines/${e}`,n),{method:"DELETE"})}function Uv(e,n){return L(Ja(`/routines/${e}/trigger`,n),{method:"POST"})}function rd(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return L(`/activity${s}`)}function Bv(e){const n=q("/activity",e);return L(n,{method:"DELETE"})}function so(e){return L(q("/workflow-steps",e))}function od(e,n){return L(q("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Hv(e,n,s){return L(q(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function qv(e,n){return L(q(`/workflow-steps/${e}`,n),{method:"DELETE"})}function ld(e,n){return L(q(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Vv(e,n){return L(q(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Wv(){return L("/workflow-step-templates")}function Gv(e,n){return L(q(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Ya(e){return L(q("/scripts",e))}function Kv(e,n,s){return L(q("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Jv(e,n){return L(q(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function oh(e,n,s){return(await L(q("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const dr={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 lh(e){if(!(e instanceof Error))return dr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?dr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?dr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:dr.NETWORK}function Yv(e,n){return L(q("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function Qv(e,n,s){return L(q(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Xv(e,n){return Hn(q(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Zv(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ga(Xv(e,n),{onOpen:()=>{l(),r=Ka(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function ey(e,n,s,i){return L(q("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function ch(e,n,s){return L(q("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function q(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function ty(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function io(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=ty(e,s,i);return L(o,r)}function aa(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/agents${i}`)}function dh(e,n){return L(q(`/agents/${encodeURIComponent(e)}`,n))}function ny(e,n){return L(q("/agents",n),{method:"POST",body:JSON.stringify(e)})}function sy(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hI(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function pI(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function fI(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function gI(e,n){return L(q(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function bI(e,n,s){const i=`path=${encodeURIComponent(n)}`;return L(q(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function xI(e,n,s,i){return L(q(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function iy(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function ay(e,n){return L(q(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function vI(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/runs${r}`)}function yI(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function kI(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function jI(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(q(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function wI(e,n){return L(q(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function ry(e){return L(q("/agents/stats",e))}function NI(e,n){return L(q(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function SI(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return L(`/agents/org-tree${i?`?${i}`:""}`)}function CI(e,n){return L(q(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function cd(e,n,s){return L(q(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function EI(e,n){return L(q(`/agents/${encodeURIComponent(e)}/tasks`,n))}function MI(){return L("/agents/companies")}function _I(e,n){return L(q("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function AI(e,n){return L(q("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function RI(e,n){return L(q(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function TI(e){return L(q("/backups",e))}function II(e){return L(q("/backups",e),{method:"POST"})}function PI(e,n){const s=q("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(i)}function $I(e,n,s){return L(q("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function dd(){return L("/projects/across-nodes")}function Ta(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function ud(){return L("/nodes")}function oy(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function ly(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function cy(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function dy(e){const n=await L(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function DI(e,n,s,i){const r=s&&s!==i?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Wi();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return L(u)}function uy(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function uh(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function md(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function my(e){return L(q("/executor/stats",e))}function hd(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return L(`/activity-feed${s}`)}function hy(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function py(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function LI(){return L("/global-concurrency")}function zI(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function fy(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function mh(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function gy(e){return L(q("/missions",e))}function by(e,n){return L(q("/missions",n),{method:"POST",body:JSON.stringify(e)})}function hh(e,n){return L(q(`/missions/${encodeURIComponent(e)}`,n))}function xy(e,n,s){return L(q(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function vy(e,n){return L(q(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yy(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return L(q(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function ky(e){return L(q("/missions/health",e))}function jy(e,n,s){return L(q(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function wy(e,n,s){return L(q(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ny(e,n){return L(q(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Sy(e,n,s){return L(q(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Cy(e,n,s){return L(q(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ey(e,n){return L(q(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function My(e,n){return L(q(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function _y(e,n,s){return L(q(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Ay(e,n,s){return L(q(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ry(e,n){return L(q(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Ty(e,n,s){return L(q(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Iy(e,n){return L(q(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Py(e,n,s,i){return L(q(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function $y(e,n){return L(q(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Co(e,n){return L(q(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Dy(e,n,s){return L(q(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Ly(e,n,s){return L(q(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function zy(e,n,s){return L(q(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Fy(e,n,s){return L(q(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Oy(e,n){return L(q(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Eo(e,n){return L(q(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function pd(e,n){return L(q(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function Uy(e,n){return L(q(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function fd(e,n){return L(q(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function By(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return L(q(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function Hy(e,n){return L(q(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function qy(e,n){return L(q(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function Vy(e,n){return L(q(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function Wy(e,n){return L(q(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Gy(e,n,s){return L(q(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ky(e,n,s){return L(q("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function Jy(e,n,s,i){return L(q("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Yy(e,n,s){return L(q(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ph(e,n,s){return L(q("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Qy(e,n,s){return L(q("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Xy(e,n,s,i){const r=Hn(q(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ga(r,{onOpen:()=>{c(),o=Ka(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Qa(e,n,s){return q(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Xa(e,n,s){return q(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Zy(e,n){return L(Qa(e,"/start",n),{method:"POST"})}function ek(e,n,s,i){return L(Qa(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function tk(e,n,s,i){const r=Hn(Qa(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ga(r,{onOpen:()=>{c(),o=Ka(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function nk(e,n,s){return L(Qa(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function sk(e,n){return L(Qa(e,"/skip",n),{method:"POST"})}function ik(e,n){return L(Xa(e,"/start",n),{method:"POST"})}function ak(e,n,s,i){return L(Xa(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function rk(e,n,s,i){const r=Hn(Xa(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ga(r,{onOpen:()=>{c(),o=Ka(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function ok(e,n,s){return L(Xa(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function lk(e,n){return L(Xa(e,"/skip",n),{method:"POST"})}async function ck(e,n){try{return await L(q(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function FI(e){return L(q("/roadmaps",e))}function OI(e,n){return L(q("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function UI(e,n){return L(q(`/roadmaps/${encodeURIComponent(e)}`,n))}function BI(e,n,s){return L(q(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function HI(e,n){return L(q(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function qI(e,n,s){return L(q(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function VI(e,n,s){return L(q(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function WI(e,n){return L(q(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function GI(e,n,s){return L(q(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function KI(e,n,s){return L(q(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function JI(e,n){return L(q(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function YI(e,n,s){return L(q(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function QI(e,n,s){return L(q(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function XI(e,n,s,i){return L(q(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function ZI(e,n){return L(q(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function eP(e,n,s,i){return L(q(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function tP(e,n,s){return L(q(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function Ki(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function fh(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Hn(`/ai-sessions${n}`),{headers:di()});return s.ok?(await s.json()).sessions??[]:[]}async function Xs(e){const n=await fetch(Hn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:di()});return n.ok?n.json():null}async function dk(e,n){const s=await L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function uk(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function mk(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function hk(e){await fetch(Hn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:di()})}function pk(e,n){return L(q(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function fk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/messages/inbox${i}`)}function gk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/messages/outbox${i}`)}function gh(e){return L(q("/messages/unread-count",e))}function bk(e,n){return L(q("/messages",n),{method:"POST",body:JSON.stringify(e)})}function xk(e,n){return L(q(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function vk(e){return L(q("/messages/read-all",e),{method:"POST"})}function yk(e,n){return L(q(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(q(i,s))}function jk(e,n){return L(q(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function nP(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function sP(e,n){return L(q(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function iP(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/performance${r}`)}function aP(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function rP(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function oP(e,n){return L(q(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function lP(e,n,s){return L(q(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function cP(e,n){return L(q(`/agents/${encodeURIComponent(e)}/budget`,n))}function dP(e,n){return L(q(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function uP(e){return L(q("/plugins",e))}async function mP(e,n){return L(q("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function hP(e,n){return L(q(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function pP(e,n){return L(q(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function fP(e,n){return L(q(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function gP(e,n){return L(q(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function bP(e,n,s){return L(q(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function xP(e,n){return L(q(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function wk(e){return L(q("/plugins/ui-slots",e))}async function vP(e){return(await L(q("/skills/discovered",e))).skills}async function yP(e,n,s){return L(q("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function kP(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return L(q(`/skills/catalog${r}`,s))}async function jP(e,n){return(await L(q(`/skills/${encodeURIComponent(e)}/content`,n))).content}function wP(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return L(`/chat/sessions${i?`?${i}`:""}`)}async function Nk(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await L(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Sk(e,n){return L(q("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function NP(e,n,s){return L(q(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function SP(e,n){return L(q(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function gd(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return L(q(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Ck(e,n){return L(q(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Ek(e,n,s,i,r){const o=Hn(q(`/chat/sessions/${encodeURIComponent(e)}/messages`,i)),l=new AbortController;let c=!1;const u=(d,m)=>{if(!(!d||!m))switch(d){case"thinking":try{s.onThinking?.(JSON.parse(m))}catch{s.onThinking?.(m)}break;case"text":try{s.onText?.(JSON.parse(m))}catch{s.onText?.(m)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(m))}catch{}break;case"done":try{s.onDone?.(JSON.parse(m))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(m);s.onError?.(h.message||h)}catch{s.onError?.(m||"Stream error")}break}};return(async()=>{try{const d=await fetch(o,{method:"POST",headers:di({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let x=`Request failed: ${d.status}`;try{x=JSON.parse(v).error||x}catch{}s.onError?.(x);return}if(!d.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const m=d.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const b=(v,x=!1)=>{g+=v;const y=g.split(`
573
- `);g=y.pop()||"",x&&g.length>0&&(y.push(g),g="");for(const E of y){const k=E.endsWith("\r")?E.slice(0,-1):E;if(k.startsWith("event:"))p=k.slice(6).trim();else if(k.startsWith("data:")){const T=k.slice(5);f.push(T.startsWith(" ")?T.slice(1):T)}else if(k===""){const T=f.join(`
574
- `);u(p,T),p="",f=[]}}if(x&&p&&f.length>0){const E=f.join(`
575
- `);u(p,E),p="",f=[]}};for(;;){const{done:v,value:x}=await m.read();if(v){b(h.decode(),!0);break}b(h.decode(x,{stream:!0}))}}catch(d){if(d instanceof DOMException&&d.name==="AbortError"){c||s.onError?.("Connection aborted");return}if(c)return;s.onError?.(d instanceof Error?d.message:"Connection error")}})(),{close:()=>{c=!0,l.abort()},isConnected:()=>!c}}function CP(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return L(q(`/insights${i}`,n))}function EP(e,n){return L(q(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function MP(e="manual",n,s){return L(q("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function _P(e){return L(q("/insights/runs",e))}function AP(e,n){return L(q(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Mk({onOpenScripts:e,onRunScript:n,projectId:s}){const[i,r]=a.useState(!1),[o,l]=a.useState({}),[c,u]=a.useState(!1),[d,m]=a.useState(-1),[h,g]=a.useState(null),p=a.useRef(null),f=a.useRef(null),b=a.useRef(null),v=a.useCallback(()=>{const P=window.visualViewport;return P&&P.width>0&&P.height>0?{width:P.width,height:P.height,offsetTop:P.offsetTop,offsetLeft:P.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),x=a.useCallback(()=>{const P=f.current;if(!P)return;const _=P.getBoundingClientRect(),I=b.current,{width:D,height:G,offsetTop:$,offsetLeft:R}=v(),w=16,H=16,V=6,B=I?.offsetWidth||Math.max(_.width,260),M=Math.min(B,Math.max(D-w*2,160)),z=I?.offsetHeight||280,X=Math.min(z,Math.max(G-H*2,160)),C=_.top-$,U=_.bottom-$,fe=_.left-R,ie=G-U,re=C,F=ie<X&&re>ie,ce=Math.min(Math.max(fe,w),D-w-M)+R,ae=F?Math.max(H+$,C-X-V+$):Math.min(U+V+$,G+$-H-X);g({top:ae,left:ce,width:M})},[v]),y=a.useMemo(()=>Object.entries(o).sort(([P],[_])=>P.localeCompare(_)),[o]),E=y.length>0,k=y.length+(E?1:0);a.useEffect(()=>{if(!i)return;let P=!1;return u(!0),Ya(s).then(_=>{P||l(_)}).catch(()=>{P||l({})}).finally(()=>{P||u(!1)}),()=>{P=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const P=_=>{p.current&&!p.current.contains(_.target)&&f.current&&!f.current.contains(_.target)&&r(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[i]),a.useEffect(()=>{if(!i)return;const P=_=>{_.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[i]),a.useEffect(()=>{if(i){m(-1);const P=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(P)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const P=requestAnimationFrame(()=>{x()});return()=>cancelAnimationFrame(P)},[i,c,y.length,E,x]),a.useEffect(()=>{if(!i)return;const P=()=>x();window.addEventListener("resize",P),window.addEventListener("scroll",P,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",P),_.addEventListener("scroll",P)),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0),_&&(_.removeEventListener("resize",P),_.removeEventListener("scroll",P))}},[i,x]);const T=a.useCallback(P=>{switch(P.key){case"ArrowDown":P.preventDefault(),m(_=>_<k-1?_+1:0);break;case"ArrowUp":P.preventDefault(),m(_=>_>0?_-1:k-1);break;case"Enter":if(P.preventDefault(),d>=0)if(d<y.length){const[_,I]=y[d];S(_,I)}else E&&d===y.length&&j();break;case"Home":P.preventDefault(),m(0);break;case"End":P.preventDefault(),m(k-1);break}},[d,k,y,E]),N=a.useCallback(()=>{r(P=>!P)},[]),S=a.useCallback((P,_)=>{n(P,_),r(!1)},[n]),j=a.useCallback(()=>{e(),r(!1)},[e]);return t.jsxs("div",{className:"quick-scripts-dropdown",ref:p,children:[t.jsxs("button",{ref:f,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick:N,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[t.jsx(Hs,{size:16}),t.jsx(zt,{size:14,className:`quick-scripts-dropdown__trigger-chevron ${i?"rotate":""}`})]}),i&&t.jsx("div",{ref:b,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:T,"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:c?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(at,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):y.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(Hs,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:j,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:y.map(([P,_],I)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${d===I?"highlighted":""}`,onClick:()=>S(P,_),role:"option","aria-selected":d===I,"data-testid":`quick-script-item-${P}`,children:[t.jsx(sn,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:P}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:_,children:_.length>50?`${_.slice(0,50)}...`:_})]})]},P))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${E&&d===y.length?"highlighted":""}`,onClick:j,"data-testid":"quick-scripts-manage",children:[t.jsx(za,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function _k(e){switch(e){case"online":return{label:"Online",dotClass:"node-status-indicator__dot--online"};case"offline":return{label:"Offline",dotClass:"node-status-indicator__dot--offline"};case"connecting":return{label:"Connecting",dotClass:"node-status-indicator__dot--connecting"};case"error":return{label:"Error",dotClass:"node-status-indicator__dot--error"};default:return{label:"Unknown",dotClass:"node-status-indicator__dot--offline"}}}function Ak({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:i}=_k(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}const bd=new Map,Rk=6e4;function bh(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function g(){const p=bd.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const b=await wk(e);if(h||u.current)return;bd.set(m,{slots:b,expiresAt:Date.now()+Rk}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return g(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function ao({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=bh(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(to,{level:"page",children:t.jsx(t.Fragment,{children:o.map(l=>t.jsx("div",{"data-plugin-slot":!0,"data-slot-id":l.slot.slotId,"data-plugin-id":l.pluginId,"data-component-path":l.slot.componentPath,"aria-label":l.slot.label},`${l.pluginId}-${l.slot.slotId}`))})})}function Tk(){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 Za(){const[e,n]=a.useState(Tk);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}const xh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Ik({projects:e,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,o]=a.useState(!1),l=a.useRef(null);a.useEffect(()=>{if(!r)return;const u=d=>{l.current&&!l.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),a.useEffect(()=>{if(!r)return;const u=d=>{d.key==="Escape"&&o(!1)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const c=a.useCallback(u=>{i?.(u),o(!1)},[i]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(u=>!u),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(zt,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(u=>{const d=n?.id===u.id,m=xh[u.status]?.color;return t.jsxs("button",{className:`project-selector-item${d?" project-selector-item--current":""}`,onClick:()=>c(u),role:"option","aria-selected":d,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:u.name}),t.jsx("span",{className:"project-selector-path",children:u.path.split("/").slice(-2).join("/")})]}),d&&t.jsx(yn,{size:14,className:"project-selector-check"})]},u.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function xd({size:e=16}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function Pk({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenSchedules:d,onOpenGitManager:m,onOpenNodes:h,showNodesButton:g,onOpenWorkflowSteps:p,onOpenScripts:f,onRunScript:b,onToggleTerminal:v,onOpenFiles:x,filesOpen:y,globalPaused:E,enginePaused:k,onToggleGlobalPause:T,onToggleEnginePause:N,view:S="board",onChangeView:j,showSkillsTab:P,showAgentsTab:_,searchQuery:I="",onSearchChange:D,projects:G=[],currentProject:$,onSelectProject:R,onViewAllProjects:w,projectId:H,isElectron:V=!1,mobileNavEnabled:B,availableNodes:M=[],currentNode:z,onSelectNode:X,isRemote:C=!1,experimentalFeatures:U}){const fe=Za(),ie=fe==="mobile",F=ie||fe==="tablet",ce=ie&&B,[ae,Q]=a.useState(!1),[de,Re]=a.useState(!1),[ge,Me]=a.useState(!1),[te,Ce]=a.useState(!1),[$e,We]=a.useState(!1),[Ge,Ee]=a.useState(!1),[Ae,Oe]=a.useState(!1),[ke,De]=a.useState(!1),[se,K]=a.useState(!1),[me,ee]=a.useState({}),[he,le]=a.useState(!1),Ie=a.useRef(null),Ze=a.useRef(null),rt=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),pe=a.useRef(null),Se=a.useRef(!1),Pe=a.useRef(null),ye=a.useRef(null),Ke=a.useRef(null),Ne=a.useRef(null),Fe=a.useMemo(()=>M.filter(He=>He.type==="remote"),[M]),Ye=Fe.length>0,xe=a.useMemo(()=>Object.entries(me).sort(([He],[ut])=>He.localeCompare(ut)),[me]),ze=a.useMemo(()=>!!(U?.insights||U?.roadmap||P||U?.memoryView||U?.devServerView),[U,P]);a.useEffect(()=>{Se.current=$e},[$e]),a.useEffect(()=>{if(!$e||!F)return;let He=!1;return le(!0),Ya(H).then(ut=>{He||ee(ut)}).catch(()=>{He||ee({})}).finally(()=>{He||le(!1)}),()=>{He=!0}},[$e,F,H]);const be=ae||I.length>0,Qe=(de||I.length>0)&&!ge,it=(S==="board"||S==="list")&&!ie&&D&&!ge&&I.length===0,mt=(S==="board"||S==="list")&&!ie&&D;a.useEffect(()=>{I===""&&Me(!1)},[I]),a.useEffect(()=>{if(!te)return;const He=ut=>{Ze.current&&!Ze.current.contains(ut.target)&&Ie.current&&!Ie.current.contains(ut.target)&&Ce(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[te]),a.useEffect(()=>{if(!se)return;const He=ut=>{oe.current&&!oe.current.contains(ut.target)&&rt.current&&!rt.current.contains(ut.target)&&K(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[se]),a.useEffect(()=>{if(!Ge)return;const He=ut=>{Pe.current&&!Pe.current.contains(ut.target)&&Ee(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[Ge]),a.useEffect(()=>{const He=ut=>{if(ut.key==="Escape"){if(De(!1),K(!1),Se.current){We(!1);return}Ce(!1),Q(!1),Ee(!1),Oe(!1)}};return document.addEventListener("keydown",He),()=>document.removeEventListener("keydown",He)},[]),a.useEffect(()=>{if(!Ae)return;const He=ut=>{ye.current&&!ye.current.contains(ut.target)&&Oe(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[Ae]),a.useEffect(()=>{if(!ke)return;const He=ut=>{Ke.current&&!Ke.current.contains(ut.target)&&Ne.current&&!Ne.current.contains(ut.target)&&De(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[ke]);const At=a.useCallback(()=>{Q(He=>!He)},[]),It=a.useCallback(()=>{Re(!0),Me(!1)},[]),Dt=a.useCallback(()=>{Re(!1),Me(!0),D&&D("")},[D]),Ut=a.useCallback(()=>{Ce(He=>!He)},[]),jt=a.useCallback(He=>{He&&He(),Ce(!1),We(!1)},[]),Pt=a.useCallback(()=>{Q(!1),D&&D("")},[D]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),ie&&G.length>=1&&R&&t.jsxs("div",{className:"mobile-project-switch",ref:ye,children:[t.jsx("button",{className:`mobile-project-switch-trigger${Ae?" mobile-project-switch-trigger--open":""}`,onClick:()=>Oe(He=>!He),title:"Switch project","aria-label":"Switch project","aria-expanded":Ae,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(zt,{size:14,className:`mobile-project-switch-chevron${Ae?" mobile-project-switch-chevron--open":""}`})}),Ae&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:G.map(He=>{const ut=$?.id===He.id,$t=xh[He.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ut?" mobile-project-switch-item--current":""}`,onClick:()=>{R(He),Oe(!1)},role:"option","aria-selected":ut,"data-testid":`mobile-project-switch-item-${He.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:$t||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:He.name}),t.jsx("span",{className:"mobile-project-switch-path",children:He.path.split("/").slice(-2).join("/")})]}),ut&&t.jsx(yn,{size:14,className:"mobile-project-switch-check"})]},He.id)})})]}),!F&&G.length>=1&&w&&t.jsx(Ik,{projects:G,currentProject:$??null,onViewAll:w,onSelectProject:R}),Ye&&t.jsxs("div",{className:`header-node-selector${ie?" header-node-selector--mobile":""}`,ref:ie?void 0:Pe,children:[t.jsx(Ak,{node:z??null,showDetails:!ie}),!ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Ge?" node-selector-trigger--open":""}`,onClick:()=>Ee(He=>!He),title:"Switch node","aria-label":"Switch node","aria-expanded":Ge,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(an,{size:12,className:`node-selector-chevron${Ge?" node-selector-chevron--open":""}`})}),Ge&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${C?"":" node-selector-option--active"}`,onClick:()=>{X?.(null),Ee(!1)},role:"option","aria-selected":!C,"data-testid":"node-option-local",children:[t.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Fe.map(He=>t.jsxs("button",{className:`node-selector-option${z?.id===He.id?" node-selector-option--active":""}`,onClick:()=>{X?.(He),Ee(!1)},role:"option","aria-selected":z?.id===He.id,"data-testid":`node-option-${He.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${He.status}`}),t.jsx("span",{className:"node-selector-option-label",children:He.name}),t.jsx("span",{className:"node-selector-option-status",children:He.status})]},He.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ce&&j&&(S==="board"||S==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>j("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>j("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Sl,{size:16})})]}),D&&ie&&(ce||S==="board"||S==="list")&&!be&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:At,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Oi,{size:16})}),it&&t.jsx("button",{className:"btn-icon",onClick:It,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Oi,{size:16})}),ie&&ce&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ss,{size:16})}),!ce&&j&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>j("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>j("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:t.jsx(Sl,{size:16})}),_&&t.jsx("button",{className:`view-toggle-btn${S==="agents"?" active":""}`,onClick:()=>j("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":S==="agents",children:t.jsx(nn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="missions"?" active":""}`,onClick:()=>j("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":S==="missions",children:t.jsx(es,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="chat"?" active":""}`,onClick:()=>j("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":S==="chat",children:t.jsx(li,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="documents"?" active":""}`,onClick:()=>j("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":S==="documents",children:t.jsx(Ni,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="mailbox"?" active":""}`,onClick:()=>j("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":S==="mailbox",children:t.jsx(Vi,{size:16})}),ze&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ne,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(S)?" active":""}`,onClick:()=>De(He=>!He),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":ke,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(zt,{size:12})}),ke&&t.jsxs("div",{ref:Ke,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[U?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="insights"?" active":""}`,onClick:()=>{j("insights"),De(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Pn,{size:14}),t.jsx("span",{children:"Insights"})]}),U?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="roadmaps"?" active":""}`,onClick:()=>{j("roadmaps"),De(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Cl,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),P&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="skills"?" active":""}`,onClick:()=>{j("skills"),De(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(bn,{size:14}),t.jsx("span",{children:"Skills"})]}),U?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="memory"?" active":""}`,onClick:()=>{j("memory"),De(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Rr,{size:14}),t.jsx("span",{children:"Memory"})]}),U?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="dev-server"||S==="devserver"?" active":""}`,onClick:()=>{j("devserver"),De(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Xm,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]})]})]})]}),!F&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ss,{size:16})}),!F&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(La,{size:16})}),!F&&!V&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(xd,{size:16})}),!F&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&i?i:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(Bs,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!F&&t.jsx("button",{className:"btn-icon btn-icon--terminal",onClick:v,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Hs,{size:16})}),!F&&x&&t.jsx("button",{className:`btn-icon${y?" btn-icon--active":""}`,onClick:x,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(kn,{size:16})}),!F&&m&&t.jsx("button",{className:"btn-icon",onClick:m,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Us,{size:16})}),!F&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Ml,{size:16})}),!F&&f&&b&&t.jsx(Mk,{onOpenScripts:f,onRunScript:b,projectId:H}),!F&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:rt,className:"btn-icon",onClick:()=>K(He=>!He),title:"More actions","aria-label":"More actions","aria-expanded":se,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(wl,{size:16})}),se&&t.jsxs("div",{ref:oe,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),K(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Ir,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{jt(d),K(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsx("button",{className:`btn-icon${k?" btn-icon--paused":""}`,onClick:N,title:k?"Resume scheduling":"Pause scheduling",disabled:!!E,children:k?t.jsx(sn,{size:16}):t.jsx(Os,{size:16})}),t.jsx("button",{className:`btn-icon${E?" btn-icon--stopped":""}`,onClick:T,title:E?"Start AI engine":"Stop AI engine",children:E?t.jsx(sn,{size:16}):t.jsx(os,{size:16})}),!F&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(za,{size:16})}),t.jsx(ao,{slotId:"header-action",projectId:H}),F&&!ce&&t.jsx("button",{ref:Ie,className:"btn-icon compact-overflow-trigger",onClick:Ut,title:"More header actions","aria-label":"More header actions","aria-expanded":te,"aria-haspopup":"menu",children:t.jsx(wl,{size:16})}),F&&!ce&&te&&t.jsxs("div",{ref:Ze,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[G.length>=1&&w&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(w),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Ym,{size:16}),t.jsx("span",{children:"Projects"})]}),x&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(x),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(kn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>jt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Bs,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),m&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(m),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Us,{size:16}),t.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Ir,{size:16}),t.jsx("span",{children:"Nodes"})]}),!V&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(n),role:"menuitem",children:[t.jsx(xd,{size:16}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[t.jsxs("div",{className:"mobile-overflow-split-row",children:[t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>jt(v),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Hs,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>We(He=>!He),role:"menuitem","aria-expanded":$e,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(an,{size:14,className:`mobile-overflow-chevron${$e?" mobile-overflow-chevron--open":""}`})})]}),$e&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:he?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(at,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):xe.length>0?t.jsxs(t.Fragment,{children:[xe.map(([He,ut])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(He,ut),Ce(!1),We(!1)},role:"menuitem","data-testid":`overflow-script-item-${He}`,children:[t.jsx(sn,{size:14}),t.jsx("span",{children:He})]},He)),f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>jt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(As,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>jt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(As,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(d),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(wi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(La,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),c&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(c),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Vi,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(o),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ss,{size:16}),t.jsx("span",{children:"View Usage"})]}),p&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Ml,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>jt(e),role:"menuitem",children:[t.jsx(za,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),mt&&Qe&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Oi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:I,onChange:He=>D(He.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Dt,"aria-label":"Close search",children:t.jsx(Tt,{size:14})})]})}),D&&ie&&be&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:Z,className:"header-search mobile-search-expanded",children:[t.jsx(Oi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:pe,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:I,onChange:He=>D(He.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Pt,"aria-label":"Close search",children:t.jsx(Tt,{size:14})})]})})]})}const $k={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},Dk={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",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:{}},Lk=Object.freeze(Object.keys($k)),zk=Object.freeze(Object.keys(Dk));function RP(e){return Lk.includes(e)}function TP(e){return zk.includes(e)}function ve(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const IP=["off","minimal","low","medium","high"],ji=["triage","todo","in-progress","in-review","done","archived"],ac=["low","normal","high","urgent"],ls="normal",Fk=["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"],Tn={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},Ok={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"},Rl={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 Uk(e){const n=e.metadata??{};return!!(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor"||n.type==="spawned"||n.internal===!0||e.role==="executor"&&typeof e.name=="string"&&e.name.startsWith("executor-")&&e.reportsTo==null||e.role==="executor"&&e.name==="verification-agent"&&e.reportsTo==null)}function Bk(e,n=1400){const s=a.useRef(null),[i,r]=a.useState(!1),o=a.useRef(null);return a.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),i}function Hk(e,n){return e==="open"?"card-github-badge--open":n==="completed"?"card-github-badge--completed":n==="not_planned"?"card-github-badge--not-planned":"card-github-badge--closed"}function vh({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(Zn,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${Hk(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Yr,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function ur(e,n){return`${e??"default"}:${n}`}class qk{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,i=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)i.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of i){const l=ur(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=ur(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=ur(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(qs(i));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=ur(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:vd(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:vd(l,"issueInfo")?l.issueInfo??null:u?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,i=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},i),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const bi=new qk;let Vk=0;function vd(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function yh(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Vk++}`);const s=a.useSyncExternalStore(o=>bi.subscribe(o),()=>bi.getSnapshot(),()=>bi.getSnapshot()),i=a.useCallback(o=>{bi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{bi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{bi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{bi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function zr(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function Wk({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=yh(o),d=!!(n||s);a.useEffect(()=>{if(!d||!r){u(e);return}return c(e),()=>{u(e)}},[d,r,o,c,e,u]);const m=l.get(`${o??"default"}:${e}`),h=zr(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=zr(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(vh,{prInfo:h,issueInfo:g})}const Gk=a.memo(Wk);Gk.displayName="TaskCardBadge";const ks={data:new Map,pendingPromise:null,lastFetchTime:null},Kk=5e3;function Mr(e,n){return n?`${n}::${e}`:e}function Jk(e,n){const s=ks.data.get(Mr(e,n));if(!(!s||Date.now()-s.timestamp>Kk))return s}function Yk(e){const[n,s]=a.useState(!1),i=a.useRef(null),r=a.useCallback(async c=>{let d=null;for(let m=0;m<3;m++)try{return await Gx(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=ve(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(g=>{const p=ks.data.get(Mr(g,e));return p&&p.timestamp>d})&&ks.lastFetchTime&&ks.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),ks.pendingPromise){s(!0);try{await ks.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ks.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))ks.data.set(Mr(f,e),{result:b,timestamp:p});ks.lastFetchTime=p}catch{}finally{ks.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>ks.data.get(Mr(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ks.lastFetchTime,getBatchData:l}}const Tl=new Map,Qk=3e4;function kh(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Xk(e,n,s,i){const r=kh(e,n,s,i),o=Tl.get(r);return o?Date.now()>o.expiresAt?(Tl.delete(r),null):o.stats:null}function Zk(e,n,s,i,r){const o=kh(e,n,s,i);Tl.set(o,{stats:r,expiresAt:Date.now()+Qk})}function ej(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const b=f?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(k=!1){if(!k){const T=Xk(e,i,b,v);if(T){x||(m(T),g(!1));return}}g(!0);try{const T=await mh(e,b,i);x||(m(T.stats),Zk(e,i,b,v,T.stats))}catch{x||m(null)}finally{x||g(!1)}}y();let E;return u&&f&&(E=setInterval(()=>{y(!0)},u)),()=>{x=!0,E&&clearInterval(E)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const tj=new Set(["failed","stuck-killed"]);function Fr(e,n,s){if(e.column!=="in-progress"||e.status&&tj.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function nj(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function sj(e){return e==="done"||e==="skipped"}function ij(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function jh(e,n){const s=(e.steps??[]).map((u,d)=>({id:`step-${d}`,name:u.name,status:u.status,source:"step",phase:"pre-merge"})),i=new Map((e.workflowStepResults??[]).map(u=>[u.workflowStepId,u])),r=(e.enabledWorkflowSteps??[]).map(u=>{const d=i.get(u);return{id:`workflow-${u}`,name:ij(u,d,n),status:d?nj(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>sj(u.status)).length;return{total:l,completed:c,items:o}}const Il=new Map;async function aj(e,n){const s=Il.get(e);if(s)return s;try{const i=await hh(e,n);return Il.set(e,i.title),i.title}catch{return e}}const yd=12;function rj(e){return e.length<=yd?e:e.slice(0,yd-3)+"..."}const Pl=new Map;async function oj(e,n){const s=Pl.get(e);if(s)return s;try{const i=await dh(e,n);return Pl.set(e,i.name),i.name}catch{return e}}function lj(e){return typeof e=="string"&&ac.includes(e)?e:ls}function cj(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const dj=new Set(["triage","todo"]),kd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),uj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},mj=new Set(["in-progress","done"]),hj=3e4;function rc(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function jd(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=rc(n);if(s==null)return null;const i=Date.now();return s>i?null:s}function pj(e){const n=rc(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function fj(e,n){return[e.updatedAt,e.createdAt].map(rc).filter(r=>r!=null).find(r=>r<=n)??null}function wd(e){if(!Number.isFinite(e)||e<0)return"";const n=Math.floor(e/6e4);if(n<1)return"<1m";if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Nd(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>e[r]===n[r])}function gj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function bj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function xj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function vj(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function yj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function kj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function jj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function wj(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.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&&kj(s.attachments,i.attachments)&&jj(s.comments,i.comments)&&bj(s.dependencies,i.dependencies)&&gj(s.steps,i.steps)&&xj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&yj(s.workflowStepResults,i.workflowStepResults)&&Nd(s.prInfo,i.prInfo)&&Nd(s.issueInfo,i.issueInfo)}function Nj({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:b}){const[v,x]=a.useState(!1),[y,E]=a.useState(!1),[k,T]=a.useState(!1),[N,S]=a.useState(e.description||""),[j,P]=a.useState(!1),[_,I]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(ue=>ue.status==="done"||ue.status==="skipped")),[D,G]=a.useState(null),[$,R]=a.useState(null),[w,H]=a.useState(!1),[V,B]=a.useState(()=>Date.now()),M=a.useRef(null),z=a.useRef(!1),X=a.useRef(null),C=a.useRef(null),[U,fe]=a.useState(!1),{badgeUpdates:ie,subscribeToBadge:re,unsubscribeFromBadge:F}=yh(n),ce=a.useRef(null),ae=a.useRef(!1),Q=a.useCallback(ue=>ue instanceof Element?!!ue.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{S(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!w)return;const ue=A=>{C.current&&!C.current.contains(A.target)&&H(!1)};return document.addEventListener("click",ue),()=>document.removeEventListener("click",ue)},[w]),a.useEffect(()=>{if(!e.missionId){G(null);return}const ue=Il.get(e.missionId);if(ue){G(ue);return}let A=!1;return aj(e.missionId,n).then(J=>{A||G(J)}),()=>{A=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){R(null);return}const ue=Pl.get(e.assignedAgentId);if(ue){R(ue);return}R(null);let A=!1;return oj(e.assignedAgentId,n).then(J=>{A||R(J)}),()=>{A=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(k&&M.current){const ue=M.current;ue.focus(),ue.style.height="auto",ue.style.height=ue.scrollHeight+"px"}},[k]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){fe(!0);return}const ue=X.current;if(!ue)return;const A=new IntersectionObserver(([J])=>{fe(J?.isIntersecting??!0)},{rootMargin:"200px"});return A.observe(ue),()=>A.disconnect()},[k,e.id]);const de=a.useCallback(ue=>{ue.dataTransfer.setData("text/plain",e.id),ue.dataTransfer.effectAllowed="move",x(!0)},[e.id]),Re=a.useCallback(()=>{x(!1)},[]),ge=a.useCallback(ue=>ue.dataTransfer.types.includes("Files"),[]),Me=a.useCallback(ue=>{ge(ue)&&(ue.preventDefault(),ue.stopPropagation(),ue.dataTransfer.dropEffect="copy",E(!0))},[ge]),te=a.useCallback(ue=>{ge(ue)&&(ue.preventDefault(),ue.stopPropagation(),E(!1))},[ge]),Ce=a.useCallback(async ue=>{if(!ge(ue))return;ue.preventDefault(),ue.stopPropagation(),E(!1);const A=Array.from(ue.dataTransfer.files);for(const J of A)try{await Fa(e.id,J,n),r(`Attached ${J.name} to ${e.id}`,"success")}catch(Ve){r(`Failed to attach ${J.name}: ${ve(Ve)}`,"error")}},[e.id,ge,r]),$e=a.useCallback(()=>{k||i(e)},[e,i,k]),We=a.useCallback(ue=>{if(z.current){z.current=!1;return}Q(ue.target)||$e()},[$e,Q]),Ge=a.useCallback(ue=>{const A=ue.touches[0];A&&(ce.current={x:A.clientX,y:A.clientY,time:Date.now()},ae.current=!1)},[]),Ee=a.useCallback(ue=>{if(!ce.current)return;const A=ue.touches[0];if(!A)return;const J=Math.abs(A.clientX-ce.current.x),Ve=Math.abs(A.clientY-ce.current.y);(J>Sd||Ve>Sd)&&(ae.current=!0)},[]),Ae=a.useCallback(ue=>{if(Q(ue.target)||!ce.current)return;const J=Date.now()-ce.current.time<Sj,Ve=!ae.current;J&&Ve&&(z.current=!0,$e()),ce.current=null,ae.current=!1},[$e,Q]),Oe=a.useCallback(async(ue,A)=>{ue.stopPropagation();try{const J=await Dr(A,n);i(J)}catch{r(`Failed to load dependency ${A}`,"error")}},[i,r]),ke=e.status==="failed",De=e.paused===!0,se=lj(e.priority),K=se!==ls,me=Fr(e,h,f),ee=e.column==="triage"&&e.status==="awaiting-approval",he=e.column==="archived",le=!o&&!s&&!ke&&!De&&!me&&!ee&&(e.column==="in-progress"||kd.has(e.status)),Ie=!s&&!De&&!k&&!he,Ze=dj.has(e.column)&&!le&&!De&&!s&&l,rt=!!(e.prInfo||e.issueInfo),oe=!!(e.assignedAgentId&&$===null),Z=a.useMemo(()=>jh(e,b),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,b]),pe=Z.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"||jd(e)==null)return;B(Date.now());const A=window.setInterval(()=>{B(Date.now())},hj);return()=>window.clearInterval(A)},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt]);const Se=a.useMemo(()=>{if(!mj.has(e.column))return null;if(e.column==="in-progress"){const dt=jd(e);if(dt==null)return null;const yt=wd(V-dt);return yt?{label:yt,title:`In progress since ${new Date(dt).toLocaleString()}`,ariaLabel:`Elapsed time ${yt}. In progress since ${new Date(dt).toLocaleString()}`}:null}const ue=pj(e);if(ue==null)return null;const A=fj(e,ue);if(A==null)return null;const J=wd(ue-A);if(!J)return null;const Ve=new Date(ue).toLocaleString();return{label:J,title:`Processing took ${J}. Completed ${Ve}`,ariaLabel:`Completed processing duration ${J}. Completed ${Ve}`}},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt,V]);a.useEffect(()=>{if(!rt||!U){F(e.id);return}return re(e.id),()=>{F(e.id)}},[rt,U,re,e.id,F]);const Pe=ie.get(`${n??"default"}:${e.id}`),ye=e.column==="in-progress"||e.column==="in-review",Ke=a.useMemo(()=>e.steps.map(ue=>`${ue.name}:${ue.status}`).join("|"),[e.steps]),{stats:Ne}=ej(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:U,worktree:e.worktree,stepVersion:ye?Ke:void 0,pollIntervalMs:ye?3e4:void 0}),Fe=a.useMemo(()=>Jk(e.id,n),[e.id,n]),Ye=a.useMemo(()=>{const ue=Pe?.prInfo,A=Pe?.timestamp,J=Fe?.result?.prInfo,Ve=Fe?.timestamp?new Date(Fe.timestamp).toISOString():void 0,dt=e.prInfo,yt=e.prInfo?.lastCheckedAt??e.updatedAt;let qt=zr(ue,A,dt,yt);const wn=A&&A>=yt?A:yt;return J&&Ve&&(!wn||Ve>wn)&&(qt=J),qt},[Pe,Fe,e.prInfo,e.updatedAt]),xe=a.useMemo(()=>{const ue=Pe?.issueInfo,A=Pe?.timestamp,J=Fe?.result?.issueInfo,Ve=Fe?.timestamp?new Date(Fe.timestamp).toISOString():void 0,dt=e.issueInfo,yt=e.issueInfo?.lastCheckedAt??e.updatedAt;let qt=zr(ue,A,dt,yt);const wn=A&&A>=yt?A:yt;return J&&Ve&&(!wn||Ve>wn)&&(qt=J),qt},[Pe,Fe,e.issueInfo,e.updatedAt]),ze=a.useCallback(ue=>{ue?.stopPropagation(),!(!Ze||j)&&(T(!0),S(e.description||""))},[Ze,j,e.description]),be=a.useCallback(()=>{T(!1),S(e.description||"")},[e.description]),Qe=a.useCallback(()=>N!==(e.description||""),[N,e.description]),it=a.useCallback(async()=>{if(!(!l||j)){if(!Qe()){be();return}P(!0);try{await l(e.id,{description:N.trim()||void 0}),r(`Updated ${e.id}`,"success"),T(!1)}catch(ue){r(`Failed to update ${e.id}: ${ve(ue)}`,"error")}finally{P(!1)}}},[l,e.id,N,j,Qe,be,r]),mt=a.useCallback(ue=>{ue.key==="Enter"&&!ue.shiftKey?(ue.preventDefault(),it()):ue.key==="Escape"&&(ue.preventDefault(),be())},[it,be]),At=a.useCallback(()=>{setTimeout(()=>{const ue=document.activeElement;ue===M.current||ue?.closest(".card-editing-content")||(Qe()?it():be())},0)},[Qe,it,be]),It=a.useCallback(ue=>{Ze&&(ue.stopPropagation(),ze(ue))},[Ze,ze]),Dt=a.useCallback(ue=>{ue.stopPropagation(),ze(ue)},[ze]),Ut=a.useCallback(ue=>{S(ue.target.value);const A=ue.target;A.style.height="auto",A.style.height=A.scrollHeight+"px"},[]),jt=a.useCallback(ue=>{ue.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(A=>{r(`Failed to archive ${e.id}: ${ve(A)}`,"error")})},[r,c,e.id]),Pt=a.useCallback(ue=>{ue.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(A=>{r(`Failed to unarchive ${e.id}: ${ve(A)}`,"error")})},[r,u,e.id]),He=a.useCallback(ue=>{ue.stopPropagation(),d&&window.confirm(`Delete ${e.id}?`)&&d(e.id).then(()=>{r(`Deleted ${e.id}`,"success")}).catch(A=>{const J=vj(A);if(!J||J.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ve(A)}`,"error");return}const Ve=J.dependentIds.join(", ");window.confirm(`${e.id} is a dependency of ${Ve}.
576
-
577
- Delete anyway by removing these dependency references first?`)&&d(e.id,{removeDependencyReferences:!0}).then(()=>{r(`Deleted ${e.id} after removing dependency references`,"success")}).catch(yt=>{r(`Failed to delete ${e.id}: ${ve(yt)}`,"error")})})},[r,d,e.id]),ut=a.useCallback(ue=>{ue.stopPropagation(),m?.(e,"changes")},[e,m]),$t=a.useCallback(ue=>{ue.stopPropagation(),I(A=>!A)},[]),St=a.useCallback(ue=>{ue.stopPropagation(),e.missionId&&g&&g(e.missionId)},[e.missionId,g]),Yt=a.useCallback(ue=>{ue.stopPropagation(),H(A=>!A)},[]),we=a.useCallback((ue,A)=>{ue.stopPropagation(),H(!1),p&&p(e.id,A).then(()=>{r(`Moved ${e.id} to ${Tn[A]}`,"success")}).catch(J=>{r(`Failed to move ${e.id}: ${ve(J)}`,"error")})},[r,p,e.id]),et=`card${v?" dragging":""}${s?" queued":""}${le?" agent-active":""}${ke?" failed":""}${De?" paused":""}${me?" stuck":""}${ee?" awaiting-approval":""}${y?" file-drop-target":""}${k?" card-editing":""}${j?" card-saving":""}`,ct=(()=>{if(e.worktree&&e.column==="in-progress"){const ue=Ne?.filesChanged;return ue==null||ue===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:ut,disabled:!m,children:[t.jsx(kn,{size:12}),t.jsxs("span",{children:[ue," ",ue===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const ue=Ne?.filesChanged,A=ue==null?e.modifiedFiles?.length:void 0,J=ue??A;return J==null||J===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:ut,disabled:!m,children:[t.jsx(kn,{size:12}),t.jsxs("span",{children:[J," ",J===1?"file":"files"," changed"]})]})}if(e.column==="done"){const ue=Ne?.filesChanged,A=e.mergeDetails?.filesChanged,J=ue??A;if(J!=null&&J>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:ut,disabled:!m,children:[t.jsx(kn,{size:12}),t.jsxs("span",{children:[J," ",J===1?"file":"files"," changed"]})]});const Ve=e.modifiedFiles?.length;if(Ve!=null&&Ve>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:ut,disabled:!m,children:[t.jsx(kn,{size:12}),t.jsxs("span",{children:[Ve," ",Ve===1?"file":"files"," changed"]})]})}return null})();return k?t.jsx("div",{ref:X,className:et,"data-id":e.id,onDoubleClick:It,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:M,className:"card-edit-desc-textarea",placeholder:"Task description",value:N,onChange:Ut,onKeyDown:mt,onBlur:At,disabled:j,rows:4}),j&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:X,className:et,"data-id":e.id,draggable:Ie,onDragStart:Ie?de:void 0,onDragEnd:Ie?Re:void 0,onDragOver:Me,onDragLeave:te,onDrop:Ce,onClick:We,onTouchStart:Ge,onTouchMove:Ee,onTouchEnd:Ae,onDoubleClick:It,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),De&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!De&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ee?" awaiting-approval":""}${kd.has(e.status)?" pulsing":""}${ke?" failed":""}${me?" stuck":""}`,children:me?"Stuck":ee?"Awaiting Approval":e.status}),me&&(De||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),rt&&t.jsx(vh,{prInfo:Ye,issueInfo:xe}),K&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${se}`,children:se}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:St,title:`Mission: ${D??e.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(es,{size:11}),rj(D??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ze&&t.jsx("button",{className:"card-edit-btn",onClick:Dt,title:"Edit task","aria-label":"Edit task",children:t.jsx(Un,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:He,title:"Delete task","aria-label":"Delete task",children:t.jsx(Bt,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:jt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Pt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&p&&t.jsxs("div",{className:"card-send-back",ref:C,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Yt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":w,children:["Send back",t.jsx(zt,{size:10})]}),w&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Rl["in-progress"].filter(ue=>ue!=="in-review").map(ue=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:A=>we(A,ue),children:Tn[ue]},ue))})]}),e.column==="in-review"&&p&&t.jsxs("div",{className:"card-send-back",ref:C,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Yt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":w,children:["Move",t.jsx(zt,{size:10})]}),w&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Rl["in-review"].map(ue=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:A=>we(A,ue),children:ue==="done"?"Done (no merge)":Tn[ue]},ue))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ke&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Ed(e.title,Cd)||Ed(e.description,Cd)||e.id}),pe&&(()=>{const ue=Z.completed/Z.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${ue}%`,backgroundColor:uj[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Z.completed,"/",Z.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:$t,"aria-expanded":_,"aria-label":_?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Z.total," step",Z.total===1?"":"s"]}),t.jsx(zt,{size:14,className:`card-steps-toggle-icon${_?" expanded":""}`})]}),_&&t.jsx("div",{className:"card-steps-list",children:Z.items.map(A=>{const J=A.source==="workflow"&&A.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${A.status}${J?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${A.status==="done"?" completed":""}`,children:A.name}),A.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${A.phase}`,title:"Workflow check",children:"workflow"})]},A.id)})})]})})(),(ct||Se)&&t.jsxs("div",{className:"card-footer-row",children:[ct,Se&&t.jsxs("span",{className:"card-time-indicator",title:Se.title,"aria-label":Se.ariaLabel,children:[t.jsx(wi,{size:12}),t.jsx("span",{children:Se.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(ue=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:A=>void Oe(A,ue),title:`Click to view ${ue}`,children:[t.jsx(qi,{size:12,style:{verticalAlign:"middle"}})," ",ue]},ue))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Si,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(wi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),e.assignedAgentId&&t.jsx("div",{className:"card-agent-row",children:t.jsxs("span",{className:`card-agent-badge${oe?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(nn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:cj($??e.assignedAgentId,15)})]})}),t.jsx(ao,{slotId:"task-card-badge",projectId:n})]})}const Sd=10,Sj=300,Cd=140;function Ed(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Or=a.memo(Nj,wj);Or.displayName="TaskCard";function Cj({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Wf,{size:14}):t.jsx(Us,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(p=>t.jsx(Or,{task:p,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id)),s.map(p=>t.jsx(Or,{task:p,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id))]})}const wh=a.memo(Cj);wh.displayName="WorktreeGroup";function Md(e){return e.toLowerCase().replace(/[-_./]/g,"")}function Ej(e,n){let s=0;for(let i=0;i<n.length&&s<e.length;i++)e[s]===n[i]&&s++;return s===e.length}function Mj(e,n,s){const i=e.length,r=n.length;if(i===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=i;c++){const u=new Array(r+1);u[0]=c;for(let d=1;d<=r;d++){const m=e[c-1]===n[d-1]?0:1;u[d]=Math.min(l[d]+1,u[d-1]+1,l[d-1]+m),c>=2&&d>=2&&e[c-1]===n[d-2]&&e[c-2]===n[d-1]&&(u[d]=Math.min(u[d],o[d-2]+1))}o=l,l=u}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function _j(e,n){const s=Md(e),i=Md(n);if(s.length===0||i.includes(s))return!0;const r=i.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&Ej(s,o)||s.length>=4&&Mj(s,o,1))return!0;return!1}function Aj(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(i=>{const r=`${i.provider} ${i.id} ${i.name}`;return s.every(o=>_j(o,r))})}const Rj={sm:16,md:20,lg:24};function Tj({size:e,color:n,label:s="Anthropic"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"anthropic-icon","aria-label":s,children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})})}function _d({size:e,color:n,label:s="OpenAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:t.jsx("path",{d:"M22.282 9.821a6 6 0 0 0-.516-4.91a6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9a6.05 6.05 0 0 0 .743 7.097a5.98 5.98 0 0 0 .51 4.911a6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206a6 6 0 0 0 3.997-2.9a6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081l4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085l4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354l-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023l-.141-.085l-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365l2.602-1.5l2.607 1.5v2.999l-2.597 1.5l-2.607-1.5Z",fill:n})})}function Ad({size:e,color:n,label:s="Google Gemini"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:t.jsx("path",{d:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",fill:n})})}function Ij({size:e,color:n,label:s="Ollama"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"ollama-icon","aria-label":s,children:t.jsx("path",{d:"M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z",fill:n})})}function Pj({size:e,color:n,label:s="MiniMax"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"minimax-icon","aria-label":s,children:t.jsx("path",{d:"M11.43 3.92a.86.86 0 1 0-1.718 0v14.236a1.999 1.999 0 0 1-3.997 0V9.022a.86.86 0 1 0-1.718 0v3.87a1.999 1.999 0 0 1-3.997 0V11.49a.57.57 0 0 1 1.139 0v1.404a.86.86 0 0 0 1.719 0V9.022a1.999 1.999 0 0 1 3.997 0v9.134a.86.86 0 0 0 1.719 0V3.92a1.998 1.998 0 1 1 3.996 0v11.788a.57.57 0 1 1-1.139 0zm10.572 3.105a2 2 0 0 0-1.999 1.997v7.63a.86.86 0 0 1-1.718 0V3.923a1.999 1.999 0 0 0-3.997 0v16.16a.86.86 0 0 1-1.719 0V18.08a.57.57 0 1 0-1.138 0v2a1.998 1.998 0 0 0 3.996 0V3.92a.86.86 0 0 1 1.719 0v12.73a1.999 1.999 0 0 0 3.996 0V9.023a.86.86 0 1 1 1.72 0v6.686a.57.57 0 0 0 1.138 0V9.022a2 2 0 0 0-1.998-1.997",fill:n})})}function $j({size:e,color:n,label:s="Z.ai"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"zai-icon","aria-label":s,children:t.jsx("path",{d:"M3 5H21V8.5L7 17.5H21V21H3V17.5L17 8.5H3Z",fill:n})})}function Mo({size:e,color:n,label:s="Kimi"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"kimi-icon","aria-label":s,children:t.jsx("path",{d:"M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.39 5.39 0 0 1-4.4 2.26 5.4 5.4 0 0 1-3.14-9.8c.2-.07.4-.1.64-.1z",fill:n})})}function Dj({size:e,color:n,label:s="OpenRouter"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openrouter-icon","aria-label":s,children:t.jsx("path",{d:"M12 2.5a9.5 9.5 0 1 0 9.5 9.5h-2.7a6.8 6.8 0 1 1-2-4.8l-3.1 3.1H22V2.5l-3.2 3.2A9.45 9.45 0 0 0 12 2.5",fill:n})})}function Rd({size:e,color:n,label:s="GitHub"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"github-icon","aria-label":s,children:t.jsx("path",{d:"M12 0a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.23c-3.34.73-4.04-1.41-4.04-1.41-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.74.08-.74 1.2.08 1.84 1.24 1.84 1.24 1.08 1.84 2.82 1.31 3.5 1 .1-.78.42-1.31.77-1.62-2.67-.3-5.47-1.34-5.47-5.95 0-1.31.47-2.38 1.24-3.22-.12-.31-.54-1.56.12-3.24 0 0 1.01-.32 3.3 1.23a11.3 11.3 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.68.24 2.93.12 3.24.77.84 1.24 1.91 1.24 3.22 0 4.62-2.8 5.64-5.48 5.94.43.37.82 1.1.82 2.22v3.29c0 .32.22.69.83.58A12 12 0 0 0 12 0",fill:n})})}function Td({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const Lj={anthropic:{component:Tj,color:"var(--provider-anthropic)"},"claude-cli":{component:Td,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Td,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:_d,color:"var(--provider-openai)"},"openai-codex":{component:_d,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ad,color:"var(--provider-gemini)"},gemini:{component:Ad,color:"var(--provider-gemini)"},ollama:{component:Ij,color:"var(--text)"},github:{component:Rd,color:"var(--text)"},"github-copilot":{component:Rd,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Dj,color:"var(--provider-openrouter)"},minimax:{component:Pj,color:"var(--provider-minimax)"},zai:{component:$j,color:"var(--provider-zai)"},kimi:{component:Mo,color:"var(--provider-kimi)"},moonshot:{component:Mo,color:"var(--provider-kimi)"},"kimi-coding":{component:Mo,color:"var(--provider-kimi)",label:"Kimi"}};function ts({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Lj[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=Rj[n];return t.jsx("span",{className:"provider-icon",style:{color:o},"data-provider":s,children:r?t.jsx(r,{size:c,color:o,label:l}):t.jsx(Zf,{size:c})})}function jn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[b,v]=a.useState(""),[x,y]=a.useState(0),[E,k]=a.useState(null),[T,N]=a.useState(null),S=a.useRef(null),j=a.useRef(null),P=a.useRef(null),_=a.useRef(null),I=a.useRef(null),D=a.useMemo(()=>Aj(e,b),[e,b]),G=a.useMemo(()=>D.reduce((Q,de)=>((Q[de.provider]??=[]).push(de),Q),{}),[D]),$=a.useMemo(()=>{const Q=[];for(const de of d){const Re=de.indexOf("/");if(Re===-1)continue;const ge=de.slice(0,Re),Me=de.slice(Re+1),te=D.find(Ce=>Ce.provider===ge&&Ce.id===Me);te&&Q.push({model:te,fullId:de})}return Q},[d,D]),R=a.useMemo(()=>{const Q=Object.entries(G),de=new Set(c);return Q.sort(([Re],[ge])=>{const Me=de.has(Re),te=de.has(ge);if(Me&&!te)return-1;if(!Me&&te)return 1;if(Me&&te){const Ce=c.indexOf(Re),$e=c.indexOf(ge);if(Ce!==$e)return Ce-$e}return Re.localeCompare(ge)})},[G,c]),w=typeof h=="string"&&h.length>0,H=a.useMemo(()=>{if(!n||w&&n===h)return null;const Q=n.indexOf("/");return Q===-1?null:n.slice(0,Q)},[w,h,n]),V=a.useMemo(()=>{const Q=[];return w&&Q.push({type:"no-change",value:h,label:g}),Q.push({type:"default",value:"",label:"Use default"}),Q},[w,g,h]),B=a.useMemo(()=>{const Q=[...V];for(const{model:de,fullId:Re}of $)Q.push({type:"favorite",value:Re,label:de.name,provider:de.provider});return R.forEach(([de,Re])=>{Q.push({type:"provider",value:`__group_${de}`,label:de,provider:de}),Re.forEach(ge=>{Q.push({type:"model",value:`${ge.provider}/${ge.id}`,label:ge.name,provider:ge.provider})})}),Q},[$,R,V]),M=a.useMemo(()=>{if(w&&n===h)return g;if(!n)return"Use default";const Q=n.indexOf("/");if(Q===-1)return n;const de=n.slice(0,Q),Re=n.slice(Q+1);return e.find(Me=>Me.provider===de&&Me.id===Re)?.name||n},[w,g,h,n,e]),z=a.useMemo(()=>B.findIndex(Q=>Q.value===n),[B,n]),X=a.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.height>0&&Q.width>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),C=a.useCallback(()=>{const{height:Q}=X(),de=typeof window.matchMedia=="function",Re=de?window.matchMedia("(max-width: 640px)").matches:!1,ge=de?window.matchMedia("(max-width: 768px)").matches:!1;return Q<=0?320:Re?Math.min(Q*.6,360):ge?Math.min(Q*.7,420):320},[X]),U=a.useCallback(()=>{const Q=j.current;if(!Q)return;const de=Q.getBoundingClientRect(),{width:Re,height:ge,offsetTop:Me,offsetLeft:te}=X(),Ce=16,$e=16,We=4,Ge=C(),Ee=de.bottom-Me,Ae=de.top-Me,Oe=de.left-te,ke=ge-Ee,De=Ae,se=Math.max(ke-$e-We,160),K=Math.max(De-$e-We,160),me=ke<Ge&&De>ke,ee=Math.max(Math.min(me?K:se,Ge),160),he=Math.min(de.width,Re-Ce*2),le=Math.min(Math.max(Oe,Ce),Re-Ce-he)+te,Ie=me?Math.max($e+Me,Ae-ee-We+Me):Math.min(Ee+We+Me,ge+Me-$e-ee);k({top:Ie,left:le,width:he,maxHeight:ee})},[X,C]);a.useEffect(()=>{N(document.body)},[]),a.useEffect(()=>{if(p){const Q=B.findIndex((de,Re)=>Re>=(z>=0?z:0)&&de.type!=="provider");y(Q>=0?Q:0)}},[p,B,z]),a.useEffect(()=>{if(!p)return;U();const Q=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(Q)},[p,U]),a.useEffect(()=>{if(!p)return;const Q=()=>U();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",Q),de.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),de&&(de.removeEventListener("resize",Q),de.removeEventListener("scroll",Q))}},[p,U]),a.useEffect(()=>{if(!p)return;const Q=de=>{const Re=de.target,ge=S.current?.contains(Re),Me=P.current?.contains(Re);!ge&&!Me&&(f(!1),v(""))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]);const fe=a.useCallback(Q=>{switch(Q.key){case"ArrowDown":if(Q.preventDefault(),!p)f(!0);else{let de=x;for(let Re=1;Re<=B.length;Re++){const ge=(x+Re)%B.length;if(B[ge]?.type!=="provider"){de=ge;break}}y(de)}break;case"ArrowUp":if(Q.preventDefault(),p){let de=x;for(let Re=1;Re<=B.length;Re++){const ge=(x-Re+B.length)%B.length;if(B[ge]?.type!=="provider"){de=ge;break}}y(de)}break;case"Enter":if(Q.preventDefault(),p){const de=B[x];de&&de.type!=="provider"&&de.type!=="favorite"&&(s(de.value),f(!1),v(""))}else f(!0);break;case"Escape":Q.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,x,B,s]),ie=a.useCallback(Q=>{s(Q),f(!1),v("")},[s]),re=a.useCallback(()=>{v(""),_.current?.focus()},[]),F=a.useCallback(()=>{r||f(Q=>!Q)},[r]);a.useEffect(()=>{if(p&&I.current){const Q=I.current.querySelector(`[data-index="${x}"]`);Q&&typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest"})}},[x,p]);const ce=b.length>0,ae=p&&E?t.jsxs("div",{ref:P,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:fe,style:{top:`${E.top}px`,left:`${E.left}px`,width:`${E.width}px`,maxHeight:`${E.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:Q=>v(Q.target.value),onClick:Q=>Q.stopPropagation()}),ce&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:re,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[D.length," model",D.length!==1?"s":""]}),t.jsxs("div",{ref:I,className:"model-combobox-list",children:[V.map((Q,de)=>t.jsx("div",{"data-index":de,className:`model-combobox-option ${x===de?"model-combobox-option--highlighted":""} ${n===Q.value?"model-combobox-option--selected":""}`,onClick:()=>ie(Q.value),onMouseEnter:()=>y(de),role:"option","aria-selected":n===Q.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Q.label})},`${Q.type}-${Q.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:Q,fullId:de},Re)=>{const ge=Re+V.length,Me=x===ge,te=n===de;return t.jsxs("div",{"data-index":ge,className:`model-combobox-option model-combobox-option--favorite ${Me?"model-combobox-option--highlighted":""} ${te?"model-combobox-option--selected":""}`,onClick:()=>ie(de),onMouseEnter:()=>y(ge),role:"option","aria-selected":te,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(ts,{provider:Q.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Q.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Q.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Ce=>{Ce.stopPropagation(),m(de)},title:"Remove from favorites","aria-label":`Remove ${Q.name} from favorites`,children:"★"})]},de)}),t.jsx("div",{className:"model-combobox-divider"})]}),R.map(([Q,de])=>{const Re=B.findIndex(te=>te.value===`__group_${Q}`),ge=c.includes(Q),Me=de.filter(te=>{const Ce=`${te.provider}/${te.id}`;return!d.includes(Ce)});return Me.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":Re,children:[t.jsx(ts,{provider:Q,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Q}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ge?"model-combobox-optgroup-favorite--active":""}`,onClick:te=>{te.stopPropagation(),u(Q)},title:ge?"Remove from favorites":"Add to favorites","aria-label":ge?`Remove ${Q} from favorites`:`Add ${Q} to favorites`,children:"★"})]}),Me.map(te=>{const Ce=`${te.provider}/${te.id}`,$e=B.findIndex(Ae=>Ae.value===Ce),We=x===$e,Ge=n===Ce,Ee=d.includes(Ce);return t.jsxs("div",{"data-index":$e,className:`model-combobox-option ${We?"model-combobox-option--highlighted":""} ${Ge?"model-combobox-option--selected":""}`,onClick:()=>ie(Ce),onMouseEnter:()=>y($e),role:"option","aria-selected":Ge,children:[t.jsx("span",{className:"model-combobox-option-text",children:te.name}),t.jsx("span",{className:"model-combobox-option-id",children:te.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ee?"model-combobox-option-favorite--active":""}`,onClick:Ae=>{Ae.stopPropagation(),m(Ce)},title:Ee?"Remove from favorites":"Add to favorites","aria-label":Ee?`Remove ${te.name} from favorites`:`Add ${te.name} to favorites`,children:Ee?"★":"☆"})]},Ce)})]},Q)}),D.length===0&&ce&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:S,className:"model-combobox",onKeyDown:fe,children:t.jsxs("button",{ref:j,type:"button",id:o,className:"model-combobox-trigger",onClick:F,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[H&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(ts,{provider:H,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:M||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),T&&ae?_a.createPortal(ae,T):null]})}function oc(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function En(e,n){return typeof window>"u"?null:window.localStorage.getItem(oc(e,n))}function cs(e,n,s){typeof window>"u"||window.localStorage.setItem(oc(e,s),n)}function Ua(e,n){typeof window>"u"||window.localStorage.removeItem(oc(e,n))}const ha="kb-quick-entry-text",zj=["image/png","image/jpeg","image/gif","image/webp"];function _o(e,n){return e&&n?`${e}/${n}`:""}function Ao(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Nh({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&En(ha,l)||""),[f,b]=a.useState(!1),[v,x]=a.useState(!1),[y,E]=a.useState(!1),k=a.useRef(null),T=a.useRef(null),N=a.useRef(!1),S=a.useRef(l),[j,P]=a.useState([]),_=a.useRef([]),[I,D]=a.useState([]),[G,$]=a.useState(!1),[R,w]=a.useState(""),[H,V]=a.useState(null),[B,M]=a.useState([]),[z,X]=a.useState(void 0),[C,U]=a.useState(!1),[fe,ie]=a.useState(!1),[re,F]=a.useState(!1),[ce,ae]=a.useState(null),[Q,de]=a.useState(void 0),[Re,ge]=a.useState(void 0),[Me,te]=a.useState(void 0),[Ce,$e]=a.useState(void 0),[We,Ge]=a.useState(void 0),[Ee,Ae]=a.useState(void 0),Oe=a.useRef(null),ke=a.useRef(null),De=a.useRef(null),se=a.useRef(null),[K,me]=a.useState(null),[ee,he]=a.useState(null),le=a.useRef(null),Ie=a.useRef(null),[Ze,rt]=a.useState(null),[oe]=a.useState(()=>typeof document<"u"?document.body:null),[Z,pe]=a.useState(!1),[Se,Pe]=a.useState(null),[ye,Ke]=a.useState(i??[]),[Ne,Fe]=a.useState([]),[Ye,xe]=a.useState([]),[ze,be]=a.useState(null),[Qe,it]=a.useState(void 0),[mt,At]=a.useState(!1),[It,Dt]=a.useState(!1),[Ut,jt]=a.useState(!1),Pt=a.useRef(null),He=a.useRef(null),[ut,$t]=a.useState(null),St=u??Ne,Yt=d??Ye,we=!e;a.useEffect(()=>{if(i)Ke(i),pe(!1),Pe(null);else{let ne=!1;return pe(!0),Pe(null),ss().then(_e=>{ne||(Ke(_e.models),u||Fe(_e.favoriteProviders),d||xe(_e.favoriteModels))}).catch(_e=>{ne||Pe(ve(_e)||"Failed to load models")}).finally(()=>{ne||pe(!1)}),no(l).then(_e=>{ne||be(_e)}).catch(()=>{}),()=>{ne=!0}}},[i,u,d,l]);const et=_o(Q,Re),ct=_o(Me,Ce),ue=_o(We,Ee),A=!!(Q&&Re),J=!!(Me&&Ce),Ve=!!(We&&Ee),dt=Number(A)+Number(J)+Number(Ve),yt=Qe?ze?.modelPresets?.find(ne=>ne.id===Qe)?.name??"Models":dt>0?`${dt} model${dt===1?"":"s"}`:"Models",qt=a.useCallback((ne,_e)=>{if(!ne||!_e)return"Using default";const st=ye.find(gt=>gt.provider===ne&&gt.id===_e);return st?`${st.provider}/${st.id}`:`${ne}/${_e}`},[ye]);a.useEffect(()=>{p(En(ha,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&cs(ha,g,l)},[g,l]),a.useEffect(()=>{S.current!==l&&(S.current=l,M([]),X(void 0),V(null),U(!1),me(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{_.current=j},[j]),a.useEffect(()=>()=>{_.current.forEach(ne=>URL.revokeObjectURL(ne.previewUrl))},[]);const wn=a.useCallback(()=>{const ne=k.current;if(!ne)return;ne.style.height="auto";const _e=Math.min(ne.scrollHeight,200);ne.style.height=`${_e}px`},[]);a.useEffect(()=>{v&&wn()},[g,v,wn]),a.useEffect(()=>{if(!f&&g===""&&k.current){const ne=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(ne)}},[f,g]),a.useEffect(()=>{G||w("")},[G]),a.useEffect(()=>{if(!It)return;const ne=_e=>{const st=_e.target,gt=Pt.current?.contains(st),bt=He.current?.contains(st);!gt&&!bt&&Dt(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[It]),a.useEffect(()=>{if(!re)return;const ne=_e=>{const st=_e.target,gt=Oe.current?.contains(st),bt=ke.current?.contains(st),rn=st instanceof Element&&st.closest?.(".model-combobox-dropdown--portal")!=null;!gt&&!bt&&!rn&&(F(!1),ae(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[re]),a.useEffect(()=>{if(!C)return;const ne=_e=>{const st=_e.target;De.current?.contains(st)||se.current?.contains(st)||(U(!1),me(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[C]);const Ft=a.useCallback(()=>{j.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),P([]),T.current&&(T.current.value=""),p(""),D([]),V(null),U(!1),me(null),de(void 0),ge(void 0),te(void 0),$e(void 0),Ge(void 0),Ae(void 0),it(void 0),At(!1),$(!1),F(!1),he(null),ae(null),Dt(!1),jt(!1),x(!1),E(!1),N.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&Ua(ha,l)},[j,l]),Dn=a.useCallback(ne=>{if(!ne||ne.length===0)return;const _e=[];for(let st=0;st<ne.length;st++){const gt=ne[st];zj.includes(gt.type)&&_e.push({file:gt,previewUrl:URL.createObjectURL(gt)})}_e.length>0&&P(st=>[...st,..._e])},[]),qn=a.useCallback(ne=>{f||Dn(ne.clipboardData?.files)},[Dn,f]),ms=a.useCallback(ne=>{P(_e=>{const st=_e[ne];return st&&URL.revokeObjectURL(st.previewUrl),_e.filter((gt,bt)=>bt!==ne)})},[]),hn=a.useCallback(async()=>{const ne=g.trim();if(!(!ne||f||!e)){b(!0);try{const _e=await e({description:ne,column:"triage",dependencies:I.length?I:void 0,...H?{assignedAgentId:H}:{},modelPresetId:Qe,modelProvider:A?Q:void 0,modelId:A?Re:void 0,validatorModelProvider:J?Me:void 0,validatorModelId:J?Ce:void 0,planningModelProvider:Ve?We:void 0,planningModelId:Ve?Ee:void 0,...mt?{executionMode:"fast"}:{}});if(_e&&j.length>0){const st=[];for(const gt of j)try{await Fa(_e.id,gt.file,l)}catch{st.push(gt.file.name)}st.length>0&&n(`Failed to upload: ${st.join(", ")}`,"error")}Ft()}catch(_e){n(ve(_e)||"Failed to create task","error")}finally{b(!1)}}},[g,f,e,I,H,A,Q,Re,J,Me,Ce,Ve,We,Ee,j,l,n,Ft,mt]),Ln=a.useCallback(ne=>{if(ne.key==="Enter"){if(ne.shiftKey&&v)return;ne.preventDefault(),hn()}else if(ne.key==="Escape"){if(ne.preventDefault(),ce){ae(null);return}if(re){F(!1),he(null);return}if(G){$(!1);return}if(It){Dt(!1);return}if(C){U(!1),me(null);return}g.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&Ua(ha,l)),x(!1),E(!1),k.current?.blur()}},[hn,g,v,G,C,re,ce,It,l,E]),Nn=a.useCallback(()=>{N.current&&(N.current=!1)},[]),pn=a.useCallback(()=>{c&&x(!0)},[c]),Vn=a.useCallback(ne=>{D(_e=>_e.includes(ne)?_e.filter(st=>st!==ne):[..._e,ne])},[]),cn=a.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.width>0&&ne.height>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ct=a.useCallback(()=>{const ne=Oe.current;if(!ne)return;const _e=ne.getBoundingClientRect(),{width:st,height:gt,offsetTop:bt,offsetLeft:rn}=cn(),Xt=16,ln=16,Wt=4,gn=st<=768,Sn=Math.min(gn?gt*.6:gt*.5,360),gs=gn?Math.min(st-Xt*2,360):Math.max(_e.width,240),Fn=Math.min(gs,Math.max(st-Xt*2,200)),Gn=_e.top-bt,On=_e.bottom-bt,Kn=_e.left-rn,dn=gt-On,Jn=Gn,Es=Math.max(dn-ln-Wt,160),Ts=Math.max(Jn-ln-Wt,160),as=dn<Sn&&Jn>dn,_n=Math.max(Math.min(as?Ts:Es,Sn),160),bs=Math.min(Math.max(Kn,Xt),st-Xt-Fn)+rn,An=as?Math.max(ln+bt,Gn-_n-Wt+bt):Math.min(On+Wt+bt,gt+bt-ln-_n);he({top:An,left:bs,width:Fn,maxHeight:_n})},[cn]),xn=a.useCallback(()=>{const ne=Pt.current?.querySelector(".refine-button");if(!ne)return;const _e=ne.getBoundingClientRect(),{width:st,height:gt,offsetTop:bt,offsetLeft:rn}=cn(),Xt=8,ln=12,Wt=4,gn=Math.min(200,Math.max(gt-ln*2,160)),Sn=Math.min(200,st-Xt*2),gs=_e.top-bt,Fn=_e.bottom-bt,Gn=_e.left-rn,On=gt-Fn,Kn=gs,dn=On<gn&&Kn>On,Jn=Math.min(Math.max(Gn,Xt),st-Xt-Sn)+rn,Es=dn?Math.max(ln+bt,gs-gn-Wt+bt):Math.min(Fn+Wt+bt,gt+bt-ln-gn);$t({top:Es,left:Jn})},[cn]),Wn=a.useCallback(()=>{const ne=le.current;if(!ne)return;const _e=ne.getBoundingClientRect(),{width:st,height:gt,offsetTop:bt,offsetLeft:rn}=cn(),Xt=16,ln=16,Wt=4,gn=st<=768,Sn=Math.min(gn?gt*.6:gt*.5,320),gs=gn?Math.min(st-Xt*2,360):Math.max(_e.width,280),Fn=Math.min(gs,Math.max(st-Xt*2,240)),Gn=_e.top-bt,On=_e.bottom-bt,Kn=_e.left-rn,dn=gt-On,Jn=Gn,Es=Math.max(dn-ln-Wt,200),Ts=Math.max(Jn-ln-Wt,200),as=dn<Sn&&Jn>dn,_n=Math.max(Math.min(as?Ts:Es,Sn),200),bs=Math.min(Math.max(Kn,Xt),st-Xt-Fn)+rn,An=as?Math.max(ln+bt,Gn-_n-Wt+bt):Math.min(On+Wt+bt,gt+bt-ln-_n);rt({top:An,left:bs,width:Fn,maxHeight:_n})},[cn]),vn=a.useCallback(()=>{const ne=De.current?.querySelector("button");if(!ne)return;const _e=ne.getBoundingClientRect(),{width:st,height:gt,offsetTop:bt,offsetLeft:rn}=cn(),Xt=16,ln=16,Wt=4,gn=st<=768,Sn=Math.min(gn?gt*.6:gt*.5,320),gs=gn?Math.min(st-Xt*2,280):Math.max(_e.width,240),Fn=Math.min(gs,Math.max(st-Xt*2,200)),Gn=_e.top-bt,On=_e.bottom-bt,Kn=_e.left-rn,dn=gt-On,Jn=Gn,Es=Math.max(dn-ln-Wt,160),Ts=Math.max(Jn-ln-Wt,160),as=dn<Sn&&Jn>dn,_n=Math.max(Math.min(as?Ts:Es,Sn),160),bs=Math.min(Math.max(Kn,Xt),st-Xt-Fn)+rn,An=as?Math.max(ln+bt,Gn-_n-Wt+bt):Math.min(On+Wt+bt,gt+bt-ln-_n);me({top:An,left:bs,width:Fn,maxHeight:_n})},[cn]);a.useEffect(()=>{if(!re)return;const ne=()=>Ct();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ne),_e.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),_e&&(_e.removeEventListener("resize",ne),_e.removeEventListener("scroll",ne))}},[re,Ct]),a.useEffect(()=>{if(!It)return;const ne=()=>xn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ne),_e.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),_e&&(_e.removeEventListener("resize",ne),_e.removeEventListener("scroll",ne))}},[It,xn]),a.useEffect(()=>{if(!G)return;const ne=()=>Wn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ne),_e.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),_e&&(_e.removeEventListener("resize",ne),_e.removeEventListener("scroll",ne))}},[G,Wn]),a.useEffect(()=>{if(!C)return;const ne=()=>vn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const _e=window.visualViewport;return _e&&(_e.addEventListener("resize",ne),_e.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),_e&&(_e.removeEventListener("resize",ne),_e.removeEventListener("scroll",ne))}},[C,vn]);const Mn=a.useCallback(ne=>{const _e=Ao(ne);Ge(_e.provider),Ae(_e.modelId)},[]),hs=a.useCallback(ne=>{const _e=Ao(ne);de(_e.provider),ge(_e.modelId)},[]),ps=a.useCallback(ne=>{const _e=Ao(ne);te(_e.provider),$e(_e.modelId)},[]),zn=a.useCallback(async ne=>{if(m){m(ne);return}const _e=Ne,gt=_e.includes(ne)?_e.filter(bt=>bt!==ne):[ne,..._e];Fe(gt);try{await tn({favoriteProviders:gt,favoriteModels:Ye})}catch{Fe(_e)}},[Ne,Ye,m]),W=a.useCallback(async ne=>{if(h){h(ne);return}const _e=Ye,gt=_e.includes(ne)?_e.filter(bt=>bt!==ne):[ne,..._e];xe(gt);try{await tn({favoriteProviders:Ne,favoriteModels:gt})}catch{xe(_e)}},[Ye,Ne,h]),Le=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}r?.(ne),Ft()},[g,r,n,Ft]),nt=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}o?.(ne),Ft()},[g,o,n,Ft]),tt=a.useCallback(()=>{hn()},[hn]),ht=a.useCallback(async ne=>{const _e=g.trim();if(!(!_e||Ut)){Dt(!1),jt(!0);try{const st=await oh(_e,ne,l);p(st),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(st){const gt=lh(st);n(gt,"error")}finally{jt(!1)}}},[g,Ut,n,l]),kt=(ne,_e)=>ne.length>_e?ne.slice(0,_e)+"…":ne,Et=a.useCallback(async()=>{if(i){Ke(i),Pe(null),pe(!1);return}pe(!0),Pe(null);try{const ne=await ss();Ke(ne.models),u||Fe(ne.favoriteProviders),d||xe(ne.favoriteModels)}catch(ne){Pe(ve(ne)||"Failed to load models")}finally{pe(!1)}},[i,u,d]),fn=a.useCallback(async()=>{if(B.length>0&&z===l){U(!0),vn();return}ie(!0);try{const ne=await aa(void 0,l);M(ne),X(l),U(!0),vn()}catch(ne){const _e=ve(ne);n(_e?`Failed to load agents: ${_e}`:"Failed to load agents","error"),U(!1)}finally{ie(!1)}},[B.length,z,l,n,vn]),Qt=(H?B.find(ne=>ne.id===H):void 0)?.name??H,xt=y,lt=a.useCallback(()=>{E(ne=>{const _e=!ne;return x(_e),_e})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:k,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ne=>p(ne.target.value),onKeyDown:Ln,onPaste:qn,onFocus:pn,onBlur:Nn,disabled:f||we,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:lt,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(Zs,{size:14}):t.jsx(zt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!xt,"aria-hidden":!xt,children:[xt&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Le,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Bs,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:nt,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Xr,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Pt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ut?"refine-button--loading":""}`,onClick:()=>{Dt(ne=>{const _e=!ne;return _e?xn():$t(null),_e})},disabled:!g.trim()||Ut,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Pn,{size:12,style:{verticalAlign:"middle"}}),Ut?"Refining...":"Refine"]}),It&&oe&&ut&&_a.createPortal(t.jsxs("div",{ref:He,className:"refine-menu refine-menu--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${ut.top}px`,left:`${ut.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ht("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>ht("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>ht("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>ht("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),oe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:le,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ne=>{const _e=!ne;return _e?(F(!1),he(null),ae(null),U(!1),Wn()):rt(null),_e})},children:[t.jsx(qi,{size:12,style:{verticalAlign:"middle"}}),I.length>0?`${I.length} deps`:"Deps"]})}),G&&oe&&Ze&&(()=>{const ne=R.toLowerCase(),_e=(ne?s.filter(st=>st.id.toLowerCase().includes(ne)||st.title&&st.title.toLowerCase().includes(ne)||st.description&&st.description.toLowerCase().includes(ne)):[...s]).sort((st,gt)=>{const bt=gt.createdAt.localeCompare(st.createdAt);if(bt!==0)return bt;const rn=parseInt(st.id.slice(st.id.lastIndexOf("-")+1),10)||0;return(parseInt(gt.id.slice(gt.id.lastIndexOf("-")+1),10)||0)-rn});return _a.createPortal(t.jsxs("div",{ref:Ie,className:"dep-dropdown dep-dropdown--portal",onMouseDown:st=>st.preventDefault(),style:{position:"fixed",top:`${Ze.top}px`,left:`${Ze.left}px`,width:`${Ze.width}px`,maxHeight:Ze.maxHeight?`${Ze.maxHeight}px`:void 0,overflowY:Ze.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:R,onChange:st=>w(st.target.value),onClick:st=>st.stopPropagation()}),_e.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):_e.map(st=>t.jsxs("div",{className:`dep-dropdown-item${I.includes(st.id)?" selected":""}`,onMouseDown:gt=>gt.preventDefault(),onClick:()=>Vn(st.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:st.id}),t.jsx("span",{className:"dep-dropdown-title",children:kt(st.title||st.description||st.id,60)})]},st.id))]}),oe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>T.current?.click(),children:[t.jsx(ob,{size:12,style:{verticalAlign:"middle"}}),j.length>0?`Attach (${j.length})`:"Attach"]}),t.jsxs("button",{ref:Oe,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),U(!1),ae(null),F(!0),Ct()},children:[t.jsx(Rr,{size:12,style:{verticalAlign:"middle"}}),yt]}),t.jsx("div",{className:"agent-trigger-wrap",ref:De,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{C?(U(!1),me(null)):fn()},"data-testid":"quick-entry-agent-button",children:[t.jsx(nn,{size:12,style:{verticalAlign:"middle"}}),Qt?` ${Qt}`:" Agent"]})}),C&&oe&&K&&_a.createPortal(t.jsxs("div",{ref:se,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${K.top}px`,left:`${K.left}px`,width:`${K.width}px`,maxHeight:K.maxHeight?`${K.maxHeight}px`:void 0,overflowY:K.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),fe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!fe&&B.filter(ne=>ne.state!=="terminated").map(ne=>t.jsxs("div",{className:`dep-dropdown-item${H===ne.id?" selected":""}`,onMouseDown:_e=>_e.preventDefault(),onClick:()=>{V(ne.id===H?null:ne.id),U(!1),me(null)},children:[t.jsx(nn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ne.role}),t.jsx("span",{className:"dep-dropdown-title",children:ne.name})]},ne.id)),!fe&&B.filter(ne=>ne.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),H&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ne=>ne.preventDefault(),onClick:()=>{V(null),U(!1),me(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),oe),t.jsx("button",{type:"button",className:`btn btn-sm ${mt?"btn-primary":""}`,onClick:()=>At(ne=>!ne),onMouseDown:ne=>ne.preventDefault(),"aria-pressed":mt,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:tt,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(eh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),j.length>0&&t.jsx("div",{className:"inline-create-previews",children:j.map((ne,_e)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ms(_e),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${_e}`,children:"×"})]},ne.previewUrl))}),re&&oe&&ee&&_a.createPortal(t.jsx("div",{ref:ke,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ne=>ne.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ee.top}px`,left:`${ee.left}px`,width:`${ee.width}px`,maxHeight:ee.maxHeight?`${ee.maxHeight}px`:void 0,overflowY:ee.maxHeight?"auto":void 0},children:ce===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Ve?"model-menu-item--active":""}`,onClick:()=>ae("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Bs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Ve?qt(We,Ee):"Using default"}),t.jsx(an,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${A?"model-menu-item--active":""}`,onClick:()=>ae("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Pn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:A?qt(Q,Re):"Using default"}),t.jsx(an,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${J?"model-menu-item--active":""}`,onClick:()=>ae("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Rr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Validator"]}),t.jsx("span",{className:"model-menu-item-value",children:J?qt(Me,Ce):"Using default"}),t.jsx(an,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>ae(null),"data-testid":"model-submenu-back",children:[t.jsx(zt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ce==="plan"&&"Plan Model",ce==="executor"&&"Executor Model",ce==="validator"&&"Validator Model"]}),t.jsx(jn,{models:ye,value:ce==="plan"?ue:ce==="executor"?et:ct,onChange:ce==="plan"?Mn:ce==="executor"?hs:ps,placeholder:"Using default",disabled:Z,id:`model-${ce}-select`,label:`${ce} model`,favoriteProviders:St,onToggleFavorite:zn,favoriteModels:Yt,onToggleModelFavorite:W}),Se&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Se}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Et,children:"Retry"})]})]})}),oe)]}),t.jsx("input",{ref:T,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ne=>{Dn(ne.target.files),ne.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function Fj(e){const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function Oj(e){const n=new Map(e.map(l=>[l.id,l])),s=[],i=new Set,r=new Set;function o(l){if(i.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const u of c.dependencies||[])n.has(u)&&o(u);r.delete(l),i.add(l),s.push(l)}for(const l of e)o(l.id);return s}function Uj(e,n,s){const i=e.filter(f=>f.worktree),r=e.filter(f=>!f.worktree),o=new Map;for(const f of i){const b=f.worktree,v=o.get(b)||[];v.push(f),o.set(b,v)}const l=new Map(n.map(f=>[f.id,f])),u=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=Oj(u).map(f=>l.get(f)).filter(f=>f!==void 0&&u.includes(f)),h=[],g=Array.from(o.keys());for(const f of g)h.push({label:Fj(f),activeTasks:o.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Id=100,Ro=50,Pd=25;function Bj({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,collapsed:y,onToggleCollapse:E,allTasks:k,availableModels:T,onPlanningMode:N,onSubtaskBreakdown:S,onOpenDetailWithTab:j,favoriteProviders:P,favoriteModels:_,onToggleFavorite:I,onToggleModelFavorite:D,isSearchActive:G,taskStuckTimeoutMs:$,onOpenMission:R,lastFetchTimeMs:w,workflowStepNameLookup:H}){const[V,B]=a.useState(!1),[M,z]=a.useState(Ro),[X,C]=a.useState(!1),[U,fe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),ae=a.useRef(null),Q=Bk(n.length);a.useEffect(()=>{if(!X)return;function he(Ie){ae.current?.contains(Ie.target)||C(!1)}function le(Ie){Ie.key==="Escape"&&C(!1)}return document.addEventListener("mousedown",he),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",he),document.removeEventListener("keydown",le)}},[X]);const de=e==="archived",Re=de&&y,ge=!de&&!G&&e!=="in-progress"&&n.length>Id;a.useEffect(()=>{z(he=>e==="in-progress"||de||n.length<=Id?Ro:Math.min(Math.max(he,Ro),n.length))},[e,de,n.length]);const Me=a.useCallback(he=>{de||(he.preventDefault(),he.dataTransfer.dropEffect="move",B(!0))},[de]),te=a.useCallback(he=>{he.currentTarget.contains(he.relatedTarget)||B(!1)},[]),Ce=a.useCallback(async he=>{he.preventDefault(),B(!1);const le=he.dataTransfer.getData("text/plain");if(!le)return;const Ie=n.find(Ze=>Ze.id===le);if(!(Ie&&Ie.column===e))try{await r(le,e)}catch(Ze){c(ve(Ze),"error")}},[e,r,c,n]),$e=a.useMemo(()=>e!=="in-progress"?[]:Uj(n,n,i),[e,n,i]),We=a.useMemo(()=>ge?n.slice(0,M):n,[ge,n,M]),Ge=Math.max(0,n.length-We.length),Ee=a.useCallback(()=>{z(he=>Math.min(he+Pd,n.length))},[n.length]),Ae=a.useCallback(async()=>{if(C(!1),!(n.length===0||!window.confirm(`Move all ${n.length} todo task${n.length===1?"":"s"} back to triage to be respecified?`))){fe(!0);try{const le=await Promise.allSettled(n.map(rt=>r(rt.id,"triage"))),Ie=le.filter(rt=>rt.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to triage for respec`,"success"):c(`Moved ${Ze} of ${le.length} tasks; ${Ie} failed`,"error")}finally{fe(!1)}}},[n,r,c]),Oe=a.useMemo(()=>n.filter(he=>!he.paused),[n]),ke=Oe.length,De=e==="todo"||e==="in-progress"||e==="in-review",se=U||ie||F,K=a.useCallback(async()=>{if(!(!o||(C(!1),ke===0)||!window.confirm(`Stop all ${ke} ${Tn[e].toLowerCase()} task${ke===1?"":"s"}?`))){re(!0);try{const le=await Promise.allSettled(Oe.map(rt=>o(rt.id))),Ie=le.filter(rt=>rt.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Stopped ${Ze} task${Ze===1?"":"s"}`,"success"):c(`Stopped ${Ze} of ${le.length} tasks; ${Ie} failed`,"error")}finally{re(!1)}}},[o,ke,e,Oe,c]),me=a.useCallback(async()=>{if(C(!1),!(n.length===0||!window.confirm(`Move all ${n.length} ${Tn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`))){ce(!0);try{const le=await Promise.allSettled(n.map(rt=>r(rt.id,"todo"))),Ie=le.filter(rt=>rt.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to Todo`,"success"):c(`Moved ${Ze} of ${le.length} tasks to Todo; ${Ie} failed`,"error")}finally{ce(!1)}}},[n,e,r,c]),ee=a.useCallback(async()=>{if(!(!x||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const le=await x();c(`Archived ${le.length} tasks`,"success")}catch(le){c(ve(le)||"Failed to archive tasks","error")}},[x,n.length,c]);return t.jsxs("div",{className:`column${V?" drag-over":""}${de?" column-archived":""}${Re?" column-collapsed":""}`,"data-column":e,onDragOver:Me,onDragLeave:te,onDrop:Ce,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Tn[e]}),t.jsx("span",{className:`column-count${Q?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&x&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:ee,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Jr,{size:16})}),de&&E&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:E,title:y?"Expand archived tasks":"Collapse archived tasks","aria-label":y?"Expand archived tasks":"Collapse archived tasks",children:y?t.jsx(zt,{size:16}):t.jsx(Zs,{size:16})}),De&&t.jsxs("div",{className:"column-menu",ref:ae,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>C(he=>!he),"aria-haspopup":"menu","aria-expanded":X,"aria-label":`${Tn[e]} column actions`,title:"Column actions",disabled:se,children:t.jsx(sg,{size:16})}),X&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ae(),disabled:n.length===0||U,children:["Respecify All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Triage"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void K(),disabled:ke===0||ie||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":ke===0?"All tasks are already paused":`Pause ${ke} active task${ke===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void me(),disabled:n.length===0||F,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!Re&&t.jsx("p",{className:"column-desc",children:Ok[e]}),!Re&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Nh,{onCreate:u,addToast:c,tasks:k??[],availableModels:T,onPlanningMode:N,onSubtaskBreakdown:S,projectId:s,autoExpand:!1,favoriteProviders:P,favoriteModels:_,onToggleFavorite:I,onToggleModelFavorite:D}),e==="in-progress"?$e.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):$e.map(he=>t.jsx(wh,{label:he.label,activeTasks:he.activeTasks,queuedTasks:he.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onOpenDetailWithTab:j,taskStuckTimeoutMs:$,onOpenMission:R,lastFetchTimeMs:w,workflowStepNameLookup:H},he.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[We.map(he=>t.jsx(Or,{task:he,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onOpenDetailWithTab:j,taskStuckTimeoutMs:$,onOpenMission:R,onMoveTask:r,lastFetchTimeMs:w,workflowStepNameLookup:H},he.id)),ge&&Ge>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ee,children:["Load ",Math.min(Pd,Ge)," more (",Ge," remaining)"]})]}),t.jsx(ao,{slotId:"board-column-footer",projectId:s})]})]})}const Sh=a.memo(Bj);Sh.displayName="Column";function Hj(e){return[...e].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 qj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const $d=new Map;function Vj(e,n){if(e.size!==n.size)return!1;for(const[s,i]of e)if(n.get(s)!==i)return!1;return!0}function Wj({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onArchiveAllDone:v,onLoadArchivedTasks:x,searchQuery:y="",availableModels:E,onPlanningMode:k,onSubtaskBreakdown:T,onOpenDetailWithTab:N,favoriteProviders:S,favoriteModels:j,onToggleFavorite:P,onToggleModelFavorite:_,taskStuckTimeoutMs:I,onOpenMission:D,lastFetchTimeMs:G}){const[$,R]=a.useState(!0),w=a.useRef(!1),{fetchBatch:H}=Yk(n),V=a.useRef(null),[B,M]=a.useState($d),z=y.trim()!=="",X=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),C=a.useCallback(()=>{R(ie=>{const re=!ie;return!re&&!w.current&&x&&(w.current=!0,x()),re})},[x]),U=a.useMemo(()=>{const ie=Object.fromEntries(ji.map(ce=>[ce,[]]));for(const ce of e)ie[ce.column].push(ce);const re=X.current,F={};for(const ce of ji){const ae=Hj(ie[ce]);F[ce]=qj(re[ce],ae)?re[ce]:ae}return X.current=F,F},[e]);a.useEffect(()=>{let ie=!1;return so(n).then(re=>{if(ie)return;const F=new Map(re.map(ce=>[ce.id,ce.name]));M(ce=>Vj(ce,F)?ce:F)}).catch(()=>{ie||M(re=>re.size===0?re:$d)}),()=>{ie=!0}},[n]);const fe=a.useMemo(()=>e.filter(ie=>ie.prInfo||ie.issueInfo).map(ie=>ie.id),[e]);return a.useEffect(()=>{if(fe.length!==0)return V.current&&clearTimeout(V.current),V.current=setTimeout(()=>{const ie=[];for(let re=0;re<fe.length;re+=50)ie.push(fe.slice(re,re+50));ie.forEach(re=>{H(re)})},500),()=>{V.current&&clearTimeout(V.current)}},[fe,H]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ji.map(ie=>t.jsx(Sh,{column:ie,tasks:U[ie],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,allTasks:e,availableModels:E,onOpenDetailWithTab:N,favoriteProviders:S,favoriteModels:j,onToggleFavorite:P,onToggleModelFavorite:_,isSearchActive:z,taskStuckTimeoutMs:I,onOpenMission:D,lastFetchTimeMs:G,workflowStepNameLookup:B,...ie==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:k,onSubtaskBreakdown:T}:{},...ie==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ie==="done"?{onArchiveAllDone:v}:{},...ie==="archived"?{collapsed:$,onToggleCollapse:C}:{}},ie))})})}const pa={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Dd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),$l=["id","title","status","column","dependencies","progress"];function Ld(e){try{const n=En("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>$l.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set($l)}function zd(e){try{const n=En("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Fd(e){try{const n=En("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>ji.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Od(e){try{const n=En("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function Gj(e){return e.status==="executing"||e.column==="in-progress"}function Ud(e){const n=jh(e);return n.total===0||!Gj(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function Kj({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:y="",lastFetchTimeMs:E}){const[k,T]=a.useState("id"),[N,S]=a.useState("desc"),[j,P]=a.useState(null),[_,I]=a.useState(null),[D,G]=a.useState(null),R=Za()==="mobile",[w,H]=a.useState(()=>Ld(b)),[V,B]=a.useState(()=>zd(b)),[M,z]=a.useState(()=>Fd(b));a.useEffect(()=>{typeof window<"u"&&cs("kb-dashboard-list-columns",JSON.stringify([...w]),b)},[b,w]),a.useEffect(()=>{typeof window<"u"&&cs("kb-dashboard-hide-done",V.toString(),b)},[V,b]),a.useEffect(()=>{typeof window<"u"&&cs("kb-dashboard-list-collapsed",JSON.stringify([...M]),b)},[M,b]);const[X,C]=a.useState(!1),U=a.useRef(null),[fe,ie]=a.useState(()=>Od(b));a.useEffect(()=>{H(Ld(b)),B(zd(b)),z(Fd(b)),ie(Od(b))},[b]),a.useEffect(()=>{typeof window<"u"&&cs("kb-dashboard-selected-tasks",JSON.stringify([...fe]),b)},[b,fe]);const re=a.useCallback(Z=>{ie(pe=>{const Se=new Set(pe);return Se.has(Z)?Se.delete(Z):Se.add(Z),Se})},[]),F=a.useCallback(()=>{ie(new Set)},[]),ce=a.useCallback(Z=>{H(pe=>{const Se=new Set(pe);return Se.has(Z)?Se.size>1&&Se.delete(Z):Se.add(Z),Se})},[]);a.useEffect(()=>{if(!X)return;const Z=Se=>{U.current&&!U.current.contains(Se.target)&&C(!1)},pe=Se=>{Se.key==="Escape"&&C(!1)};return document.addEventListener("mousedown",Z),document.addEventListener("keydown",pe),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",pe)}},[X]);const ae={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Q=a.useCallback(Z=>{k===Z?S(pe=>pe==="asc"?"desc":"asc"):(T(Z),S("asc"))},[k]),de=a.useCallback(Z=>{G(pe=>pe===Z?null:Z)},[]),Re=a.useCallback(Z=>{z(pe=>{const Se=new Set(pe);return Se.has(Z)?Se.delete(Z):Se.add(Z),Se})},[]),ge=a.useCallback(()=>{G(null)},[]),Me=a.useMemo(()=>{let Z=y?e.filter(ye=>ye.id.toLowerCase().includes(y.toLowerCase())||ye.title&&ye.title.toLowerCase().includes(y.toLowerCase())||ye.description.toLowerCase().includes(y.toLowerCase())):[...e];V&&!D&&(Z=Z.filter(ye=>ye.column!=="done"&&ye.column!=="archived"));const Se=[...D?Z.filter(ye=>ye.column===D):Z].sort((ye,Ke)=>{let Ne=0;switch(k){case"id":Ne=ye.id.localeCompare(Ke.id);break;case"title":Ne=(ye.title||ye.description).localeCompare(Ke.title||Ke.description);break;case"status":Ne=(ye.status||"").localeCompare(Ke.status||"");break;case"column":Ne=ye.column.localeCompare(Ke.column);break}return N==="asc"?Ne:-Ne}),Pe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Se.forEach(ye=>Pe[ye.column].push(ye)),Pe},[e,y,k,N,V,D]),te=a.useMemo(()=>Object.values(Me).reduce((Z,pe)=>Z+pe.length,0),[Me]),Ce=a.useMemo(()=>e.filter(Z=>Z.column==="done"||Z.column==="archived").length,[e]),$e=a.useMemo(()=>V?Ce:0,[V,Ce]),We=a.useCallback(()=>{const Z=Object.values(Me).flat().filter(pe=>pe.column!=="archived").map(pe=>pe.id);ie(pe=>{if(Z.every(Pe=>pe.has(Pe))){const Pe=new Set(pe);return Z.forEach(ye=>Pe.delete(ye)),Pe}else return new Set([...pe,...Z])})},[Me]),Ge=a.useMemo(()=>{const Z=Object.values(Me).flat().filter(pe=>pe.column!=="archived");return Z.length===0?!1:Z.every(pe=>fe.has(pe.id))},[Me,fe]),Ee=a.useMemo(()=>{const Z=Object.values(Me).flat().filter(Se=>Se.column!=="archived");if(Z.length===0)return!1;const pe=Z.filter(Se=>fe.has(Se.id)).length;return pe>0&&pe<Z.length},[Me,fe]),[Ae,Oe]=a.useState("__no_change__"),[ke,De]=a.useState("__no_change__"),[se,K]=a.useState(!1),me=a.useCallback(async()=>{if(fe.size===0)return;const Z=Array.from(fe).filter(Se=>{const Pe=e.find(ye=>ye.id===Se);return Pe&&Pe.column!=="archived"});if(Z.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const pe={taskIds:Z};if(Ae!=="__no_change__")if(Ae==="")pe.modelProvider=null,pe.modelId=null;else{const Se=Ae.indexOf("/");Se!==-1&&(pe.modelProvider=Ae.slice(0,Se),pe.modelId=Ae.slice(Se+1))}if(ke!=="__no_change__")if(ke==="")pe.validatorModelProvider=null,pe.validatorModelId=null;else{const Se=ke.indexOf("/");Se!==-1&&(pe.validatorModelProvider=ke.slice(0,Se),pe.validatorModelId=ke.slice(Se+1))}if(Object.keys(pe).length===1){i("No changes to apply","info");return}K(!0);try{const Se=await ax(pe.taskIds,pe.modelProvider,pe.modelId,pe.validatorModelProvider,pe.validatorModelId,void 0,void 0,b);f&&Se.updated.length>0&&f(Se.updated),i(`Updated ${Se.count} task${Se.count===1?"":"s"}`,"success"),F(),Oe("__no_change__"),De("__no_change__")}catch(Se){i(ve(Se)||"Failed to update models","error")}finally{K(!1)}},[fe,e,Ae,ke,b,i,F,f]),ee=a.useCallback(Z=>{s(Z)},[s]),he=a.useCallback((Z,pe)=>{if(pe.paused){Z.preventDefault();return}Z.dataTransfer.setData("text/plain",pe.id),Z.dataTransfer.effectAllowed="move",P(pe.id)},[]),le=a.useCallback(()=>{P(null),I(null)},[]),Ie=a.useCallback((Z,pe)=>{Z.preventDefault(),Z.dataTransfer.dropEffect="move",I(pe)},[]),Ze=a.useCallback(()=>{I(null)},[]),rt=a.useCallback(async(Z,pe)=>{Z.preventDefault(),I(null);const Se=Z.dataTransfer.getData("text/plain");if(Se){if(pe==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Se,pe)}catch(Pe){i(ve(Pe),"error")}}},[n,i]),oe=Z=>k!==Z?t.jsx(Hm,{size:14,className:"sort-icon"}):N==="asc"?t.jsx(ki,{size:14,className:"sort-icon active"}):t.jsx(qa,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:U,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>C(Z=>!Z),"aria-expanded":X,"aria-haspopup":"menu",children:[t.jsx(Yf,{size:14}),"Columns"]}),X&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:$l.map(Z=>{const pe=w.has(Z),Se=pe&&w.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Se?" disabled":""}`,role:"menuitem",title:Se?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:pe,onChange:()=>ce(Z),disabled:Se}),t.jsx("span",{children:ae[Z]})]},Z)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>B(Z=>!Z),"aria-pressed":V,title:V?"Show done tasks":"Hide done tasks",children:[V?t.jsx(ec,{size:14}):t.jsx(lg,{size:14}),V?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[D?`${te} of ${e.length} tasks in ${Tn[D]}`:`${te} of ${e.length} tasks`,$e>0&&!D&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",$e," hidden)"]}),D&&t.jsx("button",{className:"btn btn-sm",onClick:ge,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),fe.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[fe.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:F,children:"Clear"})]}),fe.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(jn,{models:c,value:Ae,onChange:Oe,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(jn,{models:c,value:ke,onChange:De,label:"Validator Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:me,disabled:se||Ae==="__no_change__"&&ke==="__no_change__",children:se?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:ji.map(Z=>{const pe=e.filter(Ke=>Ke.column===Z).length,Se=Z==="done"||Z==="archived",Pe=V&&Se?0:pe,ye=V&&Se&&pe>0;return t.jsxs("div",{className:`list-drop-zone${_===Z?" drag-over":""}${D===Z?" active":""}`,onClick:()=>de(Z),onDragOver:Ke=>Ie(Ke,Z),onDragLeave:Ze,onDrop:Ke=>rt(Ke,Z),"data-column":Z,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:pa[Z]}}),t.jsx("span",{className:"drop-zone-label",children:Tn[Z]}),t.jsx("span",{className:"drop-zone-count",children:ye?`${Pe} of ${pe}`:pe})]},Z)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Nh,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),te===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):R?t.jsx("div",{className:"list-cards",children:ji.map(Z=>{if(D&&Z!==D||V&&(Z==="done"||Z==="archived")&&!D)return null;const pe=Me[Z],Se=pe.length===0;if(y&&Se)return null;const Pe=M.has(Z);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>Re(Z),"aria-expanded":!Pe,role:"button",tabIndex:0,onKeyDown:ye=>{(ye.key==="Enter"||ye.key===" ")&&(ye.preventDefault(),Re(Z))},children:[t.jsx(an,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Tn[Z]}),t.jsx("span",{className:"list-section-count",children:pe.length})]}),!Pe&&t.jsx(t.Fragment,{children:Se?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):pe.map(ye=>{const Ke=ye.status==="failed",Ne=ye.paused===!0,Fe=Fr(ye,x,E),Ye=!r&&!Ke&&!Ne&&!Fe&&(ye.column==="in-progress"||Dd.has(ye.status)),xe=typeof ye.status=="string"&&ye.status.trim().length>0,ze=!!(ye.dependencies&&ye.dependencies.length>0),be=Ud(ye),Qe=be.hasProgress,it=fe.size>0;return t.jsxs("div",{className:`list-card${Ye?" agent-active":""}${it?" list-card--selectable":""}`,onClick:()=>ee(ye),"data-id":ye.id,children:[it&&t.jsx("label",{className:"list-card-checkbox",onClick:mt=>mt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:fe.has(ye.id),onChange:mt=>{mt.stopPropagation(),re(ye.id)},onClick:mt=>mt.stopPropagation(),disabled:ye.column==="archived","aria-label":`Select ${ye.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:ye.id}),ye.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),Fe?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):xe?t.jsx("span",{className:`list-status-badge list-status-badge--${ye.column}${Ke?" failed":""}${Ye?" pulsing":""}`,children:ye.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:ye.title||ye.description})}),(ze||Qe)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[ze&&t.jsxs("span",{className:"list-dep-badge",title:ye.dependencies.join(", "),children:[t.jsx(qi,{size:12})," ",ye.dependencies.length]}),Qe&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${be.percent}%`,backgroundColor:pa[ye.column]}})}),t.jsx("span",{className:"list-progress-label",children:be.label})]})]})]},ye.id)})})]},Z)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Ge,ref:Z=>{Z&&(Z.indeterminate=Ee)},onChange:We,"aria-label":"Select all visible tasks"})}),w.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("id"),children:["ID ",oe("id")]}),w.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("title"),children:["Title ",oe("title")]}),w.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("status"),children:["Status ",oe("status")]}),w.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("column"),children:["Column ",oe("column")]}),w.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),w.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ji.map(Z=>{if(D&&Z!==D||V&&(Z==="done"||Z==="archived")&&!D)return null;const pe=Me[Z],Se=pe.length===0;if(y&&Se)return null;const Pe=M.has(Z);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>Re(Z),"aria-expanded":!Pe,children:t.jsxs("th",{colSpan:w.size+1,className:"list-section-cell",children:[t.jsx(an,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Tn[Z]}),t.jsx("span",{className:"list-section-count",children:pe.length})]})}),!Pe&&t.jsx(t.Fragment,{children:Se?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:w.size+1,className:"list-empty-cell",children:"No tasks"})}):pe.map(ye=>{const Ke=ye.status==="failed",Ne=ye.paused===!0,Fe=Fr(ye,x,E),Ye=!r&&!Ke&&!Ne&&!Fe&&(ye.column==="in-progress"||Dd.has(ye.status)),xe=j===ye.id;return t.jsxs("tr",{className:`list-row${Ke?" failed":""}${Ne?" paused":""}${Fe?" stuck":""}${Ye?" agent-active":""}${xe?" dragging":""}`,onClick:()=>ee(ye),draggable:!Ne,onDragStart:ze=>he(ze,ye),onDragEnd:le,"data-id":ye.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:fe.has(ye.id),onChange:ze=>{ze.stopPropagation(),re(ye.id)},onClick:ze=>ze.stopPropagation(),disabled:ye.column==="archived","aria-label":`Select ${ye.id}`})}),w.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:ye.id}),w.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[ye.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:ye.title||ye.description})]})}),w.has("status")&&t.jsx("td",{className:"list-cell",children:Fe?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ye.status?t.jsx("span",{className:`list-status-badge list-status-badge--${ye.column}${Ke?" failed":""}${Ye?" pulsing":""}`,children:ye.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),w.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${pa[ye.column]}20`,color:pa[ye.column]},children:Tn[ye.column]})}),w.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:ye.dependencies&&ye.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:ye.dependencies.join(", "),children:[t.jsx(qi,{size:12})," ",ye.dependencies.length]}):"-"}),w.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const ze=Ud(ye);return ze.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${ze.percent}%`,backgroundColor:pa[ye.column]}})}),t.jsx("span",{className:"list-progress-label",children:ze.label})]}):"-"})()})]},ye.id)})})]},Z)})})]})]})]})}const Jj={active:{label:"Active",color:"var(--success)",icon:sn},paused:{label:"Paused",color:"var(--warning)",icon:Os},errored:{label:"Error",color:"var(--color-error)",icon:ns},initializing:{label:"Initializing",color:"var(--info)",icon:at}};function Yj(e){if(!e)return"Never";const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function Qj(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),i=e.slice(-Math.floor(n/2)+2);return`${s}...${i}`}function Xj(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,i=n.health;if(!s&&!i)return!0;if(!s||!i||s.activeTaskCount!==i.activeTaskCount||s.inFlightAgentCount!==i.inFlightAgentCount||s.totalTasksCompleted!==i.totalTasksCompleted||s.totalTasksFailed!==i.totalTasksFailed||s.status!==i.status)return!1;const r=e.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function Zj({project:e,health:n,onSelect:s,onPause:i,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:u=!1}){const[d,m]=a.useState(!1),h=Jj[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(k=>{k.stopPropagation(),i(e)},[i,e]),b=a.useCallback(k=>{k.stopPropagation(),r(e)},[r,e]),v=a.useCallback(k=>{if(k.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",y=e.status==="errored",E=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(kn,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),(l||c)&&t.jsxs("span",{className:"node-badge",title:`Assigned node: ${l?.name??c}`,children:["on: ",l?.name??c]}),t.jsx("span",{className:"project-card-path",title:e.path,children:Qj(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:E?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:Yj(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[x?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(sn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||E,title:E?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Os,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:u,title:"Open project","aria-label":"Open project",children:[t.jsx(Va,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:v,disabled:u,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(Bt,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const ew=a.memo(Zj,Xj);function tw(){return t.jsxs("div",{className:"project-overview project-overview--loading",children:[t.jsx("div",{className:"project-overview__header-skeleton",children:t.jsxs("div",{className:"project-overview__stats-row",children:[t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(kn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ss,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(en,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(ns,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__filters-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),t.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((e,n)=>t.jsxs("div",{className:"project-card project-card--skeleton",children:[t.jsxs("div",{className:"project-card-skeleton__header",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),t.jsxs("div",{className:"project-skeleton__text-group",children:[t.jsx("div",{className:"project-skeleton project-skeleton--title"}),t.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),t.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),t.jsxs("div",{className:"project-card-skeleton__health",children:[t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),t.jsxs("div",{className:"project-card-skeleton__footer",children:[t.jsx("div",{className:"project-skeleton project-skeleton--activity"}),t.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const nw=1e4,Bd=5;function sw(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let f=0;f<e.length;f+=Bd){const b=e.slice(f,f+Bd),v=await Promise.allSettled(b.map(async x=>{try{return await md(x)}catch{return null}}));if(b.forEach((x,y)=>{const E=v[y];p[x]=E.status==="fulfilled"?E.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async g=>{try{const p=await md(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},nw),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function iw({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[g,p]=a.useState("activity"),[f,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const G=localStorage.getItem("kb-dashboard-recent-projects");if(G)try{const $=JSON.parse(G);x($)}catch{}},[]);const[v,x]=a.useState([]),y=a.useMemo(()=>e.map(G=>G.id),[e]),{healthMap:E,loading:k}=sw(y),T=a.useMemo(()=>e.map(G=>({project:G,health:E[G.id]||null})),[e,E]),N=a.useMemo(()=>{let G=[...T];return u!=="all"&&(G=G.filter(({project:$})=>$.status===u)),m!==null&&(G=G.filter(({project:$})=>$.nodeId===m)),G},[T,u,m]),S=a.useMemo(()=>{const G=[...N];return G.sort(($,R)=>{let w=0;switch(g){case"name":w=$.project.name.localeCompare(R.project.name);break;case"activity":{const H=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,V=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt;w=new Date(V).getTime()-new Date(H).getTime();break}case"status":{const H={errored:0,initializing:1,paused:2,active:3};w=H[$.project.status]-H[R.project.status];break}}return f==="asc"?w:-w}),G},[N,g,f]),j=a.useMemo(()=>{const G=e.length,$=e.filter(z=>z.status==="active").length,R=e.filter(z=>z.status==="errored").length,w=new Set;e.forEach(z=>{z.nodeId&&w.add(z.nodeId)});const H=w.size||(G>0?1:0);let V=0,B=0,M=0;return Object.values(E).forEach(z=>{z&&(V+=z.activeTaskCount,B+=z.totalTasksCompleted,M+=z.inFlightAgentCount)}),{totalProjects:G,activeProjects:$,erroredProjects:R,totalNodes:H,totalActiveTasks:V,totalCompletedTasks:B,totalInFlightAgents:M}},[e,E]),P=a.useMemo(()=>({all:e.length,active:e.filter(G=>G.status==="active").length,paused:e.filter(G=>G.status==="paused").length,errored:e.filter(G=>G.status==="errored").length}),[e]),_=a.useMemo(()=>{const G=new Map;return e.forEach($=>{const R=$.nodeId,w=G.get(R);if(w)w.count++;else{const V=c.find(B=>B.id===R)?.name??$._sourceNodeName??"Local";G.set(R,{name:V,count:1})}}),Array.from(G.entries()).map(([$,{name:R,count:w}])=>({nodeId:$??null,name:R,count:w}))},[e,c]),I=a.useCallback(G=>{const $=[G.id,...v.filter(R=>R!==G.id)].slice(0,3);x($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(G)},[s,v]);return n||k&&e.length>0&&Object.keys(E).length===0?t.jsx(tw,{}):e.length===0?t.jsx("div",{className:"project-overview project-overview--empty",children:t.jsxs("div",{className:"project-empty-state",children:[t.jsx("div",{className:"project-empty-state__icon",children:t.jsx(Aa,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:i,children:[t.jsx(Ht,{size:16}),"Add Your First Project"]})]})}):t.jsxs("div",{className:"project-overview",children:[t.jsxs("div",{className:"project-overview__header",children:[t.jsxs("h2",{className:"project-overview__title",children:[t.jsx(Ci,{size:20}),"Projects"]}),t.jsxs("div",{className:"project-overview__stats",children:[t.jsxs("div",{className:"project-stat",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(kn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:j.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ss,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:j.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(en,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:j.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),j.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(ns,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:j.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),j.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ir,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:j.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(Ht,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${u==="all"?"active":""}`,onClick:()=>d("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:P.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:P.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:P.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${P.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:P.errored})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Ir,{size:14}),t.jsxs("select",{value:m??"",onChange:G=>{h(G.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),_.map(({nodeId:G,name:$,count:R})=>t.jsxs("option",{value:G??"",children:[$," (",R,")"]},G??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Tr,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:G=>{const[$,R]=G.target.value.split("-");p($),b(R)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(Hm,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:S.map(({project:G,health:$})=>{const R=c.find(H=>H.id===G.nodeId),w=R?void 0:G._sourceNodeName;return t.jsx(ew,{project:G,health:$,node:R,nodeNameFallback:w,onSelect:I,onPause:r,onResume:o,onRemove:l},G.id)})}),S.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Tr,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>d("all"),children:"Show All Projects"})]})]})}const aw=45e3,rw=3e3,ow=2e3,lw=1500,Hd="fusion:sse-client-id";let Pi=null;const ci=new Map;function qd(){const e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Ch(){if(!(typeof window>"u")){if(Pi)return Pi;try{const e=window.sessionStorage.getItem(Hd);if(e)return Pi=e,e;const n=qd();return window.sessionStorage.setItem(Hd,n),Pi=n,n}catch{return Pi=qd(),Pi}}}function Eh(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Mh(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function cw(e){const n=Ch();if(!n)return e;const s=Eh(e);return!s||!Mh(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function lc(e,n){const s=Ch();if(!s)return;const i=Eh(e);if(!i||!Mh(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=i.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),qs(`${r.pathname}${r.search}${r.hash}`)}function dw(e){if(typeof window>"u")return;const n=lc(e.url,"disconnect");if(!n)return;const s=window.navigator?.sendBeacon?.bind(window.navigator);s&&s(n)||typeof window.fetch=="function"&&window.fetch(n,{method:"POST",keepalive:!0}).catch(()=>{})}function ro(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Vd(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=lc(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),lw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function uw(e){ro(e),lc(e.url,"keepalive")&&(Vd(e),e.keepaliveTimer=window.setInterval(()=>{Vd(e)},ow))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ci.values()))if(!s.closed){if(ro(s),dw(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const i of Array.from(ci.values()))i.subscribers.size!==0&&(i.closed=!1,cc(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Ra(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{_h(e)},aw)}function _h(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),ro(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ci.get(e.url);if(!(!n||n!==e)){for(const s of e.subscribers)s.onReconnect?.();e.reconnectTimer=setTimeout(()=>{if(e.reconnectTimer=null,e.closed)return;const s=ci.get(e.url);s&&s===e&&e.subscribers.size>0&&cc(e)},rw)}}function cc(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(qs(cw(e.url)));e.es=n,uw(e),n.addEventListener("open",()=>{Ra(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const i of e.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of e.subscribers)i.onError?.(s);_h(e)}),n.addEventListener("message",()=>Ra(e)),n.addEventListener("heartbeat",()=>Ra(e)),Ah(e),Ra(e)}function Ah(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(e.nativeListeners.has(s))continue;const i=r=>{Ra(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const u of c)u(o)}};e.nativeListeners.set(s,i),e.es.addEventListener(s,i)}}function mw(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),ro(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ci.delete(e.url)}function Vs(e,n={}){let s=ci.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ci.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),cc(s),Ah(s);let r=!0;return()=>{if(!r)return;r=!1;const o=ci.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&mw(o))}}const dc="kb-planning-last-description",uc="kb-subtask-last-description",mc="kb-mission-last-goal";function hw(e,n){cs(dc,e,n)}function pw(e){return En(dc,e)||""}function $i(e){Ua(dc,e)}function fw(e,n){cs(uc,e,n)}function gw(e){return En(uc,e)||""}function To(e){Ua(uc,e)}function bw(e,n){cs(mc,e,n)}function xw(e){return En(mc,e)||""}function ai(e){Ua(mc,e)}function vw(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const i=s;if(n.id in i)return i[n.id]}return s}function yw(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(i=>i.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function kw(e){let n=0;const s=[];for(const i of e){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Cs({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=kw(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,u=!!o.thinkingOutput,d=s[l]??n,m=c?vw(o):void 0,h=o.question&&m!==void 0?yw(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Wd="fusion-tab-id";function jw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function _i(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Wd);if(e)return e;const n=jw();return window.sessionStorage.setItem(Wd,n),n}function oo(e){const n=a.useMemo(()=>_i(),[]),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(!1);a.useEffect(()=>{if(!e){i(!1),o(null),c(!1);return}let d=!0;return c(!0),Promise.resolve(dk(e,n)).then(m=>{if(d){if(m.acquired){i(!1),o(null);return}i(!0),o(m.currentHolder)}}).catch(()=>{d&&(i(!1),o(null))}).finally(()=>{d&&c(!1)}),()=>{d=!1;try{const m=uk(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),a.useEffect(()=>{if(!e||typeof window>"u")return;const d=()=>{if(typeof navigator.sendBeacon!="function")return;const m=qs(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[e,n]),a.useEffect(()=>!e||typeof EventSource>"u"?void 0:Vs("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const g=h.lockedByTab??null;o(g),i(!!(g&&g!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(mk(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const ww="fusion:ai-session-sync",Gd="fusion:ai-session-sync",Nw=3e4,Sw=6e4;function Ds(){return Date.now()}function Cw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Kd(e){if(!e||typeof e!="object")return null;const n=e;return typeof n.type!="string"||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)?null:e}class Ew{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=Cw(),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:Ds()})}broadcastUpdate(n){const s=n.timestamp??Ds();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??Ds();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=Ds();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=Ds();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Ds();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(ww),this.channel.onmessage=s=>{const i=Kd(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Gd||!s.newValue))try{const i=JSON.parse(s.newValue),r=Kd(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ds();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Nw)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Ds();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(Gd,JSON.stringify(i))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),i=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:i,heartbeats:r,timestamp:Ds()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,i=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),i&&this.emit()}applyTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(o&&i<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||i<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:i}),r&&this.emit()}updateHeartbeat(n,s,i=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),i&&this.emit())}emit(){const n=Ds(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const i=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>Sw;i.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const Ls=new Ew;function ra(){const e=a.useSyncExternalStore(c=>Ls.subscribe(c),()=>Ls.getSnapshot(),()=>Ls.getSnapshot());a.useEffect(()=>{Ls.requestSync()},[]);const n=a.useCallback(c=>{Ls.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Ls.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Ls.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Ls.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Ls.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Ls.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function Mw(e,n){return e&&n?`${e}/${n}`:""}function _w(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}const Aw=["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 Rw({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,b]=a.useState([]),[v,x]=a.useState(null),[y,E]=a.useState(!1),k=a.useRef(!1),[T,N]=a.useState(""),[S,j]=a.useState(!0),[P,_]=a.useState(!1),[I,D]=a.useState(!1),[G,$]=a.useState(!1),R=a.useRef(null),w=a.useRef(null),H=a.useRef(null),V=a.useRef(null),[B,M]=a.useState(o??null),z=a.useMemo(()=>_i(),[]),{isLockedByOther:X,takeControl:C,isLoading:U}=oo(e?B:null),{activeTabMap:fe,broadcastUpdate:ie,broadcastCompleted:re,broadcastLock:F,broadcastUnlock:ce,broadcastHeartbeat:ae}=ra(),[Q,de]=a.useState(void 0),[Re,ge]=a.useState(void 0),[Me,te]=a.useState([]),[Ce,$e]=a.useState(!0),[We,Ge]=a.useState(null),[Ee,Ae]=a.useState([]),[Oe,ke]=a.useState([]),De=Mw(Q,Re);a.useEffect(()=>{(async()=>{try{$e(!0);const Fe=await ss();te(Fe.models),Ae(Fe.favoriteProviders),ke(Fe.favoriteModels)}catch(Fe){Ge(ve(Fe)||"Failed to load models")}finally{$e(!1)}})()},[]);const se=a.useCallback(Ne=>{Ae(Fe=>{const Ye=Fe,ze=Ye.includes(Ne)?Ye.filter(be=>be!==Ne):[Ne,...Ye];return tn({favoriteProviders:ze,favoriteModels:Oe}).catch(()=>{Ae(Ye)}),ze})},[Oe]),K=a.useCallback(Ne=>{ke(Fe=>{const Ye=Fe,ze=Ye.includes(Ne)?Ye.filter(be=>be!==Ne):[Ne,...Ye];return tn({favoriteProviders:Ee,favoriteModels:ze}).catch(()=>{ke(Ye)}),ze})},[Ee]),me=a.useCallback((Ne,Fe)=>{if(!Ne||!Fe)return"Using default";const Ye=Me.find(xe=>xe.provider===Ne&&xe.id===Fe);return Ye?`${Ye.provider}/${Ye.id}`:`${Ne}/${Fe}`},[Me]),ee=a.useCallback(Ne=>{w.current?.close();const Fe=Xy(Ne,i,{onThinking:Ye=>{N(xe=>xe+Ye),ie({sessionId:Ne,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:Ye=>{_(!1),D(!1),ai(i),d({type:"question",sessionId:Ne,question:Ye}),N(""),E(!0),ie({sessionId:Ne,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:Ye=>{_(!1),D(!1),ai(i),d({type:"summary",sessionId:Ne,summary:Ye}),x(Ye),N(""),E(!0),ie({sessionId:Ne,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:Ye=>{const xe=Ye||"Session failed while contacting the AI.";_(!1),D(!1),h(null),d({type:"error",sessionId:Ne,errorMessage:xe}),N(""),E(!0),H.current=Ne,ie({sessionId:Ne,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),re({sessionId:Ne,status:"error"})},onComplete:()=>{_(!1),D(!1),H.current=null,re({sessionId:Ne,status:"complete"})},onConnectionStateChange:Ye=>{_(Ye==="reconnecting")}});w.current=Fe},[re,ie,l,i,z]),he=a.useCallback(async Ne=>{const Fe=Ne??l;if(Fe.trim()){h(null),N(""),p([]),b([]),_(!1),d({type:"loading"});try{const{sessionId:Ye}=await Ky(Fe.trim(),i,Q&&Re?{modelProvider:Q,modelId:Re}:void 0);H.current=Ye,M(Ye),ai(i),ee(Ye),p([])}catch(Ye){_(!1),h(ve(Ye)||"Failed to start interview session"),d({type:"initial"}),H.current=null,M(null)}}},[ee,l,Q,Re,i]);a.useEffect(()=>{e&&u.type==="initial"&&R.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!k.current&&u.type==="initial"){c(r);const Ne=setTimeout(()=>{k.current=!0,he(r)},0);return()=>clearTimeout(Ne)}else if(e&&!r&&!k.current&&u.type==="initial"){const Ne=xw(i);Ne&&c(Ne)}},[e,r,u.type,he]),a.useEffect(()=>{e||(k.current=!1,_(!1),D(!1),M(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Ne=!1;return Xs(o).then(Fe=>{if(Ne||!Fe)return;const Ye=Ki(Fe.conversationHistory);if(b(Ye),M(Fe.id),p(Ye.map(xe=>xe.response).filter(xe=>!!(xe&&typeof xe=="object"&&!Array.isArray(xe)))),Fe.status==="awaiting_input"&&Fe.currentQuestion)try{ai(i);const xe=JSON.parse(Fe.currentQuestion);H.current=Fe.id,E(!0),d({type:"question",sessionId:Fe.id,question:xe})}catch{h("Failed to restore session question.")}else if(Fe.status==="complete"&&Fe.result)try{ai(i);const xe=JSON.parse(Fe.result);H.current=Fe.id,E(!0),x(xe),d({type:"summary",sessionId:Fe.id,summary:xe})}catch{h("Failed to restore session result.")}else Fe.status==="generating"?(H.current=Fe.id,E(!0),Fe.thinkingOutput&&N(Fe.thinkingOutput),d({type:"loading"}),ee(Fe.id)):Fe.status==="error"&&(H.current=Fe.id,E(!0),h(null),d({type:"error",sessionId:Fe.id,errorMessage:Fe.error??"The session encountered an error."}))}).catch(()=>{Ne||h("Failed to resume session.")}),()=>{Ne=!0}},[ee,e,o,u.type,i]),a.useEffect(()=>{if(!e){V.current&&(ce(V.current,z),V.current=null);return}if(B&&V.current!==B){V.current&&ce(V.current,z),F(B,z),V.current=B;return}!B&&V.current&&(ce(V.current,z),V.current=null)},[F,ce,e,B,z]),a.useEffect(()=>{if(!e||!B||V.current!==B)return;ae(z);const Ne=setInterval(()=>{ae(z)},3e4);return()=>{clearInterval(Ne)}},[ae,e,B,z]),a.useEffect(()=>()=>{w.current?.close(),w.current=null,V.current&&(ce(V.current,z),V.current=null)},[ce,z]),a.useEffect(()=>{if(!e)return;const Ne=Fe=>{(u.type==="question"||u.type==="summary")&&(Fe.preventDefault(),Fe.returnValue=""),w.current?.close()};return window.addEventListener("beforeunload",Ne),()=>window.removeEventListener("beforeunload",Ne)},[e,u]);const le=a.useCallback(()=>{w.current?.close(),w.current=null,n()},[n]),Ie=a.useCallback(async()=>{if(l&&bw(l,i),!(y&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(w.current?.close(),w.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await ph(u.sessionId,i,z)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),N(""),_(!1),D(!1),E(!1),$(!1),de(void 0),ge(void 0),H.current=null,M(null),n()}},[l,y,u,n,i,z]);a.useEffect(()=>{if(!e)return;const Ne=Fe=>{Fe.key==="Escape"&&(y?confirm("Are you sure you want to close? Your interview progress will be lost.")&&Ie():Ie())};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[e,y,Ie]);const Ze=a.useCallback(async Ne=>{if(u.type!=="question")return;const{sessionId:Fe}=u;h(null),p(Ye=>[...Ye,Ne]),b(Ye=>[...Ye,{question:u.question,response:Ne}]),d({type:"loading"}),N("");try{ee(Fe),await Jy(Fe,Ne,i,z),E(!0)}catch(Ye){w.current?.close(),w.current=null,h(ve(Ye)||"Failed to submit response"),d({type:"question",sessionId:Fe,question:u.question})}},[u,i,z,ee]),rt=a.useCallback(async()=>{if(u.type!=="error")return;const Ne=u.sessionId;h(null),D(!0),N(""),d({type:"loading"}),ee(Ne);try{H.current=Ne,M(Ne),await Yy(Ne,i,z)}catch(Fe){let Ye=Fe;if((ve(Fe)||"").includes("not in an error state"))try{const ze=await Xs(Ne);if(!ze)throw new Error("Failed to refresh interview session.");const be=Ki(ze.conversationHistory);if(b(be),p(be.map(Qe=>Qe.response).filter(Qe=>!!(Qe&&typeof Qe=="object"&&!Array.isArray(Qe)))),H.current=ze.id,M(ze.id),E(!0),ze.status==="generating")N(ze.thinkingOutput??""),d({type:"loading"}),w.current?.isConnected()||ee(ze.id);else if(ze.status==="awaiting_input"){if(!ze.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ai(i);const Qe=JSON.parse(ze.currentQuestion);d({type:"question",sessionId:ze.id,question:Qe}),w.current?.isConnected()||ee(ze.id)}else if(ze.status==="complete"){if(!ze.result)throw new Error("Interview session is complete but has no result.");ai(i);const Qe=JSON.parse(ze.result);x(Qe),d({type:"summary",sessionId:ze.id,summary:Qe})}else ze.status==="error"&&d({type:"error",sessionId:ze.id,errorMessage:ze.error??"Retry failed. Please try again."});_(!1);return}catch(ze){Ye=ze}w.current?.close(),w.current=null,d({type:"error",sessionId:Ne,errorMessage:ve(Ye)||"Retry failed. Please try again."}),_(!1)}finally{D(!1)}},[ee,i,z,u]),oe=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const Ne=await Qy(u.sessionId,v||void 0,i);s(Ne),ai(i),w.current?.close(),w.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),N(""),_(!1),D(!1),E(!1),$(!1),H.current=null,M(null),n()}catch(Ne){h(ve(Ne)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),Z=()=>u.type==="question"?Math.min(g.length+1,6):6,pe=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Se=B?fe.get(B):null,Pe=Se&&Se.tabId!==z,ye=!!(Pe&&!Se.stale),Ke=X&&(!Pe||Se.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ne=>Ne.target===Ne.currentTarget&&Ie(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(es,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[pe&&t.jsx("button",{className:"modal-send-to-background",onClick:le,title:"Send to background","aria-label":"Send to background",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ie,"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),P&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ye&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(Pn,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref: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:l,onChange:Ne=>c(Ne.target.value),onKeyDown:Ne=>{Ne.key==="Enter"&&!Ne.shiftKey&&l.trim()&&(Ne.preventDefault(),he())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:Aw.map((Ne,Fe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Ne),children:Ne.length>45?Ne.slice(0,45)+"...":Ne},Fe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Ce&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(jn,{id:"mission-interview-modal-model",label:"Planning Model",value:De,onChange:Ne=>{const{provider:Fe,modelId:Ye}=_w(Ne);de(Fe),ge(Ye)},models:Me,disabled:Ce,favoriteProviders:Ee,onToggleFavorite:se,favoriteModels:Oe,onToggleModelFavorite:K}),We&&t.jsxs("div",{className:"form-hint form-hint-error",children:[We," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{$e(!0);const Ne=await ss();te(Ne.models),Ae(Ne.favoriteProviders),ke(Ne.favoriteModels),Ge(null)}catch(Ne){Ge(ve(Ne)||"Failed to load models")}finally{$e(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Q&&Re?"model-badge-custom":"model-badge-default"}`,children:me(Q,Re)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!l.trim(),children:[t.jsx(es,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(at,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:T?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>j(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&T&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:T})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:f}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void rt(),disabled:I,children:[I?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ie,disabled:I,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(Tw,{question:u.question,progress:Z(),historyEntries:f,onSubmit:Ze}),u.type==="summary"&&v&&t.jsx(Iw,{summary:v,historyEntries:f,onSummaryChange:x,onApprove:oe,onStartOver:()=>{d({type:"initial"}),E(!1),x(null),p([]),b([]),M(null),w.current?.close(),w.current=null},isCreating:G}),X&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Zr,{size:16}),t.jsx("span",{children:Ke?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ke&&t.jsx("button",{type:"button",onClick:()=>{C()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function Tw({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(en,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Tt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(Va,{size:16,className:"icon-ml-4"})]})})]})}function Iw({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((k,T)=>T))),[u,d]=a.useState(()=>{const k=new Set;return e.milestones.forEach((T,N)=>{T.slices.forEach((S,j)=>k.add(`${N}-${j}`))}),k}),m=k=>{c(T=>{const N=new Set(T);return N.has(k)?N.delete(k):N.add(k),N})},h=k=>{d(T=>{const N=new Set(T);return N.has(k)?N.delete(k):N.add(k),N})},g=(k,T)=>{const N=[...e.milestones];N[k]={...N[k],...T},s({...e,milestones:N})},p=(k,T,N)=>{const S=[...e.milestones],j=[...S[k].slices];j[T]={...j[T],...N},S[k]={...S[k],slices:j},s({...e,milestones:S})},f=(k,T,N,S)=>{const j=[...e.milestones],P=[...j[k].slices],_=[...P[T].features];_[N]={..._[N],...S},P[T]={...P[T],features:_},j[k]={...j[k],slices:P},s({...e,milestones:j})},b=k=>{const T=e.milestones.filter((N,S)=>S!==k);s({...e,milestones:T})},v=(k,T)=>{const N=[...e.milestones];N[k]={...N[k],slices:N[k].slices.filter((S,j)=>j!==T)},s({...e,milestones:N})},x=(k,T,N)=>{const S=[...e.milestones],j=[...S[k].slices];j[T]={...j[T],features:j[T].features.filter((P,_)=>_!==N)},S[k]={...S[k],slices:j},s({...e,milestones:S})},y=(k,T)=>{const N=[...e.milestones],S=[...N[k].slices];S[T]={...S[T],features:[...S[T].features,{title:"New feature",description:""}]},N[k]={...N[k],slices:S},s({...e,milestones:N})},E=e.milestones.reduce((k,T)=>k+T.slices.reduce((N,S)=>N+S.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(en,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",E," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:k=>s({...e,missionTitle:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,T)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(T),children:[l.has(T)?t.jsx(zt,{size:16,className:"icon-text-secondary"}):t.jsx(an,{size:16,className:"icon-text-secondary"}),t.jsx(Si,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:N=>g(T,{title:N.target.value}),onClick:N=>N.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:N=>{N.stopPropagation(),b(T)},title:"Remove milestone",children:t.jsx(Bt,{size:14,className:"icon-text-secondary"})})]}),l.has(T)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:k.description||"",onChange:N=>g(T,{description:N.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:k.verification||"",onChange:N=>g(T,{verification:N.target.value})})]}),k.slices.map((N,S)=>{const j=`${T}-${S}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(j),children:[u.has(j)?t.jsx(zt,{size:14,className:"icon-text-secondary"}):t.jsx(an,{size:14,className:"icon-text-secondary"}),t.jsx(El,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:N.title,onChange:P=>p(T,S,{title:P.target.value}),onClick:P=>P.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:P=>{P.stopPropagation(),v(T,S)},title:"Remove slice",children:t.jsx(Bt,{size:12,className:"icon-text-secondary"})})]}),u.has(j)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:N.verification||"",onChange:P=>p(T,S,{verification:P.target.value})})]}),N.features.map((P,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(jl,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:P.title,onChange:I=>f(T,S,_,{title:I.target.value})}),P.description&&t.jsx("p",{className:"roadmap-feature-text",children:P.description}),P.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",P.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(T,S,_),title:"Remove feature",children:t.jsx(Bt,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(T,S),children:[t.jsx(Ht,{size:12}),"Add Feature"]})]})]},S)})]})]},T))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(na,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(en,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function Pw({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[b,v]=a.useState([]),[x,y]=a.useState(null),[E,k]=a.useState(""),[T,N]=a.useState(!0),[S,j]=a.useState(!1),[P,_]=a.useState(!1),I=a.useRef(null),D=a.useRef(null),G=a.useRef(null),$=a.useRef(null),[R,w]=a.useState(null),H=a.useMemo(()=>_i(),[]);oo(e?R:null);const{activeTabMap:V,broadcastUpdate:B,broadcastCompleted:M,broadcastLock:z,broadcastUnlock:X,broadcastHeartbeat:C}=ra(),U=i==="milestone"?Zy:ik,fe=i==="milestone"?ek:ak,ie=i==="milestone"?tk:rk,re=i==="milestone"?nk:ok,F=i==="milestone"?sk:lk,ce=i==="milestone"?"Milestone":"Slice",ae=i==="milestone"?"milestone_interview":"slice_interview",Q=a.useCallback(ke=>{D.current?.close();const De=ie(ke,c,{onThinking:se=>{k(K=>K+se),B({sessionId:ke,status:"generating",needsInput:!1,owningTabId:H,type:ae,title:o,projectId:c??null})},onQuestion:se=>{j(!1),de(),m({type:"question",sessionId:ke,question:se}),k(""),B({sessionId:ke,status:"awaiting_input",needsInput:!0,owningTabId:H,type:ae,title:o,projectId:c??null})},onSummary:se=>{j(!1),de(),m({type:"summary",sessionId:ke,summary:se}),y(se),k(""),B({sessionId:ke,status:"complete",needsInput:!1,owningTabId:H,type:ae,title:o,projectId:c??null})},onError:se=>{const K=se||"Session failed while contacting the AI.";j(!1),g(null),m({type:"error",sessionId:ke,errorMessage:K}),k(""),G.current=ke,B({sessionId:ke,status:"error",needsInput:!1,owningTabId:H,type:ae,title:o,projectId:c??null}),M({sessionId:ke,status:"error"})},onComplete:()=>{j(!1),G.current=null,M({sessionId:ke,status:"complete"})},onConnectionStateChange:se=>{j(se==="reconnecting")}});D.current=De},[M,B,ie,ae,c,H,o]),de=()=>{y(null),f([]),v([]),k("")},Re=a.useCallback(async()=>{g(null),de(),j(!1),m({type:"loading"});try{const{sessionId:ke}=await U(r,c);G.current=ke,w(ke),Q(ke)}catch(ke){j(!1),g(ve(ke)||`Failed to start ${ce.toLowerCase()} interview`),m({type:"initial"}),G.current=null,w(null)}},[Q,c,U,r,ce]),ge=a.useCallback(async()=>{g(null),_(!0);try{await F(r,c),s(),m({type:"applied"})}catch(ke){g(ve(ke)||`Failed to skip ${ce.toLowerCase()} interview`),_(!1)}},[s,c,F,r,ce]);a.useEffect(()=>{e&&d.type==="initial"&&I.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let ke=!1;return Xs(u).then(De=>{if(ke||!De)return;const se=Ki(De.conversationHistory);if(v(se),w(De.id),f(se.map(K=>K.response).filter(K=>!!(K&&typeof K=="object"&&!Array.isArray(K)))),De.status==="awaiting_input"&&De.currentQuestion)try{const K=JSON.parse(De.currentQuestion);G.current=De.id,m({type:"question",sessionId:De.id,question:K})}catch{g("Failed to restore session question.")}else if(De.status==="complete"&&De.result)try{const K=JSON.parse(De.result);G.current=De.id,y(K),m({type:"summary",sessionId:De.id,summary:K})}catch{g("Failed to restore session result.")}else De.status==="generating"?(G.current=De.id,De.thinkingOutput&&k(De.thinkingOutput),m({type:"loading"}),Q(De.id)):De.status==="error"&&(G.current=De.id,g(null),m({type:"error",sessionId:De.id,errorMessage:De.error??"The session encountered an error."}))}).catch(()=>{ke||g("Failed to resume session.")}),()=>{ke=!0}},[Q,e,u,d.type]),a.useEffect(()=>{e||(j(!1),w(null))},[e]),a.useEffect(()=>{if(!(!e||!R)){if($.current!==R){$.current&&X($.current,H),z(R,H),$.current=R;return}!R&&$.current&&(X($.current,H),$.current=null)}},[z,X,e,R,H]),a.useEffect(()=>{if(!e||!R||$.current!==R)return;C(H);const ke=setInterval(()=>{C(H)},3e4);return()=>{clearInterval(ke)}},[C,e,R,H]),a.useEffect(()=>()=>{D.current?.close(),D.current=null,$.current&&(X($.current,H),$.current=null)},[X,H]);const Me=a.useCallback(()=>{D.current?.close(),D.current=null,n()},[n]),te=a.useCallback(async()=>{D.current?.close(),D.current=null,de(),m({type:"initial"}),g(null),G.current=null,w(null),n()},[n]),Ce=a.useCallback(async ke=>{if(d.type!=="question")return;const{sessionId:De}=d;g(null),f(se=>[...se,ke]),v(se=>[...se,{question:d.question,response:ke}]),m({type:"loading"}),k("");try{Q(De),await fe(De,ke,c,H)}catch(se){D.current?.close(),D.current=null,g(ve(se)||"Failed to submit response"),m({type:"question",sessionId:De,question:d.question})}},[Q,c,fe,H,d]),$e=a.useCallback(async()=>{if(d.type==="summary"){g(null),_(!0);try{await re(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(ke){g(ve(ke)||"Failed to apply interview results"),_(!1)}}},[re,x,s,c,d]),We=()=>d.type==="question"?Math.min(p.length+1,6):6,Ge=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ee=R?V.get(R):null,Oe=!!(Ee&&Ee.tabId!==H&&!Ee.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ke=>ke.target===ke.currentTarget&&te(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Pn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",ce,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ge&&t.jsx("button",{className:"modal-send-to-background",onClick:Me,title:"Send to background","aria-label":"Send to background",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),S&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Oe&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(Pn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",ce," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",i,"'s scope, acceptance criteria, and verification methods. Each ",i," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void Re(),children:[t.jsx(Pn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ge(),disabled:P,children:[P?t.jsx(at,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(at,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:E?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!T),type:"button",children:T?"Hide thinking":"Show thinking"}),T&&E&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:E})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx($w,{question:d.question,progress:We(),historyEntries:b,onSubmit:Ce}),d.type==="summary"&&x&&t.jsx(Dw,{summary:x,historyEntries:b,onSummaryChange:y,onApply:$e,onCancel:te,isApplying:P}),d.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(en,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ce," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",d.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function $w({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(en,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Tt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(Va,{size:16,className:"icon-ml-4"})]})})]})}function Dw({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,g)=>{const p={...l,[h]:g};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(zt,{size:16}):t.jsx(an,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:o,children:[o?t.jsx(at,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const fa={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)"}},mr={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)"}},hr={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)"}},pr={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)"}},Lw=3;function zw(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Xd({state:e}){const n=e==="planned"?"mission-plan-state-indicator--planned":e==="needs_update"?"mission-plan-state-indicator--needs-update":"mission-plan-state-indicator--not-started",s=e==="planned"?"Planned":e==="needs_update"?"Needs update":"Not planned";return t.jsx("span",{className:`mission-plan-state-indicator ${n}`,title:s,"aria-label":s})}function Zd(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Io={title:"",description:"",status:"planning",autopilotEnabled:!1},Po={title:"",description:"",status:"planning",dependencies:[]},$o={title:"",description:"",status:"pending"},Do={title:"",description:"",acceptanceCriteria:"",status:"defined"},Fw=3600*1e3;function Ur(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const i=Math.floor(s/(60*1e3));if(i<1)return"just now";if(i<60)return`${i}m ago`;const r=Math.floor(i/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function Ow(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=Fw,s=e.totalTasks>0&&e.tasksFailed>e.totalTasks*.3;return n||s?"error":e.tasksFailed>0?"warning":e.tasksFailed===0&&e.tasksInFlight<=e.totalTasks?"healthy":"warning"}function Uw(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.missionId=="string"&&typeof n.tasksCompleted=="number"&&typeof n.tasksFailed=="number"&&typeof n.tasksInFlight=="number"&&typeof n.totalTasks=="number"&&typeof n.estimatedCompletionPercent=="number"}function Bw(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.id=="string"&&typeof n.missionId=="string"&&typeof n.eventType=="string"&&typeof n.description=="string"&&typeof n.timestamp=="string"}function Lo(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.rollup?.milestoneId=="string"&&typeof n.rollup?.state=="string"&&Array.isArray(n.validationTelemetry?.validationRounds)&&typeof n.validationTelemetry?.totalRuns=="number"&&n.validationContract!==void 0&&Array.isArray(n.fixFeatures)}const Rh=["feature_triaged","feature_completed"],Th=["slice_activated","slice_completed","milestone_completed"],Ih=["mission_started","mission_paused","mission_resumed","mission_completed"],Ph=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function eu(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Ih.includes(e);case"tasks":return Rh.includes(e);case"slices":return Th.includes(e);case"autopilot":return Ph.includes(e);default:return!0}}function Hw(e){return e==="error"||e==="warning"?"mission-event__type--error":Ih.includes(e)?"mission-event__type--state":Rh.includes(e)?"mission-event__type--task":Th.includes(e)?"mission-event__type--slice":Ph.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function qw(e){return e.replace(/_/g," ")}function Vw(e,n){return n?e==="watching"?`Watching since ${Ur(n)}`:`Last activation ${Ur(n)}`:null}function Ww({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,b]=a.useState(null),[v,x]=a.useState(!0),[y,E]=a.useState(!1),[k,T]=a.useState(!1),[N,S]=a.useState(null),[j,P]=a.useState(Io),[_,I]=a.useState(!1),[D,G]=a.useState(new Set),[$,R]=a.useState(new Set),[w,H]=a.useState(null),[V,B]=a.useState(Po),[M,z]=a.useState(!1),[X,C]=a.useState(null),[U,fe]=a.useState($o),[ie,re]=a.useState(!1),[F,ce]=a.useState(null),[ae,Q]=a.useState(null),[de,Re]=a.useState(Do),[ge,Me]=a.useState(!1),[te,Ce]=a.useState(null),[$e,We]=a.useState(null),[Ge,Ee]=a.useState(""),[Ae,Oe]=a.useState(!1),[ke,De]=a.useState([]),[se,K]=a.useState(void 0),me=se??c,[ee,he]=a.useState(null),[le,Ie]=a.useState(null),[Ze,rt]=a.useState(null);a.useEffect(()=>{h&&me&&Oe(!0)},[h,me]),a.useEffect(()=>{if(!h||me)return;let O=!1;return fh(r).then(je=>{if(O)return;const Te=je.filter(pt=>pt.type==="mission_interview"&&(pt.status==="awaiting_input"||pt.status==="error"));De(Te)}).catch(je=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",je)}),()=>{O=!0}},[h,r,me]),a.useEffect(()=>{if(!h||!d)return;let O=!1;return Xs(d).then(je=>{if(!(O||!je))try{const Te=JSON.parse(je.inputPayload||"{}");Te.targetId&&Te.targetType&&he({type:Te.targetType,id:Te.targetId,title:Te.targetTitle||je.title,resumeSessionId:d})}catch{he({type:"milestone",id:"",title:je.title,resumeSessionId:d})}}).catch(je=>{O||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",je),m?.())}),()=>{O=!0}},[h,d,m]);const[oe,Z]=a.useState(null),[pe,Se]=a.useState(new Map),[Pe,ye]=a.useState(null),[Ke,Ne]=a.useState({title:"",assertion:"",status:"pending"}),[Fe,Ye]=a.useState(!1),[xe,ze]=a.useState(null),[be,Qe]=a.useState(new Map),[it,mt]=a.useState(new Set),[At,It]=a.useState(new Set),[Dt,Ut]=a.useState(null),[jt,Pt]=a.useState(new Map),[He,ut]=a.useState(null),[$t,St]=a.useState(null),[Yt,we]=a.useState(!0),[et,ct]=a.useState(new Set),[ue,A]=a.useState(new Map),[J,Ve]=a.useState(null),[dt,yt]=a.useState(new Map),[qt,wn]=a.useState(null),[Ft,Dn]=a.useState(new Map),[qn,ms]=a.useState(new Map),[hn,Ln]=a.useState("structure"),[Nn,pn]=a.useState([]),Vn=a.useRef([]),cn=a.useRef([]),Ct=a.useRef(null),xn=a.useRef(null),Wn=a.useRef("structure"),vn=a.useRef("all"),[Mn,hs]=a.useState(!1),[ps,zn]=a.useState(0),[W,Le]=a.useState("all"),[nt,tt]=a.useState(new Set),ht=a.useRef(null),kt=a.useRef(null);cn.current=g,Ct.current=f,xn.current=He,Wn.current=hn,vn.current=W;const Et=a.useCallback((O="auto")=>{const je=kt.current;if(je&&typeof je.scrollIntoView=="function"){je.scrollIntoView({block:"end",behavior:O});return}const Te=ht.current;Te&&(Te.scrollTop=Te.scrollHeight)},[]),fn=a.useCallback(()=>{const O=ht.current;return O?O.scrollHeight-O.scrollTop-O.clientHeight<=100:!0},[]),fs=a.useCallback(async O=>{if(O.length===0){ms(new Map);return}const je=await ky(r);ms(Te=>{const pt=new Map(Te);for(const[Gt,wt]of Object.entries(je))Uw(wt)&&pt.set(Gt,wt);return pt})},[r]),Qt=a.useCallback(async()=>{try{x(!0);const O=await gy(r);p(O),fs(O)}catch(O){i(ve(O)||"Failed to load missions","error")}finally{x(!1)}},[i,r,fs]),xt=a.useCallback(async O=>{try{E(!0);const je=await hh(O,r);if(b(je),je.milestones.length>0){const Te=je.milestones[0].id;ut(Te),we(!0),G(new Set([Te])),Co(Te,r).then(pt=>{Se(Gt=>{const wt=new Map(Gt);return wt.set(Te,pt),wt})}).catch(()=>{}),Eo(Te,r).then(pt=>{Pt(Gt=>{const wt=new Map(Gt);return wt.set(Te,pt),wt})}).catch(()=>{}),je.milestones[0].slices.length>0&&R(new Set([je.milestones[0].slices[0].id]))}else ut(null),St(null)}catch(je){i(ve(je)||"Failed to load mission details","error")}finally{E(!1)}},[i,r]);a.useEffect(()=>{if(!h||!He){St(null);return}let O=!1;return St(null),pd(He,r).then(je=>{if(!O){if(!Lo(je)){St(null);return}St(je),Pt(Te=>{const pt=new Map(Te);return pt.set(He,je.rollup),pt})}}).catch(()=>{O||St(null)}),()=>{O=!0}},[h,He,r]),a.useEffect(()=>{we(!0)},[He]);const lt=a.useCallback(O=>{!O||O!==xn.current||pd(O,r).then(je=>{xn.current!==O||!Lo(je)||(St(je),Pt(Te=>{const pt=new Map(Te);return pt.set(O,je.rollup),pt}))}).catch(()=>{})},[r]),ne=a.useCallback(async(O,je)=>{const Te=je?.append??!1,pt=Te?Vn.current.length:0;Te||(hs(!0),tt(new Set));try{const Gt=await yy(O,{limit:50,offset:pt,eventType:void 0},r),wt=Gt.events.filter(Ot=>eu(Ot.eventType,W));pn(Ot=>{if(!Te)return wt;const Ue=new Set(Ot.map(ft=>ft.id)),Be=[...Ot];for(const ft of wt)Ue.has(ft.id)||Be.push(ft);return Be}),zn(Gt.total),Te||requestAnimationFrame(()=>{Et("auto")})}catch(Gt){i(ve(Gt)||"Failed to load mission activity","error")}finally{Te||hs(!1)}},[i,W,r,Et]);a.useEffect(()=>{Vn.current=Nn},[Nn]),a.useEffect(()=>{h&&(Qt(),b(null),ut(null),St(null),pn([]),zn(0),Ln("structure"),Le("all"),tt(new Set))},[h,Qt]);const _e=a.useRef(null);a.useEffect(()=>{h&&u&&_e.current!==u&&g.length>0&&(_e.current=u,xt(u))},[h,u,g,xt]),a.useEffect(()=>{h||(_e.current=null)},[h]),a.useEffect(()=>{!h||!f||hn!=="activity"||ne(f.id)},[hn,h,ne,f,W]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const O=new URLSearchParams;r&&O.set("projectId",r);const je=`/api/events${O.size>0?`?${O.toString()}`:""}`,Te=()=>{fs(cn.current)},pt=Cn=>{Te();const on=Cn;if(on.data)try{const Mt=JSON.parse(on.data);Mt?.id&&p(fi=>fi.map(ys=>ys.id===Mt.id?{...ys,...Mt}:ys))}catch{}Ct.current&&xt(Ct.current.id)},Gt=Cn=>{Te(),Ct.current&&xt(Ct.current.id)},wt=()=>{Te(),Ct.current&&xt(Ct.current.id)},Ot=Cn=>{Te(),Ct.current&&xt(Ct.current.id)},Ue=Cn=>{const on=Cn;if(on.data)try{const Mt=JSON.parse(on.data);Mt&&Mt.featureId&&(Ks(Mt.featureId),Ps(Mt.featureId),Mt.milestoneId&&lt(Mt.milestoneId))}catch{}},Be=Cn=>{const on=Cn;if(on.data)try{const Mt=JSON.parse(on.data);Mt&&Mt.featureId&&(Ks(Mt.featureId),Ps(Mt.featureId),Mt.milestoneId&&lt(Mt.milestoneId),Ct.current&&xt(Ct.current.id))}catch{}},ft=Cn=>{const on=Cn;if(on.data)try{const Mt=JSON.parse(on.data);Mt&&Mt.milestoneId&&(Je(Mt.milestoneId),lt(Mt.milestoneId))}catch{}},Kt=Cn=>{const on=Cn;if(on.data)try{const Mt=JSON.parse(on.data);Mt&&Mt.milestoneId&&(Y(Mt.milestoneId),Je(Mt.milestoneId),lt(Mt.milestoneId))}catch{}};return Vs(je,{events:{"mission:updated":pt,"slice:updated":Gt,"feature:updated":wt,"milestone:updated":Ot,"mission:event":Cn=>{Te();const on=Ct.current;if(!on||Wn.current!=="activity")return;const Mt=fn(),fi=Cn;if(fi.data)try{const ys=JSON.parse(fi.data);if(!Bw(ys)||ys.missionId!==on.id||!eu(ys.eventType,vn.current))return;pn(Ys=>{const wo=Ys.filter(No=>No.id!==ys.id);return[ys,...wo].slice(0,100)}),zn(Ys=>Ys+1),Mt&&requestAnimationFrame(()=>{const Ys=ht.current;Ys&&(Ys.scrollTop=0)})}catch{}},"validator-run:started":Ue,"validator-run:completed":Be,"milestone:validation:updated":ft,"assertion:created":Kt,"assertion:updated":Kt,"assertion:deleted":Kt,"assertion:linked":Kt,"assertion:unlinked":Kt,"fix-feature:created":Cn=>{const on=Cn;if(on.data)try{const Mt=JSON.parse(on.data);if(Mt&&Mt.sourceFeatureId){Ks(Mt.sourceFeatureId);const fi=Mt?.feature?.sliceId,ys=Ct.current;if(fi&&ys){const Ys=ys.milestones.find(wo=>wo.slices.some(No=>No.id===fi));Ys&&lt(Ys.id)}Ct.current&&xt(Ct.current.id)}}catch{}}}})},[h,fn,xt,fs,r,lt]);const st=a.useCallback(()=>{T(!0),S(null),P(Io)},[]),gt=a.useCallback(O=>{S(O.id),T(!1),P({title:O.title,description:O.description||"",status:O.status,autopilotEnabled:O.autopilotEnabled??!1})},[]),bt=a.useCallback(()=>{S(null),T(!1),P(Io)},[]),rn=a.useCallback(async()=>{if(!j.title.trim()){i("Mission title is required","error");return}try{if(I(!0),k)await by({title:j.title.trim(),description:j.description.trim()||void 0,autopilotEnabled:j.autopilotEnabled},r),i("Mission created","success");else if(N){const O={title:j.title.trim(),description:j.description.trim()||void 0,status:j.status,autopilotEnabled:j.autopilotEnabled};j.autopilotEnabled&&(O.autoAdvance=!0),await xy(N,O,r),i("Mission updated","success"),f?.id===N&&await xt(N)}await Qt(),bt()}catch(O){i(ve(O)||"Failed to save mission","error")}finally{I(!1)}},[j,k,N,i,Qt,xt,f,bt,r]),Xt=a.useCallback(async O=>{try{await vy(O,r),i("Mission deleted","success"),f?.id===O&&b(null),await Qt(),Z(null)}catch(je){i(ve(je)||"Failed to delete mission","error")}},[i,Qt,f,r]),ln=a.useCallback(()=>{z(!0),H(null),B(Po)},[]),Wt=a.useCallback(O=>{H(O.id),z(!1),B({title:O.title,description:O.description||"",status:O.status,dependencies:O.dependencies})},[]),gn=a.useCallback(()=>{H(null),z(!1),B(Po)},[]),Sn=a.useCallback(async()=>{if(!V.title.trim()){i("Milestone title is required","error");return}try{I(!0),M&&f?(await jy(f.id,{title:V.title.trim(),description:V.description.trim()||void 0,dependencies:V.dependencies},r),i("Milestone created","success")):w&&(await wy(w,{title:V.title.trim(),description:V.description.trim()||void 0,status:V.status,dependencies:V.dependencies},r),i("Milestone updated","success")),await xt(f.id),gn()}catch(O){i(ve(O)||"Failed to save milestone","error")}finally{I(!1)}},[V,M,w,f,i,xt,gn,j.title,r]),gs=a.useCallback(async O=>{try{await Ny(O,r),i("Milestone deleted","success"),await xt(f.id),Z(null)}catch(je){i(ve(je)||"Failed to delete milestone","error")}},[i,xt,f,r]),Fn=a.useCallback(O=>{ut(O),we(!0),G(je=>{const Te=new Set(je);return!Te.has(O)?(Te.add(O),Co(O,r).then(Gt=>{Se(wt=>{const Ot=new Map(wt);return Ot.set(O,Gt),Ot})}).catch(()=>{}),Eo(O,r).then(Gt=>{Pt(wt=>{const Ot=new Map(wt);return Ot.set(O,Gt),Ot})}).catch(()=>{})):Te.delete(O),Te})},[r]),Gn=a.useCallback(O=>{ce(O),re(!0),C(null),fe($o)},[]),On=a.useCallback(O=>{C(O.id),re(!1),fe({title:O.title,description:O.description||"",status:O.status})},[]),Kn=a.useCallback(()=>{C(null),re(!1),ce(null),fe($o)},[]),dn=a.useCallback(async()=>{if(!U.title.trim()){i("Slice title is required","error");return}try{I(!0),ie&&F?(await Sy(F,{title:U.title.trim(),description:U.description.trim()||void 0},r),i("Slice created","success")):X&&(await Cy(X,{title:U.title.trim(),description:U.description.trim()||void 0,status:U.status},r),i("Slice updated","success")),await xt(f.id),Kn()}catch(O){i(ve(O)||"Failed to save slice","error")}finally{I(!1)}},[U,ie,X,F,f,i,xt,Kn,r]),Jn=a.useCallback(async O=>{try{await Ey(O,r),i("Slice deleted","success"),await xt(f.id),Z(null)}catch(je){i(ve(je)||"Failed to delete slice","error")}},[i,xt,f,r]),Es=a.useCallback(async O=>{try{await My(O,r),i("Slice activated","success"),await xt(f.id)}catch(je){i(ve(je)||"Failed to activate slice","error")}},[i,xt,f,r]),Ts=a.useCallback(O=>{R(je=>{const Te=new Set(je);return Te.has(O)?Te.delete(O):Te.add(O),Te})},[]),as=a.useCallback(O=>{Ce(O),Me(!0),Q(null),Re(Do)},[]),_n=a.useCallback(O=>{Q(O.id),Me(!1),Re({title:O.title,description:O.description||"",acceptanceCriteria:O.acceptanceCriteria||"",status:O.status})},[]),bs=a.useCallback(()=>{Q(null),Me(!1),Ce(null),Re(Do)},[]),An=a.useCallback(async()=>{if(!de.title.trim()){i("Feature title is required","error");return}try{I(!0),ge&&te?(await _y(te,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):ae&&(await Ay(ae,{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 xt(f.id),bs()}catch(O){i(ve(O)||"Failed to save feature","error")}finally{I(!1)}},[de,ge,ae,te,f,i,xt,bs,r]),ca=a.useCallback(async O=>{try{await Ry(O,r),i("Feature deleted","success"),await xt(f.id),Z(null)}catch(je){i(ve(je)||"Failed to delete feature","error")}},[i,xt,f,r]),po=a.useCallback(async()=>{if(!$e||!Ge.trim()){i("Task ID is required","error");return}try{await Ty($e,Ge.trim(),r),i("Feature linked to task","success"),await xt(f.id),We(null),Ee("")}catch(O){i(ve(O)||"Failed to link feature to task","error")}},[$e,Ge,i,xt,f,r]),fo=a.useCallback(async O=>{try{await Iy(O,r),i("Feature unlinked from task","success"),await xt(f.id)}catch(je){i(ve(je)||"Failed to unlink feature","error")}},[i,xt,f,r]),mi=a.useCallback(async O=>{try{I(!0),await Py(O,void 0,void 0,r),i("Feature triaged — task created","success"),await xt(f.id)}catch(je){i(ve(je)||"Failed to triage feature","error")}finally{I(!1)}},[i,xt,f,r]),sr=a.useCallback(async O=>{rt(O);try{const je=await ck(O,r);Ie({featureId:O,enrichedDescription:je.description})}catch{await mi(O)}finally{rt(null)}},[mi,r]),si=a.useCallback(async()=>{le&&(Ie(null),await mi(le.featureId))},[mi,le]),go=a.useCallback(()=>{Ie(null)},[]),ir=a.useCallback(async O=>{try{I(!0);const je=await $y(O,r);i(`Triaged ${je.count} feature${je.count!==1?"s":""}`,"success"),await xt(f.id)}catch(je){i(ve(je)||"Failed to triage slice features","error")}finally{I(!1)}},[i,xt,f,r]),Y=a.useCallback(async O=>{try{const je=await Co(O,r);Se(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch{}},[r]),Je=a.useCallback(async O=>{try{const je=await Eo(O,r);Pt(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch{}},[r]),ot=a.useCallback(async O=>{if(!Ke.title.trim()||!Ke.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await Dy(O,{title:Ke.title.trim(),assertion:Ke.assertion.trim(),status:Ke.status},r),i("Assertion created","success"),await Y(O),await Je(O),Ye(!1),Ne({title:"",assertion:"",status:"pending"})}catch(je){i(ve(je)||"Failed to create assertion","error")}finally{I(!1)}},[Ke,i,Y,Je,r]),_t=a.useCallback(O=>{ye(O.id),Ne({title:O.title,assertion:O.assertion,status:O.status})},[]),Yn=a.useCallback(()=>{ye(null),Ye(!1),Ne({title:"",assertion:"",status:"pending"})},[]),Gs=a.useCallback(async(O,je)=>{if(!Ke.title.trim()||!Ke.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await Ly(O,{title:Ke.title.trim(),assertion:Ke.assertion.trim(),status:Ke.status},r),i("Assertion updated","success"),await Y(je),await Je(je),Yn()}catch(Te){i(ve(Te)||"Failed to update assertion","error")}finally{I(!1)}},[Ke,i,Y,Je,Yn,r]),Is=a.useCallback(async O=>{try{const je=await Oy(O,r);Qe(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch{}},[r]),da=a.useCallback(async O=>{const je=xe!==O;ze(Te=>Te===O?null:O),je&&await Is(O)},[xe,Is]),ar=a.useCallback(O=>{ze(O),Is(O),requestAnimationFrame(()=>{const je=document.querySelector(`[data-mission-assertion-id="${O}"]`);je instanceof HTMLElement&&typeof je.scrollIntoView=="function"&&je.scrollIntoView({behavior:"smooth",block:"center"})})},[Is]),bo=a.useCallback(async(O,je)=>{try{mt(Te=>new Set(Te).add(je)),await zy(O,je,r),i("Feature linked to assertion","success"),await Is(je),Ut(null)}catch(Te){i(ve(Te)||"Failed to link feature","error")}finally{mt(Te=>{const pt=new Set(Te);return pt.delete(je),pt})}},[i,Is,r]),xo=a.useCallback(async(O,je)=>{const Te=`${O}-${je}`;try{It(pt=>new Set(pt).add(Te)),await Fy(O,je,r),i("Feature unlinked from assertion","success"),await Is(je)}catch(pt){i(ve(pt)||"Failed to unlink feature","error")}finally{It(pt=>{const Gt=new Set(pt);return Gt.delete(Te),Gt})}},[i,Is,r]),vo=a.useCallback(async O=>{try{ct(Te=>new Set(Te).add(O)),await Uy(O,r),i("Validation triggered","success");const je=await fd(O,r);A(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch(je){i(ve(je)||"Failed to trigger validation","error")}finally{ct(je=>{const Te=new Set(je);return Te.delete(O),Te})}},[i,r]),Ks=a.useCallback(async O=>{try{const je=await fd(O,r);A(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch{}},[r]),Ps=a.useCallback(async O=>{try{const je=await By(O,{limit:10},r);yt(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch{}},[r]),ii=a.useCallback(O=>{const je=Ct.current;if(je){for(const Te of je.milestones)for(const pt of Te.slices)if(pt.features.find(wt=>wt.id===O)){G(wt=>{const Ot=new Set(wt);return Ot.add(Te.id),Ot}),R(wt=>{const Ot=new Set(wt);return Ot.add(pt.id),Ot}),Ve(O),ut(Te.id),Ks(O),Ps(O),requestAnimationFrame(()=>{const wt=document.querySelector(`[data-mission-feature-id="${O}"]`);wt instanceof HTMLElement&&typeof wt.scrollIntoView=="function"&&wt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Ks,Ps]),hi=a.useCallback(async O=>{try{const je=await Hy(O,r);Dn(Te=>{const pt=new Map(Te);return pt.set(O,je),pt})}catch{}},[r]),ua=a.useCallback(async O=>{J===O?Ve(null):(Ve(O),await Ks(O),await Ps(O))},[J,Ks,Ps]),Tc=a.useCallback(async O=>{qt===O?wn(null):(wn(O),await hi(O))},[qt,hi]),yo=a.useCallback(async O=>{try{await qy(O,r),i("Mission resumed","success"),await xt(O),Qt()}catch(je){i(ve(je)||"Failed to resume mission","error")}},[i,xt,Qt,r]),xs=a.useCallback(async O=>{try{const Te=(await Vy(O,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Te} task${Te!==1?"s":""} paused)`,"success"),await xt(O),Qt()}catch(je){i(ve(je)||"Failed to stop mission","error")}},[i,xt,Qt,r]),Js=a.useCallback(async O=>{try{await Wy(O,r),i("Mission started — first slice activated","success"),await xt(O),Qt()}catch(je){i(ve(je)||"Failed to start mission","error")}},[i,xt,Qt,r]),$s=a.useCallback(async(O,je)=>{try{await Gy(O,{enabled:je},r),i(je?"Autopilot enabled":"Autopilot disabled","success"),await xt(O),Qt()}catch(Te){i(ve(Te)||"Failed to update autopilot","error")}},[i,xt,Qt,r]),Ms=a.useCallback(O=>{Ln("structure"),ut(null),St(null),pn([]),zn(0),Le("all"),tt(new Set),xt(O.id)},[xt]),Ic=a.useCallback(()=>{b(null),ut(null),St(null),Ln("structure"),pn([]),zn(0),Le("all"),tt(new Set),Qt()},[Qt]),ko=Nn.length<ps,Ri=f?.autopilotState??"inactive",Pc=Ri==="watching"||Ri==="activating",$c=Vw(Ri,f?.lastAutopilotActivityAt),rr=a.useMemo(()=>!$t||!He||!Lo($t)?null:$t.rollup.milestoneId===He?$t:null,[He,$t]),cf=a.useMemo(()=>{const O=new Map;for(const je of rr?.validationTelemetry.validationRounds??[]){const Te=O.get(je.featureId);(!Te||je.startedAt>Te.startedAt)&&O.set(je.featureId,je)}return O},[rr]),df=a.useCallback(()=>{!f||Mn||!ko||ne(f.id,{append:!0})},[Mn,ko,ne,f]),uf=a.useCallback(O=>{tt(je=>{const Te=new Set(je);return Te.has(O)?Te.delete(O):Te.add(O),Te})},[]),jo=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),rn())},[rn]),Dc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Sn())},[Sn]),Lc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),dn())},[dn]),zc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),An())},[An]),mf=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const O=je=>{je.key==="Escape"&&s()};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[h,s]),!h)return null;const Fc=t.jsxs("div",{ref:mf,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[f?t.jsx("button",{className:"mission-manager__back-btn",onClick:Ic,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Zl,{size:18})}):null,t.jsx(es,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Tt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(at,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(at,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):f?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[Pc&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(fa[f.status]||fa.planning).bg,color:(fa[f.status]||fa.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:O=>$s(f.id,O.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(bn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(hr[Ri]||hr.inactive).bg,color:(hr[Ri]||hr.inactive).text},"data-testid":"autopilot-state-badge",children:[Pc&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ri]})]}),$c&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:$c})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>xs(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(os,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>yo(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(sn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Js(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>gt(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Bt,{size:14})})]})]}),N===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:j.title,onChange:O=>P({...j,title:O.target.value}),onKeyDown:jo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:j.description,onChange:O=>P({...j,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:j.status,onChange:O=>P({...j,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:j.autopilotEnabled,onChange:O=>P({...j,autopilotEnabled:O.target.checked})}),t.jsx(bn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${hn==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Ln("structure"),role:"tab","aria-selected":hn==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${hn==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Ln("activity"),role:"tab","aria-selected":hn==="activity","data-testid":"mission-tab-activity",children:["Activity (",ps,")"]})]}),hn==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(O=>{const je=rr?.rollup.milestoneId===O.id?rr:null,Te=je?.rollup??jt.get(O.id),pt=je?.validationTelemetry.validationRounds??[],Gt=je?.fixFeatures??[],wt=Qd[Te?.state??"not_started"]??Qd.not_started,Ot=Te&&(Te.state==="blocked"||Te.state==="failed")?je?.validationTelemetry.validationRounds.find(Ue=>Ue.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Fn(O.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:D.has(O.id)?t.jsx(zt,{size:16}):t.jsx(an,{size:16})}),t.jsx(Si,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:O.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Jd[O.status].bg,color:Jd[O.status].text},children:O.status}),t.jsxs("span",{className:"mission-milestone__count",children:[O.slices.length," slices"]}),t.jsx(Xd,{state:zw(O.interviewState)}),Te&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:wt.bg,color:wt.text},title:"Validation state",children:Zd(Te.state)}),Te.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Te.passedAssertions??0} of ${Te.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Te.passedAssertions??0)/Te.totalAssertions*100}%`,backgroundColor:(Te.passedAssertions??0)===Te.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),O.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>he({type:"milestone",id:O.id,title:O.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ni,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ue=>Ue.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Gn(O.id),title:"Add slice",children:t.jsx(Ht,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Wt(O),title:"Edit milestone",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"milestone",id:O.id}),title:"Delete milestone",children:t.jsx(Bt,{size:14})})]})]}),D.has(O.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(M||w===O.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:V.title,onChange:Ue=>B({...V,title:Ue.target.value}),onKeyDown:Dc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:Ue=>B({...V,description:Ue.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Sn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),w?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gn,children:"Cancel"})]})]}),je&&t.jsxs("div",{className:"mission-validation-telemetry",children:[t.jsxs("div",{className:"mission-validation-telemetry__header",children:[t.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),t.jsxs("span",{className:"mission-validation-telemetry__meta",children:[je.validationTelemetry.totalRuns," rounds",je.validationTelemetry.lastValidatorStatus?` · Last ${je.validationTelemetry.lastValidatorStatus}`:""]})]}),Ot&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Ot]}),pt.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>we(Ue=>!Ue),title:Yt?"Hide validation rounds":"Show validation rounds",children:[Yt?t.jsx(zt,{size:12}):t.jsx(an,{size:12}),"Validation rounds (",pt.length,")"]}),Yt&&t.jsx("div",{className:"mission-validation-rounds__list",children:pt.map(Ue=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Ue.validatorStatus}`,children:Ue.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ue.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ue.implementationAttempt," · validator #",Ue.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ue.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ue.failedAssertionIds.map(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ar(Be),title:`Jump to assertion ${Be}`,children:Be},`${Ue.roundId}-${Be}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Ue.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ue.generatedFixFeatureIds.map(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ii(Be),title:`Jump to fix feature ${Be}`,children:Be},`${Ue.roundId}-${Be}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ue.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ue.blockedReason})]},Ue.roundId))})]}),Gt.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:Gt.map(Ue=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>ii(Ue.id),title:`Jump to feature ${Ue.id}`,children:Ue.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:mr[Ue.status].bg,color:mr[Ue.status].text},children:Ue.status}),Ue.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ue.loopState}`,children:Ue.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ii(Ue.sourceFeatureId),title:`Jump to source feature ${Ue.sourceFeatureId}`,children:Ue.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ue.runId})]}),Ue.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:Ue.failedAssertionIds.map(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ar(Be),title:`Jump to assertion ${Be}`,children:Be},`${Ue.id}-${Be}`))})]})]},Ue.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[O.slices.map(Ue=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Ts(Ue.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Ue.id)?t.jsx(zt,{size:16}):t.jsx(an,{size:16})}),t.jsx(El,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ue.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yd[Ue.status].bg,color:Yd[Ue.status].text},children:Ue.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ue.features?.length||0," features"]}),t.jsx(Xd,{state:Ue.planState??"not_started"}),Ue.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>he({type:"slice",id:Ue.id,title:Ue.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ni,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Be=>Be.stopPropagation(),children:[Ue.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Es(Ue.id),title:"Activate slice",children:t.jsx(sn,{size:14})}),Ue.status==="active"&&Ue.features?.some(Be=>Be.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ir(Ue.id),title:"Triage all features",disabled:_,children:_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(bn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>as(Ue.id),title:"Add feature",children:t.jsx(Ht,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>On(Ue),title:"Edit slice",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"slice",id:Ue.id}),title:"Delete slice",children:t.jsx(Bt,{size:14})})]})]}),$.has(Ue.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ie&&F===O.id&&!X&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:Be=>fe({...U,title:Be.target.value}),onKeyDown:Lc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:Be=>fe({...U,description:Be.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:dn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Kn,children:"Cancel"})]})]}),X===Ue.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:Be=>fe({...U,title:Be.target.value}),onKeyDown:Lc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:Be=>fe({...U,description:Be.target.value}),rows:2}),t.jsxs("select",{value:U.status,onChange:Be=>fe({...U,status:Be.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:dn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Kn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ue.features?.map(Be=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":Be.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>ua(Be.id),title:J===Be.id?"Collapse details":"Expand to show run history",children:J===Be.id?t.jsx(zt,{size:14}):t.jsx(an,{size:14})}),t.jsx(jl,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:Be.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:mr[Be.status].bg,color:mr[Be.status].text},children:Be.status}),Be.loopState&&Be.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${Be.loopState}`,title:`Loop state: ${Be.loopState}`,children:[Be.loopState==="implementing"&&"⏳",Be.loopState==="validating"&&"🔄",Be.loopState==="needs_fix"&&"🔧",Be.loopState==="passed"&&"✅",Be.loopState==="blocked"&&"🚫"]}),Be.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>ii(Be.generatedFromFeatureId),title:`Generated from feature: ${Be.generatedFromFeatureId}`,children:"🔗 Fix"}),(Be.loopState==="validating"||Be.loopState==="needs_fix")&&(()=>{const ft=ue.get(Be.id),Kt=cf.get(Be.id),vs=ft?.implementationAttemptCount??Kt?.implementationAttempt??Be.implementationAttemptCount??0,pi=ft?.retryBudgetRemaining??Math.max(0,Lw-vs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",vs," · ",pi," ",pi===1?"retry":"retries"," left"]})})(),Be.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>vo(Be.id),title:"Validate feature",disabled:et.has(Be.id),children:et.has(Be.id)?t.jsx(at,{size:14,className:"spinner"}):t.jsx(Pn,{size:14})}),Be.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(Be.taskId),title:"Click to view task",children:Be.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[Be.status==="defined"&&!Be.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>sr(Be.id),title:"Triage — create task",disabled:_||Ze===Be.id,children:Ze===Be.id?t.jsx(at,{size:14,className:"spinner"}):t.jsx(bn,{size:14})}),Be.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>fo(Be.id),title:"Unlink task",children:t.jsx(Wc,{size:14})}):Be.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>We(Be.id),title:"Link to task",children:t.jsx(qi,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>_n(Be),title:"Edit feature",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"feature",id:Be.id}),title:"Delete feature",children:t.jsx(Bt,{size:14})})]})]}),Be.description&&t.jsx("p",{className:"mission-feature__description",children:Be.description}),Be.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",Be.acceptanceCriteria]}),le?.featureId===Be.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:le.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:si,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:go,disabled:_,children:"Cancel"})]})]}),ae===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:ft=>Re({...de,title:ft.target.value}),onKeyDown:zc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:ft=>Re({...de,description:ft.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:ft=>Re({...de,acceptanceCriteria:ft.target.value}),rows:2}),t.jsxs("select",{value:de.status,onChange:ft=>Re({...de,status:ft.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:An,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),J===Be.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(dt.get(Be.id)??[]).map(ft=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Tc(ft.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${ft.status}`,title:ft.status,children:ft.status}),t.jsx("span",{className:"mission-run__time",children:new Date(ft.startedAt).toLocaleString()}),ft.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(ft.completedAt).getTime()-new Date(ft.startedAt).getTime())/1e3),"s"]}),ft.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:ft.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:qt===ft.id?"Hide details":"Show details",children:qt===ft.id?t.jsx(zt,{size:12}):t.jsx(an,{size:12})})]}),qt===ft.id&&Ft.get(ft.id)&&t.jsxs("div",{className:"mission-run__details",children:[ft.summary&&t.jsx("p",{className:"mission-run__summary",children:ft.summary}),ft.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",ft.blockedReason]}),Ft.get(ft.id)?.failures&&Ft.get(ft.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ft.get(ft.id).failures.map(Kt=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Kt.message}),Kt.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Kt.expected]}),Kt.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Kt.actual]})]},Kt.id))]}),(!Ft.get(ft.id)?.failures||Ft.get(ft.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},ft.id)),(!dt.get(Be.id)||dt.get(Be.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Be.id)),ge&&te===Ue.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:Be=>Re({...de,title:Be.target.value}),onKeyDown:zc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:Be=>Re({...de,description:Be.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:Be=>Re({...de,acceptanceCriteria:Be.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:An,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),!ge&&(!Ue.features||Ue.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(jl,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ue.id)),O.slices.length===0&&!ie&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(El,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Te&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:wt.bg,color:wt.text},children:Zd(Te.state)}),Te&&Te.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Te.passedAssertions??0} of ${Te.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Te.passedAssertions??0)/Te.totalAssertions*100}%`,backgroundColor:(Te.passedAssertions??0)===Te.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{Ye(!0),ye(null),Ne({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Ht,{size:14})})]}),Fe&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ke.title,onChange:Ue=>Ne({...Ke,title:Ue.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Ke.assertion,onChange:Ue=>Ne({...Ke,assertion:Ue.target.value}),rows:2}),t.jsxs("select",{value:Ke.status,onChange:Ue=>Ne({...Ke,status:Ue.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>ot(O.id),disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(pe.get(O.id))?pe.get(O.id):[]).map(Ue=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ue.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Pe===Ue.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ke.title,onChange:Be=>Ne({...Ke,title:Be.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Ke.assertion,onChange:Be=>Ne({...Ke,assertion:Be.target.value}),rows:2}),t.jsxs("select",{value:Ke.status,onChange:Be=>Ne({...Ke,status:Be.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Gs(Ue.id,O.id),disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(pr[Ue.status]??pr.pending).bg,color:(pr[Ue.status]??pr.pending).text},children:Ue.status}),t.jsx("span",{className:"mission-assertion__title",children:Ue.title}),(()=>{const ft=be.get(Ue.id)?.length??0;return ft>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${ft} linked feature${ft!==1?"s":""}`,children:["(",ft," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>da(Ue.id),title:"Toggle details",children:xe===Ue.id?t.jsx(zt,{size:14}):t.jsx(an,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>_t(Ue),title:"Edit assertion",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"assertion",id:Ue.id}),title:"Delete assertion",children:t.jsx(Bt,{size:14})})]})}),xe===Ue.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ue.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{xe!==Ue.id&&await da(Ue.id),Ut(Dt===Ue.id?null:Ue.id)},title:"Link a feature",children:[t.jsx(qi,{size:12}),"Link Feature"]})]}),Dt===Ue.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Be=new Set((be.get(Ue.id)??[]).map(Kt=>Kt.id)),ft=[];return f?.milestones.forEach(Kt=>Kt.slices.forEach(vs=>ft.push(...vs.features.filter(pi=>!Be.has(pi.id))))),ft.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):ft.map(Kt=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>bo(Kt.id,Ue.id),disabled:it.has(Ue.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Kt.title}),it.has(Ue.id)&&t.jsx(at,{size:12,className:"spinner"})]},Kt.id))})()})}),(()=>{const Be=be.get(Ue.id)??[];return Be.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Be.map(ft=>{const Kt=`${ft.id}-${Ue.id}`,vs=At.has(Kt);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:ft.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>xo(ft.id,Ue.id),disabled:vs,title:"Unlink feature",children:vs?t.jsx(at,{size:12,className:"spinner"}):t.jsx(Wc,{size:12})})]},ft.id)})})()]})]})]},Ue.id)),(!pe.get(O.id)||pe.get(O.id)?.length===0)&&!Fe&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},O.id)}),f&&!M&&w===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ln,children:[t.jsx(Ht,{size:16}),"Add Milestone"]}),M&&w===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:V.title,onChange:O=>B({...V,title:O.target.value}),onKeyDown:Dc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:O=>B({...V,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Sn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:gn,children:"Cancel"})]})]}),f.milestones.length===0&&!M&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Si,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:W,onChange:O=>Le(O.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[Nn.length," of ",ps]})]}),!Mn&&ko&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:df,"data-testid":"mission-activity-load-more",children:"Load more"})}),Mn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(at,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Nn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ss,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:ht,className:"mission-events","data-testid":"mission-activity-events",children:[Nn.map(O=>{const je=!!(O.metadata&&Object.keys(O.metadata).length>0),Te=nt.has(O.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${Hw(O.eventType)}`,children:qw(O.eventType)}),t.jsx("span",{className:"mission-event__time",children:Ur(O.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:O.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(O.timestamp).toLocaleString()}),je&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>uf(O.id),"data-testid":`mission-event-metadata-${O.id}`,children:[Te?"Hide":"Show"," metadata"]}),Te&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(O.metadata,null,2)})]})]},O.id)}),t.jsx("div",{ref:kt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[k&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:j.title,onChange:O=>P({...j,title:O.target.value}),onKeyDown:jo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:j.description,onChange:O=>P({...j,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.map(O=>{const je=O,Te=f,pt=Te&&Te.id===je.id,Gt=fa[je.status]||{bg:"",text:""},wt=je.summary,Ot=qn.get(je.id),Ue=Ow(Ot),Be=!!(wt&&(wt.totalMilestones>0||wt.totalFeatures>0)),ft=Ot?.totalTasks??0,Kt=Ot?.tasksCompleted??0,vs=Ot?.tasksFailed??0,pi=Ot?.estimatedCompletionPercent??wt?.progressPercent??0,Cn=Be||ft>0||vs>0||!!Ot?.lastActivityAt,on=je.status==="active"&&(Ot?.currentMilestoneId||Ot?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${pt?"mission-list__item--selected":""}`,onClick:()=>Ms(O),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(es,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:je.title}),O.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(bn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Ue}`,"data-testid":`mission-health-badge-${je.id}`,"aria-label":`Mission health: ${Ue}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Gt.bg,color:Gt.text},children:je.status})]}),je.description&&t.jsx("p",{className:"mission-list__item-description",children:je.description}),on&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",on]}),Cn&&t.jsxs("div",{className:"mission-list__item-summary",children:[Be&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[wt.completedMilestones,"/",wt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[wt.completedFeatures,"/",wt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${je.id}`,children:[Kt,"/",ft," tasks"]}),vs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Mt=>{Mt.stopPropagation(),Ms(O)},"data-testid":`mission-failed-${je.id}`,title:"View mission failures",children:[vs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${je.id}`,children:["Activity ",Ur(Ot?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Ue}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${pi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Mt=>Mt.stopPropagation(),children:[je.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>xs(je.id),title:"Stop mission",children:t.jsx(os,{size:14})}),je.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>yo(je.id),title:"Resume mission",children:t.jsx(sn,{size:14})}),je.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Js(je.id),title:"Start mission",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>gt(O),title:"Edit mission",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"mission",id:je.id}),title:"Delete mission",children:t.jsx(Bt,{size:14})})]})]},je.id)}),N&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:j.title,onChange:O=>P({...j,title:O.target.value}),onKeyDown:jo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:j.description,onChange:O=>P({...j,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:j.status,onChange:O=>P({...j,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:j.autopilotEnabled,onChange:O=>P({...j,autopilotEnabled:O.target.checked})}),t.jsx(bn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rn,disabled:_,children:[_?t.jsx(at,{size:14,className:"spinner"}):t.jsx(yn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.length===0&&!k&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(es,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!k&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[ke.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(ns,{size:16}),t.jsx("span",{children:ke.length===1?`Resume "${ke[0].title}"?`:`${ke.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:ke.map(O=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{K(O.id),Oe(!0),De([])},children:[O.status==="error"?t.jsx(mn,{size:14}):t.jsx(Pn,{size:14}),O.status==="error"?"Retry":"Resume"]},O.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Oe(!0),children:[t.jsx(Pn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:st,children:[t.jsx(Ht,{size:16}),"New Mission"]})]})]})]})}),oe&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",oe.type,"? This cannot be undone."]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{oe.type==="mission"?await Xt(oe.id):oe.type==="milestone"?await gs(oe.id):oe.type==="slice"?await Jn(oe.id):oe.type==="feature"&&await ca(oe.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Z(null),children:"Cancel"})]})]})}),$e&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:Ge,onChange:O=>Ee(O.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(O=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ee(O.id),children:[O.id,": ",O.title||"Untitled"]},O.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:po,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{We(null),Ee("")},children:"Cancel"})]})]})})]}),Oc=t.jsx(Rw,{isOpen:Ae,onClose:()=>Oe(!1),onMissionCreated:()=>{Qt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:me}),Uc=ee?t.jsx(Pw,{isOpen:!0,onClose:()=>he(null),onApplied:()=>{he(null),f&&xt(f.id)},targetType:ee.type,targetId:ee.id,targetTitle:ee.title,missionContext:f?.title,projectId:r,resumeSessionId:ee.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Fc,Oc,Uc]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:O=>O.target===O.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Fc}),Oc,Uc]})}const fr=2e3;function tu({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,b]=a.useState(!1),[v,x]=a.useState(null),y=u.trim()!==""&&g.trim().length>0&&g.length<=fr,E=a.useCallback(async()=>{if(!(!y||f)){b(!0),x(null);try{const T=m==="agent"?"user-to-agent":"system";await bk({toId:u.trim(),toType:m,content:g.trim(),type:T,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(T){const N=ve(T)||"Failed to send message";x(N),l?.(N,"error")}finally{b(!1)}}},[y,f,u,m,g,n,i,r,l]),k=a.useCallback(T=>{d(T),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Tt,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:u,onChange:T=>k(T.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(T=>t.jsx("option",{value:T.id,children:T.name||T.id},T.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(nn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:T=>p(T.target.value),maxLength:fr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:g.length>fr?"over-limit":"",children:[g.length,"/",fr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(ns,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:E,disabled:!y||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(yi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function Di(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function Gw(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const i=s?.get(e)?.trim();return i?i===e?`Agent: ${e}`:`Agent: ${i} (${e})`:`Agent: ${e}`}return"System"}function Kw(e){switch(e){case"agent-to-agent":return"Agent ↔ Agent";case"agent-to-user":return"Agent → You";case"user-to-agent":return"You → Agent";case"system":return"System"}}function nu(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Jw(e){const n=new Map;for(const s of e){const i=`${s.fromType}:${s.fromId}`,r=n.get(i);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(i,{key:i,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,i)=>new Date(i.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function Yw({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(!1),[E,k]=a.useState(null),[T,N]=a.useState(null),[S,j]=a.useState(null),[P,_]=a.useState("inbox"),[I,D]=a.useState(null),[G,$]=a.useState([]),R=a.useMemo(()=>new Map(G.map(te=>[te.id,te.name??""])),[G]),w=a.useCallback((te,Ce)=>Gw(te,Ce,R),[R]),V=Za()==="mobile",B=!V,M=a.useCallback(async()=>{g(!0);try{const te=await fk({limit:50},e);l(te),m(te.unreadCount),s?.(te.unreadCount)}catch{}finally{g(!1)}},[e,s]),z=a.useCallback(async()=>{g(!0);try{const te=await gk({limit:50},e);u(te)}catch{}finally{g(!1)}},[e]),X=a.useCallback(async te=>{g(!0);try{const Ce=await jk(te,e);D(Ce)}catch{}finally{g(!1)}},[e]),C=a.useCallback(async()=>{try{const te=await aa(void 0,e);$(te)}catch{}},[e]),U=a.useCallback(async()=>{try{const te=await gh(e);m(te.unreadCount),s?.(te.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?M():i==="outbox"?z():i==="agents"&&C()},[i,M,z,C]),a.useEffect(()=>{S&&X(S)},[S,X]),a.useEffect(()=>{U()},[U]),a.useEffect(()=>{C()},[C]),a.useEffect(()=>{if(typeof EventSource>"u")return;const te=e?`?projectId=${encodeURIComponent(e)}`:"",Ce=()=>{U(),i==="inbox"?M():i==="outbox"&&z(),S&&X(S)};return Vs(`/api/events${te}`,{events:{"message:sent":Ce,"message:received":Ce,"message:read":Ce,"message:deleted":Ce}})},[e,i,S,U,M,z,X]);const fe=a.useCallback(async te=>{if(f(te),!te.read)try{const Ce=await xk(te.id,e);Ce&&l(We=>We&&{...We,messages:We.messages.map(Ge=>Ge.id===Ce.id?Ce:Ge),unreadCount:Math.max(0,We.unreadCount-1)});const $e=Math.max(0,d-1);m($e),s?.($e)}catch{}try{const Ce=await kk(te.fromId,te.fromType,e);v(Ce)}catch{v([te])}},[e,d,s]),ie=a.useCallback(()=>{f(null),v([])},[]),re=a.useCallback(async()=>{try{const te=await vk(e);m(0),s?.(0),l(Ce=>Ce&&{...Ce,messages:Ce.messages.map($e=>({...$e,read:!0})),unreadCount:0}),n?.(`Marked ${te.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),F=a.useCallback(async te=>{try{await yk(te,e),f(null),v([]),i==="inbox"?M():i==="outbox"?z():S&&X(S),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,S,M,z,X,n]),ce=a.useCallback(te=>{k({id:te.fromId,type:te.fromType}),N({messageId:te.id,preview:nu(te.content,120)}),y(!0)},[]),ae=a.useCallback(()=>{y(!1),k(null),N(null),n?.("Message sent","success"),i==="outbox"?z():i==="agents"&&S&&X(S),U()},[i,z,S,X,n,U]),Q=a.useCallback(()=>{k(i==="agents"&&S?{id:S,type:"agent"}:null),N(null),y(!0)},[i,S]),de=a.useCallback(()=>{y(!1),k(null),N(null)},[]),Re=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[V&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ie,"data-testid":"mailbox-back-to-list",children:"← Back"}),t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:Kw(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Di(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ce(p),"data-testid":"mailbox-reply",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>F(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Bt,{size:14}),t.jsx("span",{children:"Delete"})]})]})]}),t.jsxs("div",{className:"mailbox-message-participants",children:[t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"From:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?t.jsx(nn,{size:14}):t.jsx(Ti,{size:14}),w(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(nn,{size:14}):t.jsx(Ti,{size:14}),w(p.toId,p.toType)]})]})]}),b.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(te=>{const Ce=te.metadata?.replyTo?.messageId,$e=Ce?b.find(We=>We.id===Ce):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${te.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Di(te.createdAt)})]}),Ce&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${te.id}`,children:["↪ Replying to ",$e?nu($e.content,60):`message ${Ce}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:te.content})]},te.id)})]}),b.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),ge=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(zo,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Aa,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o&&o.messages.length>0&&t.jsx("div",{className:"mailbox-conversations","data-testid":"mailbox-conversations",children:Jw(o.messages).map(te=>t.jsxs("div",{className:`mailbox-conversation-group ${te.unreadCount>0?"unread":""}`,onClick:()=>fe(te.latestMessage),"data-testid":`mailbox-conversation-${te.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(nn,{size:16}):t.jsx(Ti,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Di(te.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.latestMessage.content.slice(0,80),te.latestMessage.content.length>80?"…":""]})]}),te.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${te.key}`,children:te.unreadCount>9?"9+":te.unreadCount})]},te.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(zo,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(yi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>fe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(nn,{size:16}):t.jsx(Ti,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",w(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Di(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:G.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(nn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:S??"",onChange:te=>{j(te.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),G.map(te=>t.jsx("option",{value:te.id,children:te.name||te.id},te.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Q,"data-testid":"mailbox-compose-btn",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]})]}),S&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${P==="inbox"?"active":""}`,onClick:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Aa,{size:12}),t.jsx("span",{children:"Inbox"}),I&&I.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:I.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${P==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(yi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!S&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(nn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),S&&h&&!I&&t.jsx(zo,{}),S&&I&&P==="inbox"&&I.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Aa,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),S&&I&&P==="outbox"&&I.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(yi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),S&&I&&P==="inbox"&&I.inbox.map(te=>t.jsxs("div",{className:`mailbox-item ${te.read?"":"unread"}`,onClick:()=>fe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(nn,{size:16}):t.jsx(Ti,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Di(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id)),S&&I&&P==="outbox"&&I.outbox.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>fe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(nn,{size:16}):t.jsx(Ti,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",w(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Di(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]})]})})]}),Me=()=>x?t.jsx(tu,{recipient:E,replyContext:T,agents:G,projectId:e,onSend:ae,onCancel:de,addToast:n}):p?Re():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Vi,{size:24}),t.jsx("p",{children:"Select a conversation to read messages"})]});return t.jsxs("div",{className:"mailbox-view","data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Vi,{size:18}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:d})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Q,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:re,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Pf,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?M():i==="outbox"?z():S&&X(S)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Aa,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(yi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(nn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:B?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:ge()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Me()})]}):t.jsxs(t.Fragment,{children:[Re(),x&&t.jsx(tu,{recipient:E,replyContext:T,agents:G,projectId:e,onSend:ae,onCancel:de,addToast:n}),!p&&!x&&ge()]})})]})}function zo(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}function Qw(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const Xw=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Zw=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eN={};function su(e,n){return(eN.jsx?Zw:Xw).test(e)}const tN=/[ \t\n\f\r]/g;function nN(e){return typeof e=="object"?e.type==="text"?iu(e.value):!1:iu(e)}function iu(e){return e.replace(tN,"")===""}class er{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}er.prototype.normal={};er.prototype.property={};er.prototype.space=void 0;function $h(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new er(s,i,n)}function Dl(e){return e.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 sN=0;const Nt=Ai(),un=Ai(),Ll=Ai(),Xe=Ai(),Jt=Ai(),Bi=Ai(),rs=Ai();function Ai(){return 2**++sN}const zl=Object.freeze(Object.defineProperty({__proto__:null,boolean:Nt,booleanish:un,commaOrSpaceSeparated:rs,commaSeparated:Bi,number:Xe,overloadedBoolean:Ll,spaceSeparated:Jt},Symbol.toStringTag,{value:"Module"})),Fo=Object.keys(zl);class hc extends is{constructor(n,s,i,r){let o=-1;if(super(n,s),au(this,"space",r),typeof i=="number")for(;++o<Fo.length;){const l=Fo[o];au(this,Fo[o],(i&zl[l])===zl[l])}}}hc.prototype.defined=!0;function au(e,n,s){s&&(e[n]=s)}function oa(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new hc(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Dl(i)]=i,s[Dl(o.attribute)]=i}return new er(n,s,e.space)}const Dh=oa({properties:{ariaActiveDescendant:null,ariaAtomic:un,ariaAutoComplete:null,ariaBusy:un,ariaChecked:un,ariaColCount:Xe,ariaColIndex:Xe,ariaColSpan:Xe,ariaControls:Jt,ariaCurrent:null,ariaDescribedBy:Jt,ariaDetails:null,ariaDisabled:un,ariaDropEffect:Jt,ariaErrorMessage:null,ariaExpanded:un,ariaFlowTo:Jt,ariaGrabbed:un,ariaHasPopup:null,ariaHidden:un,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Jt,ariaLevel:Xe,ariaLive:null,ariaModal:un,ariaMultiLine:un,ariaMultiSelectable:un,ariaOrientation:null,ariaOwns:Jt,ariaPlaceholder:null,ariaPosInSet:Xe,ariaPressed:un,ariaReadOnly:un,ariaRelevant:null,ariaRequired:un,ariaRoleDescription:Jt,ariaRowCount:Xe,ariaRowIndex:Xe,ariaRowSpan:Xe,ariaSelected:un,ariaSetSize:Xe,ariaSort:null,ariaValueMax:Xe,ariaValueMin:Xe,ariaValueNow:Xe,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Lh(e,n){return n in e?e[n]:n}function zh(e,n){return Lh(e,n.toLowerCase())}const iN=oa({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Bi,acceptCharset:Jt,accessKey:Jt,action:null,allow:null,allowFullScreen:Nt,allowPaymentRequest:Nt,allowUserMedia:Nt,alt:null,as:null,async:Nt,autoCapitalize:null,autoComplete:Jt,autoFocus:Nt,autoPlay:Nt,blocking:Jt,capture:null,charSet:null,checked:Nt,cite:null,className:Jt,cols:Xe,colSpan:null,content:null,contentEditable:un,controls:Nt,controlsList:Jt,coords:Xe|Bi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Nt,defer:Nt,dir:null,dirName:null,disabled:Nt,download:Ll,draggable:un,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Nt,formTarget:null,headers:Jt,height:Xe,hidden:Ll,high:Xe,href:null,hrefLang:null,htmlFor:Jt,httpEquiv:Jt,id:null,imageSizes:null,imageSrcSet:null,inert:Nt,inputMode:null,integrity:null,is:null,isMap:Nt,itemId:null,itemProp:Jt,itemRef:Jt,itemScope:Nt,itemType:Jt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Nt,low:Xe,manifest:null,max:null,maxLength:Xe,media:null,method:null,min:null,minLength:Xe,multiple:Nt,muted:Nt,name:null,nonce:null,noModule:Nt,noValidate:Nt,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:Nt,optimum:Xe,pattern:null,ping:Jt,placeholder:null,playsInline:Nt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Nt,referrerPolicy:null,rel:Jt,required:Nt,reversed:Nt,rows:Xe,rowSpan:Xe,sandbox:Jt,scope:null,scoped:Nt,seamless:Nt,selected:Nt,shadowRootClonable:Nt,shadowRootDelegatesFocus:Nt,shadowRootMode:null,shape:null,size:Xe,sizes:null,slot:null,span:Xe,spellCheck:un,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Xe,step:null,style:null,tabIndex:Xe,target:null,title:null,translate:null,type:null,typeMustMatch:Nt,useMap:null,value:un,width:Xe,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Jt,axis:null,background:null,bgColor:null,border:Xe,borderColor:null,bottomMargin:Xe,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Nt,declare:Nt,event:null,face:null,frame:null,frameBorder:null,hSpace:Xe,leftMargin:Xe,link:null,longDesc:null,lowSrc:null,marginHeight:Xe,marginWidth:Xe,noResize:Nt,noHref:Nt,noShade:Nt,noWrap:Nt,object:null,profile:null,prompt:null,rev:null,rightMargin:Xe,rules:null,scheme:null,scrolling:un,standby:null,summary:null,text:null,topMargin:Xe,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Xe,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Nt,disableRemotePlayback:Nt,prefix:null,property:null,results:Xe,security:null,unselectable:null},space:"html",transform:zh}),aN=oa({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:rs,accentHeight:Xe,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Xe,amplitude:Xe,arabicForm:null,ascent:Xe,attributeName:null,attributeType:null,azimuth:Xe,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Xe,by:null,calcMode:null,capHeight:Xe,className:Jt,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:Xe,diffuseConstant:Xe,direction:null,display:null,dur:null,divisor:Xe,dominantBaseline:null,download:Nt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Xe,enableBackground:null,end:null,event:null,exponent:Xe,externalResourcesRequired:null,fill:null,fillOpacity:Xe,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:Bi,g2:Bi,glyphName:Bi,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Xe,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Xe,horizOriginX:Xe,horizOriginY:Xe,id:null,ideographic:Xe,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Xe,k:Xe,k1:Xe,k2:Xe,k3:Xe,k4:Xe,kernelMatrix:rs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Xe,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:Xe,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:Xe,overlineThickness:Xe,paintOrder:null,panose1:null,path:null,pathLength:Xe,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Jt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Xe,pointsAtY:Xe,pointsAtZ:Xe,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:rs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:rs,rev:rs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:rs,requiredFeatures:rs,requiredFonts:rs,requiredFormats:rs,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:Xe,specularExponent:Xe,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Xe,strikethroughThickness:Xe,string:null,stroke:null,strokeDashArray:rs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Xe,strokeOpacity:Xe,strokeWidth:null,style:null,surfaceScale:Xe,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:rs,tabIndex:Xe,tableValues:null,target:null,targetX:Xe,targetY:Xe,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:rs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Xe,underlineThickness:Xe,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Xe,values:null,vAlphabetic:Xe,vMathematical:Xe,vectorEffect:null,vHanging:Xe,vIdeographic:Xe,version:null,vertAdvY:Xe,vertOriginX:Xe,vertOriginY:Xe,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Xe,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Lh}),Fh=oa({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),Oh=oa({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:zh}),Uh=oa({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),rN={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},oN=/[A-Z]/g,ru=/-[a-z]/g,lN=/^data[-\w.:]+$/i;function cN(e,n){const s=Dl(n);let i=n,r=is;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&lN.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(ru,uN);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!ru.test(o)){let l=o.replace(oN,dN);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=hc}return new r(i,n)}function dN(e){return"-"+e.toLowerCase()}function uN(e){return e.charAt(1).toUpperCase()}const mN=$h([Dh,iN,Fh,Oh,Uh],"html"),pc=$h([Dh,aN,Fh,Oh,Uh],"svg");function hN(e){return e.join(" ").trim()}var Li={},Oo,ou;function pN(){if(ou)return Oo;ou=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
578
- `,d="/",m="*",h="",g="comment",p="declaration";function f(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,E=1;function k($){var R=$.match(n);R&&(y+=R.length);var w=$.lastIndexOf(u);E=~w?$.length-w:E+$.length}function T(){var $={line:y,column:E};return function(R){return R.position=new N($),P(),R}}function N($){this.start=$,this.end={line:y,column:E},this.source=x.source}N.prototype.content=v;function S($){var R=new Error(x.source+":"+y+":"+E+": "+$);if(R.reason=$,R.filename=x.source,R.line=y,R.column=E,R.source=v,!x.silent)throw R}function j($){var R=$.exec(v);if(R){var w=R[0];return k(w),v=v.slice(w.length),R}}function P(){j(s)}function _($){var R;for($=$||[];R=I();)R!==!1&&$.push(R);return $}function I(){var $=T();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var R=2;h!=v.charAt(R)&&(m!=v.charAt(R)||d!=v.charAt(R+1));)++R;if(R+=2,h===v.charAt(R-1))return S("End of comment missing");var w=v.slice(2,R-2);return E+=2,k(w),v=v.slice(R),E+=2,$({type:g,comment:w})}}function D(){var $=T(),R=j(i);if(R){if(I(),!j(r))return S("property missing ':'");var w=j(o),H=$({type:p,property:b(R[0].replace(e,h)),value:w?b(w[0].replace(e,h)):h});return j(l),H}}function G(){var $=[];_($);for(var R;R=D();)R!==!1&&($.push(R),_($));return $}return P(),G()}function b(v){return v?v.replace(c,h):h}return Oo=f,Oo}var lu;function fN(){if(lu)return Li;lu=1;var e=Li&&Li.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Li,"__esModule",{value:!0}),Li.default=s;const n=e(pN());function s(i,r){let o=null;if(!i||typeof i!="string")return o;const l=(0,n.default)(i),c=typeof r=="function";return l.forEach(u=>{if(u.type!=="declaration")return;const{property:d,value:m}=u;c?r(d,m,u):m&&(o=o||{},o[d]=m)}),o}return Li}var ga={},cu;function gN(){if(cu)return ga;cu=1,Object.defineProperty(ga,"__esModule",{value:!0}),ga.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(d){return!d||s.test(d)||e.test(d)},l=function(d,m){return m.toUpperCase()},c=function(d,m){return"".concat(m,"-")},u=function(d,m){return m===void 0&&(m={}),o(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(r,c):d=d.replace(i,c),d.replace(n,l))};return ga.camelCase=u,ga}var ba,du;function bN(){if(du)return ba;du=1;var e=ba&&ba.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(fN()),s=gN();function i(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,u){c&&u&&(l[(0,s.camelCase)(c,o)]=u)}),l}return i.default=i,ba=i,ba}var xN=bN();const vN=Om(xN),Bh=Hh("end"),fc=Hh("start");function Hh(e){return n;function n(s){const i=s&&s.position&&s.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function yN(e){const n=fc(e),s=Bh(e);if(n&&s)return{start:n,end:s}}function Ia(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?uu(e.position):"start"in e||"end"in e?uu(e):"line"in e||"column"in e?Fl(e):""}function Fl(e){return mu(e&&e.line)+":"+mu(e&&e.column)}function uu(e){return Fl(e&&e.start)+"-"+Fl(e&&e.end)}function mu(e){return e&&typeof e=="number"?e:1}class $n extends Error{constructor(n,s,i){super(),typeof s=="string"&&(i=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=Ia(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}$n.prototype.file="";$n.prototype.name="";$n.prototype.reason="";$n.prototype.message="";$n.prototype.stack="";$n.prototype.column=void 0;$n.prototype.line=void 0;$n.prototype.ancestors=void 0;$n.prototype.cause=void 0;$n.prototype.fatal=void 0;$n.prototype.place=void 0;$n.prototype.ruleId=void 0;$n.prototype.source=void 0;const gc={}.hasOwnProperty,kN=new Map,jN=/[A-Z]/g,wN=new Set(["table","tbody","thead","tfoot","tr"]),NN=new Set(["td","th"]),qh="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function SN(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let i;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=IN(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=TN(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"?pc:mN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Vh(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Vh(e,n,s){if(n.type==="element")return CN(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return EN(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return _N(e,n,s);if(n.type==="mdxjsEsm")return MN(e,n);if(n.type==="root")return AN(e,n,s);if(n.type==="text")return RN(e,n)}function CN(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=pc,e.schema=r),e.ancestors.push(n);const o=Gh(e,n.tagName,!1),l=PN(e,n);let c=xc(e,n);return wN.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!nN(u):!0})),Wh(e,l,o,n),bc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function EN(e,n){if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}Ba(e,n.position)}function MN(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Ba(e,n.position)}function _N(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=pc,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Gh(e,n.name,!0),l=$N(e,n),c=xc(e,n);return Wh(e,l,o,n),bc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function AN(e,n,s){const i={};return bc(i,xc(e,n)),e.create(n,e.Fragment,i,s)}function RN(e,n){return n.value}function Wh(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function bc(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function TN(e,n,s){return i;function i(r,o,l,c){const d=Array.isArray(l.children)?s:n;return c?d(o,l,c):d(o,l)}}function IN(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=fc(i);return n(r,o,l,c,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function PN(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&gc.call(n.properties,r)){const o=DN(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&NN.has(n.tagName)?i=c:s[l]=c}}if(i){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return s}function $N(e,n){const s={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else Ba(e,n.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const c=i.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else Ba(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function xc(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:kN;for(;++i<n.children.length;){const o=n.children[i];let l;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const d=r.get(u)||0;l=u+"-"+d,r.set(u,d+1)}}const c=Vh(e,o,l);c!==void 0&&s.push(c)}return s}function DN(e,n,s){const i=cN(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?Qw(s):hN(s)),i.property==="style"){let r=typeof s=="object"?s:LN(e,String(s));return e.stylePropertyNameCase==="css"&&(r=zN(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?rN[i.property]||i.property:i.attribute,s]}}function LN(e,n){try{return vN(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new $n("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=qh+"#cannot-parse-style-attribute",r}}function Gh(e,n,s){let i;if(!s)i={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=su(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}i=l}else i=su(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return gc.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);Ba(e)}function Ba(e,n){const s=new $n("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=qh+"#cannot-handle-mdx-estrees-without-createevaluater",s}function zN(e){const n={};let s;for(s in e)gc.call(e,s)&&(n[FN(s)]=e[s]);return n}function FN(e){let n=e.replace(jN,ON);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function ON(e){return"-"+e.toLowerCase()}const Uo={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"]},UN={};function vc(e,n){const s=UN,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Kh(e,i,r)}function Kh(e,n,s){if(BN(e)){if("value"in e)return e.type==="html"&&!s?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return hu(e.children,n,s)}return Array.isArray(e)?hu(e,n,s):""}function hu(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=Kh(e[r],n,s);return i.join("")}function BN(e){return!!(e&&typeof e=="object")}const pu=document.createElement("i");function yc(e){const n="&"+e+";";pu.innerHTML=n;const s=pu.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ds(e,n,s,i){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,i.length<1e4)l=Array.from(i),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<i.length;)l=i.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function ws(e,n){return e.length>0?(ds(e,e.length,0,n),e):n}const fu={}.hasOwnProperty;function Jh(e){const n={};let s=-1;for(;++s<e.length;)HN(n,e[s]);return n}function HN(e,n){let s;for(s in n){const r=(fu.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){fu.call(r,l)||(r[l]=[]);const c=o[l];qN(r[l],Array.isArray(c)?c:c?[c]:[])}}}function qN(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);ds(e,0,0,i)}function Yh(e,n){const s=Number.parseInt(e,n);return s<9||s===11||s>13&&s<32||s>126&&s<160||s>55295&&s<57344||s>64975&&s<65008||(s&65535)===65535||(s&65535)===65534||s>1114111?"�":String.fromCodePoint(s)}function Rs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Bn=ui(/[A-Za-z]/),In=ui(/[\dA-Za-z]/),VN=ui(/[#-'*+\--9=?A-Z^-~]/);function Br(e){return e!==null&&(e<32||e===127)}const Ol=ui(/\d/),WN=ui(/[\dA-Fa-f]/),GN=ui(/[!-/:-@[-`{-~]/);function vt(e){return e!==null&&e<-2}function Vt(e){return e!==null&&(e<0||e===32)}function Rt(e){return e===-2||e===-1||e===32}const lo=ui(/\p{P}|\p{S}/u),Ei=ui(/\s/);function ui(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function la(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&In(e.charCodeAt(s+1))&&In(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(i,s),encodeURIComponent(l)),i=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(i)}function Lt(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Rt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Rt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const KN={tokenize:JN};function JN(e){const n=e.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),Lt(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=u),s=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return vt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const YN={tokenize:QN},gu={tokenize:XN};function QN(e){const n=this,s=[];let i=0,r,o,l;return c;function c(E){if(i<s.length){const k=s[i];return n.containerState=k[1],e.attempt(k[0].continuation,u,d)(E)}return d(E)}function u(E){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const k=n.events.length;let T=k,N;for(;T--;)if(n.events[T][0]==="exit"&&n.events[T][1].type==="chunkFlow"){N=n.events[T][1].end;break}x(i);let S=k;for(;S<n.events.length;)n.events[S][1].end={...N},S++;return ds(n.events,T+1,0,n.events.slice(k)),n.events.length=S,d(E)}return c(E)}function d(E){if(i===s.length){if(!r)return g(E);if(r.currentConstruct&&r.currentConstruct.concrete)return f(E);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(gu,m,h)(E)}function m(E){return r&&y(),x(i),g(E)}function h(E){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(E)}function g(E){return n.containerState={},e.attempt(gu,p,f)(E)}function p(E){return i++,s.push([n.currentConstruct,n.containerState]),g(E)}function f(E){if(E===null){r&&y(),x(0),e.consume(E);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(E)}function b(E){if(E===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(E);return}return vt(E)?(e.consume(E),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(E),b)}function v(E,k){const T=n.sliceStream(E);if(k&&T.push(null),E.previous=o,o&&(o.next=E),o=E,r.defineSkip(E.start),r.write(T),n.parser.lazy[E.start.line]){let N=r.events.length;for(;N--;)if(r.events[N][1].start.offset<l&&(!r.events[N][1].end||r.events[N][1].end.offset>l))return;const S=n.events.length;let j=S,P,_;for(;j--;)if(n.events[j][0]==="exit"&&n.events[j][1].type==="chunkFlow"){if(P){_=n.events[j][1].end;break}P=!0}for(x(i),N=S;N<n.events.length;)n.events[N][1].end={..._},N++;ds(n.events,j+1,0,n.events.slice(S)),n.events.length=N}}function x(E){let k=s.length;for(;k-- >E;){const T=s[k];n.containerState=T[1],T[0].exit.call(n,e)}s.length=E}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function XN(e,n,s){return Lt(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ji(e){if(e===null||Vt(e)||Ei(e))return 1;if(lo(e))return 2}function co(e,n,s){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(n=o(n,s),i.push(o))}return n}const Ul={name:"attention",resolveAll:ZN,tokenize:e1};function ZN(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},g={...e[s][1].start};bu(h,-u),bu(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=ws(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=ws(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=ws(d,co(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=ws(d,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,d=ws(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ds(e,i-1,s-i+3,d),s=i+d.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function e1(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Ji(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=Ji(u),h=!m||m===2&&r||s.includes(u),g=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!g)),d._close=!!(o===42?g:g&&(m||!h)),n(u)}}function bu(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const t1={name:"autolink",tokenize:n1};function n1(e,n,s){let i=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Bn(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||In(p)?(i=1,c(p)):d(p)}function c(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||In(p))&&i++<32?(e.consume(p),c):(i=0,d(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||Br(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):VN(p)?(e.consume(p),d):s(p)}function m(p){return In(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):g(p)}function g(p){if((p===45||In(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const tr={partial:!0,tokenize:s1};function s1(e,n,s){return i;function i(o){return Rt(o)?Lt(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||vt(o)?n(o):s(o)}}const Qh={continuation:{tokenize:a1},exit:r1,name:"blockQuote",tokenize:i1};function i1(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return Rt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function a1(e,n,s){const i=this;return r;function r(l){return Rt(l)?Lt(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Qh,n,s)(l)}}function r1(e){e.exit("blockQuote")}const Xh={name:"characterEscape",tokenize:o1};function o1(e,n,s){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return GN(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Zh={name:"characterReference",tokenize:l1};function l1(e,n,s){const i=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),u}function u(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,l=In,m(h))}function d(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=WN,m):(e.enter("characterReferenceValue"),o=7,l=Ol,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===In&&!yc(i.sliceSerialize(g))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const xu={partial:!0,tokenize:d1},vu={concrete:!0,name:"codeFenced",tokenize:c1};function c1(e,n,s){const i=this,r={partial:!0,tokenize:T};let o=0,l=0,c;return u;function u(N){return d(N)}function d(N){const S=i.events[i.events.length-1];return o=S&&S[1].type==="linePrefix"?S[2].sliceSerialize(S[1],!0).length:0,c=N,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(N)}function m(N){return N===c?(l++,e.consume(N),m):l<3?s(N):(e.exit("codeFencedFenceSequence"),Rt(N)?Lt(e,h,"whitespace")(N):h(N))}function h(N){return N===null||vt(N)?(e.exit("codeFencedFence"),i.interrupt?n(N):e.check(xu,b,k)(N)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(N))}function g(N){return N===null||vt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(N)):Rt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Lt(e,p,"whitespace")(N)):N===96&&N===c?s(N):(e.consume(N),g)}function p(N){return N===null||vt(N)?h(N):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(N))}function f(N){return N===null||vt(N)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(N)):N===96&&N===c?s(N):(e.consume(N),f)}function b(N){return e.attempt(r,k,v)(N)}function v(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),x}function x(N){return o>0&&Rt(N)?Lt(e,y,"linePrefix",o+1)(N):y(N)}function y(N){return N===null||vt(N)?e.check(xu,b,k)(N):(e.enter("codeFlowValue"),E(N))}function E(N){return N===null||vt(N)?(e.exit("codeFlowValue"),y(N)):(e.consume(N),E)}function k(N){return e.exit("codeFenced"),n(N)}function T(N,S,j){let P=0;return _;function _(R){return N.enter("lineEnding"),N.consume(R),N.exit("lineEnding"),I}function I(R){return N.enter("codeFencedFence"),Rt(R)?Lt(N,D,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):D(R)}function D(R){return R===c?(N.enter("codeFencedFenceSequence"),G(R)):j(R)}function G(R){return R===c?(P++,N.consume(R),G):P>=l?(N.exit("codeFencedFenceSequence"),Rt(R)?Lt(N,$,"whitespace")(R):$(R)):j(R)}function $(R){return R===null||vt(R)?(N.exit("codeFencedFence"),S(R)):j(R)}}}function d1(e,n,s){const i=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}const Bo={name:"codeIndented",tokenize:m1},u1={partial:!0,tokenize:h1};function m1(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Lt(e,o,"linePrefix",5)(d)}function o(d){const m=i.events[i.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(d):s(d)}function l(d){return d===null?u(d):vt(d)?e.attempt(u1,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||vt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function h1(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):vt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Lt(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):vt(l)?r(l):s(l)}}const p1={name:"codeText",previous:g1,resolve:f1,tokenize:b1};function f1(e){let n=e.length-4,s=3,i,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(i=s;++i<n;)if(e[i][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(i=s-1,n++;++i<=n;)r===void 0?i!==n&&e[i][1].type!=="lineEnding"&&(r=i):(i===n||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),n-=i-r-2,i=r+2),r=void 0);return e}function g1(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function b1(e,n,s){let i=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),i++,c):(e.exit("codeTextSequence"),u(h))}function u(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),u):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):vt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("codeTextData"),d(h))}function d(h){return h===null||h===32||h===96||vt(h)?(e.exit("codeTextData"),u(h)):(e.consume(h),d)}function m(h){return h===96?(e.consume(h),r++,m):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",d(h))}}class x1{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&xa(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),xa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),xa(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);xa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);xa(this.left,s.reverse())}}}function xa(e,n){let s=0;if(n.length<1e4)e.push(...n);else for(;s<n.length;)e.push(...n.slice(s,s+1e4)),s+=1e4}function ep(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new x1(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(i=m.get(s),s&&i[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,v1(m,s)),s=n[s],d=!0);else if(i[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(i[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(i),m.splice(r,s-r+1,c))}}return ds(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function v1(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(b=g+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const x=c.slice(v[g],v[g+1]),y=o.pop();u.push([y,y+x.length-1]),e.splice(y,2,x)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const y1={resolve:j1,tokenize:w1},k1={partial:!0,tokenize:N1};function j1(e){return ep(e),e}function w1(e,n){let s;return i;function i(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):vt(c)?e.check(k1,l,o)(c):(e.consume(c),r)}function o(c){return e.exit("chunkContent"),e.exit("content"),n(c)}function l(c){return e.consume(c),e.exit("chunkContent"),s.next=e.enter("chunkContent",{contentType:"content",previous:s}),s=s.next,r}}function N1(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Lt(e,o,"linePrefix")}function o(l){if(l===null||vt(l))return s(l);const c=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(i.parser.constructs.flow,s,n)(l)}}function tp(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(x),e.exit(o),g):x===null||x===32||x===41||Br(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function g(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),g(x)):x===null||x===60||vt(x)?s(x):(e.consume(x),x===92?f:p)}function f(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||Vt(x))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(x)):m<d&&x===40?(e.consume(x),m++,b):x===41?(e.consume(x),m--,b):x===null||x===32||x===40||Br(x)?s(x):(e.consume(x),x===92?v:b)}function v(x){return x===40||x===41||x===92?(e.consume(x),b):b(x)}}function np(e,n,s,i,r,o){const l=this;let c=0,u;return d;function d(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),m}function m(p){return c>999||p===null||p===91||p===93&&!u||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),n):vt(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):(e.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||vt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Rt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function sp(e,n,s,i,r,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(i),e.enter(r),e.consume(g),e.exit(r),l=g===40?41:g,u):s(g)}function u(g){return g===l?(e.enter(r),e.consume(g),e.exit(r),e.exit(i),n):(e.enter(o),d(g))}function d(g){return g===l?(e.exit(o),u(l)):g===null?s(g):vt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Lt(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||vt(g)?(e.exit("chunkString"),d(g)):(e.consume(g),g===92?h:m)}function h(g){return g===l||g===92?(e.consume(g),m):m(g)}}function Pa(e,n){let s;return i;function i(r){return vt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Rt(r)?Lt(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const S1={name:"definition",tokenize:E1},C1={partial:!0,tokenize:M1};function E1(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return np.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Rs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):s(p)}function u(p){return Vt(p)?Pa(e,d)(p):d(p)}function d(p){return tp(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(C1,h,h)(p)}function h(p){return Rt(p)?Lt(e,g,"whitespace")(p):g(p)}function g(p){return p===null||vt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function M1(e,n,s){return i;function i(c){return Vt(c)?Pa(e,r)(c):s(c)}function r(c){return sp(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Rt(c)?Lt(e,l,"whitespace")(c):l(c)}function l(c){return c===null||vt(c)?n(c):s(c)}}const _1={name:"hardBreakEscape",tokenize:A1};function A1(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return vt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const R1={name:"headingAtx",resolve:T1,tokenize:I1};function T1(e,n){let s=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),s-2>i&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&e[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[s][1].end},o={type:"chunkText",start:e[i][1].start,end:e[s][1].end,contentType:"text"},ds(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function I1(e,n,s){let i=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&i++<6?(e.consume(m),l):m===null||Vt(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||vt(m)?(e.exit("atxHeading"),n(m)):Rt(m)?Lt(e,c,"whitespace")(m):(e.enter("atxHeadingText"),d(m))}function u(m){return m===35?(e.consume(m),u):(e.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||Vt(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const P1=["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"],$1={concrete:!0,name:"htmlFlow",resolveTo:z1,tokenize:F1},D1={partial:!0,tokenize:U1},L1={partial:!0,tokenize:O1};function z1(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function F1(e,n,s){const i=this;let r,o,l,c,u;return d;function d(C){return m(C)}function m(C){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(C),h}function h(C){return C===33?(e.consume(C),g):C===47?(e.consume(C),o=!0,b):C===63?(e.consume(C),r=3,i.interrupt?n:M):Bn(C)?(e.consume(C),l=String.fromCharCode(C),v):s(C)}function g(C){return C===45?(e.consume(C),r=2,p):C===91?(e.consume(C),r=5,c=0,f):Bn(C)?(e.consume(C),r=4,i.interrupt?n:M):s(C)}function p(C){return C===45?(e.consume(C),i.interrupt?n:M):s(C)}function f(C){const U="CDATA[";return C===U.charCodeAt(c++)?(e.consume(C),c===U.length?i.interrupt?n:D:f):s(C)}function b(C){return Bn(C)?(e.consume(C),l=String.fromCharCode(C),v):s(C)}function v(C){if(C===null||C===47||C===62||Vt(C)){const U=C===47,fe=l.toLowerCase();return!U&&!o&&yu.includes(fe)?(r=1,i.interrupt?n(C):D(C)):P1.includes(l.toLowerCase())?(r=6,U?(e.consume(C),x):i.interrupt?n(C):D(C)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(C):o?y(C):E(C))}return C===45||In(C)?(e.consume(C),l+=String.fromCharCode(C),v):s(C)}function x(C){return C===62?(e.consume(C),i.interrupt?n:D):s(C)}function y(C){return Rt(C)?(e.consume(C),y):_(C)}function E(C){return C===47?(e.consume(C),_):C===58||C===95||Bn(C)?(e.consume(C),k):Rt(C)?(e.consume(C),E):_(C)}function k(C){return C===45||C===46||C===58||C===95||In(C)?(e.consume(C),k):T(C)}function T(C){return C===61?(e.consume(C),N):Rt(C)?(e.consume(C),T):E(C)}function N(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(e.consume(C),u=C,S):Rt(C)?(e.consume(C),N):j(C)}function S(C){return C===u?(e.consume(C),u=null,P):C===null||vt(C)?s(C):(e.consume(C),S)}function j(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Vt(C)?T(C):(e.consume(C),j)}function P(C){return C===47||C===62||Rt(C)?E(C):s(C)}function _(C){return C===62?(e.consume(C),I):s(C)}function I(C){return C===null||vt(C)?D(C):Rt(C)?(e.consume(C),I):s(C)}function D(C){return C===45&&r===2?(e.consume(C),w):C===60&&r===1?(e.consume(C),H):C===62&&r===4?(e.consume(C),z):C===63&&r===3?(e.consume(C),M):C===93&&r===5?(e.consume(C),B):vt(C)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(D1,X,G)(C)):C===null||vt(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),D)}function G(C){return e.check(L1,$,X)(C)}function $(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),R}function R(C){return C===null||vt(C)?G(C):(e.enter("htmlFlowData"),D(C))}function w(C){return C===45?(e.consume(C),M):D(C)}function H(C){return C===47?(e.consume(C),l="",V):D(C)}function V(C){if(C===62){const U=l.toLowerCase();return yu.includes(U)?(e.consume(C),z):D(C)}return Bn(C)&&l.length<8?(e.consume(C),l+=String.fromCharCode(C),V):D(C)}function B(C){return C===93?(e.consume(C),M):D(C)}function M(C){return C===62?(e.consume(C),z):C===45&&r===2?(e.consume(C),M):D(C)}function z(C){return C===null||vt(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),z)}function X(C){return e.exit("htmlFlow"),n(C)}}function O1(e,n,s){const i=this;return r;function r(l){return vt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}function U1(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(tr,n,s)}}const B1={name:"htmlText",tokenize:H1};function H1(e,n,s){const i=this;let r,o,l;return c;function c(M){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(M),u}function u(M){return M===33?(e.consume(M),d):M===47?(e.consume(M),T):M===63?(e.consume(M),E):Bn(M)?(e.consume(M),j):s(M)}function d(M){return M===45?(e.consume(M),m):M===91?(e.consume(M),o=0,f):Bn(M)?(e.consume(M),y):s(M)}function m(M){return M===45?(e.consume(M),p):s(M)}function h(M){return M===null?s(M):M===45?(e.consume(M),g):vt(M)?(l=h,H(M)):(e.consume(M),h)}function g(M){return M===45?(e.consume(M),p):h(M)}function p(M){return M===62?w(M):M===45?g(M):h(M)}function f(M){const z="CDATA[";return M===z.charCodeAt(o++)?(e.consume(M),o===z.length?b:f):s(M)}function b(M){return M===null?s(M):M===93?(e.consume(M),v):vt(M)?(l=b,H(M)):(e.consume(M),b)}function v(M){return M===93?(e.consume(M),x):b(M)}function x(M){return M===62?w(M):M===93?(e.consume(M),x):b(M)}function y(M){return M===null||M===62?w(M):vt(M)?(l=y,H(M)):(e.consume(M),y)}function E(M){return M===null?s(M):M===63?(e.consume(M),k):vt(M)?(l=E,H(M)):(e.consume(M),E)}function k(M){return M===62?w(M):E(M)}function T(M){return Bn(M)?(e.consume(M),N):s(M)}function N(M){return M===45||In(M)?(e.consume(M),N):S(M)}function S(M){return vt(M)?(l=S,H(M)):Rt(M)?(e.consume(M),S):w(M)}function j(M){return M===45||In(M)?(e.consume(M),j):M===47||M===62||Vt(M)?P(M):s(M)}function P(M){return M===47?(e.consume(M),w):M===58||M===95||Bn(M)?(e.consume(M),_):vt(M)?(l=P,H(M)):Rt(M)?(e.consume(M),P):w(M)}function _(M){return M===45||M===46||M===58||M===95||In(M)?(e.consume(M),_):I(M)}function I(M){return M===61?(e.consume(M),D):vt(M)?(l=I,H(M)):Rt(M)?(e.consume(M),I):P(M)}function D(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(e.consume(M),r=M,G):vt(M)?(l=D,H(M)):Rt(M)?(e.consume(M),D):(e.consume(M),$)}function G(M){return M===r?(e.consume(M),r=void 0,R):M===null?s(M):vt(M)?(l=G,H(M)):(e.consume(M),G)}function $(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||Vt(M)?P(M):(e.consume(M),$)}function R(M){return M===47||M===62||Vt(M)?P(M):s(M)}function w(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),n):s(M)}function H(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),V}function V(M){return Rt(M)?Lt(e,B,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):B(M)}function B(M){return e.enter("htmlTextData"),l(M)}}const kc={name:"labelEnd",resolveAll:G1,resolveTo:K1,tokenize:J1},q1={tokenize:Y1},V1={tokenize:Q1},W1={tokenize:X1};function G1(e){let n=-1;const s=[];for(;++n<e.length;){const i=e[n][1];if(s.push(e[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return e.length!==s.length&&ds(e,0,e.length,s),e}function K1(e,n){let s=e.length,i=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(l=s);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,n],["enter",d,n]],c=ws(c,e.slice(o+1,o+i+3)),c=ws(c,[["enter",m,n]]),c=ws(c,co(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=ws(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=ws(c,e.slice(l+1)),c=ws(c,[["exit",u,n]]),ds(e,o,e.length,c),e}function J1(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(g){return o?o._inactive?h(g):(l=i.parser.defined.includes(Rs(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):s(g)}function u(g){return g===40?e.attempt(q1,m,l?m:h)(g):g===91?e.attempt(V1,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(W1,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function Y1(e,n,s){return i;function i(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Vt(h)?Pa(e,o)(h):o(h)}function o(h){return h===41?m(h):tp(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Vt(h)?Pa(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?sp(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return Vt(h)?Pa(e,m)(h):m(h)}function m(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),n):s(h)}}function Q1(e,n,s){const i=this;return r;function r(c){return np.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Rs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function X1(e,n,s){return i;function i(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const Z1={name:"labelStartImage",resolveAll:kc.resolveAll,tokenize:eS};function eS(e,n,s){const i=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(c):n(c)}}const tS={name:"labelStartLink",resolveAll:kc.resolveAll,tokenize:nS};function nS(e,n,s){const i=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(l):n(l)}}const Ho={name:"lineEnding",tokenize:sS};function sS(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Lt(e,n,"linePrefix")}}const _r={name:"thematicBreak",tokenize:iS};function iS(e,n,s){let i=0,r;return o;function o(d){return e.enter("thematicBreak"),l(d)}function l(d){return r=d,c(d)}function c(d){return d===r?(e.enter("thematicBreakSequence"),u(d)):i>=3&&(d===null||vt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Rt(d)?Lt(e,c,"whitespace")(d):c(d))}}const Xn={continuation:{tokenize:lS},exit:dS,name:"list",tokenize:oS},aS={partial:!0,tokenize:uS},rS={partial:!0,tokenize:cS};function oS(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Ol(p)){if(i.containerState.type||(i.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(_r,s,d)(p):d(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return s(p)}function u(p){return Ol(p)&&++l<10?(e.consume(p),u):(!i.interrupt||l<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),d(p)):s(p)}function d(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(tr,i.interrupt?s:m,e.attempt(aS,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Rt(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function lS(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(tr,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Lt(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Rt(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(rS,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Lt(e,e.attempt(Xn,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function cS(e,n,s){const i=this;return Lt(e,r,"listItemIndent",i.containerState.size+1);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===i.containerState.size?n(o):s(o)}}function dS(e){e.exit(this.containerState.type)}function uS(e,n,s){const i=this;return Lt(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!Rt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const ku={name:"setextUnderline",resolveTo:mS,tokenize:hS};function mS(e,n){let s=e.length,i,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){i=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[i][1],n]),e[i][1].end={...e[o][1].end}):e[i][1]=l,e.push(["exit",l,n]),e}function hS(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),Rt(d)?Lt(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||vt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const pS={tokenize:fS};function fS(e){const n=this,s=e.attempt(tr,i,e.attempt(this.parser.constructs.flowInitial,r,Lt(e,e.attempt(this.parser.constructs.flow,r,e.attempt(y1,r)),"linePrefix")));return s;function i(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const gS={resolveAll:ap()},bS=ip("string"),xS=ip("text");function ip(e){return{resolveAll:ap(e==="text"?vS:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function ap(e){return n;function n(s,i){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,i):s}}function vS(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const i=e[s-1][1],r=n.sliceStream(i);let o=r.length,l=-1,c=0,u;for(;o--;){const d=r[o];if(typeof d=="string"){for(l=d.length;d.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(d===-2)u=!0,c++;else if(d!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const d={type:s===e.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:i.start._bufferIndex+l,_index:i.start._index+o,line:i.end.line,column:i.end.column-c,offset:i.end.offset-c},end:{...i.end}};i.end={...d.start},i.start.offset===i.end.offset?Object.assign(i,d):(e.splice(s,0,["enter",d,n],["exit",d,n]),s+=2)}s++}return e}const yS={42:Xn,43:Xn,45:Xn,48:Xn,49:Xn,50:Xn,51:Xn,52:Xn,53:Xn,54:Xn,55:Xn,56:Xn,57:Xn,62:Qh},kS={91:S1},jS={[-2]:Bo,[-1]:Bo,32:Bo},wS={35:R1,42:_r,45:[ku,_r],60:$1,61:ku,95:_r,96:vu,126:vu},NS={38:Zh,92:Xh},SS={[-5]:Ho,[-4]:Ho,[-3]:Ho,33:Z1,38:Zh,42:Ul,60:[t1,B1],91:tS,92:[_1,Xh],93:kc,95:Ul,96:p1},CS={null:[Ul,gS]},ES={null:[42,95]},MS={null:[]},_S=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:ES,contentInitial:kS,disable:MS,document:yS,flow:wS,flowInitial:jS,insideSpan:CS,string:NS,text:SS},Symbol.toStringTag,{value:"Module"}));function AS(e,n,s){let i={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const u={attempt:S(T),check:S(N),consume:y,enter:E,exit:k,interrupt:S(N,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(I){return l=ws(l,I),v(),l[l.length-1]!==null?[]:(j(n,0),d.events=co(o,d.events,d),d.events)}function g(I,D){return TS(p(I),D)}function p(I){return RS(l,I)}function f(){const{_bufferIndex:I,_index:D,line:G,column:$,offset:R}=i;return{_bufferIndex:I,_index:D,line:G,column:$,offset:R}}function b(I){r[I.line]=I.column,_()}function v(){let I;for(;i._index<l.length;){const D=l[i._index];if(typeof D=="string")for(I=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===I&&i._bufferIndex<D.length;)x(D.charCodeAt(i._bufferIndex));else x(D)}}function x(I){m=m(I)}function y(I){vt(I)?(i.line++,i.column=1,i.offset+=I===-3?2:1,_()):I!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=I}function E(I,D){const G=D||{};return G.type=I,G.start=f(),d.events.push(["enter",G,d]),c.push(G),G}function k(I){const D=c.pop();return D.end=f(),d.events.push(["exit",D,d]),D}function T(I,D){j(I,D.from)}function N(I,D){D.restore()}function S(I,D){return G;function G($,R,w){let H,V,B,M;return Array.isArray($)?X($):"tokenize"in $?X([$]):z($);function z(ie){return re;function re(F){const ce=F!==null&&ie[F],ae=F!==null&&ie.null,Q=[...Array.isArray(ce)?ce:ce?[ce]:[],...Array.isArray(ae)?ae:ae?[ae]:[]];return X(Q)(F)}}function X(ie){return H=ie,V=0,ie.length===0?w:C(ie[V])}function C(ie){return re;function re(F){return M=P(),B=ie,ie.partial||(d.currentConstruct=ie),ie.name&&d.parser.constructs.disable.null.includes(ie.name)?fe():ie.tokenize.call(D?Object.assign(Object.create(d),D):d,u,U,fe)(F)}}function U(ie){return I(B,M),R}function fe(ie){return M.restore(),++V<H.length?C(H[V]):w}}}function j(I,D){I.resolveAll&&!o.includes(I)&&o.push(I),I.resolve&&ds(d.events,D,d.events.length-D,I.resolve(d.events.slice(D),d)),I.resolveTo&&(d.events=I.resolveTo(d.events,d))}function P(){const I=f(),D=d.previous,G=d.currentConstruct,$=d.events.length,R=Array.from(c);return{from:$,restore:w};function w(){i=I,d.previous=D,d.currentConstruct=G,d.events.length=$,c=R,_()}}function _(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function RS(e,n){const s=n.start._index,i=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(i,o)];else{if(l=e.slice(s,r),i>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(i):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function TS(e,n){let s=-1;const i=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
579
- `;break}case-3:{l=`\r
580
- `;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,i.push(l)}return i.join("")}function IS(e){const i={constructs:Jh([_S,...(e||{}).extensions||[]]),content:r(KN),defined:[],document:r(YN),flow:r(pS),lazy:{},string:r(bS),text:r(xS)};return i;function r(o){return l;function l(c){return AS(i,o,c)}}}function PS(e){for(;!ep(e););return e}const ju=/[\0\t\n\r]/g;function $S(){let e=1,n="",s=!0,i;return r;function r(o,l,c){const u=[];let d,m,h,g,p;for(o=n+(typeof o=="string"?o.toString():new TextDecoder(l||void 0).decode(o)),h=0,n="",s&&(o.charCodeAt(0)===65279&&h++,s=void 0);h<o.length;){if(ju.lastIndex=h,d=ju.exec(o),g=d&&d.index!==void 0?d.index:o.length,p=o.charCodeAt(g),!d){n=o.slice(h);break}if(p===10&&h===g&&i)u.push(-3),i=void 0;else switch(i&&(u.push(-5),i=void 0),h<g&&(u.push(o.slice(h,g)),e+=g-h),p){case 0:{u.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,u.push(-2);e++<m;)u.push(-1);break}case 10:{u.push(-4),e=1;break}default:i=!0,e=1}h=g+1}return c&&(i&&u.push(-5),n&&u.push(n),u.push(null)),u}}const DS=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function LS(e){return e.replace(DS,zS)}function zS(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Yh(s.slice(o?2:1),o?16:10)}return yc(s)||e}const rp={}.hasOwnProperty;function FS(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),OS(s)(PS(IS(s).document().write($S()(e,n,!0))))}function OS(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(We),autolinkProtocol:P,autolinkEmail:P,atxHeading:o(Me),blockQuote:o(ae),characterEscape:P,characterReference:P,codeFenced:o(Q),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Q,l),codeText:o(de,l),codeTextData:P,data:P,codeFlowValue:P,definition:o(Re),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(ge),hardBreakEscape:o(te),hardBreakTrailing:o(te),htmlFlow:o(Ce,l),htmlFlowData:P,htmlText:o(Ce,l),htmlTextData:P,image:o($e),label:l,link:o(We),listItem:o(Ee),listItemValue:g,listOrdered:o(Ge,h),listUnordered:o(Ge),paragraph:o(Ae),reference:C,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(Me),strong:o(Oe),thematicBreak:o(De)},exit:{atxHeading:u(),atxHeadingSequence:T,autolink:u(),autolinkEmail:ce,autolinkProtocol:F,blockQuote:u(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:fe,characterReferenceMarkerNumeric:fe,characterReferenceValue:ie,characterReference:re,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:_,codeIndented:u(x),codeText:u(R),codeTextData:_,data:_,definition:u(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:E,emphasis:u(),hardBreakEscape:u(D),hardBreakTrailing:u(D),htmlFlow:u(G),htmlFlowData:_,htmlText:u($),htmlTextData:_,image:u(H),label:B,labelText:V,lineEnding:I,link:u(w),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:U,resourceDestinationString:M,resourceTitleString:z,resource:X,setextHeading:u(j),setextHeadingLineSequence:S,setextHeadingText:N,strong:u(),thematicBreak:u()}};op(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(se){let K={type:"root",children:[]};const me={stack:[K],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},ee=[];let he=-1;for(;++he<se.length;)if(se[he][1].type==="listOrdered"||se[he][1].type==="listUnordered")if(se[he][0]==="enter")ee.push(he);else{const le=ee.pop();he=r(se,le,he)}for(he=-1;++he<se.length;){const le=n[se[he][0]];rp.call(le,se[he][1].type)&&le[se[he][1].type].call(Object.assign({sliceSerialize:se[he][2].sliceSerialize},me),se[he][1])}if(me.tokenStack.length>0){const le=me.tokenStack[me.tokenStack.length-1];(le[1]||wu).call(me,void 0,le[0])}for(K.position={start:ri(se.length>0?se[0][1].start:{line:1,column:1,offset:0}),end:ri(se.length>0?se[se.length-2][1].end:{line:1,column:1,offset:0})},he=-1;++he<n.transforms.length;)K=n.transforms[he](K)||K;return K}function r(se,K,me){let ee=K-1,he=-1,le=!1,Ie,Ze,rt,oe;for(;++ee<=me;){const Z=se[ee];switch(Z[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Z[0]==="enter"?he++:he--,oe=void 0;break}case"lineEndingBlank":{Z[0]==="enter"&&(Ie&&!oe&&!he&&!rt&&(rt=ee),oe=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:oe=void 0}if(!he&&Z[0]==="enter"&&Z[1].type==="listItemPrefix"||he===-1&&Z[0]==="exit"&&(Z[1].type==="listUnordered"||Z[1].type==="listOrdered")){if(Ie){let pe=ee;for(Ze=void 0;pe--;){const Se=se[pe];if(Se[1].type==="lineEnding"||Se[1].type==="lineEndingBlank"){if(Se[0]==="exit")continue;Ze&&(se[Ze][1].type="lineEndingBlank",le=!0),Se[1].type="lineEnding",Ze=pe}else if(!(Se[1].type==="linePrefix"||Se[1].type==="blockQuotePrefix"||Se[1].type==="blockQuotePrefixWhitespace"||Se[1].type==="blockQuoteMarker"||Se[1].type==="listItemIndent"))break}rt&&(!Ze||rt<Ze)&&(Ie._spread=!0),Ie.end=Object.assign({},Ze?se[Ze][1].start:Z[1].end),se.splice(Ze||ee,0,["exit",Ie,Z[2]]),ee++,me++}if(Z[1].type==="listItemPrefix"){const pe={type:"listItem",_spread:!1,start:Object.assign({},Z[1].start),end:void 0};Ie=pe,se.splice(ee,0,["enter",pe,Z[2]]),ee++,me++,rt=void 0,oe=!0}}}return se[K][1]._spread=le,me}function o(se,K){return me;function me(ee){c.call(this,se(ee),ee),K&&K.call(this,ee)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(se,K,me){this.stack[this.stack.length-1].children.push(se),this.stack.push(se),this.tokenStack.push([K,me||void 0]),se.position={start:ri(K.start),end:void 0}}function u(se){return K;function K(me){se&&se.call(this,me),d.call(this,me)}}function d(se,K){const me=this.stack.pop(),ee=this.tokenStack.pop();if(ee)ee[0].type!==se.type&&(K?K.call(this,se,ee[0]):(ee[1]||wu).call(this,se,ee[0]));else throw new Error("Cannot close `"+se.type+"` ("+Ia({start:se.start,end:se.end})+"): it’s not open");me.position.end=ri(se.end)}function m(){return vc(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(se){if(this.data.expectingFirstListItemValue){const K=this.stack[this.stack.length-2];K.start=Number.parseInt(this.sliceSerialize(se),10),this.data.expectingFirstListItemValue=void 0}}function p(){const se=this.resume(),K=this.stack[this.stack.length-1];K.lang=se}function f(){const se=this.resume(),K=this.stack[this.stack.length-1];K.meta=se}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const se=this.resume(),K=this.stack[this.stack.length-1];K.value=se.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const se=this.resume(),K=this.stack[this.stack.length-1];K.value=se.replace(/(\r?\n|\r)$/g,"")}function y(se){const K=this.resume(),me=this.stack[this.stack.length-1];me.label=K,me.identifier=Rs(this.sliceSerialize(se)).toLowerCase()}function E(){const se=this.resume(),K=this.stack[this.stack.length-1];K.title=se}function k(){const se=this.resume(),K=this.stack[this.stack.length-1];K.url=se}function T(se){const K=this.stack[this.stack.length-1];if(!K.depth){const me=this.sliceSerialize(se).length;K.depth=me}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function S(se){const K=this.stack[this.stack.length-1];K.depth=this.sliceSerialize(se).codePointAt(0)===61?1:2}function j(){this.data.setextHeadingSlurpLineEnding=void 0}function P(se){const me=this.stack[this.stack.length-1].children;let ee=me[me.length-1];(!ee||ee.type!=="text")&&(ee=ke(),ee.position={start:ri(se.start),end:void 0},me.push(ee)),this.stack.push(ee)}function _(se){const K=this.stack.pop();K.value+=this.sliceSerialize(se),K.position.end=ri(se.end)}function I(se){const K=this.stack[this.stack.length-1];if(this.data.atHardBreak){const me=K.children[K.children.length-1];me.position.end=ri(se.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(K.type)&&(P.call(this,se),_.call(this,se))}function D(){this.data.atHardBreak=!0}function G(){const se=this.resume(),K=this.stack[this.stack.length-1];K.value=se}function $(){const se=this.resume(),K=this.stack[this.stack.length-1];K.value=se}function R(){const se=this.resume(),K=this.stack[this.stack.length-1];K.value=se}function w(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const K=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=K,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function H(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const K=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=K,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function V(se){const K=this.sliceSerialize(se),me=this.stack[this.stack.length-2];me.label=LS(K),me.identifier=Rs(K).toLowerCase()}function B(){const se=this.stack[this.stack.length-1],K=this.resume(),me=this.stack[this.stack.length-1];if(this.data.inReference=!0,me.type==="link"){const ee=se.children;me.children=ee}else me.alt=K}function M(){const se=this.resume(),K=this.stack[this.stack.length-1];K.url=se}function z(){const se=this.resume(),K=this.stack[this.stack.length-1];K.title=se}function X(){this.data.inReference=void 0}function C(){this.data.referenceType="collapsed"}function U(se){const K=this.resume(),me=this.stack[this.stack.length-1];me.label=K,me.identifier=Rs(this.sliceSerialize(se)).toLowerCase(),this.data.referenceType="full"}function fe(se){this.data.characterReferenceType=se.type}function ie(se){const K=this.sliceSerialize(se),me=this.data.characterReferenceType;let ee;me?(ee=Yh(K,me==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ee=yc(K);const he=this.stack[this.stack.length-1];he.value+=ee}function re(se){const K=this.stack.pop();K.position.end=ri(se.end)}function F(se){_.call(this,se);const K=this.stack[this.stack.length-1];K.url=this.sliceSerialize(se)}function ce(se){_.call(this,se);const K=this.stack[this.stack.length-1];K.url="mailto:"+this.sliceSerialize(se)}function ae(){return{type:"blockquote",children:[]}}function Q(){return{type:"code",lang:null,meta:null,value:""}}function de(){return{type:"inlineCode",value:""}}function Re(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ge(){return{type:"emphasis",children:[]}}function Me(){return{type:"heading",depth:0,children:[]}}function te(){return{type:"break"}}function Ce(){return{type:"html",value:""}}function $e(){return{type:"image",title:null,url:"",alt:null}}function We(){return{type:"link",title:null,url:"",children:[]}}function Ge(se){return{type:"list",ordered:se.type==="listOrdered",start:null,spread:se._spread,children:[]}}function Ee(se){return{type:"listItem",spread:se._spread,checked:null,children:[]}}function Ae(){return{type:"paragraph",children:[]}}function Oe(){return{type:"strong",children:[]}}function ke(){return{type:"text",value:""}}function De(){return{type:"thematicBreak"}}}function ri(e){return{line:e.line,column:e.column,offset:e.offset}}function op(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?op(e,i):US(e,i)}}function US(e,n){let s;for(s in n)if(rp.call(n,s))switch(s){case"canContainEols":{const i=n[s];i&&e[s].push(...i);break}case"transforms":{const i=n[s];i&&e[s].push(...i);break}case"enter":case"exit":{const i=n[s];i&&Object.assign(e[s],i);break}}}function wu(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Ia({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Ia({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Ia({start:n.start,end:n.end})+") is still open")}function BS(e){const n=this;n.parser=s;function s(i){return FS(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function HS(e,n){const s={type:"element",tagName:"blockquote",properties:{},children:e.wrap(e.all(n),!0)};return e.patch(n,s),e.applyData(n,s)}function qS(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
581
- `}]}function VS(e,n){const s=n.value?n.value+`
582
- `:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:i,children:[{type:"text",value:s}]};return n.meta&&(o.data={meta:n.meta}),e.patch(n,o),o=e.applyData(n,o),o={type:"element",tagName:"pre",properties:{},children:[o]},e.patch(n,o),o}function WS(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function GS(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function KS(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=la(i.toLowerCase()),o=e.footnoteOrder.indexOf(i);let l,c=e.footnoteCounts.get(i);c===void 0?(c=0,e.footnoteOrder.push(i),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(i,c);const u={type:"element",tagName:"a",properties:{href:"#"+s+"fn-"+r,id:s+"fnref-"+r+(c>1?"-"+c:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};e.patch(n,u);const d={type:"element",tagName:"sup",properties:{},children:[u]};return e.patch(n,d),e.applyData(n,d)}function JS(e,n){const s={type:"element",tagName:"h"+n.depth,properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function YS(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function lp(e,n){const s=n.referenceType;let i="]";if(s==="collapsed"?i+="[]":s==="full"&&(i+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+i}];const r=e.all(n),o=r[0];o&&o.type==="text"?o.value="["+o.value:r.unshift({type:"text",value:"["});const l=r[r.length-1];return l&&l.type==="text"?l.value+=i:r.push({type:"text",value:i}),r}function QS(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return lp(e,n);const r={src:la(i.url||""),alt:n.alt};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function XS(e,n){const s={src:la(n.url)};n.alt!==null&&n.alt!==void 0&&(s.alt=n.alt),n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,i),e.applyData(n,i)}function ZS(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const i={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,i),e.applyData(n,i)}function e0(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return lp(e,n);const r={href:la(i.url||"")};i.title!==null&&i.title!==void 0&&(r.title=i.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function t0(e,n){const s={href:la(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const i={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function n0(e,n,s){const i=e.all(n),r=s?s0(s):cp(n),o={},l=[];if(typeof n.checked=="boolean"){const m=i[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},i.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:n.checked,disabled:!0},children:[]}),o.className=["task-list-item"]}let c=-1;for(;++c<i.length;){const m=i[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
583
- `}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const u=i[i.length-1];u&&(r||u.type!=="element"||u.tagName!=="p")&&l.push({type:"text",value:`
584
- `});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function s0(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let i=-1;for(;!n&&++i<s.length;)n=cp(s[i])}return n}function cp(e){const n=e.spread;return n??e.children.length>1}function i0(e,n){const s={},i=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<i.length;){const l=i[r];if(l.type==="element"&&l.tagName==="li"&&l.properties&&Array.isArray(l.properties.className)&&l.properties.className.includes("task-list-item")){s.className=["contains-task-list"];break}}const o={type:"element",tagName:n.ordered?"ol":"ul",properties:s,children:e.wrap(i,!0)};return e.patch(n,o),e.applyData(n,o)}function a0(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function r0(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function o0(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function l0(e,n){const s=e.all(n),i=s.shift(),r=[];if(i){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([i],!0)};e.patch(n.children[0],l),r.push(l)}if(s.length>0){const l={type:"element",tagName:"tbody",properties:{},children:e.wrap(s,!0)},c=fc(n.children[1]),u=Bh(n.children[n.children.length-1]);c&&u&&(l.position={start:c,end:u}),r.push(l)}const o={type:"element",tagName:"table",properties:{},children:e.wrap(r,!0)};return e.patch(n,o),e.applyData(n,o)}function c0(e,n,s){const i=s?s.children:void 0,o=(i?i.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let u=-1;const d=[];for(;++u<c;){const h=n.children[u],g={},p=l?l[u]:void 0;p&&(g.align=p);let f={type:"element",tagName:o,properties:g,children:[]};h&&(f.children=e.all(h),e.patch(h,f),f=e.applyData(h,f)),d.push(f)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(d,!0)};return e.patch(n,m),e.applyData(n,m)}function d0(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Nu=9,Su=32;function u0(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Cu(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Cu(n.slice(r),r>0,!1)),o.join("")}function Cu(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Nu||o===Su;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Nu||o===Su;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function m0(e,n){const s={type:"text",value:u0(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function h0(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const p0={blockquote:HS,break:qS,code:VS,delete:WS,emphasis:GS,footnoteReference:KS,heading:JS,html:YS,imageReference:QS,image:XS,inlineCode:ZS,linkReference:e0,link:t0,listItem:n0,list:i0,paragraph:a0,root:r0,strong:o0,table:l0,tableCell:d0,tableRow:c0,text:m0,thematicBreak:h0,toml:gr,yaml:gr,definition:gr,footnoteDefinition:gr};function gr(){}const dp=-1,uo=0,$a=1,Hr=2,jc=3,wc=4,Nc=5,Sc=6,up=7,mp=8,Eu=typeof self=="object"?self:globalThis,f0=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),i=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case uo:case dp:return s(l,r);case $a:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Hr:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case jc:return s(new Date(l),r);case wc:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Nc:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Sc:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case up:{const{name:c,message:u}=l;return s(new Eu[c](u),r)}case mp:return s(BigInt(l),r);case"BigInt":return s(Object(BigInt(l)),r);case"ArrayBuffer":return s(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:c}=new Uint8Array(l);return s(new DataView(c),l)}}return s(new Eu[o](l),r)};return i},Mu=e=>f0(new Map,e)(0),zi="",{toString:g0}={},{keys:b0}=Object,va=e=>{const n=typeof e;if(n!=="object"||!e)return[uo,n];const s=g0.call(e).slice(8,-1);switch(s){case"Array":return[$a,zi];case"Object":return[Hr,zi];case"Date":return[jc,zi];case"RegExp":return[wc,zi];case"Map":return[Nc,zi];case"Set":return[Sc,zi];case"DataView":return[$a,s]}return s.includes("Array")?[$a,s]:s.includes("Error")?[up,s]:[Hr,s]},br=([e,n])=>e===uo&&(n==="function"||n==="symbol"),x0=(e,n,s,i)=>{const r=(l,c)=>{const u=i.push(l)-1;return s.set(c,u),u},o=l=>{if(s.has(l))return s.get(l);let[c,u]=va(l);switch(c){case uo:{let m=l;switch(u){case"bigint":c=mp,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([dp],l)}return r([c,m],l)}case $a:{if(u){let g=l;return u==="DataView"?g=new Uint8Array(l.buffer):u==="ArrayBuffer"&&(g=new Uint8Array(l)),r([u,[...g]],l)}const m=[],h=r([c,m],l);for(const g of l)m.push(o(g));return h}case Hr:{if(u)switch(u){case"BigInt":return r([u,l.toString()],l);case"Boolean":case"Number":case"String":return r([u,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const g of b0(l))(e||!br(va(l[g])))&&m.push([o(g),o(l[g])]);return h}case jc:return r([c,l.toISOString()],l);case wc:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Nc:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(br(va(g))||br(va(p))))&&m.push([o(g),o(p)]);return h}case Sc:{const m=[],h=r([c,m],l);for(const g of l)(e||!br(va(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},_u=(e,{json:n,lossy:s}={})=>{const i=[];return x0(!(n||s),!!n,new Map,i)(e),i},qr=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Mu(_u(e,n)):structuredClone(e):(e,n)=>Mu(_u(e,n));function v0(e,n){const s=[{type:"text",value:"↩"}];return n>1&&s.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(n)}]}),s}function y0(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function k0(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||v0,i=e.options.footnoteBackLabel||y0,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let u=-1;for(;++u<e.footnoteOrder.length;){const d=e.footnoteById.get(e.footnoteOrder[u]);if(!d)continue;const m=e.all(d),h=String(d.identifier).toUpperCase(),g=la(h.toLowerCase());let p=0;const f=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){f.length>0&&f.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else m.push(...f);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:e.wrap(m,!0)};e.patch(d,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...qr(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
585
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
586
- `}]}}const mo=(function(e){if(e==null)return S0;if(typeof e=="function")return ho(e);if(typeof e=="object")return Array.isArray(e)?j0(e):w0(e);if(typeof e=="string")return N0(e);throw new Error("Expected function, string, or object as test")});function j0(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=mo(e[s]);return ho(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function w0(e){const n=e;return ho(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function N0(e){return ho(n);function n(s){return s&&s.type===e}}function ho(e){return n;function n(s,i,r){return!!(C0(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function S0(){return!0}function C0(e){return e!==null&&typeof e=="object"&&"type"in e}const hp=[],E0=!0,Bl=!1,M0="skip";function pp(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=mo(r),l=i?-1:1;c(e,void 0,[])();function c(u,d,m){const h=u&&typeof u=="object"?u:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(g,"name",{value:"node ("+(u.type+(p?"<"+p+">":""))+")"})}return g;function g(){let p=hp,f,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=_0(s(u,m)),p[0]===Bl))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==M0)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(f=c(y,b,v)(),f[0]===Bl)return f;b=typeof f[1]=="number"?f[1]:b+l}}return p}}}function _0(e){return Array.isArray(e)?e:typeof e=="number"?[E0,e]:e==null?hp:[e]}function Cc(e,n,s,i){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=i),pp(e,o,c,r);function c(u,d){const m=d[d.length-1],h=m?m.children.indexOf(u):void 0;return l(u,h,m)}}const Hl={}.hasOwnProperty,A0={};function R0(e,n){const s=n||A0,i=new Map,r=new Map,o=new Map,l={...p0,...s.handlers},c={all:d,applyData:I0,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:T0,wrap:$0};return Cc(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?i:r,g=String(m.identifier).toUpperCase();h.has(g)||h.set(g,m)}}),c;function u(m,h){const g=m.type,p=c.handlers[g];if(Hl.call(c.handlers,g)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(g)){if("children"in m){const{children:b,...v}=m,x=qr(v);return x.children=c.all(m),x}return qr(m)}return(c.options.unknownHandler||P0)(c,m,h)}function d(m){const h=[];if("children"in m){const g=m.children;let p=-1;for(;++p<g.length;){const f=c.one(g[p],m);if(f){if(p&&g[p-1].type==="break"&&(!Array.isArray(f)&&f.type==="text"&&(f.value=Au(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=Au(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function T0(e,n){e.position&&(n.position=yN(e))}function I0(e,n){let s=n;if(e&&e.data){const i=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof i=="string")if(s.type==="element")s.tagName=i;else{const l="children"in s?s.children:[s];s={type:"element",tagName:i,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,qr(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function P0(e,n){const s=n.data||{},i="value"in n&&!(Hl.call(s,"hProperties")||Hl.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,i),e.applyData(n,i)}function $0(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
587
- `});++i<e.length;)i&&s.push({type:"text",value:`
588
- `}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
589
- `}),s}function Au(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Ru(e,n){const s=R0(e,n),i=s.one(e,void 0),r=k0(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
590
- `},r),o}function D0(e,n){return e&&"run"in e?async function(s,i){const r=Ru(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Ru(s,{file:i,...e||n})}}function Tu(e){if(e)throw e}var qo,Iu;function L0(){if(Iu)return qo;Iu=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,r=function(d){return typeof Array.isArray=="function"?Array.isArray(d):n.call(d)==="[object Array]"},o=function(d){if(!d||n.call(d)!=="[object Object]")return!1;var m=e.call(d,"constructor"),h=d.constructor&&d.constructor.prototype&&e.call(d.constructor.prototype,"isPrototypeOf");if(d.constructor&&!m&&!h)return!1;var g;for(g in d);return typeof g>"u"||e.call(d,g)},l=function(d,m){s&&m.name==="__proto__"?s(d,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):d[m.name]=m.newValue},c=function(d,m){if(m==="__proto__")if(e.call(d,m)){if(i)return i(d,m).value}else return;return d[m]};return qo=function u(){var d,m,h,g,p,f,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),g=c(d,m),b!==g&&(y&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(b,{name:m,newValue:u(y,f,g)})):typeof g<"u"&&l(b,{name:m,newValue:g}));return b},qo}var z0=L0();const Vo=Om(z0);function ql(e){if(typeof e!="object"||e===null)return!1;const n=Object.getPrototypeOf(e);return(n===null||n===Object.prototype||Object.getPrototypeOf(n)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)}function F0(){const e=[],n={run:s,use:i};return n;function s(...r){let o=-1;const l=r.pop();if(typeof l!="function")throw new TypeError("Expected function as last argument, not "+l);c(null,...r);function c(u,...d){const m=e[++o];let h=-1;if(u){l(u);return}for(;++h<r.length;)(d[h]===null||d[h]===void 0)&&(d[h]=r[h]);r=d,m?O0(m,c)(...d):l(null,...d)}}function i(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function O0(e,n){let s;return i;function i(...l){const c=e.length>l.length;let u;c&&l.push(r);try{u=e.apply(this,l)}catch(d){const m=d;if(c&&s)throw m;return r(m)}c||(u&&u.then&&typeof u.then=="function"?u.then(o,r):u instanceof Error?r(u):o(u))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const zs={basename:U0,dirname:B0,extname:H0,join:q0,sep:"/"};function U0(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');nr(e);let s=0,i=-1,r=e.length,o;if(n===void 0||n.length===0||n.length>e.length){for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else i<0&&(o=!0,i=r+1);return i<0?"":e.slice(s,i)}if(n===e)return"";let l=-1,c=n.length-1;for(;r--;)if(e.codePointAt(r)===47){if(o){s=r+1;break}}else l<0&&(o=!0,l=r+1),c>-1&&(e.codePointAt(r)===n.codePointAt(c--)?c<0&&(i=r):(c=-1,i=l));return s===i?i=l:i<0&&(i=e.length),e.slice(s,i)}function B0(e){if(nr(e),e.length===0)return".";let n=-1,s=e.length,i;for(;--s;)if(e.codePointAt(s)===47){if(i){n=s;break}}else i||(i=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function H0(e){nr(e);let n=e.length,s=-1,i=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){i=n+1;break}continue}s<0&&(l=!0,s=n+1),c===46?r<0?r=n:o!==1&&(o=1):r>-1&&(o=-1)}return r<0||s<0||o===0||o===1&&r===s-1&&r===i+1?"":e.slice(r,s)}function q0(...e){let n=-1,s;for(;++n<e.length;)nr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":V0(s)}function V0(e){nr(e);const n=e.codePointAt(0)===47;let s=W0(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function W0(e,n){let s="",i=0,r=-1,o=0,l=-1,c,u;for(;++l<=e.length;){if(l<e.length)c=e.codePointAt(l);else{if(c===47)break;c=47}if(c===47){if(!(r===l-1||o===1))if(r!==l-1&&o===2){if(s.length<2||i!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(u=s.lastIndexOf("/"),u!==s.length-1){u<0?(s="",i=0):(s=s.slice(0,u),i=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",i=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",i=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),i=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function nr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const G0={cwd:K0};function K0(){return"/"}function Vl(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function J0(e){if(typeof e=="string")e=new URL(e);else if(!Vl(e)){const n=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+e+"`");throw n.code="ERR_INVALID_ARG_TYPE",n}if(e.protocol!=="file:"){const n=new TypeError("The URL must be of scheme file");throw n.code="ERR_INVALID_URL_SCHEME",n}return Y0(e)}function Y0(e){if(e.hostname!==""){const i=new TypeError('File URL host must be "localhost" or empty on darwin');throw i.code="ERR_INVALID_FILE_URL_HOST",i}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const i=n.codePointAt(s+2);if(i===70||i===102){const r=new TypeError("File URL path must not include encoded / characters");throw r.code="ERR_INVALID_FILE_URL_PATH",r}}return decodeURIComponent(n)}const Wo=["history","path","basename","stem","extname","dirname"];class fp{constructor(n){let s;n?Vl(n)?s={path:n}:typeof n=="string"||Q0(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":G0.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Wo.length;){const o=Wo[i];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)Wo.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?zs.basename(this.path):void 0}set basename(n){Ko(n,"basename"),Go(n,"basename"),this.path=zs.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?zs.dirname(this.path):void 0}set dirname(n){Pu(this.basename,"dirname"),this.path=zs.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?zs.extname(this.path):void 0}set extname(n){if(Go(n,"extname"),Pu(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=zs.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Vl(n)&&(n=J0(n)),Ko(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?zs.basename(this.path,this.extname):void 0}set stem(n){Ko(n,"stem"),Go(n,"stem"),this.path=zs.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 $n(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 Go(e,n){if(e&&e.includes(zs.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+zs.sep+"`")}function Ko(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Pu(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function Q0(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const X0=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),Z0={}.hasOwnProperty;class Ec extends X0{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=F0()}copy(){const n=new Ec;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Vo(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Qo("data",this.frozen),this.namespace[n]=s,this):Z0.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Qo("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=xr(n),i=this.parser||this.Parser;return Jo("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Jo("process",this.parser||this.Parser),Yo("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=xr(n),u=i.parse(c);i.run(u,c,function(m,h,g){if(m||!h||!g)return d(m);const p=h,f=i.stringify(p,g);nC(f)?g.value=f:g.result=f,d(m,g)});function d(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,i;return this.freeze(),Jo("processSync",this.parser||this.Parser),Yo("processSync",this.compiler||this.Compiler),this.process(n,r),Du("processSync","process",s),i;function r(o,l){s=!0,Tu(o),i=l}}run(n,s,i){$u(n),this.freeze();const r=this.transformers;return!i&&typeof s=="function"&&(i=s,s=void 0),i?o(void 0,i):new Promise(o);function o(l,c){const u=xr(s);r.run(n,u,d);function d(m,h,g){const p=h||n;m?c(m):l?l(p):i(void 0,p,g)}}}runSync(n,s){let i=!1,r;return this.run(n,s,o),Du("runSync","run",i),r;function o(l,c){Tu(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=xr(s),r=this.compiler||this.Compiler;return Yo("stringify",r),$u(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Qo("use",this.frozen),n!=null)if(typeof n=="function")u(n,s);else if(typeof n=="object")Array.isArray(n)?c(n):l(n);else throw new TypeError("Expected usable value, not `"+n+"`");return this;function o(d){if(typeof d=="function")u(d,[]);else if(typeof d=="object")if(Array.isArray(d)){const[m,...h]=d;u(m,h)}else l(d);else throw new TypeError("Expected usable value, not `"+d+"`")}function l(d){if(!("plugins"in d)&&!("settings"in d))throw new Error("Expected usable value but received an empty preset, which is probably a mistake: presets typically come with `plugins` and sometimes with `settings`, but this has neither");c(d.plugins),d.settings&&(r.settings=Vo(!0,r.settings,d.settings))}function c(d){let m=-1;if(d!=null)if(Array.isArray(d))for(;++m<d.length;){const h=d[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+d+"`")}function u(d,m){let h=-1,g=-1;for(;++h<i.length;)if(i[h][0]===d){g=h;break}if(g===-1)i.push([d,...m]);else if(m.length>0){let[p,...f]=m;const b=i[g][1];ql(b)&&ql(p)&&(p=Vo(!0,b,p)),i[g]=[d,p,...f]}}}}const eC=new Ec().freeze();function Jo(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Yo(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Qo(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function $u(e){if(!ql(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Du(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function xr(e){return tC(e)?e:new fp(e)}function tC(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function nC(e){return typeof e=="string"||sC(e)}function sC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const iC="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Lu=[],zu={allowDangerousHtml:!0},aC=/^(https?|ircs?|mailto|xmpp)$/i,rC=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function ei(e){const n=oC(e),s=lC(e);return cC(n.runSync(n.parse(s),s),e)}function oC(e){const n=e.rehypePlugins||Lu,s=e.remarkPlugins||Lu,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...zu}:zu;return eC().use(BS).use(s).use(D0,i).use(n)}function lC(e){const n=e.children||"",s=new fp;return typeof n=="string"&&(s.value=n),s}function cC(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||dC;for(const m of rC)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+iC+m.id,void 0);return Cc(e,d),SN(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function d(m,h,g){if(m.type==="raw"&&g&&typeof h=="number")return l?g.children.splice(h,1):g.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in Uo)if(Object.hasOwn(Uo,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],b=Uo[p];(b===null||b.includes(m.tagName))&&(m.properties[p]=u(String(f||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&i&&typeof h=="number"&&(p=!i(m,h,g)),p&&g&&typeof h=="number")return c&&m.children?g.children.splice(h,1,...m.children):g.children.splice(h,1),h}}}function dC(e){const n=e.indexOf(":"),s=e.indexOf("?"),i=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||i!==-1&&n>i||aC.test(e.slice(0,n))?e:""}function Fu(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let i=0,r=s.indexOf(n);for(;r!==-1;)i++,r=s.indexOf(n,r+n.length);return i}function uC(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function mC(e,n,s){const r=mo((s||{}).ignore||[]),o=hC(n);let l=-1;for(;++l<o.length;)pp(e,"text",c);function c(d,m){let h=-1,g;for(;++h<m.length;){const p=m[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return u(d,m)}function u(d,m){const h=m[m.length-1],g=o[l][0],p=o[l][1];let f=0;const v=h.children.indexOf(d);let x=!1,y=[];g.lastIndex=0;let E=g.exec(d.value);for(;E;){const k=E.index,T={index:E.index,input:E.input,stack:[...m,d]};let N=p(...E,T);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?g.lastIndex=k+1:(f!==k&&y.push({type:"text",value:d.value.slice(f,k)}),Array.isArray(N)?y.push(...N):N&&y.push(N),f=k+E[0].length,x=!0),!g.global)break;E=g.exec(d.value)}return x?(f<d.value.length&&y.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function hC(e){const n=[];if(!Array.isArray(e))throw new TypeError("Expected find and replace tuple or list of tuples");const s=!e[0]||Array.isArray(e[0])?e:[e];let i=-1;for(;++i<s.length;){const r=s[i];n.push([pC(r[0]),fC(r[1])])}return n}function pC(e){return typeof e=="string"?new RegExp(uC(e),"g"):e}function fC(e){return typeof e=="function"?e:function(){return e}}const Xo="phrasing",Zo=["autolink","link","image","label"];function gC(){return{transforms:[wC],enter:{literalAutolink:xC,literalAutolinkEmail:el,literalAutolinkHttp:el,literalAutolinkWww:el},exit:{literalAutolink:jC,literalAutolinkEmail:kC,literalAutolinkHttp:vC,literalAutolinkWww:yC}}}function bC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Xo,notInConstruct:Zo},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Xo,notInConstruct:Zo},{character:":",before:"[ps]",after:"\\/",inConstruct:Xo,notInConstruct:Zo}]}}function xC(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function el(e){this.config.enter.autolinkProtocol.call(this,e)}function vC(e){this.config.exit.autolinkProtocol.call(this,e)}function yC(e){this.config.exit.data.call(this,e);const n=this.stack[this.stack.length-1];n.type,n.url="http://"+this.sliceSerialize(e)}function kC(e){this.config.exit.autolinkEmail.call(this,e)}function jC(e){this.exit(e)}function wC(e){mC(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,NC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,SC]],{ignore:["link","linkReference"]})}function NC(e,n,s,i,r){let o="";if(!gp(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!CC(s)))return!1;const l=EC(s+i);if(!l[0])return!1;const c={type:"link",title:null,url:o+n+l[0],children:[{type:"text",value:n+l[0]}]};return l[1]?[c,{type:"text",value:l[1]}]:c}function SC(e,n,s,i){return!gp(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function CC(e){const n=e.split(".");return!(n.length<2||n[n.length-1]&&(/_/.test(n[n.length-1])||!/[a-zA-Z\d]/.test(n[n.length-1]))||n[n.length-2]&&(/_/.test(n[n.length-2])||!/[a-zA-Z\d]/.test(n[n.length-2])))}function EC(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],i=s.indexOf(")");const r=Fu(e,"(");let o=Fu(e,")");for(;i!==-1&&r>o;)e+=s.slice(0,i+1),s=s.slice(i+1),i=s.indexOf(")"),o++;return[e,s]}function gp(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Ei(s)||lo(s))&&(!n||s!==47)}bp.peek=DC;function MC(){this.buffer()}function _C(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function AC(){this.buffer()}function RC(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function TC(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Rs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function IC(e){this.exit(e)}function PC(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Rs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function $C(e){this.exit(e)}function DC(){return"["}function bp(e,n,s,i){const r=s.createTracker(i);let o=r.move("[^");const l=s.enter("footnoteReference"),c=s.enter("reference");return o+=r.move(s.safe(s.associationId(e),{after:"]",before:o})),c(),l(),o+=r.move("]"),o}function LC(){return{enter:{gfmFootnoteCallString:MC,gfmFootnoteCall:_C,gfmFootnoteDefinitionLabelString:AC,gfmFootnoteDefinition:RC},exit:{gfmFootnoteCallString:TC,gfmFootnoteCall:IC,gfmFootnoteDefinitionLabelString:PC,gfmFootnoteDefinition:$C}}}function zC(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:bp},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(i,r,o,l){const c=o.createTracker(l);let u=c.move("[^");const d=o.enter("footnoteDefinition"),m=o.enter("label");return u+=c.move(o.safe(o.associationId(i),{before:u,after:"]"})),m(),u+=c.move("]:"),i.children&&i.children.length>0&&(c.shift(4),u+=c.move((n?`
591
- `:" ")+o.indentLines(o.containerFlow(i,c.current()),n?xp:FC))),d(),u}}function FC(e,n,s){return n===0?e:xp(e,n,s)}function xp(e,n,s){return(s?"":" ")+e}const OC=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];vp.peek=VC;function UC(){return{canContainEols:["delete"],enter:{strikethrough:HC},exit:{strikethrough:qC}}}function BC(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:OC}],handlers:{delete:vp}}}function HC(e){this.enter({type:"delete",children:[]},e)}function qC(e){this.exit(e)}function vp(e,n,s,i){const r=s.createTracker(i),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function VC(){return"~"}function WC(e){return e.length}function GC(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||WC,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>d&&(d=e[m].length);++x<e[m].length;){const y=KC(e[m][x]);if(s.alignDelimiters!==!1){const E=r(y);v[x]=E,(u[x]===void 0||E>u[x])&&(u[x]=E)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Ou(i[h]);else{const b=Ou(i);for(;++h<d;)o[h]=b}h=-1;const g=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const E=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>u[h]&&(u[h]=y),p[h]=y),g[h]=E}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const y=b[h]||"";let E="",k="";if(s.alignDelimiters!==!1){const T=u[h]-(v[h]||0),N=o[h];N===114?E=" ".repeat(T):N===99?T%2?(E=" ".repeat(T/2+.5),k=" ".repeat(T/2-.5)):(E=" ".repeat(T/2),k=E):k=" ".repeat(T)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(E),x.push(y),s.alignDelimiters!==!1&&x.push(k),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&x.push("|")}f.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return f.join(`
592
- `)}function KC(e){return e==null?"":String(e)}function Ou(e){const n=typeof e=="string"?e.codePointAt(0):0;return n===67||n===99?99:n===76||n===108?108:n===82||n===114?114:0}function JC(e,n,s,i){const r=s.enter("blockquote"),o=s.createTracker(i);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),YC);return r(),l}function YC(e,n,s){return">"+(s?"":" ")+e}function QC(e,n){return Uu(e,n.inConstruct,!0)&&!Uu(e,n.notInConstruct,!1)}function Uu(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let i=-1;for(;++i<n.length;)if(e.includes(n[i]))return!0;return!1}function Bu(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
593
- `&&QC(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
594
- `}function XC(e,n){const s=String(e);let i=s.indexOf(n),r=i,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;i!==-1;)i===r?++o>l&&(l=o):o=1,r=i+n.length,i=s.indexOf(n,r);return l}function ZC(e,n){return!!(n.options.fences===!1&&e.value&&!e.lang&&/[^ \r\n]/.test(e.value)&&!/^[\t ]*(?:[\r\n]|$)|(?:^|[\r\n])[\t ]*$/.test(e.value))}function e2(e){const n=e.options.fence||"`";if(n!=="`"&&n!=="~")throw new Error("Cannot serialize code with `"+n+"` for `options.fence`, expected `` ` `` or `~`");return n}function t2(e,n,s,i){const r=e2(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(ZC(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,n2);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(XC(o,r)+1,3)),d=s.enter("codeFenced");let m=c.move(u);if(e.lang){const h=s.enter(`codeFencedLang${l}`);m+=c.move(s.safe(e.lang,{before:m,after:" ",encode:["`"],...c.current()})),h()}if(e.lang&&e.meta){const h=s.enter(`codeFencedMeta${l}`);m+=c.move(" "),m+=c.move(s.safe(e.meta,{before:m,after:`
595
- `,encode:["`"],...c.current()})),h()}return m+=c.move(`
596
- `),o&&(m+=c.move(o+`
597
- `)),m+=c.move(u),d(),m}function n2(e,n,s){return(s?"":" ")+e}function Mc(e){const n=e.options.quote||'"';if(n!=='"'&&n!=="'")throw new Error("Cannot serialize title with `"+n+"` for `options.quote`, expected `\"`, or `'`");return n}function s2(e,n,s,i){const r=Mc(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("[");return d+=u.move(s.safe(s.associationId(e),{before:d,after:"]",...u.current()})),d+=u.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":`
598
- `,...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),l(),d}function i2(e){const n=e.options.emphasis||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize emphasis with `"+n+"` for `options.emphasis`, expected `*`, or `_`");return n}function Ha(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Vr(e,n,s){const i=Ji(e),r=Ji(n);return i===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:i===1?r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===void 0?{inside:!1,outside:!1}:r===1?{inside:!0,outside:!1}:{inside:!1,outside:!1}}yp.peek=a2;function yp(e,n,s,i){const r=i2(s),o=s.enter("emphasis"),l=s.createTracker(i),c=l.move(r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=Vr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Ha(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Vr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Ha(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function a2(e,n,s){return s.options.emphasis||"*"}function r2(e,n){let s=!1;return Cc(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Bl}),!!((!e.depth||e.depth<3)&&vc(e)&&(n.options.setext||s))}function o2(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(r2(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
599
- `,after:`
600
- `});return h(),m(),g+`
601
- `+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
602
- `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
603
- `,...o.current()});return/^[\t ]/.test(d)&&(d=Ha(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}kp.peek=l2;function kp(e){return e.value||""}function l2(){return"<"}jp.peek=c2;function jp(e,n,s,i){const r=Mc(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("![");return d+=u.move(s.safe(e.alt,{before:d,after:"]",...u.current()})),d+=u.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":")",...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),d+=u.move(")"),l(),d}function c2(){return"!"}wp.peek=d2;function wp(e,n,s,i){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("![");const d=s.safe(e.alt,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function d2(){return"!"}Np.peek=u2;function Np(e,n,s){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(i);){let d=u.index;i.charCodeAt(d)===10&&i.charCodeAt(d-1)===13&&d--,i=i.slice(0,d)+" "+i.slice(u.index+1)}}return r+i+r}function u2(){return"`"}function Sp(e,n){const s=vc(e);return!!(!n.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(s===e.url||"mailto:"+s===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Cp.peek=m2;function Cp(e,n,s,i){const r=Mc(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Sp(e,s)){const m=s.stack;s.stack=[],c=s.enter("autolink");let h=l.move("<");return h+=l.move(s.containerPhrasing(e,{before:h,after:">",...l.current()})),h+=l.move(">"),c(),s.stack=m,h}c=s.enter("link"),u=s.enter("label");let d=l.move("[");return d+=l.move(s.containerPhrasing(e,{before:d,after:"](",...l.current()})),d+=l.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=s.enter("destinationLiteral"),d+=l.move("<"),d+=l.move(s.safe(e.url,{before:d,after:">",...l.current()})),d+=l.move(">")):(u=s.enter("destinationRaw"),d+=l.move(s.safe(e.url,{before:d,after:e.title?" ":")",...l.current()}))),u(),e.title&&(u=s.enter(`title${o}`),d+=l.move(" "+r),d+=l.move(s.safe(e.title,{before:d,after:r,...l.current()})),d+=l.move(r),u()),d+=l.move(")"),c(),d}function m2(e,n,s){return Sp(e,s)?"<":"["}Ep.peek=h2;function Ep(e,n,s,i){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("[");const d=s.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function h2(){return"["}function _c(e){const n=e.options.bullet||"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bullet`, expected `*`, `+`, or `-`");return n}function p2(e){const n=_c(e),s=e.options.bulletOther;if(!s)return n==="*"?"-":"*";if(s!=="*"&&s!=="+"&&s!=="-")throw new Error("Cannot serialize items with `"+s+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(s===n)throw new Error("Expected `bullet` (`"+n+"`) and `bulletOther` (`"+s+"`) to be different");return s}function f2(e){const n=e.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function Mp(e){const n=e.options.rule||"*";if(n!=="*"&&n!=="-"&&n!=="_")throw new Error("Cannot serialize rules with `"+n+"` for `options.rule`, expected `*`, `-`, or `_`");return n}function g2(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?f2(s):_c(s);const c=e.ordered?l==="."?")":".":p2(s);let u=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(u=!0),Mp(s)===l&&m){let h=-1;for(;++h<e.children.length;){const g=e.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function b2(e){const n=e.options.listItemIndent||"one";if(n!=="tab"&&n!=="one"&&n!=="mixed")throw new Error("Cannot serialize items with `"+n+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return n}function x2(e,n,s,i){const r=b2(s);let o=s.bulletCurrent||_c(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,g,p){return g?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function v2(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const y2=mo(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function k2(e,n,s,i){return(e.children.some(function(l){return y2(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function j2(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}_p.peek=w2;function _p(e,n,s,i){const r=j2(s),o=s.enter("strong"),l=s.createTracker(i),c=l.move(r+r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=Vr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Ha(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Vr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Ha(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function w2(e,n,s){return s.options.strong||"*"}function N2(e,n,s,i){return s.safe(e.value,i)}function S2(e){const n=e.options.ruleRepetition||3;if(n<3)throw new Error("Cannot serialize rules with repetition `"+n+"` for `options.ruleRepetition`, expected `3` or more");return n}function C2(e,n,s){const i=(Mp(s)+(s.options.ruleSpaces?" ":"")).repeat(S2(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Ap={blockquote:JC,break:Bu,code:t2,definition:s2,emphasis:yp,hardBreak:Bu,heading:o2,html:kp,image:jp,imageReference:wp,inlineCode:Np,link:Cp,linkReference:Ep,list:g2,listItem:x2,paragraph:v2,root:k2,strong:_p,text:N2,thematicBreak:C2};function E2(){return{enter:{table:M2,tableData:Hu,tableHeader:Hu,tableRow:A2},exit:{codeText:R2,table:_2,tableData:tl,tableHeader:tl,tableRow:tl}}}function M2(e){const n=e._align;this.enter({type:"table",align:n.map(function(s){return s==="none"?null:s}),children:[]},e),this.data.inTable=!0}function _2(e){this.exit(e),this.data.inTable=void 0}function A2(e){this.enter({type:"tableRow",children:[]},e)}function tl(e){this.exit(e)}function Hu(e){this.enter({type:"tableCell",children:[]},e)}function R2(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,T2));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function T2(e,n){return n==="|"?n:e}function I2(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
604
- `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,f,b,v){return d(m(p,b,v),p.align)}function c(p,f,b,v){const x=h(p,b,v),y=d([x]);return y.slice(0,y.indexOf(`
605
- `))}function u(p,f,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),E=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),E}function d(p,f){return GC(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,b){const v=p.children;let x=-1;const y=[],E=f.enter("table");for(;++x<v.length;)y[x]=h(v[x],f,b);return E(),y}function h(p,f,b){const v=p.children;let x=-1;const y=[],E=f.enter("tableRow");for(;++x<v.length;)y[x]=u(v[x],p,f,b);return E(),y}function g(p,f,b){let v=Ap.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function P2(){return{exit:{taskListCheckValueChecked:qu,taskListCheckValueUnchecked:qu,paragraph:D2}}}function $2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:L2}}}function qu(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function D2(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const i=s.children[0];if(i&&i.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(i.value=i.value.slice(1),i.value.length===0?s.children.shift():s.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,s.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function L2(e,n,s,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(i);o&&c.move(l);let u=Ap.listItem(e,n,s,{...i,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(m){return m+l}}function z2(){return[gC(),LC(),UC(),E2(),P2()]}function F2(e){return{extensions:[bC(),zC(e),BC(),I2(e),$2()]}}const O2={tokenize:W2,partial:!0},Rp={tokenize:G2,partial:!0},Tp={tokenize:K2,partial:!0},Ip={tokenize:J2,partial:!0},U2={tokenize:Y2,partial:!0},Pp={name:"wwwAutolink",tokenize:q2,previous:Dp},$p={name:"protocolAutolink",tokenize:V2,previous:Lp},ni={name:"emailAutolink",tokenize:H2,previous:zp},Ws={};function B2(){return{text:Ws}}let xi=48;for(;xi<123;)Ws[xi]=ni,xi++,xi===58?xi=65:xi===91&&(xi=97);Ws[43]=ni;Ws[45]=ni;Ws[46]=ni;Ws[95]=ni;Ws[72]=[ni,$p];Ws[104]=[ni,$p];Ws[87]=[ni,Pp];Ws[119]=[ni,Pp];function H2(e,n,s){const i=this;let r,o;return l;function l(h){return!Wl(h)||!zp.call(i,i.previous)||Ac(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Wl(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(U2,m,d)(h):h===45||h===95||In(h)?(o=!0,e.consume(h),u):m(h)}function d(h){return e.consume(h),r=!0,u}function m(h){return o&&r&&Bn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function q2(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Dp.call(i,i.previous)||Ac(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(O2,e.attempt(Rp,e.attempt(Tp,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function V2(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Lp.call(i,i.previous)&&!Ac(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Bn(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Br(h)||Vt(h)||Ei(h)||lo(h)?s(h):e.attempt(Rp,e.attempt(Tp,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function W2(e,n,s){let i=0;return r;function r(l){return(l===87||l===119)&&i<3?(i++,e.consume(l),r):l===46&&i===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function G2(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Ip,u,c)(d):d===null||Vt(d)||Ei(d)||d!==45&&lo(d)?u(d):(o=!0,e.consume(d),l)}function c(d){return d===95?i=!0:(r=i,i=void 0),e.consume(d),l}function u(d){return r||i||!o?s(d):n(d)}}function K2(e,n){let s=0,i=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&i<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(Ip,n,o)(l):l===null||Vt(l)||Ei(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function J2(e,n,s){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Vt(c)||Ei(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Vt(c)||Ei(c)?n(c):i(c)}function o(c){return Bn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):Bn(c)?(e.consume(c),l):s(c)}}function Y2(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return In(o)?s(o):n(o)}}function Dp(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Vt(e)}function Lp(e){return!Bn(e)}function zp(e){return!(e===47||Wl(e))}function Wl(e){return e===43||e===45||e===46||e===95||In(e)}function Ac(e){let n=e.length,s=!1;for(;n--;){const i=e[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const Q2={tokenize:aE,partial:!0};function X2(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:nE,continuation:{tokenize:sE},exit:iE}},text:{91:{name:"gfmFootnoteCall",tokenize:tE},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:Z2,resolveTo:eE}}}}function Z2(e,n,s){const i=this;let r=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l;for(;r--;){const u=i.events[r][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return s(u);const d=Rs(i.sliceSerialize({start:l.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),n(u))}}function eE(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",i,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",i,n]];return e.splice(s,e.length-s+1,...c),e}function tE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(h){if(o>999||h===93&&!l||h===null||h===91||Vt(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Rs(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Vt(h)||(l=!0),o++,e.consume(h),h===92?m:d}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function nE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||Vt(f))return s(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Rs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return Vt(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Lt(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function sE(e,n,s){return e.check(tr,n,e.attempt(Q2,n,s))}function iE(e){e.exit("gfmFootnoteDefinition")}function aE(e,n,s){const i=this;return Lt(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function rE(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&ds(g,g.length,0,co(p,l.slice(d+1,u),c)),ds(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),ds(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const b=Ji(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),x=Ji(f);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(f)}}}class oE{constructor(){this.map=[]}add(n,s,i){lE(this,n,s,i)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const i=[];for(;s>0;)s-=1,i.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];i.push(n.slice()),n.length=0;let r=i.pop();for(;r;){for(const o of r)n.push(o);r=i.pop()}this.map.length=0}}function lE(e,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...i);return}r+=1}e.map.push([n,s,i])}}function cE(e,n){let s=!1;const i=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=i.length-1;i[o]=i[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function dE(){return{flow:{null:{name:"table",tokenize:uE,resolveAll:mE}}}}function uE(e,n,s){const i=this;let r=0,o=0,l;return c;function c(_){let I=i.events.length-1;for(;I>-1;){const $=i.events[I][1].type;if($==="lineEnding"||$==="linePrefix")I--;else break}const D=I>-1?i.events[I][1].type:null,G=D==="tableHead"||D==="tableRow"?N:u;return G===N&&i.parser.lazy[i.now().line]?s(_):G(_)}function u(_){return e.enter("tableHead"),e.enter("tableRow"),d(_)}function d(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):vt(_)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):Rt(_)?Lt(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||Vt(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?g:h)}function g(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,Rt(_)?Lt(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):f(_))}function f(_){return _===45||_===58?v(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),b):T(_)}function b(_){return Rt(_)?Lt(e,v,"whitespace")(_):v(_)}function v(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),x):_===45?(o+=1,x(_)):_===null||vt(_)?k(_):T(_)}function x(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):T(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),E):(e.exit("tableDelimiterFiller"),E(_))}function E(_){return Rt(_)?Lt(e,k,"whitespace")(_):k(_)}function k(_){return _===124?f(_):_===null||vt(_)?!l||r!==o?T(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):T(_)}function T(_){return s(_)}function N(_){return e.enter("tableRow"),S(_)}function S(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),S):_===null||vt(_)?(e.exit("tableRow"),n(_)):Rt(_)?Lt(e,S,"whitespace")(_):(e.enter("data"),j(_))}function j(_){return _===null||_===124||Vt(_)?(e.exit("data"),S(_)):(e.consume(_),_===92?P:j)}function P(_){return _===92||_===124?(e.consume(_),j):j(_)}}function mE(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new oE;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Vu(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=vr(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=vr(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=vr(g,n,o,r,s,h)):l[1]!==0&&(h=vr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Vu(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=cE(n.events,s))}return e}function vr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Fi(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=Fi(n.events,s[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const d=Fi(n.events,s[2]),m=Fi(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,b=s[3]-s[2]-1;e.add(f,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Fi(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Vu(e,n,s,i,r){const o=[],l=Fi(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),i.end=Object.assign({},l),o.push(["exit",i,n]),e.add(s+1,0,o)}function Fi(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const hE={name:"tasklistCheck",tokenize:fE};function pE(){return{text:{91:hE}}}function fE(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return Vt(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):s(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(u)}function c(u){return vt(u)?n(u):Rt(u)?e.check({tokenize:gE},n,s)(u):s(u)}}function gE(e,n,s){return Lt(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function bE(e){return Jh([B2(),X2(),rE(e),dE(),pE()])}const xE={};function ti(e){const n=this,s=e||xE,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(bE(s)),o.push(z2()),l.push(F2(s))}const Wu=500,Gu=100;function nl(e){return e.length>Wu?e.slice(-Wu):e}function Fp(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),y=a.useRef(n),E=a.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const S=b.current,j=++E.current;f.current=!1;const P=e,_=s;async function I(){if(!P)return;l(!0),g(!1);try{const G=await Qc(P,_,{limit:Gu});if(f.current||b.current!==S||E.current!==j)return;r(nl(G.entries)),u(G.hasMore),m(G.total)}catch{if(f.current||b.current!==S||E.current!==j)return;r([]),u(!1),m(null)}finally{!f.current&&b.current===S&&E.current===j&&l(!1)}const D=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=Vs(`/api/tasks/${P}/logs/stream${D}`,{events:{"agent:log":G=>{if(!(f.current||b.current!==S))try{const $=JSON.parse(G.data);r(R=>nl([...R,$])),m(R=>R!==null?R+1:null)}catch{}}}})}return I(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const T=a.useCallback(async()=>{if(!e||h)return;const S=b.current,j=i.length,P=e;g(!0);try{const _=await Qc(P,s,{limit:Gu,offset:j});if(f.current||b.current!==S)return;r(I=>{const D=[..._.entries,...I];return nl(D)}),u(_.hasMore),m(_.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),N=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:N,loadMore:T,hasMore:c,total:d,loadingMore:h}}function vE(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const Ku={pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})},yE=50;function Op(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function kE(e){const n=new Map;return e.map(s=>{const i=Op(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function jE({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),[p,f]=a.useState(!0),[b,v]=a.useState(!1),x=a.useMemo(()=>kE(e),[e]);a.useLayoutEffect(()=>{const j=d.current;if(!j)return;const P=e.length,_=m.current,I=h.current,D=x[x.length-1]??null,G=g.current!==D;if(P>_){const $=j.scrollTop<=yE;if(G)if($)j.scrollTop=0;else{const R=j.scrollHeight-I;R>0&&(j.scrollTop+=R)}}m.current=P,h.current=j.scrollHeight,g.current=D},[e,x]);const y=a.useCallback(j=>{j.key==="Escape"&&b&&v(!1)},[b]);if(a.useEffect(()=>{if(b)return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[b,y]),n&&e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})});if(e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})});const E=[...e].reverse(),k=[...x].reverse(),T=s?.provider&&s?.modelId,N=i?.provider&&i?.modelId,S=r?.provider&&r?.modelId;return t.jsxs("div",{ref:d,className:`agent-log-viewer agent-log-viewer--streaming${b?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),T?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(ts,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Validator:"}),N?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(ts,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning/Triage:"}),S?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(ts,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>f(j=>!j),"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"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>v(j=>!j),"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?t.jsx(sa,{size:14}):t.jsx(eo,{size:14})})]})]}),u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),E.map((j,P)=>{const _=k[P]??`${Op(j)}|fallback`,I=E[P-1],D=j.type==="tool"||j.type==="tool_result"||j.type==="tool_error",G=j.agent?D||P===0||I&&(I.agent!==j.agent||I.type!==j.type):!1,$=G?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:vE(j.timestamp)}):null,R=G?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",j.agent,"]"]}),$]}):null;return j.type==="tool"?t.jsxs("div",{className:"agent-log-tool",children:[R,"⚡ ",j.text,j.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",j.detail]})]},_):j.type==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[R,p?t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],components:Ku,children:j.text})}):j.text]},_):j.type==="tool_result"?t.jsxs("div",{className:"agent-log-tool-result",children:[R,"✓ ",j.text,j.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",j.detail]})]},_):j.type==="tool_error"?t.jsxs("div",{className:"agent-log-tool-error",children:[R,"✗ ",j.text,j.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",j.detail]})]},_):t.jsxs("div",{className:"agent-log-text",children:[R,p?t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],components:Ku,children:j.text})}):j.text]},_)}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function Yi(e){return e??void 0}function yr(e){return{provider:Yi(e.modelProvider),modelId:Yi(e.modelId)}}function kr(e){return{provider:Yi(e.validatorModelProvider),modelId:Yi(e.validatorModelId)}}function jr(e){return{provider:Yi(e.planningModelProvider),modelId:Yi(e.planningModelId)}}function wE(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function NE(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function SE(e,n){return e.planningModelProvider&&e.planningModelId?{provider:e.planningModelProvider,modelId:e.planningModelId}:n?.planningProvider&&n.planningModelId?{provider:n.planningProvider,modelId:n.planningModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function sl(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return{provider:e.slice(0,n),modelId:e.slice(n+1)}}function il(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function al(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function CE(e,n){const i={executor:"Executor",validator:"Validator",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function EE({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(()=>yr(e)),[v,x]=a.useState(()=>yr(e)),[y,E]=a.useState(()=>kr(e)),[k,T]=a.useState(()=>kr(e)),[N,S]=a.useState(()=>jr(e)),[j,P]=a.useState(()=>jr(e)),[_,I]=a.useState(()=>e.thinkingLevel??null),[D,G]=a.useState(()=>e.thinkingLevel??null),[$,R]=a.useState(null),w=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),ss().then(ge=>{o(ge.models),c(ge.favoriteProviders),d(ge.favoriteModels)}).catch(ge=>{p(ge.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const H=a.useCallback(async ge=>{const Me=l,Ce=Me.includes(ge)?Me.filter($e=>$e!==ge):[ge,...Me];c(Ce);try{await tn({favoriteProviders:Ce,favoriteModels:u})}catch{c(Me),n("Failed to update favorites","error")}},[l,u,n]),V=a.useCallback(async ge=>{const Me=u,Ce=Me.includes(ge)?Me.filter($e=>$e!==ge):[ge,...Me];d(Ce);try{await tn({favoriteProviders:l,favoriteModels:Ce})}catch{d(Me),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{w.current=e.id;const ge=yr(e),Me=kr(e),te=jr(e);b(ge),x(ge),E(Me),T(Me),S(te),P(te);const Ce=e.thinkingLevel??null;I(Ce),G(Ce),R(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const B=a.useMemo(()=>il(f),[f]),M=a.useMemo(()=>il(y),[y]),z=a.useMemo(()=>il(N),[N]),X=a.useMemo(()=>wE(e,i),[e,i]),C=a.useMemo(()=>NE(e,i),[e,i]),U=a.useMemo(()=>SE(e,i),[e,i]),fe=$!==null,ie=a.useCallback(async(ge,Me)=>{const te=e.id,Ce=v,$e=k,We=j;R(ge);try{const Ge=s?ge==="executor"?{modelProvider:Me.provider??null,modelId:Me.modelId??null}:ge==="validator"?{validatorModelProvider:Me.provider??null,validatorModelId:Me.modelId??null}:{planningModelProvider:Me.provider??null,planningModelId:Me.modelId??null}:{modelProvider:(ge==="executor"?Me:v).provider??null,modelId:(ge==="executor"?Me:v).modelId??null,validatorModelProvider:(ge==="validator"?Me:k).provider??null,validatorModelId:(ge==="validator"?Me:k).modelId??null,planningModelProvider:(ge==="planning"?Me:j).provider??null,planningModelId:(ge==="planning"?Me:j).modelId??null},Ee=await Qs(te,Ge);if(w.current!==te)return;const Ae=yr(Ee),Oe=kr(Ee),ke=jr(Ee);x(Ae),b(Ae),T(Oe),E(Oe),P(ke),S(ke),s?.(Ee),n(CE(ge,{executor:Ae,validator:Oe,planning:ke}[ge]),"success")}catch(Ge){if(w.current!==te)return;ge==="executor"?b(Ce):ge==="validator"?E($e):S(We),n(ve(Ge)||"Failed to save model settings","error")}finally{w.current===te&&R(null)}},[e.id,v,k,j,n,s]),re=a.useCallback(ge=>{const Me=sl(ge);b(Me),!al(Me,v)&&ie("executor",Me)},[v,ie]),F=a.useCallback(ge=>{const Me=sl(ge);E(Me),!al(Me,k)&&ie("validator",Me)},[k,ie]),ce=a.useCallback(ge=>{const Me=sl(ge);S(Me),!al(Me,j)&&ie("planning",Me)},[j,ie]),ae=a.useCallback(async ge=>{const Me=e.id,te=D,Ce=ge===""?null:ge;I(Ce),R("thinking");try{const $e=await Qs(Me,{thinkingLevel:Ce});if(w.current!==Me)return;const We=$e.thinkingLevel??null;G(We),I(We),s?.($e);const Ge=i?.defaultThinkingLevel??"off";n(We===null?`Thinking level set to default (${Ge})`:`Thinking level set to ${We}`,"success")}catch($e){if(w.current!==Me)return;I(te),n(ve($e)||"Failed to save thinking level","error")}finally{w.current===Me&&R(null)}},[e.id,D,i,n,s]),Q=!v.provider&&!v.modelId,de=!k.provider&&!k.modelId,Re=!j.provider&&!j.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, global default settings are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),ss().then(ge=>{o(ge.models),c(ge.favoriteProviders),d(ge.favoriteModels)}).catch(ge=>p(ge.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",X.provider&&X.modelId?` (${X.provider}/${X.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(ts,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(jn,{id:"executorModel",label:"Executor Model",value:B,onChange:re,models:r,disabled:fe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:H,favoriteModels:u,onToggleModelFavorite:V}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Validator Model"}),t.jsx("div",{className:"model-selector-current",children:de?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",C.provider&&C.modelId?` (${C.provider}/${C.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&t.jsx(ts,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(jn,{id:"validatorModel",label:"Validator Model",value:M,onChange:F,models:r,disabled:fe,placeholder:"Select validator model…",favoriteProviders:l,onToggleFavorite:H,favoriteModels:u,onToggleModelFavorite:V}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:Re?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",U.provider&&U.modelId?` (${U.provider}/${U.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&t.jsx(ts,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(jn,{id:"planningModel",label:"Planning Model",value:z,onChange:ce,models:r,disabled:fe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:H,favoriteModels:u,onToggleModelFavorite:V}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:D===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:D})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:ge=>ae(ge.target.value),disabled:fe,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",i?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Q&&de&&Re&&D===null?"Using global default models.":"Model settings are up to date."})]})]})}const ME={open:t.jsx(Yr,{size:16}),closed:t.jsx(Wa,{size:16}),merged:t.jsx(Jm,{size:16})};function _E({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[E,k]=a.useState(null),T=a.useCallback(async()=>{if(h.trim()){v(!0);try{const P=await Vx(e,{title:h.trim(),body:p.trim()||void 0},n);l(P),m(!1),g(""),f(""),u(`Created PR #${P.number}`,"success")}catch(P){u(ve(P)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),N=a.useCallback(async()=>{if(s){y(!0);try{const P=await Wx(e,n);k(P),c(P.prInfo),u("PR status refreshed","success")}catch(P){u(ve(P)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Zn,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Zn,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Zn,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:P=>g(P.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:P=>f(P.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:T,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Zn,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Ht,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const S=ME[s.status]??t.jsx(Yr,{size:16}),j=E?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Zn,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:S}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:x,title:"Refresh PR status",children:t.jsx(mn,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:j.length>0?`Waiting for: ${j.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(li,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(rg,{size:14}),"View on GitHub"]})]})]})]})}const Ju=2e3;function AE(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function RE(e){return e==="agent"||e==="system"}function TE({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((S,j)=>new Date(j.createdAt).getTime()-new Date(S.createdAt).getTime()),[e.comments]),v=o.length>Ju;async function x(){const S=o.trim();if(S){g(!0);try{const j=await Nx(e.id,S,r);l(""),n?.(j),s("Comment added","success")}catch(j){s(ve(j)||"Failed to add comment","error")}finally{g(!1)}}}async function y(S){const j=d.trim();if(j){g(!0);try{const P=await vx(e.id,S,j,r);u(null),m(""),n?.(P),s("Comment updated","success")}catch(P){s(ve(P)||"Failed to update comment","error")}finally{g(!1)}}}async function E(S){f(S);try{const j=await yx(e.id,S,r);n?.(j),s("Comment deleted","success")}catch(j){s(ve(j)||"Failed to delete comment","error")}finally{f(null)}}function k(S){S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(S=>{const j=S.author===i,P=c===S.id,_=RE(S.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:S.author}),t.jsx("span",{className:"detail-log-timestamp",children:AE(S)})]}),j&&!P?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(S.id),m(S.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void E(S.id),disabled:p===S.id,children:p===S.id?"Deleting…":"Delete"})]}):null]}),P?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:I=>m(I.target.value),rows:3,className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(S.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:S.text})]},S.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:S=>l(S.target.value),onKeyDown:k,rows:3,placeholder:"Add a comment",className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",Ju]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function IE(e){return e?e.slice(0,7):"Unknown"}function PE({task:e}){if(e.column!=="done"||!e.mergeDetails)return null;const n=e.mergeDetails;return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Merge Details"}),t.jsxs("div",{className:"pr-card merge-details-card",children:[t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Status"}),t.jsx("span",{className:"detail-log-outcome",children:n.mergeConfirmed===!1?"Recorded without local merge confirmation":"Merged successfully"})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Commit"}),t.jsx("span",{className:"detail-log-outcome",children:IE(n.commitSha)})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Files changed"}),t.jsx("span",{className:"detail-log-outcome",children:n.filesChanged??0})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Insertions / Deletions"}),t.jsxs("span",{className:"detail-log-outcome",children:["+",n.insertions??0," / -",n.deletions??0]})]})}),n.mergedAt?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Merged at"}),t.jsx("span",{className:"detail-log-outcome",children:new Date(n.mergedAt).toLocaleString()})]})}):null,n.prNumber?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"PR"}),t.jsxs("span",{className:"detail-log-outcome",children:["#",n.prNumber]})]})}):null,n.mergeCommitMessage?t.jsxs("div",{className:"detail-log-entry",children:[t.jsx("div",{className:"detail-log-header",children:t.jsx("span",{className:"detail-log-action",children:"Message"})}),t.jsx("div",{className:"detail-log-outcome",children:n.mergeCommitMessage})]}):null]})]})}function Up(e){return e.split(`
606
- `).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
607
- `},i):t.jsx(Um.Fragment,{children:`${s}
608
- `},i)})}function Yu(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=[];for(let m=1;m<e.length;m++)e[m]==="/"&&r.push(m);const o=n-s.length;let l=null,c=-1;for(let m=r.length-1;m>=0;m--){const h=r[m],g=e.slice(h);if(g.length>o)continue;const p=o-g.length;for(let f=0;f<r.length;f++){const b=r[f],v=e.slice(0,b);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>c&&(c=v.length+g.length,l=v+s+g)}}if(l)return l;const u=e.slice(i);if(s.length+u.length<=n)return s+u;const d=n-s.length;return s+e.slice(e.length-d)}function $E(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function DE({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(v=>v!==null&&v>0?v-1:v)},[]),p=a.useCallback(()=>{d(v=>v!==null&&v<s.length-1?v+1:v)},[]);if(a.useEffect(()=>{if(!e)return;const v=x=>{if(x.key==="Escape"){l();return}x.key==="ArrowUp"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),g()),x.key==="ArrowDown"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),p())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[e,l,g,p]),!e)return null;const f=u!==null?s[u]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",onClick:l,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(As,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(Zl,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:p,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(an,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(v=>!v),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Pr,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(mn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Da,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((v,x)=>t.jsxs("button",{className:`changes-diff-file-item ${u===x?"selected":""}`,onClick:()=>d(x),title:v.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${v.status}`,children:$E(v.status)}),t.jsx("span",{className:"changes-diff-file-path",children:v.path}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",v.additions," -",v.deletions]})]},v.path))})]}),t.jsx("div",{className:"changes-diff-content",children:f?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:f.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",f.additions," -",f.deletions]})]}),f.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Up(f.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(As,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Qu(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function LE({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,b]=a.useState(new Set),[v,x]=a.useState(null),[y,E]=a.useState(!0),[k,T]=a.useState(!1),N=i==="done",S=N&&!!r?.commitSha,j=i==="in-progress"||i==="in-review"||S,P=a.useCallback(async()=>{if(!j){h(!1);return}try{h(!0),p(null);const $=await mh(e,void 0,s),R=$.files.map(w=>({path:w.path,status:w.status,additions:w.additions,deletions:w.deletions,patch:w.patch}));c(R),d($.stats),R.length>0&&(b(new Set([R[0].path])),x(0))}catch($){p(ve($)||"Failed to load diff")}finally{h(!1)}},[e,s,j]);a.useEffect(()=>{P()},[P]);const _=$=>{b(R=>{const w=new Set(R);if(w.has($))w.delete($);else{w.add($);const H=l.findIndex(V=>V.path===$);H!==-1&&x(H)}return w})},I=$=>{if($<0||$>=l.length)return;const R=l[$].path;b(new Set([R])),x($)},D=v!==null&&v>0,G=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(g)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(ns,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!N&&!n)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(As,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(N&&!S){const $=r?.filesChanged,R=r?.insertions,w=r?.deletions,H=$!=null||R!=null||w!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(As,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:H?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${R??0} additions, -${w??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?N&&o&&o.length>0?t.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Da,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(As,{size:24}),t.jsxs("p",{children:[o.length," file",o.length===1?"":"s"," modified during execution."]}),t.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."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:Qu("unknown")}),t.jsx("span",{className:"changes-file-path",title:$,children:Yu($)})]})},$))})]}):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(As,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:N?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Da,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(As,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>D&&I(v-1),disabled:!D,title:"Previous file","aria-label":"Previous file",children:t.jsx(Zl,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>G&&I(v+1),disabled:!G,title:"Next file","aria-label":"Next file",children:t.jsx(an,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>E($=>!$),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Pr,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:P,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>T(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(eo,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const R=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${R?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:R?t.jsx(zt,{size:14}):t.jsx(an,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:Qu($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:Yu($.path)}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),R&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Up($.patch)})})})]},$.path)})}),t.jsx(DE,{isOpen:k,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>T(!1),onRefresh:P})]})}function Xu(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function zE(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function PP(e,n){const s=zE(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}const Zu=["image/png","image/jpeg","image/gif","image/webp"];function FE(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function Bp({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,priority:c,onPriorityChange:u,executorModel:d,onExecutorModelChange:m,validatorModel:h,onValidatorModelChange:g,planningModel:p,onPlanningModelChange:f,thinkingLevel:b,onThinkingLevelChange:v,presetMode:x,onPresetModeChange:y,selectedPresetId:E,onSelectedPresetIdChange:k,selectedWorkflowSteps:T,onWorkflowStepsChange:N,onDefaultOnApplied:S,pendingImages:j,onImagesChange:P,tasks:_,projectId:I,disabled:D=!1,addToast:G,isActive:$=!0,onAutoSaveDescription:R,onPlanningMode:w,onSubtaskBreakdown:H,onClose:V,renderBelowPrimary:B,renderBelowModelConfiguration:M,hideDependencies:z,autoExpandMoreOptionsOnSelection:X=!0,reviewLevel:C,onReviewLevelChange:U,executionMode:fe,onExecutionModeChange:ie}){const re=(z?!1:o.length>0)||j.length>0||T.length>0||x!=="default"||(c??ls)!==ls||d!==""||h!==""||(p||"")!==""||(b||"")!==""||C!==void 0||fe==="fast",[F,ce]=a.useState(!1),[ae,Q]=a.useState(X?re:!1),[de,Re]=a.useState(""),[ge,Me]=a.useState([]),[te,Ce]=a.useState([]),[$e,We]=a.useState([]),[Ge,Ee]=a.useState(!1),[Ae,Oe]=a.useState(null),[ke,De]=a.useState([]),[se,K]=a.useState("idle"),[me,ee]=a.useState(!1),[he,le]=a.useState(!1),[Ie,Ze]=a.useState(!1),rt=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),pe=a.useRef(null),Se=a.useRef(null),Pe=a.useRef(null),ye=a.useRef(null),Ke=a.useRef(!1),Ne=a.useRef(re),Fe=a.useRef(n.trim()),Ye=a.useRef(n.trim());a.useEffect(()=>{$&&(Ee(!0),ss().then(A=>{Me(A.models),Ce(A.favoriteProviders),We(A.favoriteModels)}).catch(()=>{}).finally(()=>Ee(!1)),no(I).then(A=>Oe(A)).catch(()=>Oe(null)),so(I).then(A=>De(A.filter(J=>J.enabled))).catch(()=>De([])))},[$,I]);const xe=Ae?.modelPresets||[],ze=xe.find(A=>A.id===E),be=(z?!1:o.length>0)||j.length>0||T.length>0||x!=="default"||(c??ls)!==ls||d!==""||h!==""||(p||"")!==""||(b||"")!==""||C!==void 0||fe==="fast";a.useEffect(()=>{if(e!=="create"||!$||!Ae?.autoSelectModelPreset)return;const A=(Ae.defaultPresetBySize,void 0);if(A){const J=Xu(A);k(A.id),y("preset"),m(J.executorValue),g(J.validatorValue)}},[$,Ae,xe,e]);const Qe=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!$||Qe.current||ke.length===0)return;const A=ke.filter(Ve=>Ve.defaultOn);if(A.length===0)return;Qe.current=!0;const J=A.map(Ve=>Ve.id);N(J),S?.(J)},[e,$,ke]),a.useEffect(()=>{$||(Qe.current=!1)},[$]),a.useEffect(()=>{if(!X){Ne.current=be;return}be&&!Ne.current&&Q(!0),Ne.current=be},[be,X]),a.useEffect(()=>{ae||(ce(!1),Re(""))},[ae]),a.useEffect(()=>{e!=="edit"||!$||pe.current&&(pe.current.focus(),pe.current.select())},[e,$]),a.useEffect(()=>{if(!F)return;const A=J=>{oe.current&&!oe.current.contains(J.target)&&ce(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[F]),a.useEffect(()=>{(e!=="edit"||D)&&Ze(!1)},[e,D]),a.useEffect(()=>{if(e!=="edit"){K("idle");return}const A=n.trim();Fe.current=A,Ye.current=A,K("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!R||!$)return;const A=n.trim(),J=Fe.current;if(A===J||A===Ye.current){Pe.current&&(clearTimeout(Pe.current),Pe.current=null),Ke.current||K("idle");return}return Pe.current&&clearTimeout(Pe.current),Pe.current=setTimeout(async()=>{if(!Ke.current){Ke.current=!0,K("saving");try{await R(A),Ye.current=A,K("saved"),ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{K("idle"),ye.current=null},2e3)}catch{K("idle")}finally{Ke.current=!1,Pe.current=null}}},1500),()=>{Pe.current&&(clearTimeout(Pe.current),Pe.current=null)}},[e,n,R,$]),a.useEffect(()=>()=>{Pe.current&&clearTimeout(Pe.current),ye.current&&clearTimeout(ye.current)},[]),a.useEffect(()=>{if(!me)return;const A=J=>{rt.current&&!rt.current.contains(J.target)&&ee(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[me]);const it=a.useCallback(A=>{const J=A.clipboardData?.items;if(J)for(let Ve=0;Ve<J.length;Ve++){const dt=J[Ve];if(dt.type.startsWith("image/")){const yt=dt.getAsFile();if(yt&&Zu.includes(yt.type)){A.preventDefault(),P([...j,{file:yt,previewUrl:URL.createObjectURL(yt)}]);return}}}},[j,P]),mt=a.useCallback(A=>{A.preventDefault();const J=A.dataTransfer.files;for(let Ve=0;Ve<J.length;Ve++){const dt=J[Ve];if(Zu.includes(dt.type)){P([...j,{file:dt,previewUrl:URL.createObjectURL(dt)}]);return}}},[j,P]),At=a.useCallback(A=>{const J=j[A];J&&URL.revokeObjectURL(J.previewUrl),P(j.filter((Ve,dt)=>dt!==A))},[j,P]),It=a.useCallback(A=>{l(o.includes(A)?o.filter(J=>J!==A):[...o,A])},[o,l]),Dt=(A,J)=>A.length>J?A.slice(0,J)+"…":A,Ut=a.useCallback(A=>{s(A.target.value);const J=A.target;J.style.height="auto",J.style.height=J.scrollHeight+"px"},[s]),jt=a.useCallback(()=>{Ze(A=>!A)},[]),Pt=a.useCallback(A=>{!Ie||A.key!=="Escape"||(A.preventDefault(),A.stopPropagation(),Ze(!1))},[Ie]),He=a.useCallback(async A=>{const J=n.trim();if(!(!J||he)){le(!0);try{const Ve=await oh(J,A,I);s(Ve),ee(!1),G("Description refined with AI","success"),Z.current&&(Z.current.style.height="auto",Z.current.style.height=Z.current.scrollHeight+"px")}catch(Ve){const dt=lh(Ve);G(dt,"error")}finally{le(!1)}}},[n,he,G,s,I]),ut=a.useCallback(async A=>{const J=te,dt=J.includes(A)?J.filter(yt=>yt!==A):[A,...J];Ce(dt);try{await tn({favoriteProviders:dt,favoriteModels:$e})}catch{Ce(J)}},[te,$e]),$t=a.useCallback(async A=>{const J=$e,dt=J.includes(A)?J.filter(yt=>yt!==A):[A,...J];We(dt);try{await tn({favoriteProviders:te,favoriteModels:dt})}catch{We(J)}},[$e,te]),St=a.useCallback(A=>{if(A<=0)return;const J=[...T];[J[A-1],J[A]]=[J[A],J[A-1]],N(J)},[T,N]),Yt=a.useCallback(A=>{if(A>=T.length-1)return;const J=[...T];[J[A],J[A+1]]=[J[A+1],J[A]],N(J)},[T,N]),we=a.useCallback(A=>{N(T.filter(J=>J!==A))},[T,N]),et=new Map;for(const A of ke)et.set(A.id,{name:A.name,description:A.description});const ct=_.filter(A=>!o.includes(A.id)).sort((A,J)=>{const Ve=J.createdAt.localeCompare(A.createdAt);if(Ve!==0)return Ve;const dt=parseInt(A.id.slice(A.id.lastIndexOf("-")+1),10)||0;return(parseInt(J.id.slice(J.id.lastIndexOf("-")+1),10)||0)-dt}),ue=de?ct.filter(A=>A.id.toLowerCase().includes(de.toLowerCase())||A.title&&A.title.toLowerCase().includes(de.toLowerCase())||A.description&&A.description.toLowerCase().includes(de.toLowerCase())):ct;return t.jsxs("div",{className:"task-form",onDrop:mt,onDragOver:A=>A.preventDefault(),onPaste:it,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:pe,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:A=>r(A.target.value),disabled:D})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${se==="idle"?"":" is-visible"}`,"aria-live":"polite",children:se==="saving"?"Saving...":se==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Ie?" description--fullscreen":""}`,ref:rt,onKeyDown:Pt,children:[Ie&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:jt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(sa,{size:14})})]}),t.jsx("textarea",{ref:Z,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ut,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:D||he}),(()=>{const A=!!n.trim()&&!D;return t.jsxs(t.Fragment,{children:[!Ie&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${A?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:jt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(eo,{size:14})}),A&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${he?"refine-button--loading":""}`,onClick:()=>ee(J=>!J),disabled:he,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Pn,{size:12,style:{verticalAlign:"middle"}}),he?"Refining...":"Refine"]})]})})(),me&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:A=>A.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>He("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(w||H)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const A=n.trim();if(!A){G("Enter a description first","error");return}V?.(),w(A)},disabled:D||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),H&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const A=n.trim();if(!A){G("Enter a description first","error");return}V?.(),H(A)},disabled:D||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),B,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Q(A=>!A),"aria-expanded":ae,"aria-controls":"task-form-more-options",disabled:D,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ae?t.jsx(Zs,{size:14}):t.jsx(zt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ae?"":" collapsed"}`,"aria-hidden":!ae,hidden:!ae,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),j.length>0&&t.jsx("div",{className:"inline-create-previews",children:j.map((A,J)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:A.previewUrl,alt:A.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>At(J),disabled:D,title:"Remove image",children:"×"})]},A.previewUrl))}),t.jsx("input",{ref:Se,type:"file",accept:"image/*",onChange:A=>{const J=A.target.files?.[0];J&&(P([...j,{file:J,previewUrl:URL.createObjectURL(J)}]),A.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Se.current?.click(),disabled:D,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),!z&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ce(A=>!A),disabled:D,children:o.length>0?`${o.length} selected`:"Add dependencies"}),F&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:de,onChange:A=>Re(A.target.value),onClick:A=>A.stopPropagation()}),ue.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ue.map(A=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(A.id)?" selected":""}`,onClick:()=>It(A.id),onMouseDown:J=>J.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:A.id}),t.jsx("span",{className:"dep-dropdown-title",children:Dt(A.title||A.description||A.id,30)})]},A.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(A=>t.jsxs("span",{className:"dep-chip",children:[A,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>It(A),disabled:D,children:"×"})]},A))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),u&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:c??ls,onChange:A=>u(A.target.value),disabled:D,children:ac.map(A=>t.jsx("option",{value:A,children:A[0].toUpperCase()+A.slice(1)},A))})]}),ie&&fe!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:"Execution mode"}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:fe,onChange:A=>ie(A.target.value),disabled:D,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ge?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):ge.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:x==="preset"?E:x,onChange:A=>{const J=A.target.value;if(J==="default"){y("default"),k(""),m(""),g("");return}if(J==="custom"){y("custom"),k("");return}const Ve=xe.find(yt=>yt.id===J),dt=Xu(Ve);y("preset"),k(J),m(dt.executorValue),g(dt.validatorValue)},disabled:D,children:[t.jsx("option",{value:"default",children:"Use default"}),xe.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,xe.map(A=>t.jsx("option",{value:A.id,children:A.name},A.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),x==="preset"&&ze?t.jsxs("small",{children:["Using preset: ",ze.name]}):null,x==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>y("custom"),disabled:D,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(jn,{id:"executor-model",label:"Executor Model",value:d,onChange:A=>{y("custom"),k(""),m(A)},models:ge,disabled:D||x==="preset",favoriteProviders:te,onToggleFavorite:ut,favoriteModels:$e,onToggleModelFavorite:$t})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Validator"}),t.jsx(jn,{id:"validator-model",label:"Validator Model",value:h,onChange:A=>{y("custom"),k(""),g(A)},models:ge,disabled:D||x==="preset",favoriteProviders:te,onToggleFavorite:ut,favoriteModels:$e,onToggleModelFavorite:$t})]}),f&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(jn,{id:"planning-model",label:"Planning Model",value:p||"",onChange:A=>{y("custom"),k(""),f(A)},models:ge,disabled:D||x==="preset",favoriteProviders:te,onToggleFavorite:ut,favoriteModels:$e,onToggleModelFavorite:$t})]}),v&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:b||"",onChange:A=>v(A.target.value),disabled:D||x==="preset",children:[t.jsxs("option",{value:"",children:["Default (",Ae?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),U&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:C??"",onChange:A=>U(A.target.value===""?0:parseInt(A.target.value,10)),disabled:D,children:[t.jsx("option",{value:"",children:"Default (None)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),M,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:ke.length>0&&ke.map(A=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${A.id}`,children:[t.jsx("input",{type:"checkbox",checked:T.includes(A.id),onChange:J=>{N(J.target.checked?[...T,A.id]:T.filter(Ve=>Ve!==A.id))},disabled:D}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[A.name,FE(A.phase||"pre-merge",A.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:A.description})]})]},A.id))})]}),T.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),T.map((A,J)=>{const Ve=et.get(A);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${A}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:J+1}),t.jsx("span",{className:"workflow-step-order-name",children:Ve?.name||A}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>St(J),disabled:D||J===0,"data-testid":`workflow-step-move-up-${A}`,title:"Move up",children:t.jsx(Zs,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Yt(J),disabled:D||J===T.length-1,"data-testid":`workflow-step-move-down-${A}`,title:"Move down",children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>we(A),disabled:D,"data-testid":`workflow-step-remove-${A}`,title:"Remove",children:t.jsx(Tt,{size:14})})]})]},A)})]})]})]})]})}const em={pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:e}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function OE(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function UE(e,n){if(!e||!n)return null;const s=new Date(e).getTime(),r=new Date(n).getTime()-s;if(r<1e3)return`${r}ms`;const o=Math.round(r/1e3);if(o<60)return`${o}s`;const l=Math.floor(o/60),c=o%60;return`${l}m ${c}s`}function BE(e){return e?new Date(e).toLocaleString():null}function HE(e){const n=e.split(`
609
- `);return n.length<=1?e:`${n.length} lines`}function wr(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function qE({entries:e,startedAt:n,stepId:s}){const i=a.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return a.useEffect(()=>{const l=i.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),e.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:i,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",l.text,l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",l.detail]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:l.text},c):t.jsx("span",{className:"workflow-live-log-text",children:l.text},c))})}function VE({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,x]=a.useState(!1),y=n.some(C=>C.status==="pending"),{entries:E}=Fp(e,!!l&&y,o);a.useEffect(()=>{let C=!1;return so(o).then(U=>{C||b(U.filter(fe=>fe.enabled))}).catch(()=>{C||b([])}),()=>{C=!0}},[o]);const k=i??[],T=a.useMemo(()=>f.map(C=>({id:C.id,name:C.name,description:C.description,phase:C.phase||"pre-merge"})),[f]),N=a.useMemo(()=>new Map(T.map(C=>[C.id,C])),[T]),S=C=>{d(U=>({...U,[C]:!U[C]}))},j=C=>{h(U=>{const fe=U[C]??"markdown";return{...U,[C]:fe==="markdown"?"plain":"markdown"}})},P=C=>{p(C)},_=()=>{p(null)};a.useEffect(()=>{if(!g)return;const C=U=>{U.key==="Escape"&&_()};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[g]);const I=a.useCallback((C,U)=>{if(c){if(U){if(k.includes(C)){c(k);return}c([...k,C]);return}c(k.filter(fe=>fe!==C))}},[c,k]),D=a.useCallback(C=>{if(!c||C<=0)return;const U=[...k];[U[C-1],U[C]]=[U[C],U[C-1]],c(U)},[c,k]),G=a.useCallback(C=>{if(!c||C>=k.length-1)return;const U=[...k];[U[C],U[C+1]]=[U[C+1],U[C]],c(U)},[c,k]),$=a.useCallback(C=>{c&&c(k.filter(U=>U!==C))},[c,k]),R=n.length>0,w=k.length>0;a.useEffect(()=>{r||x(!1)},[r]);const H=a.useMemo(()=>k.map(C=>{const U=N.get(C);return{id:C,name:U?.name||C,description:U?.description||"Step definition not found.",phase:U?.phase||"pre-merge"}}),[k,N]),V=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:T.map(C=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${C.id}`,children:[t.jsx("input",{type:"checkbox",checked:k.includes(C.id),onChange:U=>I(C.id,U.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[C.name,wr(C.phase,C.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:C.description})]})]},C.id))})]}),k.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),k.map((C,U)=>{const fe=N.get(C);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${C}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:U+1}),t.jsx("span",{className:"workflow-step-order-name",children:fe?.name||C}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>D(U),disabled:U===0,"data-testid":`workflow-step-move-up-${C}`,title:"Move up",children:t.jsx(Zs,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(U),disabled:U===k.length-1,"data-testid":`workflow-step-move-down-${C}`,title:"Move down",children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(C),"data-testid":`workflow-step-remove-${C}`,title:"Remove",children:t.jsx(Tt,{size:14})})]})]},C)})]})]}),B=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!R)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const C=n.filter(F=>F.status==="passed").length,U=n.filter(F=>F.status==="failed").length,fe=n.filter(F=>F.status==="skipped").length,ie=n.filter(F=>F.status==="pending").length,re=[`${n.length} step${n.length!==1?"s":""}`];return C>0&&re.push(`${C} passed`),U>0&&re.push(`${U} failed`),fe>0&&re.push(`${fe} skipped`),ie>0&&re.push(`${ie} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:re.join(" · ")}),n.map((F,ce)=>{const ae=F.phase||"pre-merge",Q=u[F.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${F.status}`,"data-testid":`workflow-result-item-${F.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[F.workflowStepName,wr(ae,F.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${F.status}`,"data-testid":`workflow-result-badge-${F.workflowStepId}`,children:OE(F.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[F.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",BE(F.startedAt)]}),F.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:UE(F.startedAt,F.completedAt)})]}),F.status==="pending"&&F.startedAt?t.jsx(qE,{entries:E,startedAt:F.startedAt,stepId:F.workflowStepId}):F.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>S(F.workflowStepId),"data-testid":`workflow-result-toggle-${F.workflowStepId}`,children:Q?"Hide output":"Show output"}),!Q&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${F.workflowStepId}`,children:HE(F.output)}),Q&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>j(F.workflowStepId),"data-testid":`workflow-result-mode-toggle-${F.workflowStepId}`,title:(m[F.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[F.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>P(F.workflowStepId),"data-testid":`workflow-result-expand-${F.workflowStepId}`,title:"Expand output",children:t.jsx(eo,{size:12})})]})]}),Q&&t.jsx("div",{className:`workflow-result-output${(m[F.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${F.workflowStepId}`,children:(m[F.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],components:em,children:F.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:F.output})})]}):null]},`${F.workflowStepId}-${ce}`)})]})},M=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(C=>!C),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Un,{size:14}),"Edit"]})}):null,z=!s&&!R&&w,X=r&&R;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[z?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[H.length," step",H.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:H.map(C=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${C.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[C.name,wr(C.phase,C.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:C.description})]},C.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),V()]}):t.jsxs(t.Fragment,{children:[X&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),B(),V()]}),g&&(()=>{const C=n.find(ie=>ie.workflowStepId===g);if(!C)return null;const U=m[C.workflowStepId]??"markdown",fe=C.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ie=>{ie.target===ie.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:C.workflowStepName}),wr(fe,C.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>j(C.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:U==="markdown"?"Switch to plain text":"Switch to markdown",children:U==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Tt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${U==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:U==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],components:em,children:C.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:C.output})})})]})})})()]})}const WE=/^[a-zA-Z0-9_-]{1,64}$/,GE=200;function tm(e){return e?new Date(e).toLocaleString():""}function KE(e,n=GE){return e.length<=n?e:e.substring(0,n)+"…"}function JE({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[b,v]=a.useState(""),[x,y]=a.useState(null),[E,k]=a.useState([]),[T,N]=a.useState(!1),[S,j]=a.useState(!1),[P,_]=a.useState(""),[I,D]=a.useState(""),[G,$]=a.useState(!1),[R,w]=a.useState(null),[H,V]=a.useState(null),[B,M]=a.useState(!1),z=a.useCallback(async()=>{try{const ae=await kx(e,i);l(ae)}catch(ae){n(ve(ae)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{z()},[z]);async function X(ae){d===ae.key?(m(null),g(""),f(null),v(""),y(null),k([]),M(!1)):(m(ae.key),g(ae.content),f(null),v(""),y(null),k([]),M(!1))}async function C(ae){if(x===ae)y(null),k([]);else{y(ae),N(!0);try{const Q=await jx(e,ae,i);k(Q)}catch(Q){n(ve(Q)||"Failed to load revisions","error")}finally{N(!1)}}}function U(){d&&(f(d),v(h))}function fe(){f(null),v("")}async function ie(){if(!(!p||!b.trim())){$(!0);try{await Xc(e,p,b,{},i),f(null),v(""),await z();const ae=o.find(Q=>Q.key===p);ae&&g(ae.content),n("Document saved","success")}catch(ae){n(ve(ae)||"Failed to save document","error")}finally{$(!1)}}}async function re(){const ae=P.trim(),Q=I.trim();if(!ae){n("Document key is required","error");return}if(!WE.test(ae)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Q){n("Content is required","error");return}$(!0);try{await Xc(e,ae,Q,{},i),j(!1),_(""),D(""),await z(),n("Document created","success")}catch(de){n(ve(de)||"Failed to create document","error")}finally{$(!1)}}async function F(ae){w(ae);try{await wx(e,ae,i),V(null),w(null),d===ae&&(m(null),g("")),x===ae&&(y(null),k([])),await z(),n("Document deleted","success")}catch(Q){n(ve(Q)||"Failed to delete document","error")}finally{w(null)}}function ce(ae){g(ae.content),f(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),S&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:P,onChange:ae=>_(ae.target.value),placeholder:"e.g., plan, notes, research",disabled:G}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:I,onChange:ae=>D(ae.target.value),rows:6,placeholder:"Enter document content…",disabled:G})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{j(!1),_(""),D("")},disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void re(),disabled:G||!P.trim()||!I.trim(),children:G?"Creating…":"Create"})]})]}),o.length===0&&!S?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ae=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(Ni,{size:14}),t.jsx("span",{className:"task-document-key",children:ae.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ae.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ae.author}),t.jsx("span",{className:"task-document-timestamp",children:tm(ae.updatedAt||ae.createdAt)})]})]}),d===ae.key&&p!==ae.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>M(Q=>!Q),"aria-label":B?"Switch to plain text":"Switch to markdown","aria-pressed":B,title:B?"Switch to plain text":"Switch to markdown",children:B?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:B?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===ae.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),T?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):E.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:E.filter(Q=>Q.revision<ae.revision).sort((Q,de)=>de.revision-Q.revision).map(Q=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>ce(Q),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Q.revision]}),t.jsx("span",{className:"revision-author",children:Q.author}),t.jsx("span",{className:"revision-timestamp",children:tm(Q.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:KE(Q.content,100)})]},Q.id))})]})]}),p===ae.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:Q=>v(Q.target.value),rows:10,disabled:G}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:fe,disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ie(),disabled:G||!b.trim(),children:G?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void X(ae),children:d===ae.key?t.jsxs(t.Fragment,{children:[t.jsx(Zs,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(zt,{size:14})," Expand"]})}),d===ae.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void C(ae.key),children:[t.jsx(La,{size:14})," History"]}),r&&p!==ae.key&&t.jsx("button",{className:"btn btn-sm",onClick:U,children:"Edit"}),r&&(H===ae.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void F(ae.key),disabled:R===ae.key,children:R===ae.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>V(null),disabled:R===ae.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>V(ae.key),children:t.jsx(Bt,{size:14})}))]})]})]},ae.key))}),r&&!S&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>j(!0),children:[t.jsx(Ht,{size:14})," New Document"]})]})}function Nr(e){return e.toLocaleString()}function rl(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Sr(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),i=Math.round(n%60);return`${s}m ${i}s`}function YE(e){return(e.action||e.outcome||"").replace(/^\[timing\]\s*/i,"").replace(/^\[[^\]]+\]\s*/i,"").replace(/\s+in\s+\d+(?:\.\d+)?ms\b/i,"").replace(/\s+after\s+\d+(?:\.\d+)?ms\b/i,"").trim()||"Timing event"}function QE(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",i=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||i.includes("[timing]")}).map(n=>{const i=`${n.action??""}
610
- ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=i?Number(i[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:YE(n)}})}function XE(e){const n=e.map(r=>{if(!r.startedAt||!r.completedAt)return null;const o=new Date(r.startedAt).getTime(),l=new Date(r.completedAt).getTime();return Number.isNaN(o)||Number.isNaN(l)||l<o?null:{name:r.workflowStepName||r.workflowStepId,durationMs:l-o}}).filter(r=>r!==null),s=n.reduce((r,o)=>r+o.durationMs,0),i=n.reduce((r,o)=>!r||o.durationMs>r.durationMs?o:r,void 0);return{timedStepCount:n.length,totalDurationMs:s,longestStep:i}}function ZE({tokenUsage:e,loading:n,task:s}){const i=QE(s?.log??[]),r=i.filter(d=>typeof d.durationMs=="number"),o=r.reduce((d,m)=>d+(m.durationMs??0),0),l=r.reduce((d,m)=>!d||(m.durationMs??0)>(d.durationMs??0)?m:d,void 0),c=XE(s?.workflowStepResults??[]),u=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:i.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Sr(o)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:c.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Sr(c.totalDurationMs)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:l?.durationMs?`${l.summary} (${Sr(l.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:c.longestStep?`${c.longestStep.name} (${Sr(c.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:u>0?`${Math.min((s?.currentStep??0)+1,u)} / ${u}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${rl(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Nr(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Nr(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Nr(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Nr(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:rl(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Last used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:rl(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}function eM(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function tM(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function nM(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const i=s.text.match(/^Triage using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function sM(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=nM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function iM(e){switch(e){case"done":return"var(--color-success, #3fb950)";case"in-progress":return"var(--todo, #58a6ff)";case"skipped":return"var(--text-dim, #484f58)";case"pending":default:return"var(--border, #30363d)"}}function aM(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function rM(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function oM(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function nm(e,n){return e.length>n?e.slice(0,n)+"…":e}function sm(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function ol(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function ll(e){return e.trim()}function lM(e){const n=e.trim();return n.length>0?n:void 0}function ya(e){return typeof e=="string"&&ac.includes(e)?e:ls}function ka(e){return e==="fast"?"fast":"standard"}const cl=200,cM=new Set(["triage","todo"]);function dM({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onDuplicateTask:d,onTaskUpdated:m,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,b]=a.useState(p),[v,x]=a.useState(()=>"prompt"in e?e:null),[y,E]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){x(e),E(!1);return}let Y=!1;return E(!0),x(null),Dr(e.id,n).then(Je=>{Y||(x(Je),E(!1))}).catch(()=>{Y||E(!1)}),()=>{Y=!0}},[e.id,n]);const k=v??{...e,prompt:""},T=e.status==="failed"||e.status==="stuck-killed"||e.status==="specifying"||e.status==="needs-respecify"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt;a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{P(!1)},[e.id]);const[N,S]=a.useState("activity"),[j,P]=a.useState(!1),[_,I]=a.useState(e.attachments||[]),[D,G]=a.useState(!1),[$,R]=a.useState(e.dependencies||[]),[w,H]=a.useState(!1),[V,B]=a.useState(""),[M,z]=a.useState(null),[X,C]=a.useState([]),[U,fe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),[ae,Q]=a.useState(!1),[de,Re]=a.useState(!1),[ge,Me]=a.useState(k.prompt||""),[te,Ce]=a.useState(""),[$e,We]=a.useState(!1),[Ge,Ee]=a.useState(""),[Ae,Oe]=a.useState(!1),[ke,De]=a.useState(!1),[se,K]=a.useState(e.title||""),[me,ee]=a.useState(e.description||""),[he,le]=a.useState(e.dependencies||[]),[Ie,Ze]=a.useState(""),[rt,oe]=a.useState(""),[Z,pe]=a.useState(""),[Se,Pe]=a.useState(""),[ye,Ke]=a.useState("default"),[Ne,Fe]=a.useState(void 0),[Ye,xe]=a.useState(ls),[ze,be]=a.useState(ka(e.executionMode)),[Qe,it]=a.useState(""),[mt,At]=a.useState(e.enabledWorkflowSteps||[]),[It,Dt]=a.useState(e.sourceIssue?.provider??""),[Ut,jt]=a.useState(e.sourceIssue?.repository??""),[Pt,He]=a.useState(e.sourceIssue?.externalIssueId??""),[ut,$t]=a.useState(e.sourceIssue?.url??""),[St,Yt]=a.useState([]),[we,et]=a.useState(!1),ct=a.useRef(!1),[ue,A]=a.useState(!1),[J,Ve]=a.useState(!1),dt=a.useRef(null),yt=a.useRef(null),{getSlotsForId:qt}=bh(n),wn=qt("task-detail-tab");a.useEffect(()=>(ct.current=!0,()=>{ct.current=!1}),[]);const[Ft,Dn]=a.useState(void 0),[qn,ms]=a.useState([]),[hn,Ln]=a.useState(!1),[Nn,pn]=a.useState(e.enabledWorkflowSteps||[]);a.useEffect(()=>{K(e.title||""),ee(e.description||""),Dt(e.sourceIssue?.provider??""),jt(e.sourceIssue?.repository??""),He(e.sourceIssue?.externalIssueId??""),$t(e.sourceIssue?.url??""),be(ka(e.executionMode)),De(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{pn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Y=!1;return no(n).then(Je=>{Y||Dn(Je)}).catch(()=>{}),()=>{Y=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Y=!1;return Ln(!0),Vv(e.id,n).then(Je=>{Y||ms(Je)}).catch(Je=>{Y||h(`Failed to load workflow results: ${ve(Je)}`,"error")}).finally(()=>{Y||Ln(!1)}),()=>{Y=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Y=n?`?projectId=${encodeURIComponent(n)}`:"",Je=ot=>{try{const _t=JSON.parse(ot.data);_t.id===e.id&&Array.isArray(_t.workflowStepResults)&&ms(_t.workflowStepResults)}catch{}};return Vs(`/api/events${Y}`,{events:{"task:updated":Je}})},[f,e.id,n]),a.useEffect(()=>{w||B("")},[w]),a.useEffect(()=>{if(!e.assignedAgentId){z(null);return}const Y=X.find(ot=>ot.id===e.assignedAgentId);if(Y){z(Y);return}let Je=!1;return dh(e.assignedAgentId,n).then(ot=>{Je||z(ot)}).catch(()=>{Je||z(null)}),()=>{Je=!0}},[e.assignedAgentId,n,X]),a.useEffect(()=>{fe(!1)},[e.id]),a.useEffect(()=>{if(!(ue||J))return;const Je=ot=>{const _t=ot.target,Yn=dt.current?.contains(_t),Gs=yt.current?.contains(_t);!Yn&&ue&&A(!1),!Gs&&J&&Ve(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[ue,J]),a.useEffect(()=>{if(!(ue||J))return;const Je=ot=>{ot.key==="Escape"&&(ot.stopPropagation(),ue&&A(!1),J&&Ve(!1))};return document.addEventListener("keydown",Je),()=>document.removeEventListener("keydown",Je)},[ue,J]),a.useEffect(()=>{Re(!1),Me(k.prompt||""),Ce("")},[e.id,k.prompt]);const Vn=cM.has(e.column)&&!we,cn=a.useCallback(()=>{if(!Vn)return;De(!0),K(e.title||""),ee(e.description||""),le(e.dependencies||[]);const Y=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Je=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",ot=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Ze(Y),oe(Je),pe(ot),Pe(e.thinkingLevel??""),Ke(Y||Je||ot?"custom":"default"),it(""),At(e.enabledWorkflowSteps||[]),be(ka(e.executionMode)),Dt(e.sourceIssue?.provider??""),jt(e.sourceIssue?.repository??""),He(e.sourceIssue?.externalIssueId??""),$t(e.sourceIssue?.url??""),Yt([]),Fe(e.reviewLevel),xe(ya(e.priority))},[Vn,e]),Ct=a.useCallback(()=>{De(!1),K(e.title||""),ee(e.description||""),le(e.dependencies||[]),Dt(e.sourceIssue?.provider??""),jt(e.sourceIssue?.repository??""),He(e.sourceIssue?.externalIssueId??""),$t(e.sourceIssue?.url??""),xe(ya(e.priority)),be(ka(e.executionMode)),St.forEach(Y=>URL.revokeObjectURL(Y.previewUrl)),Yt([])},[e.title,e.description,e.dependencies,e.priority,e.executionMode,St]),xn=a.useCallback(async()=>{et(!0);try{const Y={},Je=se.trim(),ot=me.trim();Je&&Je!==(e.title??"")&&(Y.title=Je),ot&&ot!==(e.description??"")&&(Y.description=ot),sm(he,e.dependencies??[])||(Y.dependencies=he),sm(mt,e.enabledWorkflowSteps??[])||(Y.enabledWorkflowSteps=mt);const _t=ol(Ie),Yn=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Ie!==Yn&&(Y.modelProvider=_t?.provider??null,Y.modelId=_t?.modelId??null);const Gs=ol(rt),Is=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";rt!==Is&&(Y.validatorModelProvider=Gs?.provider??null,Y.validatorModelId=Gs?.modelId??null);const da=ol(Z),ar=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Z!==ar&&(Y.planningModelProvider=da?.provider??null,Y.planningModelId=da?.modelId??null);const bo=e.thinkingLevel??"";Se!==bo&&(Y.thinkingLevel=Se!==""?Se:null);const xo=e.reviewLevel;Ne!==xo&&(Y.reviewLevel=Ne);const vo=ya(e.priority);Ye!==vo&&(Y.priority=Ye);const Ks=ka(e.executionMode);ze!==Ks&&(Y.executionMode=ze==="fast"?"fast":null);const Ps=ll(It),ii=ll(Ut),hi=ll(Pt),ua=lM(ut);if(Ps.length===0&&ii.length===0&&hi.length===0&&!ua)e.sourceIssue&&(Y.sourceIssue=null);else{if(!Ps||!ii||!hi){h("Source issue provider, repository, and issue identifier are required","error"),et(!1);return}const xs=Number.parseInt(hi,10),Js=e.sourceIssue?.issueNumber??xs;if(!Number.isFinite(Js)||Js<=0){h("Source issue identifier must be numeric for new metadata","error"),et(!1);return}const $s={provider:Ps,repository:ii,externalIssueId:hi,issueNumber:Js,...ua?{url:ua}:{}},Ms=e.sourceIssue;(!Ms||Ms.provider!==$s.provider||Ms.repository!==$s.repository||Ms.externalIssueId!==$s.externalIssueId||Ms.issueNumber!==$s.issueNumber||(Ms.url??void 0)!==$s.url)&&(Y.sourceIssue=$s)}if(Object.keys(Y).length>0){const xs=await Qs(e.id,Y,n);m?.(xs)}if(St.length>0){const xs=[];for(const Js of St)try{const $s=await Fa(e.id,Js.file,n);I(Ms=>[...Ms,$s])}catch{xs.push(Js.file.name)}xs.length>0&&h(`Failed to upload: ${xs.join(", ")}`,"error")}St.forEach(xs=>URL.revokeObjectURL(xs.previewUrl)),Yt([]),h(`Updated ${e.id}`,"success"),De(!1)}catch(Y){h(`Failed to update ${e.id}: ${ve(Y)}`,"error")}finally{ct.current&&et(!1)}},[e,se,me,he,Ie,rt,Z,Se,Ne,Ye,ze,mt,It,Ut,Pt,ut,St,h,n,m]),Wn=a.useCallback(async Y=>{try{await Qs(e.id,{description:Y},n),h("Description saved","success")}catch(Je){h(`Failed to save: ${ve(Je)}`,"error")}},[e.id,h,n]),vn=a.useCallback(Y=>{ke&&(Y.key==="Escape"?(Y.preventDefault(),Ct()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),xn()))},[ke,Ct,xn]);a.useEffect(()=>{if(ke)return document.addEventListener("keydown",vn),()=>document.removeEventListener("keydown",vn)},[ke,vn]);const Mn=a.useRef(null),{entries:hs,loading:ps,loadMore:zn,hasMore:W,total:Le,loadingMore:nt}=Fp(e.id,f==="logs"&&N==="agent-log",n);a.useEffect(()=>{const Y=Je=>{Je.key==="Escape"&&!ke&&i()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[i,ke]);const tt=a.useCallback(Y=>{Y.target===Y.currentTarget&&i()},[i]),ht=a.useCallback(async Y=>{try{await o(e.id,Y),i(),h(`Moved to ${Tn[Y]}`,"success")}catch(Je){h(ve(Je),"error")}},[e.id,o,i,h]),kt=a.useCallback(async()=>{if(confirm(`Delete ${e.id}?`))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Y){const Je=oM(Y);if(!Je||Je.dependentIds.length===0){h(ve(Y),"error");return}const ot=Je.dependentIds.join(", ");if(!confirm(`${e.id} is a dependency of ${ot}.
611
-
612
- Delete anyway by removing these dependency references first?`))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Yn){h(ve(Yn),"error")}}},[e.id,l,i,h]),Et=a.useCallback(()=>{confirm(`Merge ${e.id} into the current branch?`)&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Y=>{const Je=Y.merged?`Merged ${e.id} (branch: ${Y.branch})`:`Closed ${e.id} (${Y.error||"no branch to merge"})`;h(Je,"success")}).catch(Y=>{h(ve(Y),"error")}))},[e.id,c,i,h]),fn=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Y=>{h(ve(Y),"error")}))},[e.id,u,i,h]),fs=a.useCallback(async()=>{if(d&&confirm(`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`))try{const Y=await d(e.id);i(),h(`Duplicated ${e.id} → ${Y.id}`,"success")}catch(Y){h(ve(Y),"error")}},[e.id,d,i,h]),Qt=a.useCallback(async()=>{try{e.paused?(await ux(e.id,n),h(`Unpaused ${e.id}`,"success")):(await ih(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Y){h(ve(Y),"error")}},[e.id,e.paused,i,h]),xt=a.useCallback(async()=>{try{await fx(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Y){h(ve(Y),"error")}},[e.id,i,h]),lt=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await gx(e.id,n),h(`Plan rejected — ${e.id} returned to Triage for re-specification`,"info"),i()}catch(Y){h(ve(Y),"error")}},[e.id,i,h]),ne=a.useCallback(async()=>{if(confirm("Rebuild the specification for this task? The task will move to triage for re-specification."))try{await Cx(e.id,n),i(),h(`Respecifying ${e.id}...`,"info")}catch(Y){h(ve(Y),"error")}},[e.id,n,i,h]),_e=a.useCallback(()=>{We(!0),Ee("")},[]),st=a.useCallback(()=>{A(!1),Ve(!1)},[]),gt=a.useCallback(Y=>{st(),ht(Y)},[st]),bt=a.useCallback(Y=>{st(),Y()},[st]),rn=a.useCallback(()=>{st(),Et()},[st]),Xt=a.useCallback(()=>{We(!1),Ee(""),Oe(!1)},[]),ln=a.useCallback(async()=>{if(!Ge.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Ge.length>2e3){h("Feedback must be 2000 characters or less","error");return}Oe(!0);try{const Y=await Ex(e.id,Ge.trim(),n);h(`Refinement task created: ${Y.id}`,"success"),i()}catch(Y){h(ve(Y),"error")}finally{Oe(!1)}},[e.id,Ge,h,i]),Wt=a.useCallback(async Y=>{G(!0);try{const Je=await Fa(e.id,Y,n);I(ot=>[...ot,Je]),h("Screenshot attached","success")}catch(Je){h(ve(Je),"error")}finally{G(!1)}},[e.id,h]),gn=a.useCallback(async Y=>{const Je=Y.target.files?.[0];Je&&(await Wt(Je),Mn.current&&(Mn.current.value=""))},[Wt]);a.useEffect(()=>{const Y=Je=>{const ot=Je.clipboardData?.items;if(ot)for(let _t=0;_t<ot.length;_t++){const Yn=ot[_t];if(Yn.type.startsWith("image/")){const Gs=Yn.getAsFile();if(Gs){Je.preventDefault(),Wt(Gs);return}}}};return document.addEventListener("paste",Y),()=>document.removeEventListener("paste",Y)},[Wt]);const Sn=a.useCallback(Y=>{Y.preventDefault()},[]),gs=a.useCallback(Y=>{Y.preventDefault();const Je=Y.dataTransfer.files;for(let ot=0;ot<Je.length;ot++){const _t=Je[ot];if(_t.type.startsWith("image/")){Wt(_t);return}}},[Wt]),Fn=a.useCallback(async Y=>{try{await xx(e.id,Y,n),I(Je=>Je.filter(ot=>ot.filename!==Y)),h("Attachment deleted","info")}catch(Je){h(ve(Je),"error")}},[e.id,h]),Gn=a.useCallback(async Y=>{const Je=Nn;pn(Y);try{const ot=await Qs(e.id,{enabledWorkflowSteps:Y},n);h("Workflow steps updated","success"),m?.(ot)}catch(ot){pn(Je),h(`Failed to update workflow steps: ${ve(ot)}`,"error")}},[e.id,n,Nn,m,h]),On=a.useCallback(async()=>{re(!0);try{const Y=await aa(void 0,n);C(Y),fe(!0)}catch(Y){h(`Failed to load agents: ${ve(Y)}`,"error"),fe(!1)}finally{re(!1)}},[n,h]),Kn=a.useCallback(async Y=>{try{const Je=await cd(e.id,Y,n),ot=X.find(_t=>_t.id===Y)??null;z(ot||(_t=>_t?.id===Y?_t:null)),fe(!1),m?.(Je),h("Assigned agent updated","success")}catch(Je){h(`Failed to assign agent: ${ve(Je)}`,"error")}},[e.id,n,X,m,h]),dn=a.useCallback(async()=>{try{const Y=await cd(e.id,null,n);z(null),fe(!1),m?.(Y),h("Agent unassigned","success")}catch(Y){h(`Failed to unassign agent: ${ve(Y)}`,"error")}},[e.id,n,m,h]),Jn=a.useCallback(async Y=>{const Je=[...$,Y];R(Je);try{await Qs(e.id,{dependencies:Je},n)}catch(ot){R($),h(ve(ot),"error")}},[e.id,$,h]),Es=a.useCallback(async(Y,Je)=>{Y.stopPropagation();const ot=$.filter(_t=>_t!==Je);R(ot);try{await Qs(e.id,{dependencies:ot},n)}catch(_t){R($),h(ve(_t),"error")}},[e.id,$,h]),Ts=a.useCallback(async Y=>{try{const Je=await Dr(Y,n);r(Je)}catch{h(`Failed to load dependency ${Y}`,"error")}},[r,h]),as=a.useCallback(async Y=>{ce(!0);try{await Qs(k.id,{prompt:Y},n),h("Spec updated","success"),v&&(v.prompt=Y)}catch(Je){throw h(ve(Je),"error"),Je}finally{ce(!1)}},[k,v,h]),_n=a.useCallback(async Y=>{Q(!0);try{await Sx(e.id,Y,n),h("AI revision requested. Task moved to triage.","success"),i()}catch(Je){const ot=ve(Je);ot.includes("in-review")||ot.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(ot,"error")}finally{Q(!1)}},[e.id,h,i]),bs=a.useCallback(()=>{Re(!0),Me(k.prompt||""),Ce("")},[k.prompt]),An=a.useCallback(()=>{Re(!1),Me(k.prompt||""),Ce("")},[k.prompt]),ca=a.useCallback(async()=>{if(ge===(k.prompt||"")){An();return}await as(ge),Re(!1)},[ge,k.prompt,as,An]),po=a.useCallback(async()=>{te.trim()&&await _n(te.trim())},[te,_n]),fo=a.useCallback(Y=>{Y.key==="Escape"?(Y.preventDefault(),An()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),ca())},[An,ca]),mi=s.filter(Y=>Y.id!==e.id&&!$.includes(Y.id)).sort((Y,Je)=>{const ot=Je.createdAt.localeCompare(Y.createdAt);if(ot!==0)return ot;const _t=parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0;return(parseInt(Je.id.slice(Je.id.lastIndexOf("-")+1),10)||0)-_t}),sr=M?.name??e.assignedAgentId??null,si=Rl[e.column]||[],go={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},ir=e.status?go[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",onClick:tt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg",onDragOver:Sn,onDrop:gs,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:Tn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!ke&&Vn&&t.jsx("button",{className:"modal-edit-btn",onClick:cn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&N==="agent-log"&&!ke?" detail-body--agent-log":""}`,children:[ke?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Bp,{mode:"edit",title:se,onTitleChange:K,description:me,onDescriptionChange:ee,dependencies:he,onDependenciesChange:le,executorModel:Ie,onExecutorModelChange:Ze,validatorModel:rt,onValidatorModelChange:oe,planningModel:Z,onPlanningModelChange:pe,thinkingLevel:Se,onThinkingLevelChange:Pe,presetMode:ye,onPresetModeChange:Ke,selectedPresetId:Qe,onSelectedPresetIdChange:it,selectedWorkflowSteps:mt,onWorkflowStepsChange:At,pendingImages:St,onImagesChange:Yt,tasks:s.filter(Y=>Y.id!==e.id),projectId:n,disabled:we,addToast:h,isActive:ke,onAutoSaveDescription:Wn,reviewLevel:Ne,onReviewLevelChange:Fe,priority:Ye,onPriorityChange:xe,executionMode:ze,onExecutionModeChange:be,renderBelowModelConfiguration:t.jsxs("div",{className:"form-group detail-source-edit-group",children:[t.jsx("label",{children:"Source Issue"}),t.jsxs("div",{className:"detail-source-edit-grid",children:[t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:It,onChange:Y=>Dt(Y.target.value),disabled:we,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Ut,onChange:Y=>jt(Y.target.value),disabled:we,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Pt,onChange:Y=>He(Y.target.value),disabled:we,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:ut,onChange:Y=>$t(Y.target.value),disabled:we,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const Y=e.title||e.description||e.id,Je=!j&&Y.length>cl;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Je?Y.slice(0,cl)+"…":Y}),Y.length>cl&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>P(!j),children:j?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("span",{className:`detail-priority-chip detail-priority-chip--${ya(e.priority)}`,children:["Priority: ",ya(e.priority)]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!ke&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>b("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>b("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${f==="changes"?" detail-tab-active":""}`,onClick:()=>b("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>b("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>b("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>b("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>b("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>b("stats"),children:"Stats"}),wn.map((Y,Je)=>{const ot=`plugin-${Je}`;return t.jsx("button",{className:`detail-tab${f===ot?" detail-tab-active":""}`,onClick:()=>b(ot),children:Y.slot.label},`plugin-tab-${Y.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(VE,{taskId:e.id,results:qn,loading:hn,enabledWorkflowSteps:Nn,canEdit:Vn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Gn})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(EE,{task:e,addToast:h,onTaskUpdated:m,settings:Ft})}):f==="logs"?t.jsxs("div",{className:`detail-section${N==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${N==="activity"?" log-subview-btn-active":""}`,onClick:()=>S("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${N==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>S("agent-log"),children:"Agent Log"})]}),N==="agent-log"?t.jsx(jE,{entries:hs,loading:ps,executorModel:eM(e,Ft),validatorModel:tM(e,Ft),planningModel:sM(e,hs,Ft),hasMore:W,onLoadMore:zn,loadingMore:nt,totalCount:Le}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),k.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",k.log.length," activity entries."]}):null,k.log&&k.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...k.log].reverse().map((Y,Je)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:aM(Y.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Y.action})]}),Y.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Y.outcome})]},Je))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(LE,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(TE,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(JE,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Vn}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(ao,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(ZE,{tokenUsage:k.tokenUsage,loading:y,task:k})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],children:e.summary})})]}),t.jsx(PE,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsx("h4",{children:"Source Issue"}),t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(nn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]}),t.jsxs("div",{className:"detail-agent-actions",children:[sr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(nn,{size:14}),sr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void dn(),title:"Unassign agent",children:t.jsx(Tt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{U?fe(!1):On()},children:"Assign Agent"}),U&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ie&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ie&&X.filter(Y=>Y.state!=="terminated").map(Y=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Y.id?" selected":""}`,onClick:()=>void Kn(Y.id),children:[t.jsx(nn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Y.name}),t.jsx("span",{className:"agent-picker-role",children:Y.role})]},Y.id)),!ie&&X.filter(Y=>Y.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),k.steps&&k.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:k.steps.map((Y,Je)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Y.status}`,"data-tooltip":`${Y.name} (${Y.status})`,style:{backgroundColor:iM(Y.status)}},Je))}),t.jsxs("span",{className:"step-progress-label",children:[k.steps.filter(Y=>Y.status==="done").length,"/",k.steps.length," step",k.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!de&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:bs,children:"Edit"})}),de?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:ge,onChange:Y=>Me(Y.target.value),onKeyDown:fo,disabled:F,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:An,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ca(),disabled:ge===(k.prompt||"")||F,children:F?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to triage for re-specification."}),t.jsx("textarea",{className:"spec-editor-feedback",value:te,onChange:Y=>Ce(Y.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ae,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[te.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void po(),disabled:!te.trim()||ae,children:ae?"Requesting…":"Request AI Revision"})]})]})]}):y?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):k.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],children:k.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),_.length>0?t.jsx("div",{className:"detail-attachments-grid",children:_.map(Y=>{const Je=qs(`/api/tasks/${e.id}/attachments/${Y.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Je,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Je,alt:Y.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Y.originalName," (",rM(Y.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Fn(Y.filename),title:"Delete attachment",children:"×"})]},Y.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Mn,type:"file",accept:"image/*",onChange:gn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Mn.current?.click(),disabled:D,children:D?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Y=>{const Je=s.find(_t=>_t.id===Y),ot=Je?.title||Je?.description||Y;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ts(Y),onKeyDown:_t=>{(_t.key==="Enter"||_t.key===" ")&&(_t.preventDefault(),Ts(Y))},role:"link",tabIndex:0,title:`Click to view ${Y}`,children:[t.jsx("span",{className:"detail-dep-id",children:Y}),t.jsx("span",{className:"detail-dep-label",children:nm(ot,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:_t=>Es(_t,Y),title:`Remove dependency ${Y}`,children:"×"})]},Y)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w&&B(""),H(Y=>!Y)},children:"Add Dependency"}),w&&(()=>{const Y=V.toLowerCase(),Je=Y?mi.filter(ot=>ot.id.toLowerCase().includes(Y)||ot.title&&ot.title.toLowerCase().includes(Y)||ot.description&&ot.description.toLowerCase().includes(Y)):mi;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:V,onChange:ot=>B(ot.target.value),onClick:ot=>ot.stopPropagation()}),Je.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Je.map(ot=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Jn(ot.id),H(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:ot.id}),t.jsx("span",{className:"dep-dropdown-title",children:nm(ot.title||ot.description||ot.id,30)})]},ot.id))]})})()]})]}),e.column==="in-review"&&t.jsx(_E,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Ft?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:Y=>{e.prInfo=Y,h(`PR #${Y.number} created`,"success")},onPrUpdated:Y=>{e.prInfo=Y},addToast:h})]})]})]}),t.jsx("div",{className:"modal-actions",children:ke?t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"modal-edit-hint",children:[t.jsx("kbd",{children:"Ctrl+Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Ct,disabled:we,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:xn,disabled:we,children:we?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&k.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:xt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:lt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!T&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:kt,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||T)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:yt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Ve(Y=>!Y),A(!1)},"aria-haspopup":"menu","aria-expanded":J,children:["Actions",t.jsx(zt,{size:12})]}),J&&t.jsxs("div",{className:"detail-actions-menu",role:"menu",children:[t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>bt(kt),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(fs),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(_e),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(ne),children:"Respecify"}),T&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(fn),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(Qt),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:dt,children:e.column==="in-review"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{A(Y=>!Y),Ve(!1)},"aria-haspopup":"menu","aria-expanded":ue,children:["Move",t.jsx(zt,{size:12})]}),ir?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:ir}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:rn,children:"Merge & Close"})]}),ue&&t.jsxs("div",{className:"detail-move-menu",role:"menu",children:[t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>gt("todo"),children:"Move to Todo"}),t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>gt("in-progress"),children:"Back to In Progress"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>gt(si[0]),disabled:si.length===0,children:["Move to ",si.length>0?Tn[si[0]]:""]}),si.length>1&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(Y=>!Y),Ve(!1)},"aria-haspopup":"menu","aria-expanded":ue,children:t.jsx(zt,{size:12})}),ue&&t.jsx("div",{className:"detail-move-menu",role:"menu",children:si.map(Y=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>gt(Y),children:["Move to ",Tn[Y]]},Y))})]})]})})]})}),$e&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Xt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Y=>Y.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:Xt,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:Ge,onChange:Y=>Ee(Y.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[Ge.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ln,disabled:!Ge.trim()||Ae,children:Ae?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Xt,disabled:Ae,children:"Cancel"})})]})})]})})}const uM=640;function mM({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[b,v]=a.useState([]),[x,y]=a.useState(null),[E,k]=a.useState([]),[T,N]=a.useState(null),[S,j]=a.useState(null),[P,_]=a.useState(!1),[I,D]=a.useState([]),[G,$]=a.useState(!1),[R,w]=a.useState(""),H=a.useRef(!1),[V,B]=a.useState(!1),[M,z]=a.useState("list"),X=a.useRef(null),C=new Set;for(const ee of i){const he=ee.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);he&&C.add(he[1]);const le=ee.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);le&&C.add(le[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),k([]),N(null),f("issues"),j(null),_(!1),D([]),$(!0),w(""),X.current=null,H.current=!0,Fx().then(ee=>{if(H.current)if(D(ee),$(!1),ee.length===1){const he=ee[0];l(he.owner),u(he.repo),w(he.name)}else ee.length>1&&(l(""),u(""),w(""))}).catch(()=>{H.current&&$(!1)}),()=>{H.current=!1}},[e]);const U=a.useCallback(ee=>{if(w(ee),ee==="")l(""),u("");else{const he=I.find(le=>le.name===ee);he&&(l(he.owner),u(he.repo))}},[I]),fe=a.useCallback(async()=>{if(!o.trim()||!c.trim()){j("Repository must be selected");return}g(!0),j(null),v([]),y(null);try{const ee=d.split(",").map(le=>le.trim()).filter(Boolean),he=await $x(o.trim(),c.trim(),30,ee.length>0?ee:void 0);v(he),he.length===0&&j("No open issues found")}catch(ee){j(ve(ee)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),ie=a.useCallback(async()=>{if(!o.trim()||!c.trim()){j("Repository must be selected");return}g(!0),j(null),k([]),N(null);try{const ee=await Lx(o.trim(),c.trim(),30);k(ee),ee.length===0&&j("No open pull requests found")}catch(ee){j(ve(ee)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||P)return;const ee={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};X.current?.owner===ee.owner&&X.current?.repo===ee.repo&&X.current?.labels===ee.labels&&X.current?.tab===ee.tab||(X.current=ee,p==="issues"?fe():ie())},[o,c,d,p,e,h,P,fe,ie]),a.useEffect(()=>{if(!e)return;const ee=he=>{he.key==="Escape"&&n()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[e,n]),a.useEffect(()=>{if(!e)return;const ee=()=>{B(window.innerWidth<=uM)};return ee(),window.addEventListener("resize",ee),()=>window.removeEventListener("resize",ee)},[e]);const re=a.useCallback(ee=>{y(ee),V&&z("preview")},[V]),F=a.useCallback(ee=>{N(ee),V&&z("preview")},[V]),ce=a.useCallback(()=>{z("list")},[]),ae=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;_(!0),j(null);try{const ee=await Dx(o.trim(),c.trim(),x,r);s(ee),n()}catch(ee){const he=ve(ee);he?.includes("already imported")?j(he):j(he||"Failed to import issue")}finally{_(!1)}}else{if(T===null)return;_(!0),j(null);try{const ee=await zx(o.trim(),c.trim(),T,r);s(ee),n()}catch(ee){const he=ve(ee);he?.includes("already imported")?j(he):j(he||"Failed to import pull request")}finally{_(!1)}}},[p,x,T,o,c,s,n]),Q=b.find(ee=>ee.number===x),de=E.find(ee=>ee.number===T);if(!e)return null;const Re=I.length>0,ge=I.length===1,Me=b.filter(ee=>C.has(ee.html_url)).length,te=E.filter(ee=>C.has(ee.html_url)).length,Ce=S==="No open issues found",$e=S==="No open pull requests found",We=p==="issues"?Ce:$e,Ge=!!S&&!Ce&&b.length===0&&!h,Ee=!!S&&!$e&&E.length===0&&!h,Ae=p==="issues"?Ge:Ee,Oe=h||b.length>0||Ce||Ge,ke=h||E.length>0||$e||Ee,De=p==="issues"?Oe:ke,se=!!S&&b.length>0&&!Ce,K=!!S&&E.length>0&&!$e,me=p==="issues"?se:K;return t.jsx("div",{className:"modal-overlay open",onClick:ee=>ee.target===ee.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{f("issues"),N(null)},disabled:h||P,children:[t.jsx(Yr,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),y(null)},disabled:h||P,children:[t.jsx(Zn,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:G?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(at,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):Re?ge?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:I[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[I[0].owner,"/",I[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:R,onChange:ee=>U(ee.target.value),disabled:h||P,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),I.map(ee=>t.jsxs("option",{value:ee.name,children:[ee.name," (",ee.owner,"/",ee.repo,")"]},ee.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:d,onChange:ee=>m(ee.target.value),onKeyDown:ee=>ee.key==="Enter"&&fe(),disabled:h||P||!Re,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?fe:ie,disabled:h||P||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!G&&!Re&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),me&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:S}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${V?"mobile":""} ${M==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),t.jsxs("span",{children:[Me," imported"]})]}),p==="pulls"&&E.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[E.length," pull request",E.length===1?"":"s"]}),t.jsxs("span",{children:[te," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!De&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(at,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),Ae&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:S})]})}),We&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(ee=>{const he=C.has(ee.html_url);return t.jsxs("div",{className:`issue-item ${x===ee.number?"selected":""} ${he?"imported":""}`,onClick:()=>!he&&re(ee.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===ee.number,onChange:()=>re(ee.number),disabled:he,"aria-label":`Select issue #${ee.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ee.number]}),t.jsx("span",{className:"issue-title",children:ee.title})]}),ee.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ee.labels.map(le=>t.jsx("span",{className:"label-chip",children:le.name},le.name))})]}),he&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ee.number)})}),p==="pulls"&&E.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:E.map(ee=>{const he=C.has(ee.html_url);return t.jsxs("div",{className:`issue-item ${T===ee.number?"selected":""} ${he?"imported":""}`,onClick:()=>!he&&F(ee.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:T===ee.number,onChange:()=>F(ee.number),disabled:he,"aria-label":`Select pull request #${ee.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ee.number]}),t.jsx("span",{className:"issue-title",children:ee.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ee.headBranch," → ",ee.baseBranch]})]}),he&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ee.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${V?"mobile":""} ${M==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[V&&t.jsxs("button",{className:"github-import-back-button",onClick:ce,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(na,{size:16}),t.jsx("span",{children:"Back"})]}),t.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),t.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&Q?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",Q.number]}),t.jsx("div",{className:"preview-title",children:Q.title}),t.jsx("div",{className:"preview-body",children:Q.body?Q.body.slice(0,200)+(Q.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&de?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",de.number]}),t.jsx("div",{className:"preview-title",children:de.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",de.headBranch," → ",de.baseBranch]}),t.jsx("div",{className:"preview-body",children:de.body?de.body.slice(0,200)+(de.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:P,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ae,disabled:(p==="issues"?x===null:T===null)||P,children:P?t.jsx(at,{size:14,className:"spin"}):"Import"})]})]})})}const hM=["Build a user authentication system with login and signup","Add dark mode support to the dashboard","Create an API endpoint for exporting tasks as CSV","Refactor the task card component for better performance"];function pM(e,n){return e&&n?`${e}/${n}`:""}function fM(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function gM({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,x]=a.useState([]),[y,E]=a.useState(null),k=a.useRef(!1),T=a.useRef(!1),[N,S]=a.useState(""),[j,P]=a.useState(!0),[_,I]=a.useState(!1),[D,G]=a.useState(!1),$=a.useRef(null),R=a.useRef(null),w=a.useRef(null),[H,V]=a.useState(c??null),B=a.useMemo(()=>_i(),[]),{isLockedByOther:M,takeControl:z,isLoading:X}=oo(e?H:null),{activeTabMap:C,broadcastUpdate:U,broadcastCompleted:fe,broadcastLock:ie,broadcastUnlock:re,broadcastHeartbeat:F}=ra(),[ce,ae]=a.useState(void 0),[Q,de]=a.useState(void 0),[Re,ge]=a.useState([]),[Me,te]=a.useState(!1),[Ce,$e]=a.useState(null),[We,Ge]=a.useState([]),[Ee,Ae]=a.useState([]),Oe=a.useRef(null),ke=pM(ce,Q),De=a.useCallback((xe,ze)=>{if(!xe||!ze)return"Using default";const be=Re.find(Qe=>Qe.provider===xe&&Qe.id===ze);return be?`${be.provider}/${be.id}`:`${xe}/${ze}`},[Re]),se=a.useCallback(async()=>{te(!0),$e(null);try{const xe=await ss();ge(xe.models),Ge(xe.favoriteProviders),Ae(xe.favoriteModels)}catch(xe){$e(ve(xe)||"Failed to load models")}finally{te(!1)}},[]),K=a.useCallback(xe=>{Ge(ze=>{const be=ze,it=be.includes(xe)?be.filter(mt=>mt!==xe):[xe,...be];return tn({favoriteProviders:it,favoriteModels:Ee}).catch(()=>{Ge(be)}),it})},[Ee]),me=a.useCallback(xe=>{Ae(ze=>{const be=ze,it=be.includes(xe)?be.filter(mt=>mt!==xe):[xe,...be];return tn({favoriteProviders:We,favoriteModels:it}).catch(()=>{Ae(be)}),it})},[We]),ee=a.useCallback(xe=>{R.current?.close();const ze=Lv(xe,l,{onThinking:be=>{S(Qe=>Qe+be),U({sessionId:xe,status:"generating",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:be=>{I(!1),G(!1),$i(l),h({type:"question",session:{sessionId:xe,currentQuestion:be,summary:null}}),S(""),U({sessionId:xe,status:"awaiting_input",needsInput:!0,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:be=>{I(!1),G(!1),$i(l),h({type:"summary",session:{sessionId:xe,currentQuestion:null,summary:be},summary:be}),E(be),S(""),U({sessionId:xe,status:"complete",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:be=>{const Qe=be||"Session failed while contacting the AI.";I(!0),(async()=>{try{const it=await Xs(xe);if(it&&(it.status==="generating"||it.status==="awaiting_input")){ee(xe);return}}catch{}I(!1),G(!1),p(null),h(it=>it.type==="question"||it.type==="summary"||it.type==="error"?{type:"error",session:it.session,errorMessage:Qe}:{type:"error",session:{sessionId:xe,currentQuestion:null,summary:null},errorMessage:Qe}),S(""),w.current=xe,U({sessionId:xe,status:"error",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),fe({sessionId:xe,status:"error"})})()},onComplete:()=>{I(!1),G(!1),w.current=null,fe({sessionId:xe,status:"complete"})},onConnectionStateChange:be=>{I(be==="reconnecting")}});R.current=ze},[fe,U,u,l,B]),he=a.useCallback(async xe=>{const ze=xe??u;if(ze.trim()){p(null),S(""),x([]),b([]),I(!1),h({type:"loading"});try{const be=ce&&Q?{planningModelProvider:ce,planningModelId:Q}:void 0,{sessionId:Qe}=await kv(ze.trim(),l,be);w.current=Qe,V(Qe),ee(Qe),b([])}catch(be){I(!1),p(ve(be)||"Failed to start planning session"),h({type:"initial"}),w.current=null,V(null)}}},[ee,u,Q,ce,l]);a.useEffect(()=>{e&&m.type==="initial"&&$.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&se()},[e,se]),a.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){d(o);const xe=setTimeout(()=>{k.current=!0,he(o)},0);return()=>clearTimeout(xe)}else if(e&&!o&&!k.current&&!T.current&&m.type==="initial"){T.current=!0;const xe=pw(l);xe&&d(xe)}},[e,o,m.type,he,l]),a.useEffect(()=>{if(!e||!c||m.type!=="initial")return;let xe=!1;return(async()=>{try{const ze=await Xs(c);if(xe||!ze)return;w.current=c,V(c);const be=Ki(ze.conversationHistory);if(x(be),b(be.map(Qe=>Qe.response).filter(Qe=>!!(Qe&&typeof Qe=="object"&&!Array.isArray(Qe)))),ze.status==="awaiting_input"&&ze.currentQuestion){$i(l);const Qe=JSON.parse(ze.currentQuestion);h({type:"question",session:{sessionId:c,currentQuestion:Qe,summary:null}}),ze.thinkingOutput&&S(ze.thinkingOutput),ee(c)}else if(ze.status==="complete"&&ze.result){$i(l);const Qe=JSON.parse(ze.result);h({type:"summary",session:{sessionId:c,currentQuestion:null,summary:Qe},summary:Qe}),E(Qe)}else ze.status==="generating"?(h({type:"loading"}),ze.thinkingOutput&&S(ze.thinkingOutput),ee(c)):ze.status==="error"&&(p(null),h({type:"error",session:{sessionId:c,currentQuestion:null,summary:null},errorMessage:ze.error||"Session failed"}))}catch{p("Failed to resume session")}})(),()=>{xe=!0}},[ee,e,c,m.type,l]),a.useEffect(()=>{e||(k.current=!1,T.current=!1,I(!1),G(!1),V(null))},[e]),a.useEffect(()=>{if(!e){Oe.current&&(re(Oe.current,B),Oe.current=null);return}if(H&&Oe.current!==H){Oe.current&&re(Oe.current,B),ie(H,B),Oe.current=H;return}!H&&Oe.current&&(re(Oe.current,B),Oe.current=null)},[ie,re,e,H,B]),a.useEffect(()=>{if(!e||!H||Oe.current!==H)return;F(B);const xe=setInterval(()=>{F(B)},3e4);return()=>{clearInterval(xe)}},[F,e,H,B]),a.useEffect(()=>()=>{R.current?.close(),R.current=null,Oe.current&&(re(Oe.current,B),Oe.current=null)},[re,B]),a.useEffect(()=>{if(!e)return;const xe=()=>{R.current?.close(),R.current=null};return window.addEventListener("beforeunload",xe),()=>window.removeEventListener("beforeunload",xe)},[e]);const le=a.useCallback(()=>{R.current?.close(),R.current=null,n()},[n]),Ie=a.useCallback(()=>{let xe=null;m.type==="question"||m.type==="summary"||m.type==="error"?xe=m.session.sessionId:m.type==="breakdown"?xe=m.sessionId:m.type==="loading"&&(xe=w.current),u&&hw(u,l),R.current?.close(),R.current=null,xe&&rh(xe,l,B).catch(()=>{}),d(""),h({type:"initial"}),p(null),b([]),x([]),E(null),S(""),I(!1),G(!1),ae(void 0),de(void 0),w.current=null,V(null),n()},[u,n,l,B,m]);a.useEffect(()=>{if(!e)return;const xe=ze=>{ze.key==="Escape"&&Ie()};return document.addEventListener("keydown",xe),()=>document.removeEventListener("keydown",xe)},[e,Ie]);const Ze=a.useCallback(async xe=>{if(m.type!=="question")return;const{session:ze}=m,be=ze.sessionId,Qe=ze.currentQuestion;if(!Qe){p("No active question in session");return}p(null),b(it=>[...it,xe]),x(it=>[...it,{question:Qe,response:xe}]),h({type:"loading"}),S("");try{await jv(be,xe,l,B)}catch(it){p(ve(it)||"Failed to submit response"),h({type:"question",session:ze})}},[l,B,m]),rt=a.useCallback(async()=>{if(m.type!=="error")return;const xe=m.session;p(null),G(!0),S(""),h({type:"loading"}),ee(xe.sessionId);try{w.current=xe.sessionId,V(xe.sessionId),await wv(xe.sessionId,l,B)}catch(ze){let be=ze;if((ve(ze)||"").includes("not in an error state"))try{const it=await Xs(xe.sessionId);if(!it)throw new Error("Failed to refresh planning session.");if(w.current=it.id,V(it.id),it.status==="generating")S(it.thinkingOutput??""),h({type:"loading"});else if(it.status==="awaiting_input"){if(!it.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const mt=JSON.parse(it.currentQuestion);$i(l),h({type:"question",session:{sessionId:it.id,currentQuestion:mt,summary:null}}),R.current?.isConnected()||ee(it.id)}else if(it.status==="complete"){if(!it.result)throw new Error("Planning session is complete but has no result.");const mt=JSON.parse(it.result);$i(l),h({type:"summary",session:{sessionId:it.id,currentQuestion:null,summary:mt},summary:mt}),E(mt)}else it.status==="error"&&h({type:"error",session:{sessionId:it.id,currentQuestion:null,summary:null},errorMessage:it.error||"Retry failed. Please try again."});I(!1);return}catch(it){be=it}R.current?.close(),R.current=null,h({type:"error",session:xe,errorMessage:ve(be)||"Retry failed. Please try again."}),I(!1)}finally{G(!1)}},[ee,l,B,m]),oe=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const xe=await Nv(m.session.sessionId,y??void 0,l);s(xe),Ie()}catch(xe){p(ve(xe)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l,s,Ie]),Z=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const xe=await Sv(m.session.sessionId,y??void 0,l);V(xe.sessionId),h({type:"breakdown",sessionId:xe.sessionId,subtasks:xe.subtasks,dirty:!1})}catch(xe){p(ve(xe)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),pe=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const xe=await Cv(m.sessionId,m.subtasks,l);i(xe.tasks),d(""),h({type:"initial"}),p(null),b([]),x([]),E(null),S(""),ae(void 0),de(void 0),w.current=null,V(null),n()}catch(xe){p(ve(xe)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[m,i,n,l]),Se=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const xe=f.slice(0,-1);b(xe),h({type:"question",session:m.session})}},[m,f]),Pe=()=>m.type==="question"?Math.min(f.length+1,3):3,ye=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",Ke=H?C.get(H):null,Ne=Ke&&Ke.tabId!==B,Fe=!!(Ne&&!Ke.stale),Ye=M&&(!Ne||Ke.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:xe=>xe.target===xe.currentTarget&&Ie(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Bs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ye&&t.jsx("button",{className:"modal-send-to-background",onClick:le,title:"Send to background","aria-label":"Send to background",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ie,"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Fe&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),m.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(Pn,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:$,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:u,onChange:xe=>d(xe.target.value),onKeyDown:xe=>{xe.key==="Enter"&&!xe.shiftKey&&u.trim()&&(xe.preventDefault(),he())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:hM.map((xe,ze)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(xe),children:xe.length>40?xe.slice(0,40)+"...":xe},ze))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Me&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(jn,{id:"planning-modal-model",label:"Planning Model",value:ke,onChange:xe=>{const{provider:ze,modelId:be}=fM(xe);ae(ze),de(be)},models:Re,disabled:Me,favoriteProviders:We,onToggleFavorite:K,favoriteModels:Ee,onToggleModelFavorite:me}),Ce&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ce," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{se()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ce&&Q?"model-badge-custom":"model-badge-default"}`,children:De(ce,Q)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!u.trim(),children:[t.jsx(Bs,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(at,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:N?"AI is thinking...":"Generating next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>P(!j),type:"button",children:j?"Hide thinking":"Show thinking"}),j&&N&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:N})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void rt(),disabled:D,children:[D?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:D?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ie,disabled:D,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(at,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(bM,{question:m.session.currentQuestion,progress:Pe(),historyEntries:v,onSubmit:Ze,onBack:f.length>0?Se:void 0})}),m.type==="summary"&&y&&t.jsx(xM,{summary:y,historyEntries:v,onSummaryChange:E,tasks:r,onCreateTask:oe,onBreakIntoTasks:Z,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(yM,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:xe=>h({...m,subtasks:xe,dirty:!0}),onCreateTasks:pe,onBack:()=>{const ze={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:ze,summary:y})}}),M&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Zr,{size:16}),t.jsx("span",{children:Ye?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ye&&t.jsx("button",{type:"button",onClick:()=>{z()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function bM({question:e,progress:n,historyEntries:s,onSubmit:i,onBack:r}){const[o,l]=a.useState({}),[c,u]=a.useState(""),d=a.useCallback(()=>{e.type==="text"?i({[e.id]:c}):e.type==="confirm"?i({[e.id]:o[e.id]===!0}):i(o)},[e,o,c,i]);a.useEffect(()=>{l({}),u("")},[e.id]);const m=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(h=>t.jsx("div",{className:`planning-progress-step ${h<=n?"active":""}`},h))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&c.trim()&&(h.preventDefault(),d())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(h=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:h.id,checked:o[e.id]===h.id,onChange:()=>l({[e.id]:h.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(h=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:h.id,checked:g.includes(h.id),onChange:p=>{const f=p.target.checked?[...g,h.id]:g.filter(b=>b!==h.id);l({[e.id]:f})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:h.label}),h.description&&t.jsx("span",{className:"planning-option-desc",children:h.description})]})]},h.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(en,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Tt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(na,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:d,disabled:!m(),children:["Continue",t.jsx(Va,{size:16,className:"icon-ml-4"})]})]})]})}function xM({summary:e,historyEntries:n,onSummaryChange:s,tasks:i,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[u,d]=a.useState(!1),[m,h]=a.useState(e.suggestedDependencies),g=p=>{const f=m.includes(p)?m.filter(b=>b!==p):[...m,p];h(f),s({...e,suggestedDependencies:f})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(en,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>d(!u),children:u?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${u?"expanded":""}`,rows:u?10:4,value:e.description,onChange:p=>s({...e,description:p.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Size"}),t.jsxs("select",{className:"planning-size-select",value:e.suggestedSize,onChange:p=>s({...e,suggestedSize:p.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),i.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:i.map(p=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(p.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(p.id),onChange:()=>g(p.id)}),t.jsx("span",{className:"planning-dep-id",children:p.id}),t.jsx("span",{className:"planning-dep-title",children:p.title||p.description.slice(0,30)})]},p.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((p,f)=>t.jsx("li",{children:p},f))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(na,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xr,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(en,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function im(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),i.add(o),!1};return e.some(o=>r(o.id))}function vM(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function yM({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:i,onCreateTasks:r,onBack:o}){const[l,c]=a.useState(null),[u,d]=a.useState(null),[m,h]=a.useState(null),g=a.useRef([]),p=a.useMemo(()=>e.length===0||e.some(S=>!S.title.trim())?!0:im(e),[e]),f=a.useCallback((S,j)=>{i(e.map(P=>P.id===S?{...P,...j}:P))},[e,i]),b=a.useCallback(()=>{i([...e,vM(e.length+1)])},[e,i]),v=a.useCallback(S=>{i(e.filter(j=>j.id!==S).map(j=>({...j,dependsOn:j.dependsOn.filter(P=>P!==S)})))},[e,i]),x=a.useCallback((S,j)=>{if(j<0||j>=e.length)return;const P=[...e],[_]=P.splice(S,1);P.splice(j,0,_),i(P)},[e,i]),y=a.useCallback(S=>j=>{c(S),j.dataTransfer.setData("text/plain",S),j.dataTransfer.effectAllowed="move"},[]),E=a.useCallback(()=>{c(null),d(null),h(null)},[]),k=a.useCallback(S=>j=>{if(j.preventDefault(),S===l)return;const P=j.currentTarget.getBoundingClientRect(),_=P.top+P.height/2,I=j.clientY<_?"before":"after";d(S),h(I)},[l]),T=a.useCallback(S=>j=>{j.preventDefault();const P=j.dataTransfer.getData("text/plain");if(!P||P===S){E();return}const _=e.findIndex(R=>R.id===P),I=e.findIndex(R=>R.id===S);if(_===-1||I===-1){E();return}const D=[...e],[G]=D.splice(_,1);let $=I;m==="after"&&_<I&&$--,m==="after"&&$++,D.splice($,0,G),i(D),E()},[e,m,i,E]),N=a.useCallback(S=>{const j=S.currentTarget.getBoundingClientRect(),P=S.clientX,_=S.clientY;(P<j.left||P>j.right||_<j.top||_>j.bottom)&&(d(null),h(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xr,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((S,j)=>{const P=l===S.id,_=u===S.id,I=["task-detail-section","subtask-item",P?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:I,"data-testid":`subtask-item-${j}`,draggable:!s,onDragStart:y(S.id),onDragEnd:E,onDragOver:k(S.id),onDrop:T(S.id),onDragLeave:N,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(tc,{size:16}),t.jsx("strong",{children:S.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(j,j-1),disabled:s||j===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ki,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(j,j+1),disabled:s||j===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(qa,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(S.id),disabled:s,children:[t.jsx(Bt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:D=>{g.current[j]=D},value:S.title,onChange:D=>f(S.id,{title:D.target.value}),onKeyDown:D=>{D.key==="Enter"&&(D.preventDefault(),j<e.length-1&&g.current[j+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:S.description,onChange:D=>f(S.id,{description:D.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:S.suggestedSize,onChange:D=>f(S.id,{suggestedSize:D.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,j).filter(D=>D.id!==S.id).map(D=>{const G=S.dependsOn.includes(D.id);return t.jsxs("label",{className:`planning-dep-chip ${G?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:G,onChange:()=>{const $=G?S.dependsOn.filter(R=>R!==D.id):[...S.dependsOn,D.id];f(S.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:D.id}),t.jsx("span",{className:"planning-dep-title",children:D.title||"Untitled"})]},D.id)}),j===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),j>0&&e.slice(0,j).filter(D=>D.id!==S.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},S.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(Ht,{size:16,className:"icon-mr-6"})," Add subtask"]}),im(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:o,disabled:s,children:[t.jsx(na,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:r,disabled:s||p,children:s?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function kM(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function am(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,i=new Set,r=o=>{if(s.has(o))return!0;if(i.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),i.add(o),!1};return e.some(o=>r(o.id))}function jM({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[b,v]=a.useState(!0),[x,y]=a.useState(!1),[E,k]=a.useState(!1),[T,N]=a.useState(s),[S,j]=a.useState(null),[P,_]=a.useState(!1),[I,D]=a.useState(null),[G,$]=a.useState(null),[R,w]=a.useState(null),H=a.useRef(null),V=a.useRef([]),B=a.useRef(!1),M=a.useRef(null),z=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,X=a.useMemo(()=>_i(),[]),{isLockedByOther:C,takeControl:U,isLoading:fe}=oo(e?z:null),{activeTabMap:ie,broadcastUpdate:re,broadcastCompleted:F,broadcastLock:ce,broadcastUnlock:ae,broadcastHeartbeat:Q}=ra(),de=a.useMemo(()=>d.length===0||d.some(oe=>!oe.title.trim())?!0:am(d),[d]),Re=c.type==="generating"||c.type==="editing"||c.type==="error",ge=z?ie.get(z):null,Me=ge&&ge.tabId!==X,te=!!(Me&&!ge.stale),Ce=C&&(!Me||ge.stale),$e=a.useCallback(()=>{T&&fw(T,o),H.current?.close(),H.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),k(!1),j(null),_(!1),B.current=!1},[T,o]),We=a.useCallback(()=>{H.current?.close(),H.current=null,n()},[n]),Ge=a.useCallback(async()=>{if(!((P||c.type==="editing"||c.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(z)try{await ch(z,o,X)}catch{}$e(),n()}},[P,n,$e,z,X,c.type,o]),Ee=a.useCallback(oe=>{H.current?.close(),H.current=Zv(oe,o,{onThinking:Z=>{f(pe=>pe+Z),re({sessionId:oe,status:"generating",needsInput:!1,owningTabId:X,type:"subtask",title:T.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Z=>{y(!1),k(!1),To(o),m(Z),u({type:"editing",sessionId:oe}),_(!1),re({sessionId:oe,status:"awaiting_input",needsInput:!0,owningTabId:X,type:"subtask",title:T.trim()||"Subtask breakdown",projectId:o??null})},onError:Z=>{const pe=Z||"Session failed while contacting the AI.";y(!1),k(!1),j(null),u({type:"error",sessionId:oe,errorMessage:pe}),re({sessionId:oe,status:"error",needsInput:!1,owningTabId:X,type:"subtask",title:T.trim()||"Subtask breakdown",projectId:o??null}),F({sessionId:oe,status:"error"})},onComplete:()=>{F({sessionId:oe,status:"complete"})},onConnectionStateChange:Z=>{y(Z==="reconnecting")}})},[F,re,T,o,X]),Ae=a.useCallback(async()=>{if(T.trim()){j(null),g([]),f(""),y(!1);try{const{sessionId:oe}=await Yv(T.trim(),o);u({type:"generating",sessionId:oe}),Ee(oe)}catch(oe){j(ve(oe)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ee,T,o]);a.useEffect(()=>{if(!e){$e();return}if(e&&s&&!B.current)N(s),B.current=!0,Ae();else if(e&&!s&&!B.current){const oe=gw(o);oe&&N(oe)}},[e,s,Ae,$e]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const oe=await Xs(l);if(!oe)return;const Z=Ki(oe.conversationHistory);if(g(Z),oe.status==="generating"||oe.status==="awaiting_input")f(oe.thinkingOutput??""),u({type:"generating",sessionId:l}),Ee(l);else if(oe.status==="complete"&&oe.result){To(o);const pe=JSON.parse(oe.result);m(pe),u({type:"editing",sessionId:l})}else oe.status==="error"&&(j(null),u({type:"error",sessionId:l,errorMessage:oe.error??"Session encountered an error"}))}catch(oe){j(ve(oe)||"Failed to resume session")}})()},[Ee,e,l,c.type,o]),a.useEffect(()=>{if(!e){M.current&&(ae(M.current,X),M.current=null);return}if(z&&M.current!==z){M.current&&ae(M.current,X),ce(z,X),M.current=z;return}!z&&M.current&&(ae(M.current,X),M.current=null)},[ce,ae,e,z,X]),a.useEffect(()=>{if(!e||!z||M.current!==z)return;Q(X);const oe=setInterval(()=>{Q(X)},3e4);return()=>{clearInterval(oe)}},[Q,e,z,X]),a.useEffect(()=>()=>{H.current?.close(),M.current&&(ae(M.current,X),M.current=null)},[ae,X]),a.useEffect(()=>{if(!e)return;const oe=Z=>{Z.key==="Escape"&&(Z.preventDefault(),Ge())};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[e,Ge]);const Oe=a.useCallback((oe,Z)=>{m(pe=>pe.map(Se=>Se.id===oe?{...Se,...Z}:Se)),_(!0)},[]),ke=a.useCallback(()=>{m(oe=>[...oe,kM(oe.length+1)]),_(!0)},[]),De=a.useCallback(oe=>{m(Z=>Z.filter(pe=>pe.id!==oe).map(pe=>({...pe,dependsOn:pe.dependsOn.filter(Se=>Se!==oe)}))),_(!0)},[]),se=a.useCallback(oe=>Z=>{D(oe),Z.dataTransfer.setData("text/plain",oe),Z.dataTransfer.effectAllowed="move"},[]),K=a.useCallback(()=>{D(null),$(null),w(null)},[]),me=a.useCallback(oe=>Z=>{if(Z.preventDefault(),oe===I)return;const pe=Z.currentTarget.getBoundingClientRect(),Se=pe.top+pe.height/2,Pe=Z.clientY<Se?"before":"after";$(oe),w(Pe)},[I]),ee=a.useCallback(oe=>Z=>{Z.preventDefault();const pe=Z.dataTransfer.getData("text/plain");if(!pe||pe===oe){D(null),$(null),w(null);return}m(Se=>{const Pe=Se.findIndex(Ye=>Ye.id===pe),ye=Se.findIndex(Ye=>Ye.id===oe);if(Pe===-1||ye===-1)return Se;const Ke=[...Se],[Ne]=Ke.splice(Pe,1);let Fe=ye;return R==="after"&&Pe<ye&&Fe--,R==="after"&&Fe++,Ke.splice(Fe,0,Ne),Ke}),_(!0),D(null),$(null),w(null)},[R]),he=a.useCallback(oe=>{const Z=oe.currentTarget.getBoundingClientRect(),pe=oe.clientX,Se=oe.clientY;(pe<Z.left||pe>Z.right||Se<Z.top||Se>Z.bottom)&&($(null),w(null))},[]),le=a.useCallback((oe,Z)=>{Z<0||Z>=d.length||(m(pe=>{const Se=[...pe],[Pe]=Se.splice(oe,1);return Se.splice(Z,0,Pe),Se}),_(!0))},[d.length]),Ie=a.useCallback(oe=>{V.current[oe+1]?.focus()},[]),Ze=a.useCallback(async()=>{if(!(!z||de)){j(null),u({type:"creating",sessionId:z});try{const oe=await ey(z,d,r,o);i(oe.tasks),$e(),n()}catch(oe){j(ve(oe)||"Failed to create tasks"),u({type:"editing",sessionId:z})}}},[de,n,i,r,o,$e,z,d]),rt=a.useCallback(async()=>{if(c.type!=="error")return;const oe=c.sessionId;j(null),k(!0),f(""),u({type:"generating",sessionId:oe}),Ee(oe);try{await Qv(oe,o,X)}catch(Z){let pe=Z;if((ve(Z)||"").includes("not in an error state"))try{const Pe=await Xs(oe);if(!Pe)throw new Error("Failed to refresh subtask session.");if(g(Ki(Pe.conversationHistory)),Pe.status==="generating"||Pe.status==="awaiting_input")f(Pe.thinkingOutput??""),u({type:"generating",sessionId:Pe.id}),H.current?.isConnected()||Ee(Pe.id);else if(Pe.status==="complete"){if(!Pe.result)throw new Error("Subtask session is complete but has no result.");To(o);const ye=JSON.parse(Pe.result);m(ye),u({type:"editing",sessionId:Pe.id}),_(!1)}else Pe.status==="error"&&u({type:"error",sessionId:Pe.id,errorMessage:Pe.error??"Retry failed. Please try again."});y(!1);return}catch(Pe){pe=Pe}H.current?.close(),H.current=null,u({type:"error",sessionId:oe,errorMessage:ve(pe)||"Retry failed. Please try again."}),y(!1)}finally{k(!1)}},[Ee,o,X,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:oe=>oe.target===oe.currentTarget&&void Ge(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Xr,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Re&&t.jsx("button",{className:"modal-send-to-background",onClick:We,title:"Send to background","aria-label":"Send to background",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ge(),"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[S&&t.jsx("div",{className:"form-error planning-error",children:S}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),te&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:T})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(at,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:c.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void rt(),disabled:E,children:[E?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:E?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ge(),disabled:E,children:"Cancel"})]})]})]})}),(c.type==="editing"||c.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(en,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((oe,Z)=>{const pe=I===oe.id,Se=G===oe.id,Pe=["task-detail-section","subtask-item",pe?"subtask-item-dragging":"",Se?"subtask-item-drop-target":"",Se&&R==="before"?"subtask-item-drop-before":"",Se&&R==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Pe,"data-testid":`subtask-item-${Z}`,draggable:c.type!=="creating",onDragStart:se(oe.id),onDragEnd:K,onDragOver:me(oe.id),onDrop:ee(oe.id),onDragLeave:he,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(tc,{size:16}),t.jsx("strong",{children:oe.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(Z,Z-1),disabled:c.type==="creating"||Z===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ki,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>le(Z,Z+1),disabled:c.type==="creating"||Z===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(qa,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>De(oe.id),disabled:c.type==="creating",children:[t.jsx(Bt,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:ye=>{V.current[Z]=ye},value:oe.title,onChange:ye=>Oe(oe.id,{title:ye.target.value}),onKeyDown:ye=>{ye.key==="Enter"&&(ye.preventDefault(),Ie(Z))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:oe.description,onChange:ye=>Oe(oe.id,{description:ye.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:oe.suggestedSize,onChange:ye=>Oe(oe.id,{suggestedSize:ye.target.value}),disabled:c.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[d.slice(0,Z).filter(ye=>ye.id!==oe.id).map(ye=>{const Ke=oe.dependsOn.includes(ye.id);return t.jsxs("label",{className:`planning-dep-chip ${Ke?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Ke,onChange:()=>{const Ne=Ke?oe.dependsOn.filter(Fe=>Fe!==ye.id):[...oe.dependsOn,ye.id];Oe(oe.id,{dependsOn:Ne})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:ye.id}),t.jsx("span",{className:"planning-dep-title",children:ye.title||"Untitled"})]},ye.id)}),Z===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Z>0&&d.slice(0,Z).filter(ye=>ye.id!==oe.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},oe.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:ke,disabled:c.type==="creating",children:[t.jsx(Ht,{size:16,className:"icon-mr-6"})," Add subtask"]}),am(d)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void Ge(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void Ze(),disabled:c.type==="creating"||de,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),C&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Zr,{size:16}),t.jsx("span",{children:Ce?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ce&&t.jsx("button",{type:"button",onClick:()=>{U()},disabled:fe,className:"btn btn-primary session-lock-take-control",children:fe?"Taking control...":"Take Control"})]})})]})]})}):null}const wM=5,NM=1e3,SM=45e3;function Cr(){return{scrollback:null,connected:null,data:[]}}function CM(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(Cr()),E=a.useCallback($=>{p.current.add($);const R=y.current;return R.data.length>0&&(R.data.forEach(w=>$(w)),R.data=[]),()=>p.current.delete($)},[]),k=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),T=a.useCallback($=>{b.current.add($);const R=y.current;return R.connected&&($(R.connected),R.connected=null),()=>b.current.delete($)},[]),N=a.useCallback($=>{v.current.add($);const R=y.current;return R.scrollback&&($(R.scrollback),R.scrollback=null),()=>v.current.delete($)},[]),S=a.useCallback($=>(x.current.add($),()=>x.current.delete($)),[]),j=a.useCallback($=>{const R=u.current;R?.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"input",data:$}))},[]),P=a.useCallback(($,R)=>{const w=u.current;w?.readyState===WebSocket.OPEN&&w.send(JSON.stringify({type:"resize",cols:$,rows:R}))},[]),_=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(u.current.onopen=null,u.current.onmessage=null,u.current.onclose=null,u.current.onerror=null,u.current.close(),u.current=null),y.current=Cr()},[]),I=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),y.current=Cr()},[]),D=a.useCallback(()=>{if(!e){i("disconnected");return}if(u.current?.readyState===WebSocket.OPEN)return;u.current&&(g.current=!0,u.current.close()),g.current=!1,i("connecting");const $=r.current;let w=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(w+=`&projectId=${encodeURIComponent(n)}`);const H=new WebSocket(qs(w));u.current=H,H.onopen=()=>{if(r.current!==$){H.close();return}y.current=Cr(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&H.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"ping"}))},SM)},H.onmessage=V=>{if(r.current===$)try{const B=JSON.parse(V.data),M=y.current;switch(B.type){case"data":B.data&&(p.current.size===0&&M.data.push(B.data),p.current.forEach(z=>z(B.data)));break;case"scrollback":B.data&&(M.scrollback=B.data,v.current.forEach(z=>z(B.data)));break;case"connected":B.shell&&B.cwd&&(M.connected={shell:B.shell,cwd:B.cwd},b.current.forEach(z=>z({shell:B.shell,cwd:B.cwd})));break;case"exit":B.exitCode!==void 0&&f.current.forEach(z=>z(B.exitCode));break;case"ping":H.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},H.onclose=V=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(V.code===4e3||V.code===4004){i("disconnected"),V.code===4004&&x.current.forEach(z=>z());return}if(d.current++,d.current>wM){i("disconnected");return}const B=NM*Math.pow(2,d.current-1);i("reconnecting");const M=r.current;m.current=setTimeout(()=>{r.current===M&&(g.current||D())},Math.min(B,16e3))},H.onerror=()=>{}},[e,n]),G=a.useCallback(()=>{d.current=0,I(),D()},[I,D]);return a.useEffect(()=>(c&&(_(),d.current=0,i("disconnected")),e?D():i("disconnected"),I),[e,n,c,D,I,_]),{connectionStatus:s,sendInput:j,resize:P,onData:E,onExit:k,onConnect:T,onScrollback:N,reconnect:G,onSessionInvalid:S}}const Hp="kb-terminal-tabs",EM=15e3,MM=15e3;function rm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function om(e){if(typeof window>"u")return[];try{const n=En(Hp,e);if(n)return JSON.parse(n)}catch{}return[]}function dl(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function lm(e,n,s){let i;const r=new Promise((o,l)=>{i=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(i))}function _M(e){const[n,s]=a.useState(()=>om(e)),[i,r]=a.useState(!1),[o,l]=a.useState(!0),[c,u]=a.useState(null),[d,m]=a.useState(0),h=a.useRef(0);a.useEffect(()=>{h.current+=1,s(om(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{cs(Hp,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let T=!1;const N=h.current;return(async()=>{if(!T)try{const j=await lm(Kx(e),EM,"listTerminalSessions");if(T||N!==h.current)return;const P=new Set(j.map(_=>_.id));l(!0),s(_=>{if(T||N!==h.current)return _;const D=_.map(R=>({...R,_verified:P.has(R.sessionId)})).filter(R=>R._verified);if(D.length===0)return[];const G=D.map(({_verified:R,...w})=>w);return G.find(R=>R.isActive)?G:G.map((R,w)=>({...R,isActive:w===0}))}),r(!0)}catch(j){if(T||N!==h.current)return;const P=dl(j);P||console.warn("Failed to validate terminal sessions with server:",j),l(!P),r(!0)}})(),()=>{T=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const T=h.current,N=setTimeout(()=>{lm(lr(void 0,void 0,void 0,e),MM,"createTerminalSession").then(S=>{if(T!==h.current)return;const j={id:rm(),sessionId:S.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(P=>P.length>0?P:[...P.map(I=>({...I,isActive:!1})),j]),u(null)}).catch(S=>{if(T!==h.current)return;dl(S)||console.error(S);const j=S instanceof Error?S.message:typeof S=="string"?S:"Failed to create terminal session";u(j)})},0);return()=>clearTimeout(N)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const T=await lr(void 0,void 0,void 0,e),N={id:rm(),sessionId:T.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(S=>[...S.map(P=>({...P,isActive:!1})),N]),N},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(T=>{s(N=>{const S=N.find(I=>I.id===T);if(!S)return N;Zc(S.sessionId,e).catch(I=>{console.warn(`Failed to kill terminal session ${S.sessionId}:`,I)});const j=N.findIndex(I=>I.id===T),P=S.isActive,_=N.filter(I=>I.id!==T);if(_.length===0)return[];if(P){const I=Math.min(j,_.length-1);return _.map((D,G)=>({...D,isActive:G===I}))}return _})},[]),b=a.useCallback(T=>{s(N=>{let S=!1;const j=N.map(P=>P.id===T?(S=!0,{...P,isActive:!0}):{...P,isActive:!1});return S?j:N})},[]),v=a.useCallback((T,N)=>{s(S=>S.map(j=>j.id===T?{...j,title:N}:j))},[]),x=a.useCallback(async()=>{s(S=>{const j=S.find(P=>P.isActive);return j&&Zc(j.sessionId,e).catch(P=>{console.warn(`Failed to kill old session ${j.sessionId}:`,P)}),S});const T=n.find(S=>S.isActive);if(!T)return;const N=await lr(void 0,void 0,void 0,e);s(S=>S.map(j=>j.id===T.id?{...j,sessionId:N.sessionId}:j))},[n]),y=a.useCallback(async()=>{const T=n.find(N=>N.isActive);if(T)try{const N=await lr(void 0,void 0,void 0,e);s(S=>S.map(j=>j.id===T.id?{...j,sessionId:N.sessionId}:j)),u(null)}catch(N){dl(N)||console.error(N);const S=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";u(S)}},[n]),E=n.find(T=>T.isActive)??null,k=a.useCallback(()=>{u(null),h.current+=1,m(T=>T+1)},[]);return{tabs:n,activeTab:E,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:k,replaceActiveTabSession:y}}const AM=1e4,RM=[500,1500,3e3];function TM(e){const n=typeof e=="string"?e:e instanceof Error?e.message:String(e);return n.includes("MIME type")||n.includes("Failed to fetch dynamically imported module")}function IM(e){return new Promise(n=>setTimeout(n,e))}async function PM(e,n=RM){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!TM(r))throw r;s===void 0&&(s=r);const o=n[i];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${i+1}/${n.length+1}). Retrying in ${o}ms...`,l),await IM(o)}throw s??new Error("Dynamic import failed")}function cm(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function $M(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=DM()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let ul=null;function DM(){return ul===null&&(ul=window.innerHeight),ul}function LM({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(0),[f,b]=a.useState(0),[v,x]=a.useState(null),y=a.useRef(null),E=a.useRef(null),k=a.useRef(null),T=a.useRef(null),N=a.useRef(!1),S=a.useRef(!1),j=a.useRef(null),P=a.useRef(0),_=a.useRef(null),I=a.useRef(i);P.current=f;const D=a.useCallback(Ee=>{if(Ee&&S.current!==Ee)return;const Ae=T.current,Oe=k.current,ke=j.current;if(!(!Ae||!Oe)&&!(Ee&&S.current!==Ee))try{Ae.fit(),ke&&ke(Oe.cols,Oe.rows)}catch{}},[]);a.useEffect(()=>{e&&p(Ee=>Ee+1)},[e]),a.useEffect(()=>{if(!e||!cm())return;const Ee=window.visualViewport;if(!Ee)return;const Ae=()=>{const Oe=$M();b(Oe),x(Ee.height),Oe>0&&E.current?.scrollIntoView&&E.current.scrollIntoView({block:"end",behavior:"smooth"}),_.current!==null&&(cancelAnimationFrame(_.current),_.current=null);const ke=typeof S.current=="string"?S.current:void 0;_.current=requestAnimationFrame(()=>{_.current=null,D(ke)})};return Ae(),Ee.addEventListener("resize",Ae),Ee.addEventListener("scroll",Ae),()=>{Ee.removeEventListener("resize",Ae),Ee.removeEventListener("scroll",Ae),_.current!==null&&(cancelAnimationFrame(_.current),_.current=null),b(0),x(null)}},[D,e]);const{tabs:G,activeTab:$,isReady:R,bootstrapError:w,createTab:H,closeTab:V,setActiveTab:B,updateTabTitle:M,restartActiveTab:z,retryBootstrap:X,replaceActiveTabSession:C}=_M(i),{connectionStatus:U,sendInput:fe,resize:ie,onData:re,onConnect:F,onExit:ce,onScrollback:ae,reconnect:Q,onSessionInvalid:de}=CM($?.sessionId??null,i);j.current=ie,a.useEffect(()=>{if(!e||!R)return;const Ee=$?.sessionId;if(!Ee)return;const Ae=I.current!==i;if(Ae&&(I.current=i),S.current===Ee&&k.current&&!Ae)return;k.current&&(S.current!==Ee||Ae)&&(k.current.dispose(),k.current=null,T.current=null,S.current=!1,d(!1),h(null));let Oe=!0,ke;return(async()=>{const se=PM(()=>Promise.all([Zt(()=>import("./vendor-xterm-DzcZoU0P.js").then(he=>he.x),__vite__mapDeps([0,1,2])),Zt(()=>import("./addon-fit-C7jRorKK.js").then(he=>he.a),__vite__mapDeps([3,1])),Zt(()=>import("./addon-web-links-CkJwd4cQ.js").then(he=>he.a),__vite__mapDeps([4,1]))])),K=new Promise((he,le)=>{ke=setTimeout(()=>{le(new Error("xterm initialization timed out"))},AM)});let me,ee;try{const[{Terminal:he},{FitAddon:le},{WebLinksAddon:Ie}]=await Promise.race([se,K]);if(!Oe||!y.current||k.current)return;me=new he({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}),ee=new le,me.loadAddon(ee);const Ze=new Ie;if(me.loadAddon(Ze),!cm())try{const{WebglAddon:oe}=await Zt(async()=>{const{WebglAddon:pe}=await import("./addon-webgl-BjvOw43o.js").then(Se=>Se.a);return{WebglAddon:pe}},__vite__mapDeps([5,1])),Z=new oe;Z.onContextLoss(()=>{Z.dispose()}),me.loadAddon(Z)}catch{}me.open(y.current),ke&&clearTimeout(ke);const rt=y.current?.querySelector(".xterm-helper-textarea");if(rt&&rt.focus(),y.current)try{y.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ee.fit();const oe=y.current?.querySelector(".xterm-helper-textarea");oe&&oe.focus()},50),k.current=me,T.current=ee,S.current=Ee,P.current>0&&(_.current!==null&&(cancelAnimationFrame(_.current),_.current=null),_.current=requestAnimationFrame(()=>{_.current=null,D(Ee)})),d(!0),h(null)}catch(he){if(ke&&clearTimeout(ke),!Oe)return;const le=he instanceof Error?he.message:"xterm initialization failed";h(le)}})(),()=>{Oe=!1,ke&&clearTimeout(ke)}},[D,e,R,$?.sessionId,i]),a.useEffect(()=>{if(!e||!u||!$?.sessionId||!k.current)return;const Ee=$.sessionId,Oe=k.current.onData(De=>{S.current===Ee&&fe(De)}),ke=()=>{if(S.current===Ee&&T.current&&k.current)try{T.current.fit();const{cols:De,rows:se}=k.current;ie(De,se)}catch{}};return window.addEventListener("resize",ke),()=>{Oe.dispose(),window.removeEventListener("resize",ke)}},[e,u,$?.sessionId,fe,ie]),a.useEffect(()=>{e||(k.current&&(k.current.dispose(),k.current=null),T.current=null,S.current=!1,d(!1),h(null),N.current=!1,o(null),c(null))},[e]),a.useEffect(()=>{if(!u||!k.current||!$)return;const Ee=$.sessionId,Ae=K=>{S.current===Ee&&k.current?.write(K)},Oe=re(K=>{Ae(K)}),ke=ae(K=>{Ae(K)}),De=F(K=>{M($.id,K.shell.split("/").pop()||K.shell)}),se=ce(K=>{S.current===Ee&&(c(K),k.current?.write(`\r
613
- \x1B[33m[Process exited with code ${K}]\x1B[0m\r
614
- `))});return()=>{Oe(),ke(),De(),se()}},[u,$?.sessionId,$?.id,$,U,re,ae,F,ce,M]),a.useEffect(()=>{U==="connected"&&s&&N.current!==s&&$&&(N.current=s,setTimeout(()=>{fe(s+`
615
- `)},500))},[U,s,fe,$,g]),a.useEffect(()=>{if(!e)return;const Ee=Ae=>{if(!(!Ae.ctrlKey&&!Ae.metaKey)){if(Ae.code==="Equal"||Ae.code==="NumpadAdd"){if(Ae.preventDefault(),k.current){const Oe=k.current.options.fontSize||14;k.current.options.fontSize=Math.min(Oe+1,32),T.current?.fit()}return}if(Ae.code==="Minus"||Ae.code==="NumpadSubtract"){if(Ae.preventDefault(),k.current){const Oe=k.current.options.fontSize||14;k.current.options.fontSize=Math.max(Oe-1,8),T.current?.fit()}return}if(Ae.code==="Digit0"||Ae.code==="Numpad0"){Ae.preventDefault(),k.current&&(k.current.options.fontSize=14,T.current?.fit());return}}};return window.addEventListener("keydown",Ee),()=>window.removeEventListener("keydown",Ee)},[e]),a.useEffect(()=>{if(!e)return;const Ee=Ae=>{Ae.key==="Escape"&&n()};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[e,n]),a.useEffect(()=>{U==="connected"&&k.current&&setTimeout(()=>{if(!k.current||!y.current)return;const Ee=y.current.querySelector(".xterm-helper-textarea");Ee&&Ee.focus();try{y.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[U]);const Re=a.useCallback(()=>{if(!y.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;k.current?.focus();const Ae=y.current.querySelector(".xterm-helper-textarea");if(!Ae)return;Ae.autocapitalize="off",Ae.autocomplete="off",Ae.autocorrect="off",Ae.spellcheck=!1,Ae.setAttribute("inputmode","text");try{Ae.focus({preventScroll:!0})}catch{Ae.focus()}const Oe=Ae.value.length;Ae.setSelectionRange(Oe,Oe)},[]);a.useEffect(()=>de(()=>{k.current?.clear(),c(null),N.current=!1,k.current&&(k.current.dispose(),k.current=null),T.current=null,S.current=!1,d(!1),h(null),C().catch(Ae=>{console.error("Failed to replace invalid terminal session:",Ae)})}),[de,C]);const ge=a.useCallback(Ee=>{Ee.target===Ee.currentTarget&&n()},[n]),Me=a.useCallback(()=>{k.current?.clear()},[]),te=a.useCallback(async()=>{k.current?.clear(),c(null),N.current=!1;try{await z()}catch(Ee){o(ve(Ee)||"Failed to restart terminal session")}},[z]),Ce=a.useCallback(()=>{k.current&&(k.current.dispose(),k.current=null),T.current=null,S.current=!1,h(null),d(!1)},[]),$e=a.useCallback(()=>{window.location.reload()},[]);if(!e)return null;const We=()=>{switch(U){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Ge=!R||!$&&!w||!u&&!m;return t.jsx("div",{className:"modal-overlay open",onClick:ge,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:E,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[G.map(Ee=>t.jsxs("div",{className:`terminal-tab ${Ee.isActive?"terminal-tab--active":""}`,onClick:()=>B(Ee.id),title:Ee.title,role:"tab","aria-selected":Ee.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ee.title}),G.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Ae=>{Ae.stopPropagation(),V(Ee.id)},title:"Close tab",children:"×"})]},Ee.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:H,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Hs,{size:16}),We()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[U==="disconnected"&&$&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Q,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(mn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:te,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(mn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Me,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Bt,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(Tt,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Ge&&!w&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),w&&!$&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",w]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:X,"data-testid":"terminal-retry-btn",children:[t.jsx(mn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:$e,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(mn,{size:14}),"Refresh page"]})]})]})}),m&&$&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Ce,"data-testid":"terminal-reinit-btn",children:[t.jsx(mn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:$e,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(mn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:y,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Re,onTouchStart:Re},$?.sessionId)]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${U}`,children:[U==="connected"&&"Connected",U==="connecting"&&"Connecting...",U==="reconnecting"&&"Reconnecting...",U==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • Ctrl+L clear • Esc close"})]})]})})}const ja={name:"",command:""};function dm(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function zM(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function FM({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(ja),[b,v]=a.useState(!1),[x,y]=a.useState(null),[E,k]=a.useState(null),T=a.useCallback(async()=>{try{u(!0);const R=await Ya(i);l(R)}catch(R){s(ve(R)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&T()},[e,T]);const N=a.useCallback(()=>{m(!0),g(null),f(ja),k(null)},[]),S=a.useCallback((R,w)=>{g(R),m(!1),f({name:R,command:w}),k(null)},[]),j=a.useCallback(()=>{g(null),m(!1),f(ja),k(null)},[]),P=a.useCallback(R=>{f(w=>({...w,name:R})),R&&!dm(R)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),_=a.useCallback(async()=>{const R=p.name.trim(),w=p.command.trim();if(!R){s("Script name is required","error");return}if(!dm(R)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!w){s("Script command is required","error");return}v(!0);try{await Kv(R,w,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(ja),k(null),await T()}catch(H){const V=ve(H);V?.includes("already exists")?s("A script with this name already exists","error"):s(V||"Failed to save script","error")}finally{v(!1)}},[p,h,s,T,i]),I=a.useCallback(async R=>{try{await Jv(R,i),s("Script deleted","success"),y(null),h===R&&(g(null),f(ja)),await T()}catch(w){s(ve(w)||"Failed to delete script","error")}},[h,s,T,i]),D=a.useCallback((R,w)=>{r&&r(R,w)},[r]);if(!e)return null;const G=d||h!==null,$=Object.entries(o).map(([R,w])=>({name:R,command:w}));return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",onClick:R=>R.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Hs,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(at,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):G?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:R=>P(R.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:E?"var(--color-error)":void 0}}),E&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:E}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:R=>f(w=>({...w,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"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:j,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:b||!!E,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:N,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Ht,{size:14}),"Add Script"]})]}),$.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(Hs,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:$.map(R=>t.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:t.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:t.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:R.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:R.command,children:zM(R.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>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:[t.jsx(sn,{size:12}),"Run"]}),t.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:t.jsx(Ht,{size:14,style:{transform:"rotate(45deg)"}})}),x===R.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>I(R.name),title:"Confirm delete","aria-label":`Confirm delete ${R.name}`,"data-testid":`confirm-delete-script-${R.name}`,style:{color:"var(--color-error)"},children:t.jsx(Bt,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${R.name}`,children:t.jsx(Tt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(R.name),title:"Delete","aria-label":`Delete ${R.name}`,"data-testid":`delete-script-${R.name}`,children:t.jsx(Bt,{size:14})})]})]})},R.name))})]})})]})})}function OM(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(b=>b+1)},[]),f=a.useCallback(b=>{l(b),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){u(!0),m(null);try{const x=await mv(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(ve(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function UM(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(!1),[f,b]=a.useState(null),v=a.useCallback(E=>{o(E),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let E=!1;async function k(){h(!0),b(null);try{const T=await hv(e,n,i);E||(o(T.content),c(T.content),d(T.mtime))}catch(T){E||(b(ve(T)||"Failed to load file"),o(""),c(""),d(null))}finally{E||h(!1)}}return k(),()=>{E=!0}},[e,n,s,i]);const x=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const E=await pv(e,n,r,i);c(r),d(E.mtime)}catch(E){throw b(ve(E)||"Failed to save file"),E}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:x,mtime:u}}const BM=1e4;function HM(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function qM(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function VM(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const g=await uv(e);if(d)return;s(HM(g.project)),r(g.tasks.map(qM)),u(null)}catch(g){d||u(ve(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},BM);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function WM(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function GM(e){return e?new Date(e).toLocaleDateString():""}function um(e,n){return e==="."?n:`${e}/${n}`}const wa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},ml={type:null,entry:null,entryFullPath:""},KM=200,JM=500,mm=10;function YM({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,v=g?.offsetTop??0,x=8;let y=e-b,E=n-v;y+h.width>p-x&&(y=p-x-h.width),E+h.height>f-x&&(E=f-x-h.height),y<x&&(y=x),E<x&&(E=x),c({x:y+b,y:E+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Hi,disabled:!1},{id:"move",label:"Move",icon:ib,disabled:!1},{id:"rename",label:"Rename",icon:Un,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Jr,disabled:!1}]:[{id:"download",label:"Download",icon:tg,disabled:!1}],{id:"divider",label:"",icon:Hi,disabled:!0},{id:"delete",label:"Delete",icon:Bt,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:m=>m.stopPropagation(),children:d.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>i(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function QM({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const f=n.name.lastIndexOf(".");f>0?c.current.setSelectionRange(0,f):c.current.select()}},[e,n.name]);const h=f=>{f.key==="Enter"&&d.trim()&&i(d.trim()),f.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:f=>m(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function XM({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:c,onRefresh:u,projectId:d}){const[m,h]=a.useState(wa),[g,p]=a.useState(ml),[f,b]=a.useState(!1),[v,x]=a.useState(null),[y,E]=a.useState(!1),[k,T]=a.useState(null),N=a.useRef(null),S=a.useRef(null),j=a.useRef(null),P=a.useRef(!1),_=a.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]),I=a.useCallback(()=>{_(),j.current=null,E(!1),T(null)},[_]);a.useEffect(()=>()=>{_()},[_]);const D=a.useCallback((z,X,C,U)=>{h({visible:!0,x:z,y:X,entry:C,entryFullPath:U})},[]),G=a.useCallback((z,X,C)=>{if(z.touches.length!==1)return;const U=z.touches[0];U&&(I(),j.current={x:U.clientX,y:U.clientY},S.current=window.setTimeout(()=>{E(!0),T(C)},KM),N.current=window.setTimeout(()=>{const fe=j.current;fe&&(P.current=!0,E(!1),T(null),_(),D(fe.x,fe.y,X,C))},JM))},[I,_,D]),$=a.useCallback(z=>{const X=j.current,C=z.touches[0];!X||!C||(Math.abs(C.clientX-X.x)>mm||Math.abs(C.clientY-X.y)>mm)&&I()},[I]),R=a.useCallback(()=>{I()},[I]);a.useEffect(()=>{if(!m.visible)return;const z=document.querySelector(".file-browser-list"),X=()=>{P.current=!1,I(),h(wa)};return z?.addEventListener("scroll",X),()=>z?.removeEventListener("scroll",X)},[I,m.visible]),a.useEffect(()=>{if(!m.visible)return;const z=X=>{X.key==="Escape"&&(P.current=!1,h(wa))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m.visible]);const w=a.useCallback((z,X)=>{z.preventDefault(),z.stopPropagation(),I(),P.current=!1,D(z.clientX,z.clientY,X,um(n,X.name))},[I,n,D]),H=a.useCallback(z=>{if(!m.entry)return;P.current=!1;const X=m.entry,C=m.entryFullPath;if(h(wa),z==="download"){if(!c)return;const U=ah(c,C,d);window.open(qs(U),"_blank");return}if(z==="download-zip"){if(!c)return;const U=yv(c,C,d);window.open(qs(U),"_blank");return}p({type:z,entry:X,entryFullPath:C}),x(null)},[m,c,d]),V=a.useCallback(async z=>{if(!(!g.type||!g.entry||!c)){b(!0),x(null);try{switch(g.type){case"copy":await gv(c,g.entryFullPath,z,d);break;case"move":await bv(c,g.entryFullPath,z,d);break;case"rename":await vv(c,g.entryFullPath,z,d);break;case"delete":await xv(c,g.entryFullPath,d);break}p(ml),u?.()}catch(X){x(ve(X)||"Operation failed")}finally{b(!1)}}},[g,c,u,d]),B=a.useCallback(()=>{p(ml),x(null)},[]),M=a.useCallback((z,X)=>{if(P.current){P.current=!1;return}m.visible||(z.type==="directory"?i(X):s(X))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(at,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{const z=n.split("/").filter(Boolean);z.pop(),i(z.length===0?".":z.join("/"))},children:[t.jsx(an,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":n})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(z=>{const X=um(n,z.name),C=y&&k===X;return t.jsxs("div",{className:`file-node file-node--${z.type} ${C?"file-node--long-pressing":""}`,onClick:()=>M(z,X),onContextMenu:U=>w(U,z),onTouchStart:U=>G(U,z,X),onTouchMove:$,onTouchEnd:R,onTouchCancel:R,children:[t.jsx("div",{className:"file-node-icon",children:z.type==="directory"?t.jsx(kn,{size:16}):t.jsx(Km,{size:16})}),t.jsx("div",{className:"file-node-name",children:z.name}),z.type==="file"&&z.size!==void 0&&t.jsx("div",{className:"file-node-size",children:WM(z.size)}),z.mtime&&t.jsx("div",{className:"file-node-time",children:GM(z.mtime)})]},z.name)})}),m.visible&&m.entry&&t.jsx(YM,{x:m.x,y:m.y,entry:m.entry,onAction:H,onClose:()=>{P.current=!1,h(wa)}}),g.type&&g.entry&&t.jsx(QM,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:V,onCancel:B,loading:f,error:v})]})}function ZM(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function e_({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=ZM(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),g=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Gm,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(ec,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Pr,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Pr,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ei,{remarkPlugins:[ti],children:e})}):t.jsx("textarea",{className:`file-editor-textarea ${l?"file-editor-textarea--wrap":""}`,value:e,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function t_(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function n_({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const[r,o]=a.useState(!1),l=a.useMemo(()=>e==="project"?n||"Project Root":s.find(u=>u.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(qc,{size:14}):t.jsx(Nl,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(zt,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{i("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(qc,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{i(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Nl,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:t_(c.title)})]},c.id))]})]})]})}const s_=768,qp=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),i_=new Set([...qp,".exe",".dll",".so",".dylib",".zip",".tar",".gz",".bz2",".xz",".7z",".rar",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".mp3",".mp4",".avi",".mov",".webm",".mkv",".flv",".woff",".woff2",".ttf",".otf",".eot",".wasm",".bin"]);function hm(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return i_.has(n)}function a_(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return qp.has(n)}function r_({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=VM(i),[l,c]=a.useState(e),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState("list"),{entries:f,currentPath:b,setPath:v,loading:x,error:y,refresh:E}=OM(l,!0,i),{content:k,setContent:T,originalContent:N,loading:S,saving:j,error:P,save:_,hasChanges:I,mtime:D}=UM(l,u,!0,i);a.useEffect(()=>{c(e)},[e]),a.useEffect(()=>{const z=()=>{h(window.innerWidth<=s_)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{u||p("list")},[u]),a.useEffect(()=>{const z=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),I&&!j&&_())};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[n,I,j,_]);const G=a.useCallback(z=>{d(z),m&&p("editor")},[m]),$=a.useCallback(()=>{p("list")},[]),R=a.useCallback(()=>{T(N)},[N,T]),w=a.useCallback(z=>{c(z),d(null),p("list"),s?.(z)},[s]),V=`Files — ${a.useMemo(()=>l==="project"?"Project":o.find(z=>z.id===l)?.id??l,[l,o])}`,B=a.useMemo(()=>!u||!a_(u)?null:ah(l,u,i),[u,l,i]),M=z=>{const X=new Blob([z]).size;return X<1024?`${X} B`:`${(X/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",onClick:n,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",onClick:z=>z.stopPropagation(),children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(kn,{size:18}),t.jsx("span",{children:V}),u&&t.jsx("span",{className:"file-browser-header-path",children:u})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(n_,{currentWorkspace:l,projectName:r,workspaces:o,onSelect:w}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${m?"mobile":""} ${g==="list"?"active":""}`,children:t.jsx(XM,{entries:f,currentPath:b,onSelectFile:G,onNavigate:v,loading:x,error:y,onRetry:E,workspace:l,onRefresh:E,projectId:i})}),t.jsx("div",{className:`file-browser-content ${m?"mobile":""} ${g==="editor"?"active":""}`,children:u?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[m&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:$,"aria-label":"Back to file list",children:[t.jsx(na,{size:16}),t.jsx("span",{children:"Back"})]}),u,hm(u)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(kg,{size:12}),"Binary file — read only"]}),D&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(D).toLocaleString()]}),S&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!B&&I&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:R,disabled:j,children:[t.jsx(gb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void _(),disabled:j,children:[t.jsx(eh,{size:14}),j?"Saving...":"Save"]})]})})]}),P&&!B&&t.jsx("div",{className:"file-browser-error-banner",children:P}),B?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:B,alt:u??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(e_,{content:k,onChange:T,filePath:u,readOnly:hm(u)})}),!B&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:M(k)}),I&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(kn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function o_(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=a.useRef(null),l=a.useRef(null),c=a.useCallback(async(d=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,d&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await Mx();r({providers:m,loading:!1,error:null,lastUpdated:new Date})}catch(m){if(m instanceof Error&&m.name==="AbortError")return;r(h=>({...h,loading:!1,error:ve(m)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{c()},[c]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const u=a.useCallback(()=>c(!0),[c]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:u}}function l_(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function c_(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}function d_({window:e,viewMode:n,providerName:s}){const i=c_(e.percentUsed),r=n==="remaining",o=Math.round(r?e.percentLeft:e.percentUsed),l=r?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,c=r?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const b=new Date(e.resetAt).getTime()-Date.now();if(b>0){const v=Math.floor(b/36e5),x=Math.floor(v/24),y=v%24;x>0&&y>0?u=`resets in ${x}d ${y}h`:x>0?u=`resets in ${x}d`:v>0?u=`resets in ${v}h`:u=`resets in ${Math.floor(b/6e4)}m`}}const d=e.pace,m=d!==void 0;let h=0;m&&(h=r?100-d.percentElapsed:d.percentElapsed);const g=d?.status==="ahead",p=d?.status==="behind",f=d?.status==="on-track";return t.jsxs("div",{className:"usage-window",children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsx("span",{className:"usage-window-percentage",children:l})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${i}`,style:{width:`${o}%`},role:"progressbar","aria-valuenow":o,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${l}`})}),m&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${h}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:c}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:l_(e.resetAt)})]})]}),m&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[g&&t.jsxs(t.Fragment,{children:[t.jsx(nc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:d.message})]}),p&&t.jsxs(t.Fragment,{children:[t.jsx(Rb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:d.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(en,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:d.message})]})]})]})}function u_(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":e}function m_({provider:e,viewMode:n}){const s=()=>{switch(e.status){case"ok":return t.jsx("span",{className:"usage-status-badge usage-status-badge--connected",children:"Connected"});case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:"usage-provider","data-provider":e.name,"data-status":e.status,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(ts,{provider:u_(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name})]}),s()]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((i,r)=>t.jsx(d_,{window:i,viewMode:n,providerName:e.name},`${e.name}-${i.label}-${r}`))}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function h_(){return t.jsx("div",{className:"usage-skeleton",children:[1,2,3].map(e=>t.jsxs("div",{className:"usage-skeleton-provider",children:[t.jsxs("div",{className:"usage-skeleton-header",children:[t.jsx("div",{className:"usage-skeleton-icon"}),t.jsx("div",{className:"usage-skeleton-name"}),t.jsx("div",{className:"usage-skeleton-badge"})]}),t.jsx("div",{className:"usage-skeleton-bar"}),t.jsx("div",{className:"usage-skeleton-text"})]},e))})}function p_({isOpen:e,onClose:n,projectId:s}){const{providers:i,loading:r,error:o,lastUpdated:l,refresh:c}=o_({autoRefresh:e}),[u,d]=a.useState(!1),[m,h]=a.useState("used"),g=a.useRef(null),p=a.useRef(e),f=a.useRef(!1);a.useEffect(()=>{e||(f.current=!1)},[e]),a.useEffect(()=>{i.length>0&&(f.current=!0)},[i.length]),a.useEffect(()=>{!p.current&&e&&(!l||Date.now()-l.getTime()>5e3)&&c(),p.current=e},[e,l,c]),a.useEffect(()=>{const y=En("kb-usage-view-mode",s);if(y==="used"||y==="remaining"){h(y);return}h("used")},[s]);const b=a.useCallback(y=>{h(y),cs("kb-usage-view-mode",y,s)},[s]),v=a.useCallback(async()=>{d(!0),await c(),d(!1)},[c]);a.useEffect(()=>{if(!e)return;const y=E=>{E.key==="Escape"&&n()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,n]);const x=a.useCallback(y=>{y.target===y.currentTarget&&n()},[n]);return e?t.jsx("div",{className:"modal-overlay open",onClick:x,"data-testid":"usage-modal-overlay",children:t.jsxs("div",{className:"modal usage-modal","data-testid":"usage-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ss,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${m==="used"?"active":""}`,onClick:()=>b("used"),"aria-pressed":m==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${m==="remaining"?"active":""}`,onClick:()=>b("remaining"),"aria-pressed":m==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(Tt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:g,children:(r||!f.current&&!o)&&i.length===0?t.jsx(h_,{}):o&&i.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:o}),t.jsx("button",{className:"btn btn-sm",onClick:v,children:"Retry"})]}):i.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:i.map(y=>t.jsx(m_,{provider:y,viewMode:m},y.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:l&&t.jsxs("span",{children:["Last updated: ",l.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:v,disabled:r||u,"data-testid":"usage-refresh-btn",children:[t.jsx(mn,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function Vp(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function Wr(e){const n=Date.now(),s=new Date(e).getTime(),i=n-s;if(i<0){const r=Math.abs(i);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const f_={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Wp={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},g_={cron:qm,webhook:th,api:Vm,manual:bn},b_={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},x_={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function v_({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(en,{size:12}):t.jsx(Wa,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Vp(n)})]})}function y_({result:e,index:n}){const[s,i]=a.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${Wr(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(en,{size:12}):t.jsx(Wa,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Wr(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Wp[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Vp(r)}),s?t.jsx(Zs,{size:12}):t.jsx(zt,{size:12})]}),s&&t.jsxs("div",{className:"schedule-history-detail",children:[e.output&&t.jsx("pre",{className:"schedule-history-output",children:e.output}),e.error&&t.jsx("div",{className:"schedule-history-error",children:e.error})]})]})}function k_({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o}){const[l,c]=a.useState(!1),u=a.useCallback(()=>{window.confirm(`Delete routine "${e.name}"? This cannot be undone.`)&&s(e)},[e,s]),d=f_[e.trigger.type],m=g_[e.trigger.type],h=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:d,color:d},children:[t.jsx(m,{size:10}),Wp[e.trigger.type]]}),e.scope&&t.jsxs("span",{className:`routine-scope-badge${e.scope==="global"?" global":" project"}`,title:`${e.scope==="global"?"Global":"Project"}-scoped routine`,children:[e.scope==="global"?t.jsx(Qr,{size:10}):t.jsx(kn,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(Os,{size:14}):t.jsx(sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Un,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:u,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Bt,{size:14})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Si,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&h&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(wi,{size:12}),t.jsx("code",{className:"routine-cron",children:h})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:b_[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:x_[e.catchUpPolicy]})}),e.nextRunAt&&e.enabled&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Next:"}),t.jsx("span",{title:e.nextRunAt,children:Wr(e.nextRunAt)})]}),e.lastRunAt&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Last:"}),t.jsx("span",{title:e.lastRunAt,children:Wr(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(v_,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>c(g=>!g),"aria-expanded":l,children:[l?t.jsx(Zs,{size:12}):t.jsx(zt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),l&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,p)=>t.jsx(y_,{result:g,index:p},`${g.startedAt}-${p}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function j_({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Hs,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(Wg,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(Pn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function hl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function w_(e){return e==="command"?{id:hl(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:hl(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:hl(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function N_({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,y]=a.useState(e.taskDescription??""),[E,k]=a.useState(e.taskColumn??"triage"),[T,N]=a.useState(e.timeoutMs),[S,j]=a.useState(e.continueOnFailure??!1),[P,_]=a.useState({}),[I,D]=a.useState([]),[G,$]=a.useState(!1),[R,w]=a.useState(null);a.useEffect(()=>{let z=!1;return $(!0),w(null),ss().then(X=>{z||D(X.models)}).catch(X=>{z||w(X instanceof Error?X.message:"Failed to load models")}).finally(()=>{z||$(!1)}),()=>{z=!0}},[]);const H=a.useCallback(()=>{const z={};return i.trim()||(z.name="Step name is required"),o==="command"&&!c.trim()&&(z.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(z.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(z.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(z.modelProvider="Both model provider and model ID must be set together"),T!==void 0&&T<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(z),Object.keys(z).length===0},[i,o,c,d,x,h,p,T]),V=h&&p?`${h}/${p}`:"",B=a.useCallback(z=>{if(!z)g(""),f("");else{const X=z.indexOf("/");X!==-1&&(g(z.slice(0,X)),f(z.slice(X+1)))}},[]),M=a.useCallback(()=>{if(!H())return;const z={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?E:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:T||void 0,continueOnFailure:S};o!=="ai-prompt"&&delete z.prompt,o!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[H,n,e,i,o,c,d,b,x,E,h,p,T,S]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:z=>r(z.target.value),"aria-invalid":!!P.name}),P.name&&t.jsx("small",{className:"field-error",children:P.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:z=>l(z.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:z=>u(z.target.value),rows:2,"aria-invalid":!!P.command}),P.command&&t.jsx("small",{className:"field-error",children:P.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:z=>m(z.target.value),rows:3,"aria-invalid":!!P.prompt}),P.prompt&&t.jsx("small",{className:"field-error",children:P.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(jn,{id:`step-model-${e.id}`,label:"Model",models:I,value:V,onChange:B,placeholder:"Use default",disabled:G}),R&&t.jsx("small",{className:"field-error",children:R}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:z=>v(z.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:z=>y(z.target.value),rows:4,"aria-invalid":!!P.taskDescription}),P.taskDescription&&t.jsx("small",{className:"field-error",children:P.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:E,onChange:z=>k(z.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(jn,{id:`step-task-model-${e.id}`,label:"Model",models:I,value:V,onChange:B,placeholder:"Use default",disabled:G}),R&&t.jsx("small",{className:"field-error",children:R}),P.modelProvider&&t.jsx("small",{className:"field-error",children:P.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:T??"",onChange:z=>N(z.target.value?Number(z.target.value):void 0),"aria-invalid":!!P.timeoutMs}),P.timeoutMs&&t.jsx("small",{className:"field-error",children:P.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:S,onChange:z=>j(z.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:M,children:"Save Step"})]})]})}function S_({steps:e,onChange:n,onEditingChange:s}){const[i,r]=a.useState(null);a.useEffect(()=>{s?.(i!==null)},[i,s]);const o=a.useCallback(d=>{const m=w_(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(f=>f.id===d);if(h<0)return;const g=m==="up"?h-1:h+1;if(g<0||g>=e.length)return;const p=[...e];[p[h],p[g]]=[p[g],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(N_,{step:d,onSave:u,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(tc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(j_,{type:d.type}),t.jsx("span",{className:"step-card-name",children:d.name}),d.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${d.name} up`,children:t.jsx(Zs,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${d.name} down`,children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(Un,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Bt,{size:14})})]})]})},d.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Ht,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Ht,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Ht,{size:14}),"Add Create Task Step"]})]})]})}const Gp={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},C_={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function E_(e){const n=e.trim();for(const[s,i]of Object.entries(Gp))if(i===n)return s;return"custom"}function M_(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function __(e,n,s,i,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:i||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function A_(e){const n=e.trigger;switch(n.type){case"cron":return{triggerType:"cron",cronExpression:n.cronExpression,webhookPath:"",webhookSecret:"",endpoint:""};case"webhook":return{triggerType:"webhook",cronExpression:"",webhookPath:n.webhookPath,webhookSecret:n.secret||"",endpoint:""};case"api":return{triggerType:"api",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:n.endpoint};case"manual":return{triggerType:"manual",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:""}}}const R_=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],T_=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function pm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function fm({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?A_(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[g,p]=a.useState(c.triggerType),[f,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":E_(c.cronExpression)),[y,E]=a.useState(c.webhookPath),[k,T]=a.useState(c.webhookSecret),[N,S]=a.useState(c.endpoint),[j,P]=a.useState(e?.executionPolicy??"queue"),[_,I]=a.useState(e?.catchUpPolicy??"run_one"),[D,G]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,R=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[w,H]=a.useState(e?.steps&&e.steps.length>0&&!$&&!R?"advanced":"simple"),[V,B]=a.useState(()=>$?"ai-prompt":R?"create-task":"command"),[M,z]=a.useState(e?.command??""),[X,C]=a.useState(e?.steps??[]),[U,fe]=a.useState(!1),[ie,re]=a.useState(e?.timeoutMs??3e5),[F,ce]=a.useState($?e.steps?.[0]?.prompt??"":""),[ae,Q]=a.useState(R?e.steps?.[0]?.taskTitle??"":""),[de,Re]=a.useState(R?e.steps?.[0]?.taskDescription??"":""),[ge,Me]=a.useState(R?e.steps?.[0]?.taskColumn??"triage":"triage"),[te,Ce]=a.useState($||R?e.steps?.[0]?.modelProvider??"":""),[$e,We]=a.useState($||R?e.steps?.[0]?.modelId??"":""),[Ge,Ee]=a.useState([]),[Ae,Oe]=a.useState(!1),[ke,De]=a.useState(null),[se,K]=a.useState(i??"global"),[me,ee]=a.useState({}),[he,le]=a.useState(!1),Ie=a.useRef(!0);a.useEffect(()=>()=>{Ie.current=!1},[]),a.useEffect(()=>{i&&K(i)},[i]),a.useEffect(()=>{let be=!1;return Oe(!0),De(null),ss().then(Qe=>{be||Ee(Qe.models)}).catch(Qe=>{be||De(Qe instanceof Error?Qe.message:"Failed to load models")}).finally(()=>{be||Oe(!1)}),()=>{be=!0}},[]);const Ze=te&&$e?`${te}/${$e}`:"",rt=a.useCallback(be=>{if(!be){Ce(""),We("");return}const Qe=be.indexOf("/");Qe!==-1&&(Ce(be.slice(0,Qe)),We(be.slice(Qe+1)))},[]),oe=a.useCallback(()=>{const be={};if(u.trim()||(be.name="Name is required"),se==="project"&&!r&&(be.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?M_(f)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(be.webhookPath="Webhook path is required"),g==="api"&&!N.trim()&&(be.endpoint="API endpoint is required"),w==="simple")V==="command"&&!M.trim()&&(be.command="Command is required"),V==="ai-prompt"&&!F.trim()&&(be.prompt="Prompt is required"),V==="create-task"&&!de.trim()&&(be.taskDescription="Task description is required"),(te.trim()&&!$e.trim()||!te.trim()&&$e.trim())&&(be.model="Both model provider and model ID must be set, or both must be empty");else{X.length===0&&(be.steps="At least one step is required"),U&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const Qe=[];X.forEach((it,mt)=>{it.name?.trim()||Qe.push(`Step ${mt+1}: Name is required`),it.type==="command"&&!it.command?.trim()&&Qe.push(`Step ${mt+1}: Command is required`),it.type==="ai-prompt"&&!it.prompt?.trim()&&Qe.push(`Step ${mt+1}: Prompt is required`),it.type==="create-task"&&!it.taskDescription?.trim()&&Qe.push(`Step ${mt+1}: Task description is required`)}),Qe.length>0&&(be.steps=Qe.join("; "))}return ie<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),ee(be),Object.keys(be).length===0},[u,g,f,v,y,N,se,r,w,V,M,F,de,te,$e,X,U,ie]),Z=a.useCallback(async be=>{if(be.preventDefault(),!!oe()){le(!0);try{let Qe=e?.scope??se??(r?"project":"global");Qe==="project"&&!r&&(Qe="global");const it=__(g,f,y,k,N);let mt,At;w==="simple"?V==="command"?mt=M.trim()||void 0:V==="ai-prompt"?At=[{id:pm(),type:"ai-prompt",name:u.trim(),prompt:F.trim(),modelProvider:te.trim()||void 0,modelId:$e.trim()||void 0}]:At=[{id:pm(),type:"create-task",name:u.trim(),taskTitle:ae.trim()||void 0,taskDescription:de.trim(),taskColumn:ge,modelProvider:te.trim()||void 0,modelId:$e.trim()||void 0}]:At=X;const It={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:it,command:mt,steps:At,timeoutMs:ie,executionPolicy:j,catchUpPolicy:_,enabled:D,scope:Qe};await n(It)}finally{Ie.current&&le(!1)}}},[oe,n,u,m,g,f,y,k,N,w,V,M,F,te,$e,ae,de,ge,X,ie,j,_,D,se,r,e?.scope,e?.agentId]),pe="routine-name-error",Se="routine-cron-error",Pe="routine-webhook-error",ye="routine-endpoint-error",Ke="routine-command-error",Ne="routine-prompt-error",Fe="routine-task-description-error",Ye="routine-model-error",xe="routine-timeout-error",ze=a.useCallback(be=>{x(be),be!=="custom"&&b(Gp[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:Z,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:be=>d(be.target.value),"aria-invalid":!!me.name,"aria-describedby":me.name?pe:void 0}),me.name&&t.jsx("small",{id:pe,className:"field-error",children:me.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:be=>h(be.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="global"?" active":""}`,onClick:()=>{K("global"),o?.("global")},role:"radio","aria-checked":se==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Qr,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="project"?" active":""}`,onClick:()=>{K("project"),o?.("project")},role:"radio","aria-checked":se==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(kn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":se==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),me.scope&&t.jsx("small",{className:"field-error",children:me.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[t.jsx(qm,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[t.jsx(th,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[t.jsx(Vm,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(bn,{size:14}),"Manual"]})]})]}),g==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:be=>ze(be.target.value),children:Object.entries(C_).map(([be,Qe])=>t.jsx("option",{value:be,children:Qe},be))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:be=>b(be.target.value),disabled:v!=="custom","aria-invalid":!!me.cronExpression,"aria-describedby":me.cronExpression?Se:void 0}),me.cronExpression?t.jsx("small",{id:Se,className:"field-error",children:me.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:be=>E(be.target.value),"aria-invalid":!!me.webhookPath,"aria-describedby":me.webhookPath?Pe:void 0}),me.webhookPath?t.jsx("small",{id:Pe,className:"field-error",children:me.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:k,onChange:be=>T(be.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:N,onChange:be=>S(be.target.value),"aria-invalid":!!me.endpoint,"aria-describedby":me.endpoint?ye:void 0}),me.endpoint?t.jsx("small",{id:ye,className:"field-error",children:me.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${w==="simple"?" active":""}`,onClick:()=>H("simple"),role:"radio","aria-checked":w==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${w==="advanced"?" active":""}`,onClick:()=>H("advanced"),role:"radio","aria-checked":w==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:w==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),w==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${V==="command"?" active":""}`,onClick:()=>B("command"),role:"radio","aria-checked":V==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${V==="ai-prompt"?" active":""}`,onClick:()=>B("ai-prompt"),role:"radio","aria-checked":V==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${V==="create-task"?" active":""}`,onClick:()=>B("create-task"),role:"radio","aria-checked":V==="create-task",children:"Create Task"})]})]}),V==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:M,onChange:be=>z(be.target.value),"aria-invalid":!!me.command,"aria-describedby":me.command?Ke:void 0}),me.command?t.jsx("small",{id:Ke,className:"field-error",children:me.command}):t.jsx("small",{children:"Shell command to execute."})]}):V==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:F,onChange:be=>ce(be.target.value),rows:3,"aria-invalid":!!me.prompt,"aria-describedby":me.prompt?Ne:void 0}),me.prompt?t.jsx("small",{id:Ne,className:"field-error",children:me.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx(jn,{id:"routine-model",label:"Model",models:Ge,value:Ze,onChange:rt,placeholder:"Use default",disabled:Ae}),ke&&t.jsx("small",{className:"field-error",children:ke}),me.model&&t.jsx("small",{id:Ye,className:"field-error",children:me.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:ae,onChange:be=>Q(be.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:de,onChange:be=>Re(be.target.value),rows:4,"aria-invalid":!!me.taskDescription,"aria-describedby":me.taskDescription?Fe:void 0}),me.taskDescription?t.jsx("small",{id:Fe,className:"field-error",children:me.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:ge,onChange:be=>Me(be.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx(jn,{id:"routine-task-model",label:"Executor Model",models:Ge,value:Ze,onChange:rt,placeholder:"Use default",disabled:Ae}),ke&&t.jsx("small",{className:"field-error",children:ke}),me.model&&t.jsx("small",{id:Ye,className:"field-error",children:me.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(S_,{steps:X,onChange:C,onEditingChange:fe}),me.steps&&t.jsx("small",{className:"field-error",children:me.steps}),me.stepsEditing&&t.jsx("small",{className:"field-error",children:me.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:ie,onChange:be=>re(Number(be.target.value)),"aria-invalid":!!me.timeoutMs,"aria-describedby":me.timeoutMs?xe:void 0}),me.timeoutMs?t.jsx("small",{id:xe,className:"field-error",children:me.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:j,onChange:be=>P(be.target.value),children:R_.map(be=>t.jsx("option",{value:be.value,children:be.label},be.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:be=>I(be.target.value),children:T_.map(be=>t.jsx("option",{value:be.value,children:be.label},be.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:D,onChange:be=>G(be.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:he,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:he,children:he?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const I_=3e4;function P_({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,g]=a.useState(null),p=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),f=a.useCallback(async()=>{try{const I=await zv(p);l(I)}catch(I){n(ve(I)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const I=setInterval(()=>{f()},I_);return()=>clearInterval(I)},[f]),a.useEffect(()=>{const I=D=>{D.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,c]);const b=a.useCallback(I=>{I.target===I.currentTarget&&e()},[e]),v=a.useCallback(async I=>{try{await Fv(I,p),n("Routine created","success"),u("list"),await f()}catch(D){n(ve(D)||"Failed to create routine","error")}},[n,f,p]),x=a.useCallback(I=>{m(I),u("edit")},[]),y=a.useCallback(async I=>{if(d)try{await ad(d.id,I,p),n("Routine updated","success"),u("list"),m(void 0),await f()}catch(D){n(ve(D)||"Failed to update routine","error")}},[d,n,f,p]),E=a.useCallback(async I=>{try{await Ov(I.id,p),n(`Deleted "${I.name}"`,"success"),await f()}catch(D){n(ve(D)||"Failed to delete routine","error")}},[n,f,p]),k=a.useCallback(async I=>{g(I.id);try{const{result:D}=await Uv(I.id,p);D.success?n(`"${I.name}" completed successfully`,"success"):n(`"${I.name}" failed: ${D.error||"Unknown error"}`,"error"),await f()}catch(D){n(ve(D)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),T=a.useCallback(async I=>{try{await ad(I.id,{enabled:!I.enabled},p),n(`"${I.name}" ${I.enabled?"disabled":"enabled"}`,"success"),await f()}catch(D){n(ve(D)||"Failed to toggle routine","error")}},[n,f,p]),N=a.useCallback(()=>{u("list"),m(void 0)},[]),S=a.useCallback(I=>{r(I),u("list"),m(void 0)},[]),j=()=>c==="create"?t.jsx(fm,{onSubmit:v,onCancel:N,scope:i,projectId:s}):c==="edit"&&d?t.jsx(fm,{routine:d,onSubmit:y,onCancel:N,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(bn,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),children:[t.jsx(Ht,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(I=>t.jsx(k_,{routine:I,onEdit:x,onDelete:E,onRun:k,onToggle:T,running:h===I.id},I.id))}),P=()=>j(),_=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",onClick:b,children:t.jsxs("div",{className:"modal modal-lg",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header scheduling-modal-header",children:[t.jsxs("div",{className:"scheduling-header-main-row",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(bn,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsxs("div",{className:"modal-header-actions",children:[_&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(Ht,{size:14}),"New Automation"]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Tt,{size:20})})]})]}),t.jsx("div",{className:"scheduling-header-scope-row",role:"group","aria-label":"Scheduling scope",children:t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>S("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(Qr,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>S("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(kn,{size:14}),"Project"]})]})})]}),t.jsxs("div",{className:"scheduling-summary","aria-live":"polite",children:[t.jsx(bn,{size:14}),t.jsxs("span",{children:[o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"detail-tabs",role:"tablist",children:t.jsxs("button",{className:"detail-tab detail-tab-active",role:"tab",id:"tab-routines","aria-selected":"true","aria-controls":"scheduled-tasks-content",onClick:()=>{u("list"),m(void 0)},children:[t.jsx(bn,{size:14})," Routines"]})}),t.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:P()})]})})}const $_=3e4,Gl=new Map,pl=new Map;function gm(e){return e??"default"}function bm(e){const n=Gl.get(e);return n?Date.now()>=n.expiresAt?(Gl.delete(e),null):n:null}function D_(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),i=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function L_(e){const n=pl.get(e);if(n)return n;const s=Oa().then(({providers:i,ghCli:r})=>{const l={...D_(i,r),ghCli:r,expiresAt:Date.now()+$_};return Gl.set(e,l),l}).finally(()=>{pl.delete(e)});return pl.set(e,s),s}function Kp(e){const n=gm(e),s=bm(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=gm(e),p=bm(g);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function f(){!m.current&&d(!0);try{const v=await L_(g);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return f(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function Jp({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){if(e&&n)return null;const r=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:t.jsx(Tt,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function z_({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const[u,d]=a.useState(""),[m,h]=a.useState([]),[g,p]=a.useState([]),[f,b]=a.useState(!1),[v,x]=a.useState(""),[y,E]=a.useState(""),[k,T]=a.useState(""),[N,S]=a.useState(""),[j,P]=a.useState(""),[_,I]=a.useState("default"),[D,G]=a.useState(!1),[$,R]=a.useState([]),[w,H]=a.useState(!1),[V,B]=a.useState(void 0),[M,z]=a.useState(ls),[X,C]=a.useState(null),[U,fe]=a.useState([]),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),ae=a.useRef(null),[Q,de]=a.useState(!1),[Re,ge]=a.useState(""),Me=a.useRef(null),{hasAiProvider:te,hasGithub:Ce,loading:$e}=Kp(s),We=a.useCallback(le=>{H(!0),R(le)},[]),Ge=a.useCallback(()=>{H(!1)},[]),Ee=a.useCallback(async()=>{if(U.length>0){re(!0);return}ce(!0);try{const le=await aa(void 0,s);fe(le),re(!0)}catch(le){const Ie=ve(le);o(Ie?`Failed to load agents: ${Ie}`:"Failed to load agents","error"),re(!1)}finally{ce(!1)}},[U.length,s,o]);a.useEffect(()=>{if(!ie)return;const le=Ie=>{ae.current&&!ae.current.contains(Ie.target)&&re(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ie]),a.useEffect(()=>{if(!Q)return;const le=Ie=>{Me.current&&!Me.current.contains(Ie.target)&&(de(!1),ge(""))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Q]);const Ae=i.filter(le=>!m.includes(le.id)).sort((le,Ie)=>{const Ze=Ie.createdAt.localeCompare(le.createdAt);if(Ze!==0)return Ze;const rt=parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-rt}),Oe=Re?Ae.filter(le=>le.id.toLowerCase().includes(Re.toLowerCase())||le.title&&le.title.toLowerCase().includes(Re.toLowerCase())||le.description&&le.description.toLowerCase().includes(Re.toLowerCase())):Ae,ke=(le,Ie)=>le.length>Ie?le.slice(0,Ie)+"…":le;a.useEffect(()=>{const le=u.trim()!==""||m.length>0||g.length>0||v!==""||y!==""||k!==""||N!==""||$.length>0||X!==null||V!==void 0||M!==ls;G(le)},[u,m,g,v,y,k,N,$,X,V,M]);const De=a.useCallback(()=>{D&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(le=>URL.revokeObjectURL(le.previewUrl)),p([]),d(""),h([]),x(""),E(""),T(""),S(""),P(""),I("default"),R([]),H(!1),C(null),re(!1),B(void 0),z(ls),G(!1),n())},[D,n,g]),se=a.useCallback(async()=>{const le=u.trim();if(!(!le||f)){b(!0);try{const Ie=v.indexOf("/"),Ze=y.indexOf("/"),rt=k.indexOf("/"),oe=await r({title:void 0,description:le,column:"triage",dependencies:m.length?m:void 0,enabledWorkflowSteps:w?$.length>0?$:[]:void 0,...X?{assignedAgentId:X}:{},modelPresetId:_==="preset"&&j||void 0,modelProvider:v&&Ie!==-1?v.slice(0,Ie):void 0,modelId:v&&Ie!==-1?v.slice(Ie+1):void 0,validatorModelProvider:y&&Ze!==-1?y.slice(0,Ze):void 0,validatorModelId:y&&Ze!==-1?y.slice(Ze+1):void 0,planningModelProvider:k&&rt!==-1?k.slice(0,rt):void 0,planningModelId:k&&rt!==-1?k.slice(rt+1):void 0,thinkingLevel:N!==""?N:void 0,reviewLevel:V,priority:M});if(g.length>0){const Z=[];for(const pe of g)try{await Fa(oe.id,pe.file,s)}catch{Z.push(pe.file.name)}Z.length>0&&o(`Failed to upload: ${Z.join(", ")}`,"error")}g.forEach(Z=>URL.revokeObjectURL(Z.previewUrl)),p([]),d(""),h([]),x(""),E(""),T(""),S(""),P(""),I("default"),R([]),H(!1),C(null),re(!1),B(void 0),z(ls),o(`Created ${oe.id}`,"success"),n()}catch(Ie){o(ve(Ie)||"Failed to create task","error")}finally{b(!1)}}},[u,m,g,v,y,k,N,f,r,o,n,s,_,j,$,w,X,V,M]),K=a.useCallback(le=>{le.key==="Escape"&&(le.preventDefault(),De())},[De]),ee=(X?U.find(le=>le.id===X):void 0)?.name??X,he=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Me,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(le=>!le),disabled:f,"data-testid":"dep-trigger",children:m.length>0?`${m.length} selected`:"Add dependencies"}),Q&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Re,onChange:le=>ge(le.target.value),onClick:le=>le.stopPropagation()}),Oe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Oe.map(le=>t.jsxs("div",{className:`dep-dropdown-item${m.includes(le.id)?" selected":""}`,onClick:()=>{h(m.includes(le.id)?m.filter(Ie=>Ie!==le.id):[...m,le.id]),de(!1),ge("")},onMouseDown:Ie=>Ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:le.id}),t.jsx("span",{className:"dep-dropdown-title",children:ke(le.title||le.description||le.id,30)})]},le.id))]})]}),m.length>0&&t.jsx("div",{className:"selected-deps",children:m.map(le=>t.jsxs("span",{className:"dep-chip",children:[le,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(m.filter(Ie=>Ie!==le)),disabled:f,children:"×"})]},le))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ae,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ie?re(!1):Ee()},disabled:f,"data-testid":"new-task-agent-button",children:[t.jsx(nn,{size:12,style:{verticalAlign:"middle"}}),ee?` ${ee}`:" Assign agent"]}),ie&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:le=>le.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),F&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!F&&U.filter(le=>le.state!=="terminated").map(le=>t.jsxs("div",{className:`dep-dropdown-item${X===le.id?" selected":""}`,onMouseDown:Ie=>Ie.preventDefault(),onClick:()=>{C(le.id===X?null:le.id),re(!1)},"data-testid":`agent-option-${le.id}`,children:[t.jsx(nn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:le.role}),t.jsx("span",{className:"dep-dropdown-title",children:le.name})]},le.id)),!F&&U.filter(le=>le.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),X&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:le=>le.preventDefault(),onClick:()=>{C(null),re(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:De,onKeyDown:K,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:le=>le.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:De,disabled:f,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!$e&&t.jsx(Jp,{hasAiProvider:te,hasGithub:Ce}),t.jsx(Bp,{mode:"create",description:u,onDescriptionChange:d,dependencies:m,onDependenciesChange:h,executorModel:v,onExecutorModelChange:x,validatorModel:y,onValidatorModelChange:E,presetMode:_,onPresetModeChange:I,selectedPresetId:j,onSelectedPresetIdChange:P,selectedWorkflowSteps:$,onWorkflowStepsChange:We,onDefaultOnApplied:Ge,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:De,planningModel:k,onPlanningModelChange:T,thinkingLevel:N,onThinkingLevelChange:S,reviewLevel:V,onReviewLevelChange:B,priority:M,onPriorityChange:z,renderBelowPrimary:he,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:De,disabled:f,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:se,disabled:!u.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const F_=5e3;function O_(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let E;o?E=await hd({limit:i,projectId:n,type:s}):E=(await rd({limit:i,type:s,projectId:n})).map(T=>({...T,projectId:n??"",projectName:""})),c(E),p(E.length===i),E.length>0&&(b.current=E[E.length-1].timestamp)}catch(E){h(E instanceof Error?E.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let E;o?E=await hd({limit:i,projectId:n,type:s,since:b.current}):E=(await rd({limit:i,type:s,since:b.current,projectId:n})).map(T=>({...T,projectId:n??"",projectName:""})),c(k=>[...k,...E]),p(E.length===i),E.length>0&&(b.current=E[E.length-1].timestamp)}catch(E){h(E instanceof Error?E.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},F_),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:x}}const fl={"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"},U_={"task:created":t.jsx(Ht,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Va,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(mn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Tt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(en,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Wa,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(za,{size:14,className:"activity-icon settings"})};function B_(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function H_({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:E,refresh:k,hasMore:T}=O_({projectId:b,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),N=x.map(I=>({id:I.id,timestamp:I.timestamp,type:I.type,taskId:I.taskId,taskTitle:I.taskTitle,details:I.details,metadata:I.metadata,projectId:I.projectId,projectName:I.projectName})),S=async()=>{try{await Bv(),k(),p(!1)}catch{p(!1)}},j=I=>{i&&i(I)},P=I=>{h(I),l?.(I==="all"?void 0:I)};a.useEffect(()=>{if(!e)return;const I=D=>{D.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,n,g]);const _=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:I=>{I.target===I.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(La,{size:18}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("div",{className:"activity-log-actions",children:[o.length>0&&t.jsxs("div",{className:"activity-log-filter activity-log-filter--project",children:[t.jsx(kn,{size:14}),t.jsxs("select",{value:m,onChange:I=>P(I.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(I=>t.jsx("option",{value:I.id,children:I.name},I.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Tr,{size:14}),t.jsxs("select",{value:u,onChange:I=>d(I.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(fl).map(([I,D])=>t.jsx("option",{value:I,children:D},I))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14})}),N.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Bt,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(I=>I.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",fl[u]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[E&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(ns,{size:16}),t.jsx("span",{children:E})]}),N.length===0&&!y&&!E&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(La,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:N.map(I=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:U_[I.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:fl[I.type]}),t.jsx("span",{className:"activity-log-entry-time",children:B_(I.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[I.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>j(I.taskId),"data-testid":"activity-task-link",children:I.taskId}),I.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:I.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:I.details})]}),I.metadata&&Object.keys(I.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof I.metadata.from=="string"&&typeof I.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[I.metadata.from," → ",I.metadata.to]}),typeof I.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${I.metadata.merged?"success":"error"}`,children:I.metadata.merged?"Merged":"Not merged"})]})]})]},I.id))}),T&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&N.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(at,{size:20,className:"spin"})})]}),g&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:S,children:"Clear Log"})]})]})})]})}):null}const Na=[{id:"status",label:"Status",icon:Zm},{id:"changes",label:"Changes",icon:Wm},{id:"commits",label:"Commits",icon:Da},{id:"branches",label:"Branches",icon:Us},{id:"worktrees",label:"Worktrees",icon:$g},{id:"stashes",label:"Stashes",icon:Jr},{id:"remotes",label:"Remotes",icon:Jm}];function xm({status:e}){switch(e){case"added":case"untracked":return t.jsx(gg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Gm,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(hg,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ni,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(xg,{size:14,className:"gm-file-icon"})}}function vm({status:e}){const n=e==="untracked"?"U":e==="added"?"A":e==="modified"?"M":e==="deleted"?"D":e==="renamed"?"R":e==="copied"?"C":"?";return t.jsx("span",{className:`gm-file-badge gm-file-badge-${e}`,children:n})}function q_(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Qi(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function V_({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const[o,l]=a.useState("status"),[c,u]=a.useState(!1),[d,m]=a.useState(null),h=a.useRef(null),g=q_(i),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(new Set),[E,k]=a.useState(""),[T,N]=a.useState(!1),[S,j]=a.useState(null),[P,_]=a.useState(!1),[I,D]=a.useState(null),[G,$]=a.useState(null),R=a.useRef(0),[w,H]=a.useState([]),[V,B]=a.useState(null),[M,z]=a.useState(null),[X,C]=a.useState(!1),[U,fe]=a.useState(20),[ie,re]=a.useState(""),[F,ce]=a.useState([]),[ae,Q]=a.useState(""),[de,Re]=a.useState(""),[ge,Me]=a.useState(""),[te,Ce]=a.useState(null),[$e,We]=a.useState([]),[Ge,Ee]=a.useState(!1),[Ae,Oe]=a.useState(null),[ke,De]=a.useState(null),[se,K]=a.useState(!1),[me,ee]=a.useState([]),[he,le]=a.useState([]),[Ie,Ze]=a.useState(""),[rt,oe]=a.useState(null),[Z,pe]=a.useState(null),[Se,Pe]=a.useState(null),ye=a.useCallback(async()=>{if(e){u(!0),m(null);try{switch(o){case"status":{const A=await _s(r);f(A);break}case"changes":{const[A,J]=await Promise.all([_s(r),Ii(r)]);f(A),v(J),y(new Set),$(null),j(null),D(null);break}case"commits":{const A=await Jx(U,r);H(A);break}case"branches":{const[A,J]=await Promise.all([ma(r),_s(r)]);ce(A),f(J);break}case"worktrees":{const A=await Zx(r);ee(A);break}case"stashes":{const A=await cr(r);le(A);break}case"remotes":{const A=await _s(r);f(A);break}}}catch(A){m(ve(A)||"Failed to fetch git data"),i(ve(A)||"Failed to fetch git data","error")}finally{u(!1)}}},[o,e,U,i,r]);a.useEffect(()=>{e&&ye()},[ye,e]),a.useEffect(()=>{if(!e)return;const A=J=>{if(J.key==="Escape"){n();return}if((J.key==="ArrowUp"||J.key==="ArrowDown")&&J.altKey){J.preventDefault();const Ve=Na.findIndex(dt=>dt.id===o);J.key==="ArrowUp"&&Ve>0?l(Na[Ve-1].id):J.key==="ArrowDown"&&Ve<Na.length-1&&l(Na[Ve+1].id)}};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,n,o]);const Ke=a.useCallback(async A=>{try{await td(A,r),i(`Staged ${A.length} file(s)`,"success");const J=await Ii(r);v(J),y(new Set),$(null),j(null),D(null)}catch(J){i(ve(J)||"Failed to stage files","error")}},[i,r]),Ne=a.useCallback(async A=>{try{await cv(A,r),i(`Unstaged ${A.length} file(s)`,"success");const J=await Ii(r);v(J),y(new Set),$(null),j(null),D(null)}catch(J){i(ve(J)||"Failed to unstage files","error")}},[i,r]),Fe=a.useCallback(async A=>{if(confirm(`Discard changes to ${A.length} file(s)? This cannot be undone.`))try{await dv(A,r),i(`Discarded changes to ${A.length} file(s)`,"success");const[J,Ve]=await Promise.all([Ii(r),_s(r)]);v(J),f(Ve),y(new Set),$(null),j(null),D(null)}catch(J){i(ve(J)||"Failed to discard changes","error")}},[i,r]),Ye=a.useCallback(async A=>{if(A.preventDefault(),!!E.trim()){N(!0);try{const J=await nd(E.trim(),r);i(`Committed: ${J.hash}`,"success"),k("");const[Ve,dt]=await Promise.all([Ii(r),_s(r)]);v(Ve),f(dt),$(null),j(null),D(null)}catch(J){i(ve(J)||"Failed to commit","error")}finally{N(!1)}}},[E,i,r]),xe=a.useCallback(async()=>{if(E.trim()){N(!0);try{const A=b.filter(yt=>!yt.staged).map(yt=>yt.file);A.length>0&&await td(A,r);const J=await nd(E.trim(),r);i(`Committed: ${J.hash}`,"success"),k("");const[Ve,dt]=await Promise.all([Ii(r),_s(r)]);v(Ve),f(dt),$(null),j(null),D(null)}catch(A){i(ve(A)||"Failed to commit","error")}finally{N(!1)}}},[E,b,i,r]),ze=a.useCallback(async(A,J)=>{$({file:A,staged:J}),_(!0),D(null);const Ve=R.current+1;R.current=Ve;try{const dt=await lv(A,J,r);if(R.current!==Ve)return;j(dt)}catch(dt){if(R.current!==Ve)return;const yt=ve(dt)||"Failed to load file diff";j(null),D(yt),i(yt,"error")}finally{R.current===Ve&&_(!1)}},[i,r]),be=a.useCallback(A=>{y(J=>{const Ve=new Set(J);return Ve.has(A)?Ve.delete(A):Ve.add(A),Ve})},[]),Qe=a.useCallback(async A=>{if(V===A){B(null),z(null);return}B(A),C(!0);try{const J=await Lr(A,r);z(J)}catch(J){i(ve(J)||"Failed to load diff","error"),z(null)}finally{C(!1)}},[V,i,r]),it=a.useCallback(()=>{fe(A=>Math.min(A+20,100))},[]),mt=a.useMemo(()=>{if(!ie.trim())return w;const A=ie.toLowerCase();return w.filter(J=>J.message.toLowerCase().includes(A)||J.author.toLowerCase().includes(A)||J.shortHash.toLowerCase().includes(A))},[w,ie]),At=a.useCallback(async A=>{if(A.preventDefault(),!!ae.trim()){u(!0);try{await ev(ae.trim(),de.trim()||void 0,r),i(`Created branch ${ae}`,"success"),Q(""),Re("");const J=await ma(r);ce(J)}catch(J){i(ve(J)||"Failed to create branch","error")}finally{u(!1)}}},[ae,de,i,r]),It=a.useCallback(async A=>{u(!0);try{await tv(A,r),i(`Switched to ${A}`,"success");const[J,Ve]=await Promise.all([_s(r),ma(r)]);f(J),ce(Ve)}catch(J){i(ve(J)||"Failed to checkout branch","error")}finally{u(!1)}},[i,r]),Dt=a.useCallback(async A=>{if(confirm(`Delete branch "${A}"?`)){u(!0);try{await ed(A,void 0,r),i(`Deleted branch ${A}`,"success");const J=await ma(r);ce(J)}catch(J){if(ve(J).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await ed(A,!0,r),i(`Force deleted branch ${A}`,"success");const Ve=await ma(r);ce(Ve)}catch(Ve){i(ve(Ve)||"Failed to delete branch","error")}}else i(ve(J)||"Failed to delete branch","error")}finally{u(!1)}}},[i,r]),Ut=a.useMemo(()=>{if(!ge.trim())return F;const A=ge.toLowerCase();return F.filter(J=>J.name.toLowerCase().includes(A))},[F,ge]),jt=a.useCallback(async A=>{if(te===A){Ce(null),We([]),Oe(null),De(null);return}Ce(A),We([]),Oe(null),De(null),Ee(!0);try{const J=await Xx(A,10,r);We(J)}catch{We([])}finally{Ee(!1)}},[te,r]),Pt=a.useCallback(async A=>{if(Ae===A){Oe(null),De(null);return}Oe(A),De(null),K(!0);try{const J=await Lr(A,r);De(J)}catch{De(null)}finally{K(!1)}},[Ae,r]),He=a.useCallback(()=>{Ce(null),We([]),Oe(null),De(null)},[]),ut=a.useCallback(async A=>{A.preventDefault(),oe("create");try{await av(Ie.trim()||void 0,r),i("Changes stashed","success"),Ze("");const J=await cr(r);le(J)}catch(J){i(ve(J)||"Failed to stash changes","error")}finally{oe(null)}},[Ie,i,r]),$t=a.useCallback(async(A,J=!1)=>{oe(`apply-${A}`);try{await rv(A,J,r),i(J?"Stash popped":"Stash applied","success");const Ve=await cr(r);le(Ve)}catch(Ve){i(ve(Ve)||"Failed to apply stash","error")}finally{oe(null)}},[i,r]),St=a.useCallback(async A=>{if(confirm(`Drop stash@{${A}}? This cannot be undone.`)){oe(`drop-${A}`);try{await ov(A,r),i("Stash dropped","success");const J=await cr(r);le(J)}catch(J){i(ve(J)||"Failed to drop stash","error")}finally{oe(null)}}},[i,r]),Yt=a.useCallback(async()=>{pe("fetch");try{const A=await nv(void 0,r);Pe(A),i(A.message||"Fetch completed",A.fetched?"success":"info");const J=await _s(r);f(J)}catch(A){i(ve(A)||"Fetch failed","error")}finally{pe(null)}},[i,r]),we=a.useCallback(async()=>{pe("pull");try{const A=await sv(r);Pe(A),A.conflict?i("Merge conflict detected. Resolve manually.","error"):i(A.message||"Pull completed","success");const J=await _s(r);f(J)}catch(A){i(ve(A)||"Pull failed","error")}finally{pe(null)}},[i,r]),et=a.useCallback(async()=>{pe("push");try{const A=await iv(r);Pe(A),i(A.message||"Push completed","success");const J=await _s(r);f(J)}catch(A){i(ve(A)||"Push failed","error")}finally{pe(null)}},[i,r]),ct=a.useMemo(()=>b.filter(A=>A.staged),[b]),ue=a.useMemo(()=>b.filter(A=>!A.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",onClick:A=>A.target===A.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Nl,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ye,disabled:c,title:"Refresh",children:t.jsx(mn,{size:14,className:c?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Tt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Na.map(A=>{const J=A.icon;return t.jsxs("button",{role:"tab","aria-selected":o===A.id,className:`gm-nav-item${o===A.id?" active":""}`,onClick:()=>l(A.id),children:[t.jsx(J,{size:16}),t.jsx("span",{className:"gm-nav-label",children:A.label})]},A.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[c&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(at,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),d&&!c&&t.jsxs("div",{className:"gm-error",children:[t.jsx(ns,{size:18}),t.jsx("span",{children:d}),t.jsx("button",{className:"btn btn-sm",onClick:ye,children:"Retry"})]}),o==="status"&&!c&&p&&t.jsx(W_,{status:p,copyToClipboard:g}),o==="changes"&&!c&&t.jsx(G_,{status:p,stagedFiles:ct,unstagedFiles:ue,selectedFiles:x,toggleFileSelection:be,onStageFiles:Ke,onUnstageFiles:Ne,onDiscardChanges:Fe,onSelectDiffFile:ze,selectedDiffTarget:G,changeDiff:S,loadingChangeDiff:P,changeDiffError:I,commitMessage:E,setCommitMessage:k,onCommit:Ye,onStageAllAndCommit:xe,committing:T}),o==="commits"&&!c&&t.jsx(K_,{commits:mt,commitSearch:ie,setCommitSearch:re,selectedCommit:V,commitDiff:M,loadingDiff:X,onCommitClick:Qe,onLoadMore:it,canLoadMore:w.length>=U&&U<100,copyToClipboard:g}),o==="branches"&&!c&&t.jsx(J_,{branches:Ut,branchSearch:ge,setBranchSearch:Me,newBranchName:ae,setNewBranchName:Q,branchBase:de,setBranchBase:Re,onCreateBranch:At,onCheckoutBranch:It,onDeleteBranch:Dt,loading:c,allBranches:F,selectedBranch:te,branchCommits:$e,loadingBranchCommits:Ge,expandedBranchCommit:Ae,branchCommitDiff:ke,loadingBranchCommitDiff:se,onSelectBranch:jt,onBranchCommitClick:Pt,onCloseBranchDetails:He}),o==="worktrees"&&!c&&t.jsx(Y_,{worktrees:me}),o==="stashes"&&!c&&t.jsx(Q_,{stashes:he,stashMessage:Ie,setStashMessage:Ze,onCreateStash:ut,onApplyStash:$t,onDropStash:St,stashLoading:rt}),o==="remotes"&&!c&&t.jsx(X_,{status:p,remoteLoading:Z,lastRemoteResult:Se,onFetch:Yt,onPull:we,onPush:et,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function W_({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Us,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(Hi,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(ns,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(en,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(ki,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(qa,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(en,{size:12}),"Up to date"]})]})]})]})]})}function G_({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(k=>i.has(`unstaged:${k.file}`)),E=n.filter(k=>i.has(`staged:${k.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Us,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(Ht,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(Wa,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(k=>{const T=d?.file===k.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${T?" active":""}`,onClick:()=>u(k.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(xm,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(vm,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(Ht,{size:12})})]},`unstaged:${k.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[E.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(E.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",E.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(k=>{const T=d?.file===k.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${T?" active":""}`,onClick:()=>u(k.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(xm,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(vm,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(Tt,{size:12})})]},`staged:${k.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Wm,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&t.jsx("div",{className:"gm-diff-error",children:g}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>f(k.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(at,{size:14,className:"spin"}):t.jsx(yi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function K_({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:u,copyToClipboard:d}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Oi,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Qi(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Hi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function J_({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:E,onCloseBranchDetails:k}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Oi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:T=>s(T.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:T=>r(T.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:T=>l(T.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(T=>t.jsx("option",{value:T.name,children:T.name},T.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(Ht,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(T=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${T.isCurrent?" current":""}${g===T.name?" selected":""}`,onClick:()=>y(T.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[T.isCurrent&&t.jsx(yn,{size:14,className:"gm-current-icon"}),T.name]}),T.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",T.remote]}),T.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Qi(T.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!T.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),u(T.name)},disabled:m,title:"Checkout",children:t.jsx(Us,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),d(T.name)},disabled:m,title:"Delete",children:t.jsx(Bt,{size:14})})]})})]}),g===T.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Da,{size:14}),"Commits on ",T.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(Tt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(N=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>E(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),t.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:N.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Qi(N.date)}),N.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===N.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},N.hash))})]})]},T.name))})]})}function Y_({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:n.path.split("/").pop()||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Us,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function Q_({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(at,{size:14,className:"spin"}):t.jsx(Jr,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Us,{size:12}),c.branch]}),t.jsx("span",{children:Qi(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(at,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(at,{size:14,className:"spin"}):t.jsx(Bt,{size:14})})]})]},c.index))})]})}function X_({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=K=>{try{return new URL(K).hostname}catch{return K.replace(/^git@/,"").split(":")[0]||K}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[v,x]=a.useState(""),[y,E]=a.useState(""),[k,T]=a.useState(null),[N,S]=a.useState(""),[j,P]=a.useState(""),[_,I]=a.useState(!1),[D,G]=a.useState([]),[$,R]=a.useState(!1),[w,H]=a.useState(null),[V,B]=a.useState([]),[M,z]=a.useState(!1),[X,C]=a.useState(null),U=m.find(K=>K.name===w),[fe,ie]=a.useState(null),[re,F]=a.useState(null),[ce,ae]=a.useState(!1),[Q,de]=a.useState(null),[Re,ge]=a.useState(null),[Me,te]=a.useState(!1);a.useEffect(()=>{Ce()},[]),a.useEffect(()=>{e&&e.ahead>0?$e():e&&e.ahead===0&&G([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!w&&H(m[0].name)},[m]),a.useEffect(()=>{w?We(w):(B([]),C(null))},[w]),a.useEffect(()=>{w&&!m.find(K=>K.name===w)&&H(m.length>0?m[0].name:null)},[m,w]);const Ce=async()=>{p(!0);try{const K=await Ox(c);h(K)}catch(K){l(ve(K)||"Failed to load remotes","error")}finally{p(!1)}},$e=async()=>{R(!0);try{const K=await Yx(c);G(K)}catch{G([])}finally{R(!1)}},We=async K=>{z(!0),C(null);try{const me=await Qx(K,void 0,10,c);B(me)}catch(me){C(ve(me)||"Failed to load remote commits"),B([])}finally{z(!1)}},Ge=async K=>{if(K.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await Ux(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),E(""),I(!1),await Ce()}catch(me){l(ve(me)||"Failed to add remote","error")}finally{b(null)}}},Ee=async K=>{if(confirm(`Are you sure you want to remove remote '${K}'?`)){b(`remove-${K}`);try{await Bx(K,c),l(`Remote '${K}' removed`,"success"),await Ce()}catch(me){l(ve(me)||"Failed to remove remote","error")}finally{b(null)}}},Ae=async K=>{if(j.trim()){b(`rename-${K}`);try{await Hx(K,j.trim(),c),l(`Remote renamed to '${j.trim()}'`,"success"),T(null),P(""),await Ce()}catch(me){l(ve(me)||"Failed to rename remote","error")}finally{b(null)}}},Oe=async K=>{if(N.trim()){b(`url-${K}`);try{await qx(K,N.trim(),c),l("Remote URL updated","success"),T(null),S(""),await Ce()}catch(me){l(ve(me)||"Failed to update remote URL","error")}finally{b(null)}}},ke=a.useCallback(async(K,me)=>{if(me==="ahead"){if(fe===K){ie(null),F(null);return}ie(K),F(null),ae(!0);try{const ee=await Lr(K);F(ee)}catch{F(null)}finally{ae(!1)}}else{if(Q===K){de(null),ge(null);return}de(K),ge(null),te(!0);try{const ee=await Lr(K);ge(ee)}catch{ge(null)}finally{te(!1)}}},[fe,Q]),De=K=>{T(`url-${K.name}`),S(K.pushUrl||K.fetchUrl)},se=K=>{T(`name-${K.name}`),P(K.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>I(!_),disabled:f!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(Tt,{size:14}):t.jsx(Ht,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ge,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:K=>x(K.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:K=>E(K.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||f==="add",children:[f==="add"?t.jsx(at,{size:12,className:"spin"}):t.jsx(Ht,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(K=>t.jsxs("div",{className:`gm-remote-selector-item${w===K.name?" selected":""}`,onClick:()=>H(K.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[K.name,K.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(K.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:me=>{me.stopPropagation(),Ee(K.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Bt,{size:14})})]},K.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[w&&U?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:w}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx(ki,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(qa,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?t.jsx(at,{size:14,className:"spin"}):t.jsx(mn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(at,{size:14,className:"spin"}):t.jsx(Zn,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(at,{size:14,className:"spin"}):t.jsx(ki,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),k===`url-${w}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:K=>S(K.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Oe(w),disabled:f===`url-${w}`,children:f===`url-${w}`?t.jsx(at,{size:12,className:"spin"}):t.jsx(yn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{T(null),S("")},title:"Cancel",children:t.jsx(Tt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:U.fetchUrl,children:U.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Hi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>De(U),disabled:f!==null,title:"Edit remote URL",children:t.jsx(Un,{size:14})})]})]}),U.pushUrl&&U.pushUrl!==U.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:U.pushUrl,children:U.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Hi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${w}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:j,onChange:K=>P(K.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ae(w),disabled:f===`rename-${w}`,children:f===`rename-${w}`?t.jsx(at,{size:12,className:"spin"}):t.jsx(yn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{T(null),P("")},title:"Cancel",children:t.jsx(Tt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>se(U),disabled:f!==null,title:"Edit remote name",children:t.jsx(Un,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(ki,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(at,{size:14,className:"spin"}),"Loading..."]}):D.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:D.map(K=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ke(K.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:K.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:K.message,children:K.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:K.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Qi(K.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:fe===K.hash?t.jsx(zt,{size:14}):t.jsx(an,{size:14})})]}),fe===K.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ce?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading diff..."]}):re?t.jsxs(t.Fragment,{children:[K.message&&t.jsx("div",{className:"gm-commit-message-full",children:K.message}),re.stat&&t.jsx("pre",{className:"gm-diff-stat",children:re.stat}),t.jsx("pre",{className:"gm-diff-patch",children:re.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},K.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Zm,{size:14}),"Recent commits on ",w]})}),M?t.jsxs("div",{className:"gm-loading",children:[t.jsx(at,{size:14,className:"spin"}),"Loading commits..."]}):X?t.jsxs("div",{className:"gm-error",children:[t.jsx(ns,{size:14}),X]}):V.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",w,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:V.map(K=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ke(K.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:K.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:K.message,children:K.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:K.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Qi(K.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Q===K.hash?t.jsx(zt,{size:14}):t.jsx(an,{size:14})})]}),Q===K.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Me?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(at,{size:16,className:"spin"}),"Loading diff..."]}):Re?t.jsxs(t.Fragment,{children:[K.message&&t.jsx("div",{className:"gm-commit-message-full",children:K.message}),Re.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Re.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Re.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},K.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const Sa={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function Z_(e,n){return e&&n?`${e}/${n}`:""}function eA(e){if(!e)return{provider:"",modelId:""};const n=e.indexOf("/");return n===-1?{provider:"",modelId:""}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function tA(e){switch(e){case"file-text":return Ni;case"check-circle":return en;case"shield":return wb;case"zap":return bn;case"eye":return ec;case"globe":return Qr;case"layout-grid":return Ci;default:return en}}function nA(e){switch(e.toLowerCase()){case"quality":return"wfm-badge-category wfm-badge-category-quality";case"security":return"wfm-badge-category wfm-badge-category-security";default:return"wfm-badge-category"}}function sA({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,b]=a.useState(null),[v,x]=a.useState(!1),[y,E]=a.useState(Sa),[k,T]=a.useState(!1),[N,S]=a.useState(!1),[j,P]=a.useState(null),[_,I]=a.useState(null),[D,G]=a.useState({}),[$,R]=a.useState([]),w=a.useCallback(async()=>{try{d(!0);const F=await so(i);o(F)}catch(F){s(ve(F)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),H=a.useCallback(async()=>{try{const F=await Ya(i);G(F||{})}catch{}},[i]),V=a.useCallback(async()=>{try{const F=await ss();R(F.models||[])}catch{}},[]),B=a.useCallback(async()=>{try{h(!0);const F=await Wv();c(F.templates)}catch(F){s(ve(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(w(),B(),H(),V())},[e,w,B,H,V]);const M=a.useCallback(()=>{x(!0),b(null),E(Sa)},[]),z=a.useCallback(F=>{b(F.id),x(!1),E({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||""})},[]),X=a.useCallback(()=>{b(null),x(!1),E(Sa)},[]),C=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}T(!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(v){const ce={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 od(ce,i),s("Workflow step created","success")}else f&&(await Hv(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"));x(!1),b(null),E(Sa),await w()}catch(F){s(ve(F)||"Failed to save workflow step","error")}finally{T(!1)}},[y,v,f,s,w]),U=a.useCallback(async F=>{try{await qv(F,i),s("Workflow step deleted","success"),P(null),f===F&&(b(null),E(Sa)),await w()}catch(ce){s(ve(ce)||"Failed to delete workflow step","error")}},[f,s,w]),fe=a.useCallback(async()=>{if(!(!f&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}T(!0);try{const F=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},ce={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},ae=await od(ce,i);x(!1),b(ae.id),S(!0);const Q=await ld(ae.id,i);E(de=>({...de,prompt:Q.prompt})),s("Prompt refined with AI","success"),await w()}catch(F){s(ve(F)||"Failed to refine prompt","error")}finally{T(!1),S(!1)}return}if(f){S(!0);try{const F=await ld(f,i);E(ce=>({...ce,prompt:F.prompt})),s("Prompt refined with AI","success"),await w()}catch(F){s(ve(F)||"Failed to refine prompt","error")}finally{S(!1)}}}},[f,v,y,s,w]),ie=a.useCallback(async F=>{I(F.id);try{await Gv(F.id,i),s(`Added ${F.name} workflow step`,"success"),await w(),p("my-steps")}catch(ce){const ae=ve(ce);ae?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(ae||"Failed to add workflow step from template","error")}finally{I(null)}},[s,w]);if(!e)return null;const re=v||f!==null;return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"workflow-step-manager",children:t.jsxs("div",{className:"modal workflow-step-manager-modal",onClick:F=>F.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!re&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Mf,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Ci,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!re&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(F=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${F.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:F.name}),t.jsx("span",{className:`wfm-badge ${F.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:F.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(F.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(F.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.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&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:F.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>z(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(Un,{size:14})}),j===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>U(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx(yn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>P(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Tt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>P(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(Bt,{size:14})})]})]})},F.id))})]}),g==="templates"&&!re&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(at,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(F=>{const ce=tA(F.icon),ae=nA(F.category),Q=_===F.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${F.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ce,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:F.name}),t.jsx("span",{className:ae,children:F.category})]}),t.jsx("div",{className:"wfm-template-desc",children:F.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ie(F),disabled:Q,"data-testid":`add-template-${F.id}`,children:Q?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Ht,{size:12}),"Add"]})})]})]})},F.id)})})}),re&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:F=>E(ce=>({...ce,name:F.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:F=>E(ce=>({...ce,description:F.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>E(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(li,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>E(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Hs,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>E(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>E(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:fe,disabled:!y.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?t.jsx(at,{size:12,className:"spin"}):t.jsx(Pn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:F=>E(ce=>({...ce,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"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>E(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(jn,{models:$,value:Z_(y.modelProvider,y.modelId),onChange:F=>{const ce=eA(F);E(ae=>({...ae,modelProvider:ce.provider,modelId:ce.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(D).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:F=>E(ce=>({...ce,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(D).map(([F,ce])=>t.jsxs("option",{value:F,children:[F," (",ce,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:F=>E(ce=>({...ce,enabled:F.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:F=>E(ce=>({...ce,defaultOn:F.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:X,disabled:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:C,disabled:k||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:k?"Saving...":v?"Create":"Save"})]})]})]})]})}),!re&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:M,"data-testid":"add-workflow-step",children:[t.jsx(Ht,{size:14}),"Add Workflow Step"]})})]})})}const iA=36e5,aA=3e5,gl=[{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 rA(e){return e<1e3?`${e}ms`:e<6e4?`${Math.round(e/1e3)}s`:e<36e5?`${Math.round(e/6e4)}m`:e<864e5?`${Math.round(e/36e5)}h`:e<6048e5?`${Math.round(e/864e5)}d`:`${Math.round(e/6048e5)}w`}function oA(e){return typeof e!="number"||!Number.isFinite(e)?iA:Math.max(aA,Math.round(e))}function $P(e){if(gl.some(s=>s.value===e))return[...gl];const n={value:e,label:`${rA(e)} (custom)`};return[...gl,n].sort((s,i)=>s.value-i.value)}const lA=4,cA=5*6e4;function dA(e){const n=oA(e?.heartbeatIntervalMs);return Math.max(n*lA,cA)}function uA(e){const n=e.metadata;return n&&(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor")?!0:!!(e.role==="executor"&&e.name?.startsWith("executor-")&&e.taskId)}function mA(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=uA(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(os,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Os,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ss,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(nn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=dA(o);return u>d?{label:"Unresponsive",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(Lg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ca=[{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 hA({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[g,p]=a.useState("custom"),[f,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const w=En("fn-agent-view",i);return w==="board"||w==="list"?w:"list"});a.useEffect(()=>{const w=En("fn-agent-view",i);if(w==="board"||w==="list"){x(w);return}x("list")},[i]),a.useEffect(()=>{cs("fn-agent-view",v,i)},[i,v]);const[y,E]=a.useState(null),k=a.useRef(null),T=a.useMemo(()=>f==="all"?r.filter(w=>w.state!=="terminated"):r,[r,f]),N=a.useCallback(async()=>{c(!0);try{const H=await aa(f!=="all"?{state:f}:void 0,i);o(H)}catch(w){s(`Failed to load agents: ${ve(w)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&N()},[e,N]),a.useEffect(()=>{if(!e)return;const w=setInterval(()=>{N()},3e4);return()=>{clearInterval(w)}},[e,N]);const S=async()=>{if(m.trim())try{await ny({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),N()}catch(w){s(`Failed to create agent: ${ve(w)}`,"error")}},j=async(w,H)=>{try{await iy(w,H,i),s(`Agent state updated to ${H}`,"success"),N()}catch(V){s(`Failed to update state: ${ve(V)}`,"error")}},P=async(w,H)=>{if(confirm(`Delete agent "${H}"? This cannot be undone.`))try{await ay(w,i),s(`Agent "${H}" deleted`,"success"),N()}catch(V){s(`Failed to delete agent: ${ve(V)}`,"error")}},_=async(w,H)=>{const V=r.find(B=>B.id===w);if(V){if(V.role===H){E(null);return}try{await sy(w,{role:H},i),s(`Agent role updated to ${Ca.find(B=>B.value===H)?.label??H}`,"success"),E(null),N()}catch(B){s(`Failed to update role: ${ve(B)}`,"error")}}},I=(w,H)=>{w.key==="Escape"&&E(null)},D=w=>Ca.find(H=>H.value===w)?.label??w,G=w=>Ca.find(H=>H.value===w)?.icon??"◆",$=w=>mA(w),R=w=>w.color==="var(--state-active-text)"?"active":w.color==="var(--state-paused-text)"?"paused":w.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:w=>w.target===w.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(nn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>x("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>x("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(Sl,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void N(),title:"Refresh",disabled:l,children:t.jsx(mn,{size:16,className:l?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:"modal-content agent-modal-content",children:[t.jsxs("div",{className:"agent-controls",children:[t.jsxs("div",{className:"agent-state-filter",children:[t.jsx(Tr,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:w=>b(w.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn--primary",onClick:()=>d(!u),children:[t.jsx(Ht,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:w=>h(w.target.value),onKeyDown:w=>w.key==="Enter"&&S(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:w=>p(w.target.value),children:Ca.map(w=>t.jsxs("option",{value:w.value,children:[w.icon," ",w.label]},w.value))}),t.jsx("button",{className:"btn btn--primary",onClick:()=>void S(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:T.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(nn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?T.map(w=>{const H=$(w),V=R(H);return t.jsxs("div",{className:"agent-board-card","data-state":w.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:G(w.role)}),t.jsx("span",{className:"agent-board-badge","data-state":w.state,children:w.state}),t.jsx("span",{className:"agent-board-health","data-health":V,title:H.label,children:H.icon})]}),t.jsx("div",{className:"agent-board-name",title:w.name,children:w.name}),t.jsx("div",{className:"agent-board-id",children:w.id}),t.jsxs("div",{className:"agent-board-actions",children:[w.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"active"),title:"Activate",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:t.jsx(Bt,{size:14})})]}),w.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"paused"),title:"Pause",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:t.jsx(os,{size:14})})]}),w.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"active"),title:"Resume",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:t.jsx(os,{size:14})})]}),w.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"paused"),title:"Pause",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:t.jsx(os,{size:14})})]}),w.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"active"),title:"Retry",children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:t.jsx(os,{size:14})})]}),w.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:t.jsx(Bt,{size:14})})]})]},w.id)}):T.map(w=>{const H=$(w),V=R(H);return t.jsxs("div",{className:"agent-card","data-state":w.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===w.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:w.role,onChange:B=>void _(w.id,B.target.value),onKeyDown:B=>I(B,w.id),onBlur:()=>E(null),autoFocus:!0,children:Ca.map(B=>t.jsxs("option",{value:B.value,children:[B.icon," ",B.label]},B.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>E(w.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&E(w.id)},children:G(w.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:w.name}),t.jsx("span",{className:"agent-id text-secondary",children:w.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":w.state,children:w.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":V,title:H.label,children:[H.icon,!H.stateDerived&&` ${H.label}`]}),t.jsx("span",{className:"badge text-secondary",children:D(w.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[w.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:w.taskId})]}),w.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(w.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[w.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"active"),title:"Activate",children:[t.jsx(sn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:[t.jsx(Bt,{size:14})," Delete"]})]}),w.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"paused"),title:"Pause",children:[t.jsx(Os,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:[t.jsx(os,{size:14})," Stop"]})]}),w.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"active"),title:"Resume",children:[t.jsx(sn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:[t.jsx(os,{size:14})," Stop"]})]}),w.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"paused"),title:"Pause",children:[t.jsx(Os,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:[t.jsx(os,{size:14})," Stop"]})]}),w.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void j(w.id,"active"),title:"Retry",children:[t.jsx(sn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void j(w.id,"terminated"),title:"Stop",children:[t.jsx(os,{size:14})," Stop"]})]}),w.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void j(w.id,"active"),title:"Start",children:[t.jsx(sn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:[t.jsx(Bt,{size:14})," Delete"]})]})]})]},w.id)})})]})]})}):null}function pA({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await _x();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await Ax(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(ts,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(fA,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(ym,{status:i,authenticated:e}),c&&t.jsx(km,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(ts,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,t.jsx(ym,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(km,{action:c})]})}function fA({status:e,authenticated:n}){const s=e?.enabled??n,i=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function ym({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(at,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function km({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Claude-CLI-routed models are now visible in the model picker.":"Claude-CLI-routed models are hidden from the model picker."]})}const Mi="fusion_model_onboarding_state",Xi=[],Zi=[],Gr=!1,Kr=!1,ea={},gA=void 0,oi=["ai-setup","github","project-setup","first-task"],bA={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function us(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Mi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?xA(n):null}catch{return null}}function xA(e){const n=e.postOnboardingDismissedAt??gA;return{...e,completedSteps:e.completedSteps??Xi,skippedSteps:e.skippedSteps??Zi,dismissed:e.dismissed??Gr,completed:e.completed??Kr,stepData:e.stepData??ea,...n?{postOnboardingDismissedAt:n}:{}}}function Er(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Xi,skippedSteps:Zi,dismissed:Gr,completed:Kr,stepData:ea};try{localStorage.setItem(Mi,JSON.stringify(s))}catch{}return}try{const s=us(),i=new Date().toISOString(),r=n.completed??Kr;let o=n.dismissed??Gr;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Xi,c=n.skippedSteps??s?.skippedSteps??Zi,u={...s?.stepData??ea};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem(Mi,JSON.stringify(d))}catch{}}}function vA(e){if(!(typeof window>"u"))try{const n=us(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Xi,skippedSteps:[e],dismissed:Gr,completed:Kr,stepData:ea};localStorage.setItem(Mi,JSON.stringify(o));return}const i=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:i,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(Mi,JSON.stringify(r))}catch{}}function jm(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Xi,skippedSteps:Zi,dismissed:!1,completed:!0,stepData:ea};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function ta(){const e=us();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function yA(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Xi,skippedSteps:Zi,dismissed:!1,completed:!1,stepData:ea,postOnboardingDismissedAt:n};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function Yp(){const e=us();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function kA(){const e=us();return!e||ta()?!1:e.currentStep!=="complete"}function jA(){const e=us();if(!e||ta()||e.currentStep==="complete")return null;const n=e.currentStep,s=bA[n]??SA(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function wA(){const e=us();return e?e.skippedSteps:Zi}function NA(e){const n=us();return!n||!n.stepData?null:n.stepData[e]??null}function SA(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Qp="fusion_onboarding_events",wm="fusion_onboarding_session_id",CA=200,EA=50;function js(e,n={}){if(!(typeof window>"u"))try{const s=_A(),i=TA(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:MA()},o=RA([...s,r]);AA(o)}catch{}}function MA(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(wm);if(e)return e;const n=Nm();return sessionStorage.setItem(wm,n),n}catch{return Nm()}}function Nm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function _A(){try{const e=localStorage.getItem(Qp);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(IA):[]}catch{return[]}}function AA(e){try{localStorage.setItem(Qp,JSON.stringify(e))}catch{}}function RA(e){const n=[...e];for(;n.length>CA;)n.splice(0,EA);return n}function TA(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function IA(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.type=="string"&&typeof n.timestamp=="string"&&typeof n.sessionId=="string"&&!!n.metadata&&typeof n.metadata=="object"}const PA={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"}}},Xp={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:"..."}},$A={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Sm={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 Kl(e){if(Sm[e])return Sm[e];const n=e.trim();return n?n.split(/[-_\s]+/).filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"This provider"}const bl=["anthropic","openai","google","gemini","ollama"],DA=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],LA={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"},zA={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Jl(e){return LA[e]??e}function Cm(e){const n=Jl(e),s=DA.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Em(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Cm(e.id),i=Cm(n.id);if(s!==i)return s-i;const r=Jl(e.id),o=Jl(n.id);if(r!==o)return r.localeCompare(o);const l=zA[r];if(l){const u=l.indexOf(e.id),d=l.indexOf(n.id);if(u!==d)return(u===-1?Number.POSITIVE_INFINITY:u)-(d===-1?Number.POSITIVE_INFINITY:d)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function FA(e,n){const s=n.trim();if(!s)return"API key is required";const i=Xp[e]??$A;return i.pattern.test(s)?null:`${Kl(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const Zp={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"},OA={description:"AI provider — connect to start using AI models",apiKeyInfo:Zp};function Yl(e){return PA[e]??OA}function UA(e){return Yl(e.id).apiKeyInfo??Zp}function Fs({summary:e,children:n,className:s=""}){const[i,r]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[t.jsx(an,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),i&&t.jsx("div",{className:"onboarding-disclosure-content",children:n})]})}function BA({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const i=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:i}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function HA({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),g=Xp[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,f=t.jsxs(t.Fragment,{children:[g&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(Fs,{summary:"Advanced setup details",children:f}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:b=>c(e.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(Fs,{summary:"Advanced setup details",children:f})]})}const qA=150;function VA({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=us(),d=u?.currentStep,m=d==="complete"?"ai-setup":oi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??wA(),[p,f]=a.useState(!0),[b,v]=a.useState(m),[x,y]=a.useState(h),[E,k]=a.useState(g),[T,N]=a.useState(!1),[S,j]=a.useState(""),[P,_]=a.useState(!1),[I,D]=a.useState(null),[G,$]=a.useState(null),[R,w]=a.useState([]),[H,V]=a.useState(void 0),[B,M]=a.useState(!0),[z,X]=a.useState(null),[C,U]=a.useState({}),[fe,ie]=a.useState([]),[re,F]=a.useState(""),[ce,ae]=a.useState(!1),[Q,de]=a.useState({}),[Re,ge]=a.useState({}),[Me,te]=a.useState({}),Ce=a.useRef({}),$e=a.useRef(null),We=a.useRef(null),[Ge,Ee]=a.useState({}),[Ae,Oe]=a.useState(()=>us()?.stepData?.github?.skipped===!0),ke=a.useRef(0),De=a.useRef(l),se=a.useRef(!1),K=u?.currentStep,me=!!u&&u.currentStep!=="complete",[ee,he]=a.useState(()=>us()?.stepData?.["ai-setup"]?.skippedProviders??{}),le=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Ie=le.findIndex(W=>W.key===b),Ze=b==="complete"?le.length:Ie;a.useEffect(()=>{b!=="complete"&&Er(b,{completedSteps:x,skippedSteps:E})},[b,x,E]),a.useEffect(()=>{se.current||(se.current=!0,js("onboarding:wizard-opened",{source:me?"resume":"initial",resumedFromStep:K}))},[me,K]),a.useEffect(()=>{const W=De.current!=null,Le=l!=null;!W&&Le&&N(!0),Le||N(!1),De.current=l},[l]);const rt=a.useRef(m);a.useEffect(()=>{if(rt.current==="ai-setup"&&b!=="ai-setup"&&!R.some(Le=>Le.id!=="github"&&Le.authenticated)){const Le={};for(const nt of R)nt.id!=="github"&&!nt.authenticated&&!ee[nt.id]&&(Le[nt.id]=!0);if(Object.keys(Le).length>0){const nt={...ee,...Le};he(nt),Er(b,{stepData:{"ai-setup":{skippedProviders:nt}}})}}rt.current=b},[b,R,ee]);const oe=a.useCallback(async()=>{try{const{providers:W,ghCli:Le}=await Oa();w(W),V(Le),U(nt=>{const tt={};for(const[ht,kt]of Object.entries(nt)){const Et=W.find(fn=>fn.id===ht);Et&&!Et.authenticated&&(tt[ht]=kt)}return Object.keys(tt).length===Object.keys(nt).length?nt:tt}),he(nt=>{const tt={...nt};for(const ht of W)ht.authenticated&&tt[ht.id]&&delete tt[ht.id];return Object.keys(tt).length===Object.keys(nt).length?nt:tt})}catch{}},[]),Z=a.useRef(!1);a.useEffect(()=>{Z.current&&oe(),Z.current=b!=="ai-setup"},[b,oe]);const pe=R.find(W=>W.id==="github"),Se=!!pe,Pe=pe?.authenticated??!1,ye=H?.authenticated??!1,Ke=Pe||ye,Ne=!Pe&&ye,Fe=a.useCallback(W=>{if(W.authenticated)return"connected";const Le=Ge?.[W.id];return Le==="timeout"||Le==="failed"?"retry":ee[W.id]?"skipped":"not-connected"},[Ge,ee]);function Ye({status:W}){const Le={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:nt,className:tt}=Le[W];return t.jsx("span",{"data-testid":"provider-status-badge",className:tt,"data-status":W,children:nt})}const xe=a.useCallback(()=>{if(Ke)return"connected";const W=Ge.github;return W==="pending"?"pending":W==="failed"||W==="timeout"?"failed":Ae?"skipped":"not-connected"},[Ke,Ge,Ae]);function ze({status:W}){const Le={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:nt,className:tt}=Le[W];return t.jsx("span",{"data-testid":"github-status-badge",className:tt,"data-status":W,children:nt})}const be=a.useCallback(async()=>{try{const W=await ss();ie(W.models)}catch{}},[]),Qe=a.useCallback(async()=>{try{const W=await ia();if(W.defaultProvider&&W.defaultModelId){const Le=`${W.defaultProvider}/${W.defaultModelId}`;F(Le)}}catch{}},[]);a.useEffect(()=>{Promise.all([oe(),be(),Qe()]).finally(()=>M(!1))},[oe,be,Qe]),a.useEffect(()=>{const W=NA("ai-setup");if(W?.loginOutcomes){const Le=W.loginOutcomes,nt={};for(const[tt,ht]of Object.entries(Le))ht!=="pending"&&(nt[tt]=ht);Object.keys(nt).length>0&&Ee(nt)}},[]);const it=a.useCallback((W,Le)=>{Er(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[W]:Le}}}})},[b,x]);a.useEffect(()=>{const W=Object.entries(Ge).filter(([Le,nt])=>nt!=="pending");for(const[Le,nt]of W)it(Le,nt)},[Ge,it]),a.useEffect(()=>()=>{We.current&&clearInterval(We.current),Object.values(Ce.current).forEach(clearTimeout),Ce.current={}},[]);const mt=a.useCallback(W=>{Oe(W),Er(b,{completedSteps:x,stepData:{github:{skipped:W}}})},[b,x]),At=a.useCallback(W=>W==="complete"?-1:oi.indexOf(W),[]),It=a.useCallback(()=>{y(Le=>[...new Set([...Le,b])]),k(Le=>Le.filter(nt=>nt!==b)),js("onboarding:step-completed",{step:b}),b==="github"&&!Pe&&mt(!1);const W=At(b);W>=0&&W<oi.length-1&&v(oi[W+1])},[b,Pe,mt,At]),Dt=a.useCallback(()=>{k(Le=>[...new Set([...Le,b])]),vA(b),js("onboarding:step-skipped",{step:b}),b==="github"&&!Pe&&mt(!0);const W=At(b);W>=0&&W<oi.length-1&&v(oi[W+1])},[b,Pe,mt,At]),Ut=a.useCallback(()=>{const W=b;y(nt=>nt.filter(tt=>tt!==W)),k(nt=>nt.filter(tt=>tt!==W)),W==="github"&&!Pe&&mt(!1);const Le=At(b);Le>0&&v(oi[Le-1])},[b,Pe,mt,At]),jt=a.useCallback(()=>{Dt()},[Dt]),Pt=a.useCallback(async W=>{Ee(Le=>{const nt=Le[W];if(nt&&nt!=="pending"){const{[W]:tt,...ht}=Le;return ht}return Le}),U(Le=>{if(!(W in Le))return Le;const nt={...Le};return delete nt[W],nt}),Ee(Le=>({...Le,[W]:"pending"})),X(W),ke.current=0;try{const{url:Le,instructions:nt}=await Rx(W);nt?.trim()&&U(tt=>({...tt,[W]:nt})),window.open(qs(Le),"_blank"),We.current=setInterval(async()=>{if(ke.current++,ke.current>=qA){We.current&&(clearInterval(We.current),We.current=null),X(null),Ee(tt=>({...tt,[W]:"timeout"})),U(tt=>{if(!(W in tt))return tt;const ht={...tt};return delete ht[W],ht}),n("Login timed out. Please try again.","warning");return}try{const{providers:tt,ghCli:ht}=await Oa();w(tt),V(ht),tt.find(Et=>Et.id===W)?.authenticated&&(We.current&&(clearInterval(We.current),We.current=null),X(null),Ee(Et=>({...Et,[W]:"success"})),U(Et=>{if(!(W in Et))return Et;const fn={...Et};return delete fn[W],fn}),W==="github"&&mt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Le){Le instanceof Error&&Le.message.includes("already in progress")||Le&&typeof Le=="object"&&"status"in Le&&Le.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ee(tt=>({...tt,[W]:"failed"}))):(n(Le instanceof Error?Le.message:"Login failed","error"),Ee(tt=>({...tt,[W]:"failed"}))),X(null),U(tt=>{if(!(W in tt))return tt;const ht={...tt};return delete ht[W],ht})}},[n,mt]),He=a.useCallback(W=>{We.current&&(clearInterval(We.current),We.current=null),X(null),ke.current=0,Ee(Le=>({...Le,[W]:"cancelled"})),U(Le=>{if(!(W in Le))return Le;const nt={...Le};return delete nt[W],nt})},[]),ut=a.useCallback((W,Le)=>{de(tt=>({...tt,[W]:Le}));const nt=Ce.current[W];nt&&(clearTimeout(nt),delete Ce.current[W]),ge(tt=>{if(!tt[W])return tt;const ht={...tt};return delete ht[W],ht}),te(tt=>{if(!tt[W])return tt;const ht={...tt};return delete ht[W],ht})},[]),$t=a.useCallback(()=>{const W=$e.current;if(!W)return;const Le=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof W.scrollTo=="function"){W.scrollTo({top:0,behavior:Le?"auto":"smooth"});return}}catch{}W.scrollTop=0},[]),St=a.useCallback(async(W,Le)=>{const nt=(Le??Q[W]??"").trim(),tt=FA(W,nt);if(tt){ge(kt=>({...kt,[W]:tt}));return}const ht=Ce.current[W];ht&&(clearTimeout(ht),delete Ce.current[W]),X(W),ge(kt=>{const Et={...kt};return delete Et[W],Et}),te(kt=>{if(!kt[W])return kt;const Et={...kt};return delete Et[W],Et});try{await Ix(W,nt),await oe(),$t(),de(kt=>{const Et={...kt};return delete Et[W],Et}),ge(kt=>{if(!kt[W])return kt;const Et={...kt};return delete Et[W],Et}),te(kt=>({...kt,[W]:"✓ Key saved"})),Ce.current[W]=setTimeout(()=>{te(kt=>{if(!kt[W])return kt;const Et={...kt};return delete Et[W],Et}),delete Ce.current[W]},3e3),n("API key saved","success")}catch(kt){const Et=kt instanceof TypeError&&kt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":kt instanceof Error?kt.message:"Failed to save API key";ge(fn=>({...fn,[W]:Et})),te(fn=>{if(!fn[W])return fn;const fs={...fn};return delete fs[W],fs}),n(Et,"error")}finally{X(null)}},[Q,n,oe,$t]),Yt=a.useCallback(async W=>{X(W);try{await Px(W),await oe(),n("API key removed","success")}catch(Le){n(Le instanceof Error?Le.message:"Failed to clear API key","error")}finally{X(null)}},[n,oe]),we=a.useCallback(async W=>{X(W);try{await Tx(W),await oe(),n("Logged out","success")}catch(Le){n(Le instanceof Error?Le.message:"Logout failed","error")}finally{X(null)}},[n,oe]),et=a.useCallback(W=>{F(W)},[]),ct=a.useCallback(async()=>{try{const W={modelOnboardingComplete:!0};if(re){const Le=re.indexOf("/"),nt=Le!==-1?re.slice(0,Le):void 0,tt=Le!==-1?re.slice(Le+1):re,ht=fe.find(kt=>kt.id===tt);ht?(W.defaultProvider=ht.provider,W.defaultModelId=ht.id):nt&&tt&&(W.defaultProvider=nt,W.defaultModelId=tt)}await tn(W),jm()}catch{}},[re,fe,tn,jm]),ue=a.useCallback(async()=>{const W=[...new Set([...x,"first-task"])];ae(!0);try{await ct(),js("onboarding:completed",{completedSteps:W,skippedSteps:E}),y(W),k(Le=>Le.filter(nt=>nt!=="first-task")),v("complete")}finally{ae(!1)}},[ct,x,E]),A=a.useCallback(async()=>{if(!s)return;const W=S.trim();if(!W){D("Please enter a task description.");return}D(null),_(!0);let Le=!1;try{const nt=await sh({description:W},s);$(nt),N(!0),js("onboarding:first-task-created",{taskId:nt?.id}),n("Task created","success"),Le=!0}catch(nt){const tt=nt instanceof Error?nt.message:"Something went wrong creating your task. Please try again.";D(tt),n(tt,"error")}finally{_(!1)}Le&&ct()},[s,S,n,ct]),J=a.useCallback(async()=>{ae(!0);try{await ct()}finally{ae(!1)}js("onboarding:open-new-task",{}),r?.()},[ct,r]),Ve=a.useCallback(async()=>{if(Ke){ae(!0);try{await ct()}finally{ae(!1)}f(!1),e(),js("onboarding:open-github-import",{}),o?.()}},[ct,Ke,e,o]),dt=a.useCallback(async()=>{js("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:E}),ae(!0);try{await tn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[b,x,E,e]),yt=a.useCallback(()=>{js("onboarding:finished",{}),f(!1),e()},[e]),qt=a.useCallback(()=>{const W=l??G;W&&(ct(),c?.(W),e())},[l,G,ct,c,e]),wn=a.useCallback(()=>{ct(),e()},[ct,e]);if(!p)return null;const Ft=xe(),Dn=R.filter(W=>W.id!=="github"),qn=[...Dn].sort(Em),ms=qn.some(W=>!W.type||W.type==="oauth"),hn=qn.some(W=>W.type==="api_key"),Ln=Dn.filter(W=>W.authenticated),Nn=Ln.length>0,pn=!!s,Vn=b==="github"&&!Nn,cn=(()=>{if(!re)return"";const W=re.indexOf("/"),Le=W===-1?void 0:re.slice(0,W),nt=W===-1?re:re.slice(W+1),tt=fe.find(ht=>ht.id===nt&&(!Le||ht.provider===Le));return tt?.name?tt.name:Le?`${Kl(Le)} ${nt}`:re})(),Ct=[];if(pn?Ct.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Ct.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Nn){const W=Kl(Ln[0]?.id??"");Ct.push({label:"AI Provider",status:"connected",detail:`${W} connected — AI agents can work on tasks`})}else Dn.length>0&&Dn.some(W=>ee[W.id])?Ct.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Ct.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Ke?Ct.push({label:"GitHub",status:"connected",detail:Ne?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Se||Ae?Ct.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Ct.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),cn&&Ct.push({label:"Default Model",status:"connected",detail:cn});const xn=l??G,Wn=xn?.description?.split(`
616
- `)[0]?.trim()||xn?.title||"",vn=new Set(bl),Mn=qn.filter(W=>vn.has(W.id)).sort((W,Le)=>{const nt=bl.indexOf(W.id),tt=bl.indexOf(Le.id);return nt!==tt?nt-tt:Em(W,Le)}),hs=qn.filter(W=>W.authenticated&&!vn.has(W.id)),ps=qn.filter(W=>!W.authenticated&&!vn.has(W.id)),zn=W=>{if(W.id==="claude-cli"&&W.type==="cli")return t.jsx(pA,{authenticated:W.authenticated,onToggled:()=>{oe()}},W.id);if(W.type==="api_key"){const Le=Yl(W.id),nt=UA(W);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${W.id}`,className:`onboarding-provider-card${W.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${W.id}`,"aria-hidden":"true",children:t.jsx(ts,{provider:W.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Qm,{size:14,className:"onboarding-provider-key-icon"}),W.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Le.description}),t.jsx(Ye,{status:Fe(W)}),W.authenticated&&W.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",W.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(HA,{provider:W,apiKeyInfo:nt,inputValue:Q[W.id]??"",isSaving:z===W.id,error:Re[W.id],success:Me[W.id],isConnected:W.authenticated,onInputChange:ut,onSave:St,onClear:Yt})})]},W.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${W.id}`,className:`onboarding-provider-card${W.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${W.id}`,"aria-hidden":"true",children:t.jsx(ts,{provider:W.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:W.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Yl(W.id).description}),t.jsx(Ye,{status:Fe(W)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===W.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:W.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>He(W.id),children:"Cancel"})]}):W.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>we(W.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Pt(W.id),children:"Login"})}),z===W.id&&C[W.id]&&t.jsx("p",{className:"auth-login-instructions","data-testid":`onboarding-login-instructions-${W.id}`,children:C[W.id]}),Ge[W.id]==="timeout"&&z!==W.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ge[W.id]==="failed"&&z!==W.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},W.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(bn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Zn,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Vc,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Vc,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(en,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:dt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Tt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:le.map((W,Le)=>{const nt=Ze>Le,tt=x.includes(W.key)&&nt,ht=E.includes(W.key)&&!x.includes(W.key)&&nt,kt=tt||ht;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Le>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Le<=Ze?"done":""}`}),kt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===W.key?"active":""} ${tt?"done":""} ${ht?"skipped":""}`,onClick:()=>v(W.key),"aria-label":`Go back to ${W.label}`,title:`Review ${W.label}`,children:[t.jsx("span",{className:"step-number",children:tt?t.jsx(en,{size:14}):ht?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Le+1}),t.jsx("span",{className:"step-label",children:W.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===W.key?"active":""} ${tt?"done":""} ${ht?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:tt?t.jsx(en,{size:14}):ht?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Le+1}),t.jsx("span",{className:"step-label",children:W.label})]})]},W.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:$e,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!B&&R.length>0&&(()=>{const W=R.filter(kt=>kt.id!=="github"&&kt.authenticated).length,Le=R.filter(kt=>kt.id!=="github").length,nt=Object.keys(ee).filter(kt=>!R.find(Et=>Et.id===kt)?.authenticated).length;if(Le===0)return null;let tt="onboarding-provider-summary",ht="";return W>0?(tt+=" onboarding-provider-summary--connected",ht=`✓ ${W} of ${Le} provider${Le!==1?"s":""} connected`):nt>0?(tt+=" onboarding-provider-summary--skipped",ht=`${nt} provider${nt!==1?"s":""} skipped`):(tt+=" onboarding-provider-summary--none",ht="No providers connected yet"),t.jsx("div",{className:tt,"data-testid":"provider-summary",children:ht})})(),t.jsx(Fs,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),R.length>0&&!R.some(W=>W.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),B?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(at,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):R.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),Mn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Mn.map(W=>zn(W))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),hs.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),t.jsx("div",{className:"model-onboarding-providers",children:hs.map(W=>zn(W))})]}),t.jsx(Fs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:ps.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ps.map(W=>zn(W))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),ms&&t.jsx(Fs,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),hn&&t.jsx(Fs,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(Fs,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),fe.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(jn,{models:fe,value:re,onChange:et,placeholder:"Select a default model…",label:"Default model"})}),re&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",fe.find(W=>W.id===re)?.name??re]})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),t.jsx("div",{className:"onboarding-feature-list",children:t.jsxs("ul",{children:[t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"Without GitHub (available now):"})}),t.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),t.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),t.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"With GitHub (after connecting):"})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),Vn&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(Fs,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),Se?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(Zn,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(ze,{status:Ft})})]}),Pe&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>we("github"),children:"Disconnect"}))]}),(Ft==="not-connected"||Ft==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="github"?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>He("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Pt("github"),children:[t.jsx(Zn,{size:16}),"Connect"]}),z==="github"&&C.github&&t.jsx("p",{className:"auth-login-instructions","data-testid":"onboarding-login-instructions-github",children:C.github})]}),Ft==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Ne?"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."}),Ft==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:"Connection failed or timed out."}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:jt,children:"Skip for now"})]})]}),Ft==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Ft==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),t.jsx("div",{className:"onboarding-github-feedback-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt("github"),children:"Connect anyway"})})]}),Ft==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx(Zn,{size:48,className:"optional-icon"}),Ne?t.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."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:"Continue without GitHub →"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),pn?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(Fs,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),T&&xn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(en,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:xn.id}),Wn&&t.jsx("p",{className:"onboarding-task-created__description",children:Wn}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:qt,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:wn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[pn?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:S,onChange:W=>{j(W.target.value),D(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:A,disabled:P,"data-testid":"onboarding-first-task-submit",children:P?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),I&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:I}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(BA,{items:Ct}),pn&&t.jsxs(t.Fragment,{children:[t.jsx(Fs,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:J,disabled:ce,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Ht,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${Ke?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Ve,disabled:ce||!Ke,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Zn,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Ke&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(en,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:dt,disabled:ce,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:It,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ut,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:It,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ut,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:It,disabled:!pn,children:"Next →"})]}),b==="first-task"&&!T&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ut,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:ue,disabled:ce,children:ce?t.jsxs(t.Fragment,{children:[t.jsx(at,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:yt,children:[t.jsx(en,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function ef({toasts:e}){return t.jsx("div",{className:"toast-container",id:"toasts",children:e.map(n=>t.jsx("div",{className:`toast toast-${n.type}`,children:n.message},n.id))})}const WA=a.lazy(()=>Zt(()=>import("./SetupWizardModal-WdaR2eQQ.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),GA=a.lazy(()=>Zt(()=>import("./SettingsModal-BZLL2xAP.js"),__vite__mapDeps([11,1,12,13,14,0,2,15])).then(e=>({default:e.SettingsModal})));function KA(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Zt(()=>import("./SettingsModal-BZLL2xAP.js"),__vite__mapDeps([11,1,12,13,14,0,2,15]))},{timeout:1500})}function JA({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[b,v]=a.useState(null),x=p??c.closeSettings,y=a.useCallback(()=>{c.openNewTask()},[c]),E=a.useCallback(()=>{c.openGitHubImport()},[c]),k=a.useCallback(N=>{v(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),T=a.useCallback(async N=>{const S=await d.handleModalCreate(N);return c.modelOnboardingOpen&&v(S),S},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{KA()},[]),t.jsxs(t.Fragment,{children:[c.detailTask&&t.jsx(gi,{children:t.jsx(dM,{task:c.detailTask,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(gi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(GA,{onClose:x,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(mM,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(gi,{children:t.jsx(gM,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:d.handlePlanningTaskCreated,onTasksCreated:d.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(gi,{children:t.jsx(jM,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(LM,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(FM,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(r_,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(p_,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e}),c.schedulesOpen&&t.jsx(P_,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(gi,{children:t.jsx(z_,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:T,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(H_,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:N=>{const S=n.find(j=>j.id===N);S&&c.openDetailTask(S)}}),t.jsx(gi,{children:t.jsx(V_,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(gi,{children:t.jsx(sA,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(hA,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(WA,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(VA,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:y,onOpenGitHubImport:E,firstCreatedTask:b,onViewTask:k}),t.jsx(ef,{toasts:o,onRemove:l})]})}function YA({errorMessage:e,isRetrying:n,onRetry:s}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const Ql=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function QA(e,n){if(n==="ready")return"done";const s=Ql.findIndex(r=>r.id===n),i=Ql.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function XA({stage:e}){return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":"Loading Fusion dashboard","data-stage":e,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Ql.map(n=>{const s=QA(n.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${s}`,"data-testid":`dashboard-loader-step-${n.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:s==="done"?"✓":s==="active"?t.jsx(at,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const ZA=5e3;function eR(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function tR(e,n,s){let i=0,r=0,o=0,l=0,c=0;for(const u of e){switch(u.column){case"in-progress":i++,Fr(u,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}u.blockedBy&&u.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function nR(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await my(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},ZA),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=tR(e,s,i),f=eR(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const sR={planning:Bs,subtask:Si,mission_interview:es,milestone_interview:es,slice_interview:es},iR={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function aR({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const[o,l]=a.useState(!1),[c,u]=a.useState(new Set),d=a.useRef(null),m=a.useRef(new Map),h=a.useRef(null),{activeTabMap:g}=ra(),p=a.useMemo(()=>_i(),[]);if(a.useEffect(()=>{if(!o)return;const v=x=>{d.current&&!d.current.contains(x.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[o]),a.useEffect(()=>{const v=new Set,x=new Map;for(const y of e){const E=g.get(y.id),k=[y.status,y.updatedAt,E?.tabId??y.lockedByTab??"",E?.stale?"stale":"fresh"].join("|"),T=m.current.get(y.id);T&&T!==k&&v.add(y.id),x.set(y.id,k)}if(m.current=x,v.size!==0)return u(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{u(new Set),h.current=null},500),()=>{h.current&&(clearTimeout(h.current),h.current=null)}},[g,e]),e.length===0)return null;const f=e.length,b=s>0;return t.jsxs("div",{ref:d,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${b?" background-tasks-indicator__pill--attention":""}`,onClick:()=>l(v=>!v),title:`${f} background AI task${f!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(at,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Hc,{size:12}),t.jsxs("span",{children:["AI ",f]})]}),o&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(v=>{const x=sR[v.type],y=v.status==="generating",E=v.status==="awaiting_input",k=v.status==="error",T=g.get(v.id),N=T?.tabId??v.lockedByTab??null,S=!!(N&&N!==p&&!T?.stale),j=c.has(v.id);return t.jsxs("div",{className:`background-tasks-indicator__item${j?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:j?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:j?"translateY(-1px)":void 0},onClick:()=>{S&&!window.confirm("This session is active in another tab. Open anyway?")||(i(v),l(!1))},children:[k?t.jsx(ns,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(x,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:v.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[k?"Failed":iR[v.type],y&&" — generating...",E&&!S&&" — needs input",E&&S&&" — active in another tab"]})]}),y&&t.jsx(at,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),E&&!S&&t.jsx(Hc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),E&&S&&t.jsx(Zr,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:P=>{P.stopPropagation(),r(v.id)},title:"Dismiss",children:t.jsx(Tt,{size:12})})]},v.id)})})]})]})}function rR(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),i=n-s,r=Math.floor(i/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function oR(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:sn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Os};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:bn}}}function lR({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=nR(e,n,s,u),[f,b]=a.useState(!1),v=a.useMemo(()=>oR(h.executorState),[h.executorState]),x=a.useMemo(()=>rR(h.lastActivityAt),[h.lastActivityAt]),y=v.icon;return p?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(nc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(aR,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(E=>!E),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(kn,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(wi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const cR={planning:Bs,subtask:Si,mission_interview:es,milestone_interview:es,slice_interview:es},dR={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},vi=new Set;function uR({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(vi.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of vi){const x=f.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(vi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!vi.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{vi.add(f),l()},g=f=>{vi.delete(f.id),l(),n(f)},p=()=>{for(const f of c)vi.add(f.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(ns,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Tt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const b=cR[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(ns,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":dR[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(Tt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function mR({onResume:e}){const n=jA();if(!n)return null;const s=n.completedSteps.length,i=oi.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(Pn,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{js("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(sn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function hR({onOpenSettings:e,onOpenModelOnboarding:n}){const s=ta(),i=Yp(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let x=!1;return(async()=>{try{o(!0),c(!1);const[E,k]=await Promise.all([Oa(),ia()]);if(x)return;const T=E.providers??[],N=T.find(I=>I.id==="github"),j=!T.some(I=>I.id!=="github"&&I.authenticated),P=!k.defaultProvider&&!k.defaultModelId,_=N?!N.authenticated:!1;h({needsAiProvider:j,needsDefaultModel:P,needsGitHub:_})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const g=a.useCallback(()=>{yA(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.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:bn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Qm}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:Zn}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,f,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Bs,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(ns,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Tt,{size:16,"aria-hidden":!0})})]})}function pR({size:e=20}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function xl(e){return e>99?"99+":String(e)}function fR({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenMailbox:l,mailboxUnreadCount:c=0,onOpenGitManager:u,onOpenWorkflowSteps:d,onOpenSchedules:m,onOpenScripts:h,onToggleTerminal:g,onOpenFiles:p,onOpenGitHubImport:f,onOpenPlanning:b,onResumePlanning:v,activePlanningSessionCount:x=0,onOpenUsage:y,onRunScript:E,projectId:k,onViewAllProjects:T,showSkillsTab:N,experimentalFeatures:S}){const j=Za(),[P,_]=a.useState(!1),[I,D]=a.useState(!1),[G,$]=a.useState({}),[R,w]=a.useState(!1),H=a.useMemo(()=>Object.entries(G).sort(([re],[F])=>re.localeCompare(F)),[G]);a.useEffect(()=>{if(!I)return;let re=!1;return w(!0),Ya(k).then(F=>{re||$(F)}).catch(()=>{re||$({})}).finally(()=>{re||w(!1)}),()=>{re=!0}},[I,k]);const V=a.useCallback(()=>_(!1),[]),B=a.useCallback(re=>{V(),re?.()},[V]);if(a.useEffect(()=>{if(!P)return;const re=F=>{F.key==="Escape"&&_(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[P]),j!=="mobile"||i)return null;const M=x>0&&v?v:b,z=!!S?.roadmap,X=!!N,C=z&&(!X||e==="roadmaps"),U=X&&(!z||e!=="roadmaps"),fe=X&&!U,ie=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="roadmaps"&&!C||e==="skills"&&!U;return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(Ci,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(nn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(es,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(li,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsx(Vi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:xl(c)})]}),U&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="skills"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-skills",role:"tab","aria-selected":e==="skills",onClick:()=>n("skills"),children:[t.jsx(bn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),C&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":e==="roadmaps",onClick:()=>n("roadmaps"),children:[t.jsx(Cl,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ie?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>_(re=>!re),children:[t.jsx(wl,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:V}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>B(l),children:[t.jsx(Vi,{}),t.jsx("span",{children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:xl(c)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>B(o),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>B(u),children:[t.jsx(Us,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>B(g),children:[t.jsx(Hs,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>D(re=>!re),"aria-expanded":I,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(an,{size:14,className:`mobile-more-chevron${I?" mobile-more-chevron--open":""}`})})]}),I&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:R?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(at,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):H.length>0?t.jsxs(t.Fragment,{children:[H.map(([re,F])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${re}`,onClick:()=>{E&&E(re,F),V(),D(!1)},children:[t.jsx(sn,{size:14}),t.jsx("span",{children:re})]},re)),h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{V(),D(!1),h()},children:[t.jsx(As,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{V(),D(!1),h()},children:[t.jsx(As,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>B(p),children:[t.jsx(kn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>B(M),children:[t.jsx(Bs,{}),t.jsx("span",{children:"Planning"}),x>0&&t.jsx("span",{className:"mobile-more-item-badge",children:xl(x)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>B(d),children:[t.jsx(Ml,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>B(m),children:[t.jsx(wi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>B(f),children:[t.jsx(pR,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>B(y),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>B(T),children:[t.jsx(Ym,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>B(()=>n("documents")),children:[t.jsx(Ni,{}),t.jsx("span",{children:"Documents"})]}),fe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>B(()=>n("skills")),children:[t.jsx(bn,{}),t.jsx("span",{children:"Skills"})]}),z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>B(()=>n("roadmaps")),children:[t.jsx(Cl,{}),t.jsx("span",{children:"Roadmaps"})]}),S?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>B(()=>n("insights")),children:[t.jsx(Pn,{}),t.jsx("span",{children:"Insights"})]}),S?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>B(()=>n("memory")),children:[t.jsx(Rr,{}),t.jsx("span",{children:"Memory"})]}),S?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{B(()=>n("dev-server"))},children:[t.jsx(Xm,{size:14}),t.jsx("span",{children:"Dev Server"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>B(r),children:[t.jsx(za,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function gR({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(nn,{size:14,"aria-hidden":"true"}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}const Rc="__fn_agent__";function tf(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Mm(e,n,s){const i=typeof e=="string"?e.trim():"",r=tf(n,s),o=i||(r.modelProvider&&r.modelId?Rc:"");return o?{agentId:o,...r}:null}function vl(e,n,s){const i=tf(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function bR(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(i=>i!==null);return s.length>0?s:void 0}function _m(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:bR(e.metadata),createdAt:e.createdAt}}function xR(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,b]=a.useState(""),[v,x]=a.useState([]),[y,E]=a.useState(""),k=a.useRef(null),T=a.useRef(!1),N=a.useRef(""),S=a.useRef(""),j=a.useRef(null);a.useEffect(()=>{N.current=y},[y]);const P=a.useCallback(async B=>{const M={agentId:B.agentId};return B.modelProvider&&B.modelId&&(M.modelProvider=B.modelProvider,M.modelId=B.modelId),(await Sk(M,e)).session},[e]),_=a.useCallback(async(B,M,z)=>{const X=Mm(B,M,z);if(!X)return;const C=vl(X.agentId,X.modelProvider,X.modelId);o(!0);try{const{session:U}=await Nk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},e);if(U)i(U),S.current=C;else{const fe=await P(X);i(fe),S.current=C}}catch(U){console.error("[useQuickChat] Failed to initialize session:",U),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,P]),I=a.useCallback(async()=>{if(s){d(!0);try{const B=await gd(s.id,{limit:50},e);c(B.messages.map(_m))}catch(B){console.error("[useQuickChat] Failed to load messages:",B)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?I():c([])},[s,I]);const D=a.useCallback(async()=>{if(s){d(!0);try{const B=await gd(s.id,{limit:50},e);c(B.messages.map(_m))}catch(B){console.error("[useQuickChat] Failed to reload messages:",B)}finally{d(!1)}}},[s,e]),G=a.useCallback(async(B,M,z)=>{const X=Mm(B,M,z);if(!X)return;const C=vl(X.agentId,X.modelProvider,X.modelId);if(j.current=X,k.current&&(k.current.close(),k.current=null),p(""),b(""),x([]),h(!1),C===S.current&&s){await D();return}c([]),S.current=C,await _(X.agentId,X.modelProvider,X.modelId)},[_,D,s]),$=a.useCallback(async(B,M)=>{await G(Rc,B,M)},[G]),R=a.useCallback(async()=>{const B=j.current;if(!B)return;const M=vl(B.agentId,B.modelProvider,B.modelId);k.current&&(k.current.close(),k.current=null),p(""),b(""),x([]),h(!1),c([]),o(!0);try{const z=await P(B);i(z),S.current=M}catch(z){console.error("[useQuickChat] Failed to start a fresh session:",z),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,P]),w=a.useCallback(()=>{s&&(T.current=!0,k.current?.close(),k.current=null,Ck(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),H=a.useCallback(()=>{N.current="",E("")},[]),V=a.useCallback(B=>{if(!s||!B.trim())return;if(m){N.current=B,E(B);return}T.current=!1,k.current&&(k.current.close(),k.current=null);const z={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:B,createdAt:new Date().toISOString()};c(ie=>[...ie,z]),p(""),b(""),x([]),h(!0);let X="",C="",U=[];const fe={onThinking:ie=>{C+=ie,b(C)},onText:ie=>{X+=ie,p(X)},onToolStart:ie=>{U=[...U,{toolName:ie.toolName,args:ie.args,isError:!1,status:"running"}],x(U)},onToolEnd:ie=>{const re=[...U];for(let F=re.length-1;F>=0;F--){const ce=re[F];if(ce?.toolName===ie.toolName&&ce.status==="running"){re[F]={...ce,status:"completed",isError:ie.isError,result:ie.result},U=re,x(re);return}}U=[...re,{toolName:ie.toolName,isError:ie.isError,result:ie.result,status:"completed"}],x(U)},onDone:ie=>{const re={id:ie.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:C||void 0,toolCalls:U.length>0?U:void 0,createdAt:new Date().toISOString()};c(ce=>[...ce,re]),p(""),b(""),x([]),h(!1),k.current=null;const F=N.current.trim();F&&(N.current="",E(""),V(F))},onError:ie=>{if(p(""),b(""),x([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",ie),n?.("Failed to get response","error"),!T.current){const re=N.current.trim();re&&(N.current="",E(""),V(re))}D()}};k.current=Ek(s.id,B,fe,e)},[s,m,e,n,D]);return a.useEffect(()=>()=>{k.current&&(k.current.close(),k.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:V,stopStreaming:w,clearPendingMessage:H,switchSession:G,startModelChat:$,startFreshSession:R,loadMessages:I,reloadMessages:D}),[s,r,l,u,m,g,f,v,y,V,w,H,G,$,R,I,D])}function vR(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,b=n?.showSystemAgents??!1,v=await aa({...f,...g,includeEphemeral:g?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await ry(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Vs(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!Uk(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function yR({visible:e,position:n,files:s,selectedIndex:i,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const u=l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")+1):"",d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Km,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:d}),u&&t.jsx("span",{className:"file-mention-popup-item-path",children:u})]})]},l.path)})})]}):null}const kR=200;function jR(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((N,S)=>{if(S<0||S>N.length){r(!1);return}const j=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=S-1;P>=0;P--){if(N[P]==="#")if(P===0){const _=N.slice(P+1,S);u(P),l(_),f(0),r(!0);return}else{const _=N[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const I=N.slice(P+1,S);u(P),l(I),f(0),r(!0);return}r(!1);return}if(!j(N[P])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),E=a.useCallback(async N=>{if(!N.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const S=await fv(N,s,n);m(S.files),f(0)}catch(S){S.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{E(o)},kR),()=>{b.current&&clearTimeout(b.current)}},[o,i,E]);const k=a.useCallback((N,S)=>{if(!i||c<0)return S;const j=S.slice(0,c),P=S.slice(c+1),_=P.match(/[\s]|$/),I=_?_.index:P.length,D=P.slice(I);return`${j}#${N.path}${D}`},[i,c]),T=a.useCallback((N,S)=>{if(!i||d.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),f(j=>Math.min(j+1,d.length-1)),!0;case"ArrowUp":return N.preventDefault(),f(j=>Math.max(j-1,0)),!0;case"Enter":case"Tab":return d[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:x,selectFile:k,dismissMention:y,handleKeyDown:T}}const wR={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"},NR={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function SR(e){return`${e.name?.trim()||e.id} (${e.role})`}function CR(e){const n=e.trim(),s=n.indexOf("/");return!n||s<=0||s>=n.length-1?null:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function ER(e,n){return n?e?.name?.trim()?e.name.trim():n.modelId.replace(/[-_]/g," ").replace(/\s+/g," ").replace(/^\w/,s=>s.toUpperCase()).trim():null}function Ar(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function MR(e){if(!e)return null;const n=Object.entries(e);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}=${Ar(r,50)}`}).join(", ")}function _R(e){if(e===void 0)return null;if(typeof e=="string")return Ar(e,200);try{return Ar(JSON.stringify(e),200)}catch{return Ar(String(e),200)}}function Am(e,n=!1){return!e||e.length===0?null:t.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(zb,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),e.map((s,i)=>{const r=s.status==="running",o=s.status==="completed"&&s.isError,l=MR(s.args),c=_R(s.result),u=r?l:c?`result: ${c}`:l?`args: ${l}`:null,d=r?"running":o?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${o?" chat-tool-call--error":""}`,open:r,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:s.toolName}),u&&t.jsx("span",{className:"chat-tool-call-preview",title:u,children:u}),t.jsx("span",{className:"chat-tool-call-status-text",children:d})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[l&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:l})]}),c&&t.jsxs("div",{className:`chat-tool-call-row${o?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:c})]})]})]},`${s.toolName}-${i}`)})]})}const AR={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"quick-chat-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"quick-chat-markdown-table",children:e})};function RR(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}function TR(e,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,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,E=window.innerWidth>768?s():0,k=window.innerWidth-v-x,T=window.innerHeight-v-x-y-E;return{x:Math.max(x,Math.min(k,b.x)),y:Math.max(x,Math.min(T,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,E=u.current.y-x,k=m({x:y,y:E});o(k)}},[l,m]),f=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function IR({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=vR(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?we=>{r?.(typeof we=="function"?we(p):we)}:h,[b,v]=a.useState("agent"),[x,y]=a.useState(""),[E,k]=a.useState([]),[T,N]=a.useState(!1),[S,j]=a.useState(""),[P,_]=a.useState(""),[I,D]=a.useState(""),[G,$]=a.useState(!1),[R,w]=a.useState(0),[H,V]=a.useState(-1),[B,M]=a.useState(!0),[,z]=a.useState(!1),[X,C]=a.useState({top:0,left:0}),U=jR({projectId:e}),fe=a.useCallback(we=>{if(!we||!U.mentionActive)return;const et=we.getBoundingClientRect();C({top:et.top-260,left:et.left+8})},[U.mentionActive]),ie=a.useRef(!1),re=a.useRef(!1),F=a.useRef(""),ce=a.useRef(0),ae=a.useRef(null),{position:Q,isDragging:de,handlePointerDown:Re,handlePointerMove:ge,handlePointerUp:Me}=TR(e,ie),{activeSession:te,messages:Ce,isStreaming:$e,streamingText:We,streamingThinking:Ge,streamingToolCalls:Ee,sessionsLoading:Ae,messagesLoading:Oe,sendMessage:ke,stopStreaming:De,pendingMessage:se,clearPendingMessage:K,switchSession:me,startModelChat:ee,startFreshSession:he}=xR(e,n),le=a.useRef(null),Ie=a.useRef(null),Ze=a.useRef(null),rt=a.useRef(null),oe=a.useMemo(()=>CR(S),[S]),Z=a.useMemo(()=>E.find(we=>`${we.provider}/${we.id}`===S)??null,[E,S]),pe=a.useMemo(()=>ER(Z,oe),[Z,oe]),Se=a.useMemo(()=>b==="model"?oe?`${Rc}::${oe.modelProvider}/${oe.modelId}`:"":x?`${x}::`:"",[b,oe,x]),Pe=b==="agent"?!!x:!!oe;a.useEffect(()=>{if(d.length===0){y(""),v("model");return}d.some(et=>et.id===x)||y(d[0]?.id??"")},[d,x]),a.useEffect(()=>{!p||re.current||(re.current=!0,N(!0),ss().then(we=>{const et=we.models??[];if(k(et),d.length===0&&et.length>0&&!S){const ct=et[0];ct&&j(`${ct.provider}/${ct.id}`)}}).catch(we=>{console.error("[QuickChatFAB] Failed to load models:",we),k([])}).finally(()=>{N(!1)}))},[p,d.length,S]),a.useEffect(()=>{if(!p){F.current="";return}if(!Se){F.current="";return}if(Se!==F.current){if(F.current=Se,b==="model"&&oe){ee(oe.modelProvider,oe.modelId);return}b==="agent"&&x&&me(x)}},[p,b,oe,x,Se,ee,me]),a.useEffect(()=>{p||($(!1),D(""),V(-1))},[p]);const ye=a.useCallback(we=>{y(we)},[]),Ke=a.useCallback(we=>{j(we)},[]),Ne=a.useCallback(()=>{!Pe||Ae||he()},[Pe,Ae,he]),Fe=a.useMemo(()=>d.find(we=>we.id===x)??null,[d,x]),Ye=a.useMemo(()=>{const we=I.trim().toLowerCase();return we?d.filter(et=>et.name.toLowerCase().includes(we)):d},[d,I]),xe=a.useMemo(()=>{const we=new Map;for(const et of d)we.set(et.name.toLowerCase(),et);return we},[d]);a.useEffect(()=>{w(0)},[I,G]),a.useEffect(()=>()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),a.useEffect(()=>{if(!p)return;const we=ct=>{const ue=ct.target;le.current?.contains(ue)||Ie.current?.contains(ue)||ue.closest(".model-combobox-dropdown--portal")||f(!1)},et=ct=>{ct.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",we),document.addEventListener("keydown",et),()=>{document.removeEventListener("mousedown",we),document.removeEventListener("keydown",et)}},[p,f]),a.useEffect(()=>{if(!p)return;const we=Ze.current;we&&(we.scrollTop=we.scrollHeight)},[Ce,We,Ge,p]);const ze=a.useMemo(()=>b==="agent"?Fe?`Message ${Fe.name||Fe.id}`:"Select an agent to start chatting":pe?`Message ${pe}`:"Select a model to start chatting",[b,Fe,pe]),be=!Pe||!te||Ae,Qe=se.length>50?`${se.slice(0,50)}…`:se,it=a.useCallback(()=>{const we=P.trim();!we||be||(_(""),$(!1),D(""),V(-1),ke(we))},[ke,be,P]),mt=a.useCallback((we,et)=>{const ct=RR(we,et);if(ct){$(!0),D(ct.filter),V(ct.start);return}$(!1),D(""),V(-1)},[]),At=a.useCallback(we=>{const et=rt.current;if(!et||H<0)return;const ct=et.selectionStart??ce.current,ue=et.selectionEnd??ct,A=Math.max(ct,ue),J=Math.min(H,A),dt=`${`@${we.name.replace(/\s+/g,"_")}`} `,yt=P.slice(0,J)+dt+P.slice(A),qt=J+dt.length;_(yt),$(!1),D(""),w(0),V(-1),window.requestAnimationFrame(()=>{rt.current&&(rt.current.focus(),rt.current.setSelectionRange(qt,qt))})},[H,P]),It=a.useCallback(we=>{const et=we.target.value,ct=we.target.selectionStart??et.length;ce.current=ct,_(et),mt(et,ct),U.detectMention(et,ct),z(U.mentionActive),U.mentionActive&&fe(we.target)},[mt,U,fe]),Dt=a.useCallback(()=>{ae.current!==null&&window.clearTimeout(ae.current),ae.current=window.setTimeout(()=>{$(!1),D(""),V(-1),z(!1),U.dismissMention(),ae.current=null},120)},[U]),Ut=a.useCallback(()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),jt=a.useCallback(we=>{const et=we.currentTarget,ct=et.selectionStart??et.value.length;ce.current=ct,mt(et.value,ct),U.detectMention(et.value,ct),z(U.mentionActive),U.mentionActive&&fe(et)},[mt,U,fe]),Pt=a.useCallback(we=>{we.key!=="Escape"&&jt(we)},[jt]),He=a.useCallback(we=>{const et=/@([\w-]+)/g,ct=[];let ue=0,A=et.exec(we);for(;A;){const[J,Ve=""]=A,dt=A.index;dt>ue&&ct.push(we.slice(ue,dt));const yt=Ve.replace(/_/g," ").toLowerCase(),qt=xe.get(yt);qt?ct.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",qt.name.replace(/\s+/g,"_")]},`${qt.id}-${dt}`)):ct.push(J),ue=dt+J.length,A=et.exec(we)}return ue<we.length&&ct.push(we.slice(ue)),ct.length===0?we:ct},[xe]),ut=a.useCallback(we=>B?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ei,{remarkPlugins:[ti],components:AR,children:we})}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:we}),[B]),$t=a.useCallback(we=>{if(ce.current=we.currentTarget.selectionStart??ce.current,U.mentionActive&&U.files.length>0){if(U.handleKeyDown(we,P),we.key==="Enter"||we.key==="Tab"){const et=U.files[U.selectedIndex];if(et){const ct=U.selectFile(et,P);_(ct),U.dismissMention(),z(!1)}}return}if(G&&we.key==="ArrowDown"){we.preventDefault(),Ye.length>0&&w(et=>(et+1)%Ye.length);return}if(G&&we.key==="ArrowUp"){we.preventDefault(),Ye.length>0&&w(et=>et===0?Ye.length-1:et-1);return}if(G&&we.key==="Enter"){we.preventDefault();const et=Ye[R]??Ye[0];et&&At(et);return}if(G&&we.key==="Escape"){we.preventDefault(),we.stopPropagation(),$(!1),D(""),V(-1);return}we.key!=="Enter"||we.shiftKey||(we.preventDefault(),it())},[G,Ye,R,At,it,U,P]),St=a.useCallback(()=>{if(ie.current){ie.current=!1;return}f(we=>!we)},[f]),Yt=Q.y+60;return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Ie,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":de?"true":"false",style:{right:Q.x,bottom:Q.y},onPointerDown:Re,onPointerMove:ge,onPointerUp:Me,onClick:St,children:t.jsx(li,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:le,"data-testid":"quick-chat-panel",style:{right:Q.x,bottom:Yt},children:[t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{style:NR,children:[t.jsx("h3",{children:"Quick Chat"}),pe&&t.jsx("span",{style:wR,"data-testid":"quick-chat-model-tag",title:pe,children:pe})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsxs("div",{className:"quick-chat-render-mode-toggle",role:"group","aria-label":"Assistant response render mode",children:[t.jsx("button",{type:"button",className:`quick-chat-render-mode-btn${B?" quick-chat-render-mode-btn--active":""}`,"data-testid":"quick-chat-render-mode-markdown","aria-pressed":B,"aria-label":"Render assistant responses as markdown",onClick:()=>M(!0),children:"Markdown"}),t.jsx("button",{type:"button",className:`quick-chat-render-mode-btn${B?"":" quick-chat-render-mode-btn--active"}`,"data-testid":"quick-chat-render-mode-plain","aria-pressed":!B,"aria-label":"Render assistant responses as plain text",onClick:()=>M(!1),children:"Plain"})]}),t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:Ne,disabled:!Pe||Ae,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Tt,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{v("agent"),j("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{v("model"),y("")},children:"Model"})]}),b==="agent"&&d.length>0&&t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),t.jsx("select",{id:"quick-chat-agent-select",value:x,onChange:we=>ye(we.target.value),"data-testid":"quick-chat-agent-select",children:d.map(we=>t.jsx("option",{value:we.id,children:SR(we)},we.id))})]}),b==="model"&&t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[t.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),t.jsx(jn,{id:"quick-chat-model-override",models:E,value:S,onChange:Ke,label:"Select model override",placeholder:T?"Loading models…":"Select a model",disabled:T||E.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ze,"data-testid":"quick-chat-messages",children:Ae||Oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ce.length===0&&!We&&!Ge&&!$e?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ce.map(we=>{const et=we.role==="user";return t.jsxs("div",{className:`quick-chat-panel-message ${et?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${we.id}`,children:[et?t.jsx("p",{children:He(we.content)}):ut(we.content),Am(we.toolCalls,!0)]},we.id)}),$e&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[We?t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:ut(We)}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ge?"Thinking…":"Connecting…"}),Am(Ee,!0),Ge&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:Ge})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:rt,type:"text",value:P,onChange:It,onKeyDown:$t,onKeyUp:Pt,onClick:jt,onBlur:Dt,onFocus:Ut,placeholder:ze,disabled:be,"data-testid":"quick-chat-input"}),t.jsx(gR,{agents:d,filter:I,highlightedIndex:R,visible:G,onSelect:At,position:"above"}),t.jsx(yR,{visible:U.mentionActive&&!G,position:X,files:U.files,selectedIndex:U.selectedIndex,onSelect:we=>{const et=U.selectFile(we,P);_(et),U.dismissMention(),z(!1),rt.current?.focus()},loading:U.loading}),se&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Qe}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:K,children:"×"})]})]}),$e?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:De,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(os,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void it(),disabled:be||P.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(yi,{size:16})})]})]})]})}function Ea(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Rm(e){return e.status==="generating"||e.status==="awaiting_input"}function Ma(e){return e==="complete"||e==="error"}function PR(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=ra(),d=a.useCallback(()=>{fh(e).then(p=>{const f=p.filter(v=>{const x=Ea(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of f)b.set(v.id,Ea(v.updatedAt));i.current=b,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(x<y)continue;const E=r.current.get(v.sessionId);if(E!==void 0&&x<=E)continue;if(E!==void 0&&x>E&&!Ma(v.status)&&r.current.delete(v.sessionId),Ma(v.status)){b.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,x);continue}const k=b.get(v.sessionId),T=v.type??k?.type,N=v.title??k?.title;if(!k&&(!T||!N))continue;const S={id:v.sessionId,type:T??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??k?.projectId??e??null,lockedByTab:v.owningTabId??k?.lockedByTab??null,updatedAt:v.updatedAt??k?.updatedAt??new Date(x).toISOString()},j=b.get(v.sessionId);(!j||j.status!==S.status||j.title!==S.title||j.type!==S.type||j.projectId!==S.projectId||j.lockedByTab!==S.lockedByTab||j.updatedAt!==S.updatedAt)&&(b.set(v.sessionId,S),i.current.set(v.sessionId,x),f=!0)}return f?[...b.values()].sort((v,x)=>Ea(x.updatedAt)-Ea(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const x=JSON.parse(v.data),y=Ea(x.updatedAt)||Date.now();s(E=>{const k=i.current.get(x.id)??0;if(y<k)return E;const T=r.current.get(x.id);if(T!==void 0&&y<=T)return E;if(T!==void 0&&y>T&&!Ma(x.status)&&r.current.delete(x.id),i.current.set(x.id,y),Ma(x.status))return E.filter(S=>S.id!==x.id);const N=E.findIndex(S=>S.id===x.id);if(N>=0){const S=[...E];return S[N]=x,S}return Rm(x)?[x,...E]:E}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),Ma(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data);s(y=>y.filter(E=>E.id!==x)),i.current.delete(x),r.current.delete(x)}catch{}};return Vs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":b}})},[c,l,e]);const m=a.useCallback(async p=>{const b=n.find(k=>k.id===p)?.type,v=_i();let x=!1,y=!1;if(b==="planning")try{await rh(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${p}: locked by another tab`))}else if(b==="subtask")try{await ch(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${p}: locked by another tab`))}else if(b==="mission_interview")try{await ph(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&(y=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${p}: locked by another tab`))}if(y)return;x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const E=Date.now();r.current.set(p,E),i.current.set(p,Math.max(i.current.get(p)??0,E)),c({sessionId:p,status:"complete",timestamp:E});try{await hk(p)}catch{}s(k=>k.filter(T=>T.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Rm(p)),[n]),g=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:g,dismissSession:m,refresh:d}}function Rn(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Tm(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function $R(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=a.useCallback(async R=>{const w=++m.current,H=n,V=R?.searchQueryOverride??s,B=R?.includeArchivedOverride??u.current;try{const M=await ix(void 0,void 0,H,V,B);if(m.current!==w||n!==H)return;o(M.map(Rn)),f.current=Date.now()}catch{if(m.current!==w||n!==H)return;if(R?.clearOnError){o([]);return}o(M=>M)}},[n,s]);p.current=y;const E=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const R=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(R)},[s]),a.useEffect(()=>{y({clearOnError:!0});const R=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-h.current<x||(h.current=w,y())};return document.addEventListener("visibilitychange",R),()=>{document.removeEventListener("visibilitychange",R)}},[y]),a.useEffect(()=>{if(i===!1)return;const R=b.current,w=n?`?projectId=${encodeURIComponent(n)}`:"",H=()=>b.current!==R;let V=!0;const B=fe=>{if(H())return;const ie=Rn(JSON.parse(fe.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(re=>re.some(F=>F.id===ie.id)?re:[...re,ie])},M=fe=>{if(H())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie,to:re}=JSON.parse(fe.data),F=Rn(ie);o(ce=>ce.map(ae=>ae.id===F.id?{...F,column:re}:ae)),f.current=Date.now()},z=fe=>{if(H())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=Rn(JSON.parse(fe.data));o(re=>re.map(F=>{if(F.id!==ie.id||Tm(ie.updatedAt,F.updatedAt)<0)return F;if(F.column===ie.column)return ie;const ae=Tm(F.columnMovedAt,ie.columnMovedAt);return F.columnMovedAt&&!ie.columnMovedAt?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ae>0?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ie})),f.current=Date.now()},X=fe=>{if(H())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=Rn(JSON.parse(fe.data));o(re=>re.filter(F=>F.id!==ie.id))},C=fe=>{if(H())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie}=JSON.parse(fe.data),re=Rn(ie);o(F=>F.map(ce=>ce.id===re.id?{...re,column:"done"}:ce))},U=Vs(`/api/events${w}`,{events:{"task:created":B,"task:moved":M,"task:updated":z,"task:deleted":X,"task:merged":C},onReconnect:()=>{V&&(H()||p.current())}});return()=>{V=!1,U()}},[n,i]);const k=a.useCallback(async R=>{const w=Rn(await sh(R,n));return o(H=>H.some(V=>V.id===w.id)?H:[...H,w]),w},[n]),T=a.useCallback(async(R,w)=>Rn(await rx(R,w,n)),[n]),N=a.useCallback(async R=>Rn(await ih(R,n)),[n]),S=a.useCallback(async R=>Rn(await ox(R,n)),[n]),j=a.useCallback(async R=>lx(R,n),[n]),P=a.useCallback(async R=>Rn(await cx(R,n)),[n]),_=a.useCallback(async R=>{const w=Rn(await dx(R,n));return o(H=>H.some(V=>V.id===w.id)?H:[...H,w]),w},[n]),I=a.useCallback(async(R,w)=>{const H=d.current.find(B=>B.id===R),V=H?{...H,...w,updatedAt:new Date().toISOString()}:void 0;V&&o(B=>B.map(M=>M.id===R?V:M));try{const B=Rn(await Qs(R,w,n));return o(M=>M.map(z=>z.id===R?B:z)),B}catch(B){throw H&&o(M=>M.map(z=>z.id===R?H:z)),B}},[n]),D=a.useCallback(async R=>{const w=Rn(await mx(R,n));return o(H=>H.map(V=>V.id===R?w:V)),w},[n]),G=a.useCallback(async R=>{const w=Rn(await hx(R,n));return o(H=>H.map(V=>V.id===R?w:V)),w},[n]),$=a.useCallback(async()=>{const w=(await px(n)).map(Rn);return o(H=>H.map(V=>w.find(M=>M.id===V.id)||V)),w},[n]);return{tasks:r,createTask:k,moveTask:T,pauseTask:N,deleteTask:S,mergeTask:j,retryTask:P,duplicateTask:_,updateTask:I,archiveTask:D,unarchiveTask:G,archiveAllDone:$,loadArchivedTasks:E,includeArchived:l,lastFetchTimeMs:f.current}}const DR=5e3,LR=1e3;function zR(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await dd();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const b=performance.now();try{const v=await dd(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),Ta("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),Ta("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<LR||(c.current=b,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},DR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await uy(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await fy(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await uh(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const FR=1e4,OR=1e3;function UR(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const p=await ud();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await ud();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<OR||(c.current=v,u())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},FR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await oy(p);return n(b=>[...b,f]),f},[]),m=a.useCallback(async(p,f)=>{const b=await ly(p,f);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await cy(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await dy(p);n(b=>b.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const BR="kb-dashboard-current-project";function HR(e){return e??"local"}function qR(e,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[o,l]=a.useState(!0),c=a.useRef(!1),u=a.useRef(!1),d=a.useRef(null),m=HR(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ia();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(BR);if(x){const y=JSON.parse(x);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await tn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,tn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,tn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,tn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const nf=a.createContext(null);function VR({children:e}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),o=a.useCallback(c=>{const u=r.current.get(c);u!==void 0&&(clearTimeout(u),r.current.delete(c)),s(d=>d.filter(m=>m.id!==c))},[]),l=a.useCallback((c,u="info")=>{const d=i.current++;s(h=>[...h,{id:d,message:c,type:u}]);const m=setTimeout(()=>o(d),4e3);r.current.set(d,m)},[o]);return a.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),Um.createElement(nf.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function WR(){const e=a.useContext(nf);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const sf="kb-dashboard-theme-mode",af="kb-dashboard-color-theme",rf=[...Fk],Xl="theme-data",yl="theme-data.css";function GR(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${yl}`:e.replace(/\/[^/]+$/,`/${yl}`):`/${yl}`}const Ns=typeof window<"u",KR=Ns?a.useLayoutEffect:a.useEffect;function of(e){return e==="dark"||e==="light"||e==="system"}function Im(){if(!Ns)return"dark";try{const e=localStorage.getItem(sf);if(of(e))return e}catch{}return"dark"}function Pm(){if(!Ns)return"default";try{const e=localStorage.getItem(af);if(e&&rf.includes(e))return e}catch{}return"default"}function $m(e){if(Ns)try{localStorage.setItem(sf,e)}catch{}}function Dm(e){if(Ns)try{localStorage.setItem(af,e)}catch{}}function JR(e,n){return e==="system"?n?"dark":"light":e}function YR(e,n,s){if(!Ns)return;const i=JR(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Lm(){if(!Ns)return;const e=GR(),n=document.getElementById(Xl);if(n){n.href!==e&&(n.href=e),n.parentNode===document.head&&document.head.lastChild!==n&&document.head.appendChild(n);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Xl,document.head.appendChild(s)}function zm(){if(!Ns)return;const e=document.getElementById(Xl);e&&e.remove()}function QR(){const[e,n]=a.useState(()=>Im()),[s,i]=a.useState(()=>Pm()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ns?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),u=a.useRef(e),d=a.useRef(s),m=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{u.current=e},[e]),a.useEffect(()=>{d.current=s},[s]),a.useEffect(()=>{if(!Ns||!r)return;let f=!1;return ia().then(b=>{f||(of(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),Im()!==b.themeMode&&$m(b.themeMode)),b.colorTheme&&rf.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Pm()!==b.colorTheme&&Dm(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ns)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{c(v.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),KR(()=>{YR(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ns||r||(s!=="default"?Lm():zm())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),$m(f),tn({themeMode:f}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),Dm(f),f!=="default"?Lm():zm(),tn({colorTheme:f}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function XR(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(void 0),[v,x]=a.useState(null),[y,E]=a.useState("definition"),[k,T]=a.useState(!1),[N,S]=a.useState(void 0),[j,P]=a.useState(!1),[_,I]=a.useState(!1),[D,G]=a.useState(!1),[$,R]=a.useState(!1),[w,H]=a.useState(void 0),[V,B]=a.useState(!1),[M,z]=a.useState("project"),[X,C]=a.useState(!1),[U,fe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),[ae,Q]=a.useState(!1),[de,Re]=a.useState(!1),[ge,Me]=a.useState(!1),te=!!(v||k||s||r||m||$||V||X||U||ie||ae||F||D||j||_||de||ge),Ce=a.useCallback(()=>i(!0),[]),$e=a.useCallback(()=>i(!1),[]),We=a.useCallback(()=>o(!0),[]),Ge=a.useCallback(we=>{c(we),o(!0)},[]),Ee=a.useCallback(()=>{const we=n[0];we&&(d(we.id),o(!0))},[n]),Ae=a.useCallback(we=>{d(we),o(!0)},[]),Oe=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ke=a.useCallback(we=>{p(we),h(!0)},[]),De=a.useCallback(we=>{b(we),h(!0)},[]),se=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),K=a.useCallback((we,et="definition")=>{x(we),E(et)},[]),me=a.useCallback(we=>{x(we),E("changes")},[]),ee=a.useCallback(we=>{x(et=>et&&{...et,...we})},[]),he=a.useCallback(()=>{x(null)},[]),le=a.useCallback(we=>{S(we),T(!0)},[]),Ie=a.useCallback(()=>{T(!1),S(void 0)},[]),Ze=a.useCallback(()=>P(!0),[]),rt=a.useCallback(()=>P(!1),[]),oe=a.useCallback(()=>I(!0),[]),Z=a.useCallback(()=>I(!1),[]),pe=a.useCallback(()=>G(!0),[]),Se=a.useCallback(()=>G(!1),[]),Pe=a.useCallback(()=>{R(we=>!we)},[]),ye=a.useCallback(()=>{R(!1),H(void 0)},[]),Ke=a.useCallback(()=>B(!0),[]),Ne=a.useCallback(()=>B(!1),[]),Fe=a.useCallback(we=>{z(we)},[]),Ye=a.useCallback(()=>C(!0),[]),xe=a.useCallback(()=>C(!1),[]),ze=a.useCallback(()=>fe(!0),[]),be=a.useCallback(()=>fe(!1),[]),Qe=a.useCallback(()=>re(!0),[]),it=a.useCallback(()=>re(!1),[]),mt=a.useCallback(()=>ce(!0),[]),At=a.useCallback(()=>ce(!1),[]),It=a.useCallback(()=>Q(!0),[]),Dt=a.useCallback(()=>Q(!1),[]),Ut=a.useCallback(async(we,et)=>{Q(!1),H(et),R(!0)},[]),jt=a.useCallback(()=>Re(!0),[]),Pt=a.useCallback(()=>Re(!1),[]),He=a.useCallback(()=>Me(!0),[]),ut=a.useCallback(()=>Me(!1),[]),$t=a.useCallback((we,et)=>{et(`Created ${we.id} from planning mode`,"success"),o(!1),c(null)},[]),St=a.useCallback((we,et)=>{const ct=we.map(ue=>ue.id).join(", ");et(`Created ${ct} from planning mode`,"success"),o(!1),c(null)},[]),Yt=a.useCallback((we,et)=>{const ct=we.map(ue=>ue.id).join(", ");et(`Created ${ct} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:k,settingsInitialSection:N,schedulesOpen:j,githubImportOpen:_,usageOpen:D,terminalOpen:$,terminalInitialCommand:w,filesOpen:V,fileBrowserWorkspace:M,activityLogOpen:X,gitManagerOpen:U,workflowStepsOpen:ie,agentsOpen:F,scriptsOpen:ae,setupWizardOpen:de,modelOnboardingOpen:ge,anyModalOpen:te,openNewTask:Ce,closeNewTask:$e,openPlanning:We,openPlanningWithInitialPlan:Ge,resumePlanning:Ee,openPlanningWithSession:Ae,closePlanning:Oe,openSubtaskBreakdown:ke,openSubtaskWithSession:De,closeSubtask:se,openDetailTask:K,openDetailWithChangesTab:me,updateDetailTask:ee,closeDetailTask:he,openSettings:le,closeSettings:Ie,openSchedules:Ze,closeSchedules:rt,openGitHubImport:oe,closeGitHubImport:Z,openUsage:pe,closeUsage:Se,toggleTerminal:Pe,closeTerminal:ye,openFiles:Ke,closeFiles:Ne,setFileWorkspace:Fe,openActivityLog:Ye,closeActivityLog:xe,openGitManager:ze,closeGitManager:be,openWorkflowSteps:Qe,closeWorkflowSteps:it,openAgents:mt,closeAgents:At,openScripts:It,closeScripts:Dt,runScript:Ut,openSetupWizard:jt,closeSetupWizard:Pt,openModelOnboarding:He,closeModelOnboarding:ut,onPlanningTaskCreated:$t,onPlanningTasksCreated:St,onSubtaskTasksCreated:Yt}}function ZR(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState({}),[E,k]=a.useState(!1),[T,N]=a.useState(!1),[S,j]=a.useState(!1),[P,_]=a.useState(!1),I=a.useCallback(async()=>{const[w,H]=await Promise.allSettled([bx(e),no(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),H.status==="fulfilled"){const V=H.value;l(!!V.autoMerge),u(!!V.globalPause),m(!!V.enginePaused),v(!!V.prAuthAvailable),g(V.taskStuckTimeoutMs),f(V.showQuickChatFAB===!0),y(V.experimentalFeatures??{});const B=V.experimentalFeatures??{};k(B.insights===!0),N(B.roadmap===!0),j(B.memoryView===!0),_(B.devServerView===!0||B.devServer===!0)}},[e]);a.useEffect(()=>{I()},[I]);const D=a.useCallback(async()=>{const w=!o;l(w);try{await or({autoMerge:w},e)}catch{l(!w)}},[o,e]),G=a.useCallback(async()=>{const w=!c;u(w);try{await or({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{u(!w)}},[c,e]),$=a.useCallback(async()=>{const w=!d;m(w);try{await or({enginePaused:w},e)}catch{m(!w)}},[d,e]),R=a.useCallback(async()=>{const w=!p;f(w);try{await or({showQuickChatFAB:w},e)}catch{f(!w)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:x,insightsEnabled:E,roadmapEnabled:T,memoryEnabled:S,devServerEnabled:P,toggleAutoMerge:D,toggleGlobalPause:G,toggleEnginePause:$,toggleShowQuickChatFAB:R,refresh:I}}function eT(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,Dr(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function tT(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{ss().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await tn({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await tn({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function nT({projectId:e,openModelOnboarding:n,openSettings:s}){const i=a.useRef(!1);a.useEffect(()=>{if(i.current)return;i.current=!0;let r=!1,o=!1;Oa().then(({providers:l})=>{const c=l.some(d=>d.authenticated);if(l.length>0&&!c||l.length>0&&c)return ia().then(d=>{const m=!!(d.defaultProvider&&d.defaultModelId);(d.modelOnboardingComplete===!1||d.modelOnboardingComplete===void 0)&&(!c||!m)&&!ta()?r=!0:!c&&!ta()&&(o=!0)})}).then(()=>{r?(js("onboarding:auto-triggered",{trigger:"first-run"}),n()):o&&(js("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[e,n,s])}const sT=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function Fm(e){return e!==null&&sT.includes(e)}function iT(e){return e==="devserver"?"dev-server":e}function aT(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[g,p]=a.useState(()=>{const x=En("kb-dashboard-task-view");return Fm(x)?x:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=En("kb-dashboard-task-view",r?.id);if(Fm(x)){const y=!f.current&&x==="devserver";p(y?"devserver":iT(x))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{cs("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(u),E=x[(y+1)%x.length];d(E)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function rT(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(j=>{n(j),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(j=>{h(),n(j),i("project"),u(`Project ${j.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),E=a.useCallback(async j=>{try{await hy(j.id),u(`Project ${j.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${j.name}`,"error")}},[u,o]),k=a.useCallback(async j=>{try{await py(j.id),u(`Project ${j.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${j.name}`,"error")}},[u,o]),T=a.useCallback(async j=>{try{await uh(j.id),u(`Project ${j.name} removed`,"success"),r?.id===j.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${j.name}`,"error")}},[r,s,i,u,o]),N=a.useCallback(async j=>{try{await l(j)}catch{u("Failed to update favorites","error")}},[l,u]),S=a.useCallback(async j=>{try{await c(j)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:E,handleResumeProject:k,handleRemoveProject:T,handleToggleFavorite:N,handleToggleModelFavorite:S}}function oT(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function lT(e){return io("/health",{nodeId:e})}async function cT(e){return io("/projects",{nodeId:e})}async function dT(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),io(`/tasks?${i.toString()}`,{nodeId:e})}async function uT(e,n){return io(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function DP(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function LP(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function zP(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function FP(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function mT(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const x=new AbortController;f.current=x,h(!0),p(null);try{const y=[lT(e),cT(e)];s&&(y.push(dT(e,s,i)),y.push(uT(e,s)));const E=await Promise.allSettled(y);if(x.signal.aborted)return;const k=E[0],T=E[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),T.status==="rejected"){p(`Failed to fetch projects: ${T.reason}`),h(!1);return}if(o(T.value),s&&E[2]){const N=E[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function hT(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return Vs(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:i}}const pT="fusion-dashboard-current-node",lf=a.createContext(null);function fT({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await ia();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(pT);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(l.current=b.id,await tn({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,tn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,tn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,tn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(lf.Provider,{value:d,children:e})}function gT(){const e=a.useContext(lf);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function bT({open:e}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{e&&i.current?.focus()},[e]);const r=a.useCallback(()=>{const l=n.trim();l&&(Gb(l),window.location.reload())},[n]),o=a.useCallback(()=>{Kb(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const xT=a.lazy(()=>Zt(()=>import("./AgentsView-BS17exn3.js").then(e=>e.A),__vite__mapDeps([16,1,17,8,18])).then(e=>({default:e.AgentsView}))),vT=a.lazy(()=>Zt(()=>import("./DocumentsView-DOz1KFGN.js"),__vite__mapDeps([19,1,0,2,20])).then(e=>({default:e.DocumentsView}))),yT=a.lazy(()=>Zt(()=>import("./InsightsView-CHZTJUic.js"),__vite__mapDeps([21,1,14,0,2,22])).then(e=>({default:e.InsightsView}))),kT=a.lazy(()=>Zt(()=>import("./NodesView-BtGNRj2z.js"),__vite__mapDeps([23,1,17,0,2,24])).then(e=>({default:e.NodesView}))),jT=a.lazy(()=>Zt(()=>import("./ChatView-BUlq3WNJ.js"),__vite__mapDeps([25,1,0,2])).then(e=>({default:e.ChatView}))),wT=a.lazy(()=>Zt(()=>import("./RoadmapsView-C413ISVU.js"),__vite__mapDeps([26,1,0,2,27])).then(e=>({default:e.RoadmapsView}))),NT=a.lazy(()=>Zt(()=>import("./SkillsView-BcE57w8i.js"),__vite__mapDeps([28,1,0,2,29])).then(e=>({default:e.SkillsView}))),ST=a.lazy(()=>Zt(()=>import("./MemoryView-V0QdeO3e.js"),__vite__mapDeps([30,1,12,13,0,2,31])).then(e=>({default:e.MemoryView}))),CT=a.lazy(()=>Zt(()=>import("./DevServerView-qMPpnXRb.js"),__vite__mapDeps([32,1,0,2,33])).then(e=>({default:e.DevServerView})));function ET(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Zt(()=>import("./AgentsView-BS17exn3.js").then(n=>n.A),__vite__mapDeps([16,1,17,8,18])),Zt(()=>import("./DocumentsView-DOz1KFGN.js"),__vite__mapDeps([19,1,0,2,20])),Zt(()=>import("./InsightsView-CHZTJUic.js"),__vite__mapDeps([21,1,14,0,2,22])),Zt(()=>import("./NodesView-BtGNRj2z.js"),__vite__mapDeps([23,1,17,0,2,24])),Zt(()=>import("./ChatView-BUlq3WNJ.js"),__vite__mapDeps([25,1,0,2])),Zt(()=>import("./RoadmapsView-C413ISVU.js"),__vite__mapDeps([26,1,0,2,27])),Zt(()=>import("./SkillsView-BcE57w8i.js"),__vite__mapDeps([28,1,0,2,29])),Zt(()=>import("./MemoryView-V0QdeO3e.js"),__vite__mapDeps([30,1,12,13,0,2,31])),Zt(()=>import("./DevServerView-qMPpnXRb.js"),__vite__mapDeps([32,1,0,2,33]))})}const kl="kb-setup-warning-dismissed";function MT(){const{toasts:e,addToast:n,removeToast:s}=WR(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{ET()},[]);const{projects:r,loading:o,error:l,refresh:c}=zR(),{nodes:u}=UR(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=gT(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:x}=qR(r,{nodeId:m}),{hasAiProvider:y,hasGithub:E,loading:k,hasWarnings:T}=Kp(f?.id);a.useEffect(()=>{if(m&&!d&&u.length>0){const lt=u.find(ne=>ne.id===m);if(lt){g(lt);return}}m&&u.length>0&&(u.some(ne=>ne.id===m)||p())},[m,d,u,g,p]);const[N,S]=a.useState(""),j=mT(m,{projectId:f?.id,searchQuery:N||void 0});hT(m);const P=h&&j.projects.length>0?j.projects:r,{themeMode:_,colorTheme:I,setThemeMode:D,setColorTheme:G}=QR(),{sessions:$,generating:R,needsInput:w,planningSessions:H,dismissSession:V}=PR(f?.id),B=$.filter(lt=>lt.status==="awaiting_input"||lt.status==="error"),M=XR({projectId:f?.id,planningSessions:H}),{viewMode:z,setViewMode:X,taskView:C,handleChangeTaskView:U}=aT({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:f,projectsLength:r.length,setupWizardOpen:M.setupWizardOpen,openSetupWizard:M.openSetupWizard,themeMode:_,setThemeMode:D}),fe=a.useCallback(lt=>{lt==="missions"&&(pe(void 0),Pe(void 0),Ke(void 0)),U(lt)},[U]),ie=C==="board"||C==="list",{tasks:re,createTask:F,moveTask:ce,pauseTask:ae,deleteTask:Q,mergeTask:de,retryTask:Re,updateTask:ge,duplicateTask:Me,archiveTask:te,unarchiveTask:Ce,archiveAllDone:$e,loadArchivedTasks:We,lastFetchTimeMs:Ge}=$R({...f?{projectId:f.id}:{},searchQuery:N||void 0,sseEnabled:ie}),[Ee,Ae]=a.useState(!1),Oe=a.useRef(performance.now()),ke=a.useRef(!1),De=a.useRef(!1),se=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!ke.current){ke.current=!0;const lt=`projects loaded at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${lt}`),Ta("[App]",lt)}if(!x&&!De.current){De.current=!0;const lt=`current-project resolved at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${lt}`),Ta("[App]",lt)}},[o,x]),a.useEffect(()=>{if(Ee||o||x)return;const lt=performance.now(),ne=window.setTimeout(()=>{const _e=`dashboard ready at ${Math.round(performance.now()-Oe.current)}ms from mount (settle delay=${Math.round(performance.now()-lt)}ms)`;console.log(`[App] ${_e}`),Ta("[App]",_e),Ae(!0)},200);return()=>{window.clearTimeout(ne)}},[Ee,o,x]);const me=Za()==="mobile",[ee,he]=a.useState(0),le=a.useCallback(()=>{gh(f?.id).then(lt=>{he(lt.unreadCount)}).catch(lt=>{console.warn("[App] Failed to fetch mailbox unread count:",lt)})},[f?.id]);a.useEffect(()=>{le();const lt=new URLSearchParams;f?.id&&lt.set("projectId",f.id);const ne=lt.size>0?`?${lt.toString()}`:"";return Vs(`/api/events${ne}`,{events:{"message:sent":le,"message:received":le,"message:read":le,"message:deleted":le}})},[f?.id,le]);const[Ie,Ze]=a.useState(!1),[rt,oe]=a.useState(!1),[Z,pe]=a.useState(void 0),[Se,Pe]=a.useState(void 0),[ye,Ke]=a.useState(void 0),[Ne,Fe]=a.useState(!1),[Ye,xe]=a.useState(!1),[ze,be]=a.useState(()=>En(kl,f?.id)==="true");a.useEffect(()=>{be(En(kl,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const lt=()=>{xe(!0)};return window.addEventListener(_l,lt),()=>{window.removeEventListener(_l,lt)}},[]);const Qe=a.useCallback(()=>{cs(kl,"true",f?.id),be(!0)},[f?.id]),{maxConcurrent:it,autoMerge:mt,globalPaused:At,enginePaused:It,taskStuckTimeoutMs:Dt,showQuickChatFAB:Ut,prAuthAvailable:jt,experimentalFeatures:Pt,insightsEnabled:He,roadmapEnabled:ut,memoryEnabled:$t,devServerEnabled:St,toggleAutoMerge:Yt,toggleGlobalPause:we,toggleEnginePause:et,refresh:ct}=ZR(f?.id),ue=Pt.skillsView===!0,A=Pt.nodesView===!0,J=!0;a.useEffect(()=>{Object.keys(Pt).length!==0&&(C==="insights"&&!He&&U("board"),C==="roadmaps"&&!ut&&U("board"),C==="memory"&&!$t&&U("board"),(C==="devserver"||C==="dev-server")&&!St&&U("board"))},[C,He,ut,Pt,U,J,$t,St]),a.useEffect(()=>{Ie&&!A&&Ze(!1)},[Ie,A]);const{availableModels:Ve,favoriteProviders:dt,favoriteModels:yt,toggleFavoriteProvider:qt,toggleFavoriteModel:wn}=tT();nT({projectId:f?.id,openModelOnboarding:M.openModelOnboarding,openSettings:M.openSettings});const{handleSelectProject:Ft,handleViewAllProjects:Dn,handleOpenSettings:qn,handleAddProject:ms,handleSetupComplete:hn,handleModelOnboardingComplete:Ln,handlePauseProject:Nn,handleResumeProject:pn,handleRemoveProject:Vn,handleToggleFavorite:cn,handleToggleModelFavorite:Ct}=rT({setCurrentProject:b,clearCurrentProject:v,setViewMode:X,currentProject:f,refreshProjects:c,toggleFavoriteProvider:qt,toggleFavoriteModel:wn,addToast:n,openSettings:M.openSettings,openSetupWizard:M.openSetupWizard,closeSetupWizard:M.closeSetupWizard,closeModelOnboarding:M.closeModelOnboarding}),{handleDetailClose:xn}=eT({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:M.openDetailTask,closeTaskDetail:M.closeDetailTask}),{handleBoardQuickCreate:Wn,handleModalCreate:vn,handlePlanningTaskCreated:Mn,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:zn}=oT({createTask:F,onPlanningTaskCreated:M.onPlanningTaskCreated,onPlanningTasksCreated:M.onPlanningTasksCreated,onSubtaskTasksCreated:M.onSubtaskTasksCreated,addToast:n}),W=a.useCallback((lt,ne)=>{if(ne==="changes"){M.openDetailWithChangesTab(lt);return}M.openDetailTask(lt,ne)},[M]),Le=a.useCallback(()=>{A&&Ze(lt=>!lt)},[A]),nt=a.useCallback(()=>{M.setFileWorkspace("project"),M.openFiles()},[M]),tt=a.useCallback(async()=>{oe(!0);try{await c()}finally{oe(!1)}},[c]),ht=a.useCallback(lt=>{Pe(lt),pe(void 0),U("missions")},[U]),kt=a.useCallback(lt=>{lt.type==="planning"?M.openPlanningWithSession(lt.id):lt.type==="subtask"?M.openSubtaskWithSession(lt.id):lt.type==="mission_interview"?(Pe(void 0),pe(lt.id),Ke(void 0),U("missions")):(lt.type==="milestone_interview"||lt.type==="slice_interview")&&(pe(void 0),Pe(void 0),Ke(lt.id),U("missions"))},[U,M]),Et=a.useCallback(()=>{for(const lt of B)V(lt.id)},[V,B]),fn=!o&&!x&&r.length===0&&!f&&!!l,fs=()=>fn?t.jsx(YA,{errorMessage:l??"Failed to fetch projects",isRetrying:rt,onRetry:tt}):Ie?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(kT,{addToast:n,onClose:()=>Ze(!1)})})})}):z==="overview"?t.jsx(Qn,{children:t.jsx(iw,{projects:r,loading:o,onSelectProject:Ft,onAddProject:ms,onPauseProject:Nn,onResumeProject:pn,onRemoveProject:Vn,nodes:u})}):C==="skills"?ue?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(NT,{addToast:n,projectId:f?.id,onClose:()=>U("board")})})}):(U("board"),null):C==="chat"?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(jT,{addToast:n,projectId:f?.id})})}):C==="mailbox"?t.jsx(Qn,{children:t.jsx(Yw,{projectId:f?.id,addToast:n,onUnreadCountChange:he})}):C==="roadmaps"?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(wT,{addToast:n,projectId:f?.id})})}):C==="missions"?t.jsx(Qn,{children:t.jsx(Ww,{isInline:!0,isOpen:!0,onClose:()=>{Pe(void 0),pe(void 0),Ke(void 0),U("board")},addToast:n,projectId:f?.id,onSelectTask:lt=>{const ne=re.find(_e=>_e.id===lt);ne&&M.openDetailTask(ne)},availableTasks:re.map(lt=>({id:lt.id,title:lt.title})),resumeSessionId:Z,targetMissionId:Se,milestoneSliceResumeSessionId:ye,onMilestoneSliceResumeFetchError:()=>Ke(void 0)})}):C==="agents"&&J?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(xT,{addToast:n,projectId:f?.id})})}):C==="documents"?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(vT,{projectId:f?.id,addToast:n,onOpenDetail:M.openDetailTask})})}):C==="insights"?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(yT,{projectId:f?.id,addToast:n,onClose:()=>U("board")})})}):C==="memory"?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(ST,{addToast:n,projectId:f?.id})})}):C==="devserver"||C==="dev-server"?t.jsx(Qn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(CT,{addToast:n,projectId:f?.id})})}):C==="board"?t.jsx(Qn,{children:t.jsx(Wj,{tasks:h&&j.tasks.length>0?j.tasks:re,projectId:f?.id,maxConcurrent:it,onMoveTask:ce,onPauseTask:ae,onOpenDetail:M.openDetailTask,addToast:n,onQuickCreate:Wn,onNewTask:M.openNewTask,onPlanningMode:M.openPlanningWithInitialPlan,onSubtaskBreakdown:M.openSubtaskBreakdown,autoMerge:mt,onToggleAutoMerge:Yt,globalPaused:At,onUpdateTask:ge,onArchiveTask:te,onUnarchiveTask:Ce,onDeleteTask:Q,onArchiveAllDone:$e,onLoadArchivedTasks:We,searchQuery:N,availableModels:Ve,onOpenDetailWithTab:W,favoriteProviders:dt,favoriteModels:yt,onToggleFavorite:cn,onToggleModelFavorite:Ct,taskStuckTimeoutMs:Dt,onOpenMission:ht,lastFetchTimeMs:Ge})}):t.jsx(Qn,{children:t.jsx(Kj,{tasks:h&&j.tasks.length>0?j.tasks:re,projectId:f?.id,onMoveTask:ce,onOpenDetail:M.openDetailTask,addToast:n,globalPaused:At,onNewTask:M.openNewTask,onQuickCreate:Wn,onPlanningMode:M.openPlanningWithInitialPlan,onSubtaskBreakdown:M.openSubtaskBreakdown,availableModels:Ve,favoriteProviders:dt,favoriteModels:yt,onToggleFavorite:cn,onToggleModelFavorite:Ct,taskStuckTimeoutMs:Dt,searchQuery:N,lastFetchTimeMs:Ge})});if(!Ee)return t.jsxs(t.Fragment,{children:[t.jsx(XA,{stage:se}),t.jsx(ef,{toasts:e,onRemove:s})]});const Qt=!M.modelOnboardingOpen&&kA(),xt=!M.modelOnboardingOpen&&!Qt&&ta()&&!Yp();return t.jsxs(t.Fragment,{children:[t.jsx(Pk,{isElectron:i,onOpenSettings:qn,onOpenGitHubImport:M.openGitHubImport,onOpenPlanning:M.openPlanning,onResumePlanning:M.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:M.openUsage,onOpenActivityLog:M.openActivityLog,onOpenMailbox:()=>fe("mailbox"),mailboxUnreadCount:ee,onOpenSchedules:M.openSchedules,onOpenGitManager:M.openGitManager,onOpenNodes:Le,showNodesButton:A,onOpenWorkflowSteps:M.openWorkflowSteps,onOpenScripts:M.openScripts,onRunScript:M.runScript,onToggleTerminal:M.toggleTerminal,onOpenFiles:M.openFiles,filesOpen:M.filesOpen,globalPaused:At,enginePaused:It,onToggleGlobalPause:we,onToggleEnginePause:et,view:C,onChangeView:z==="project"&&f?fe:void 0,showSkillsTab:ue,showAgentsTab:J,searchQuery:N,onSearchChange:S,projects:P,currentProject:f,onSelectProject:Ft,onViewAllProjects:Dn,projectId:f?.id,mobileNavEnabled:me,availableNodes:u,currentNode:d,onSelectNode:lt=>{lt===null?p():g(lt)},isRemote:h,experimentalFeatures:{insights:He,roadmap:ut,memoryView:$t,devServer:St,devServerView:St}}),z==="project"&&f&&!Ie&&C!=="missions"&&!M.isPlanningOpen&&t.jsx(uR,{sessions:B,onResumeSession:kt,onDismissSession:V,onDismissAll:Et}),z==="project"&&f&&Qt&&t.jsx(mR,{onResume:M.openModelOnboarding}),z==="project"&&f&&xt&&t.jsx(hR,{onOpenModelOnboarding:M.openModelOnboarding,onOpenSettings:lt=>M.openSettings(lt)}),z==="project"&&f&&!k&&T&&!ze&&t.jsx(Jp,{hasAiProvider:y,hasGithub:E,onDismiss:Qe}),t.jsx("div",{className:`project-content${z==="project"&&f?" project-content--with-footer":""}${me?" project-content--with-mobile-nav":""}`,children:fs()}),z==="project"&&f&&!Ie&&t.jsx(lR,{tasks:h&&j.tasks.length>0?j.tasks:re,projectId:f.id,taskStuckTimeoutMs:Dt,backgroundSessions:$,backgroundGenerating:R,backgroundNeedsInput:w,onOpenBackgroundSession:kt,onDismissBackgroundSession:V,lastFetchTimeMs:Ge,currentProjectPath:f.path,onOpenProjectDirectory:nt}),t.jsx(fR,{view:C,onChangeView:z==="project"&&f?fe:()=>{},footerVisible:z==="project"&&!!f,modalOpen:M.anyModalOpen,onOpenSettings:qn,onOpenActivityLog:M.openActivityLog,onOpenMailbox:()=>fe("mailbox"),mailboxUnreadCount:ee,onOpenGitManager:M.openGitManager,onOpenWorkflowSteps:M.openWorkflowSteps,onOpenSchedules:M.openSchedules,onOpenScripts:M.openScripts,onToggleTerminal:M.toggleTerminal,onOpenFiles:M.openFiles,onOpenGitHubImport:M.openGitHubImport,onOpenPlanning:M.openPlanning,onResumePlanning:M.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:M.openUsage,onViewAllProjects:Dn,onRunScript:M.runScript,projectId:f?.id,showSkillsTab:ue,experimentalFeatures:{insights:He,roadmap:ut,memoryView:$t,devServer:St,devServerView:St}}),z==="project"&&f&&C!=="chat"&&C!=="mailbox"&&C!=="insights"&&C!=="devserver"&&C!=="dev-server"&&t.jsx(IR,{projectId:f.id,addToast:n,showFAB:Ut,open:Ne,onOpenChange:Fe,favoriteProviders:dt,favoriteModels:yt,onToggleFavorite:cn,onToggleModelFavorite:Ct}),t.jsx(JA,{projectId:f?.id,tasks:re,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:M,projectActions:{handleAddProject:ms,handleSetupComplete:hn,handleModelOnboardingComplete:Ln},taskHandlers:{handleModalCreate:vn,handlePlanningTaskCreated:Mn,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:zn},taskOperations:{moveTask:ce,deleteTask:Q,mergeTask:de,retryTask:Re,duplicateTask:Me},deepLink:{handleDetailClose:xn},settings:{prAuthAvailable:jt,themeMode:_,colorTheme:I,setThemeMode:D,setColorTheme:G},onSettingsClose:()=>{M.closeSettings(),ct()},onReopenOnboarding:()=>{M.closeSettings(),M.openModelOnboarding()}}),t.jsx(bT,{open:Ye})]})}function _T(){return t.jsx(VR,{children:t.jsx(fT,{children:t.jsx(MT,{})})})}tx();hf.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(Ub,{children:t.jsx(_T,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{console.log("SW registered:",e.scope)}).catch(e=>{console.log("SW registration failed:",e)});export{nI as $,Ss as A,nn as B,en as C,an as D,sn as E,Ni as F,Qr as G,gl as H,Bt as I,Os as J,zt as K,at as L,mA as M,sy as N,aA as O,ts as P,rA as Q,mn as R,Oi as S,nc as T,iy as U,ay as V,jI as W,Tt as X,tI as Y,bn as Z,Zt as _,cs as a,eP as a$,Dr as a0,hv as a1,lg as a2,ec as a3,na as a4,ei as a5,ti as a6,Zs as a7,CP as a8,_P as a9,NP as aA,SP as aB,Ck as aC,Ek as aD,jR as aE,Za as aF,Zl as aG,gR as aH,yR as aI,os as aJ,yi as aK,li as aL,zb as aM,FI as aN,UI as aO,OI as aP,BI as aQ,HI as aR,qI as aS,VI as aT,WI as aU,GI as aV,KI as aW,JI as aX,YI as aY,QI as aZ,XI as a_,MP as aa,EP as ab,AP as ac,Pn as ad,ns as ae,Rb as af,Bs as ag,rg as ah,Jr as ai,wi as aj,zP as ak,DP as al,LP as am,FP as an,Ir as ao,wb as ap,za as aq,tg as ar,Un as as,eh as at,UR as au,zR as av,wP as aw,gd as ax,Ua as ay,Sk as az,RI as b,TP as b$,tP as b0,ZI as b1,yn as b2,tc as b3,Hi as b4,kP as b5,yP as b6,jP as b7,DT as b8,$T as b9,Rv as bA,sI as bB,sa as bC,eo as bD,Xm as bE,Wi as bF,uy as bG,Gb as bH,Kb as bI,Mf as bJ,OM as bK,GT as bL,LI as bM,TT as bN,Oa as bO,TI as bP,Ox as bQ,Rx as bR,qs as bS,Tx as bT,Ix as bU,Px as bV,YT as bW,II as bX,PI as bY,$I as bZ,RP as b_,PT as ba,LT as bb,VT as bc,WT as bd,BT as be,FT as bf,OT as bg,UT as bh,zT as bi,IT as bj,HT as bk,e_ as bl,rI as bm,aI as bn,mI as bo,iI as bp,oI as bq,lI as br,cI as bs,dI as bt,$v as bu,uI as bv,ic as bw,Tv as bx,Iv as by,Pv as bz,qe as c,zI as c0,kn as c1,XM as c2,pA as c3,ao as c4,Xu as c5,IP as c6,PP as c7,qT as c8,nP as c9,fI as cA,xI as cB,dP as cC,uP as cD,gb as cE,El as cF,bP as cG,xP as cH,pP as cI,hP as cJ,fP as cK,mP as cL,gP as cM,DI as cN,QT as cO,KT as cP,JT as cQ,ZT as cR,eI as cS,XT as cT,iP as ca,oP as cb,aP as cc,sP as cd,rP as ce,lP as cf,dh as cg,Qc as ch,Lg as ci,cP as cj,NI as ck,vI as cl,kI as cm,yI as cn,EI as co,CI as cp,Gm as cq,bI as cr,gI as cs,iA as ct,wI as cu,Wa as cv,jE as cw,pI as cx,hI as cy,pv as cz,_I as d,AI as e,vP as f,En as g,ss as h,aa as i,jn as j,ny as k,MI as l,vR as m,no as n,or as o,ve as p,Uk as q,SI as r,Vs as s,Sl as t,tn as u,Us as v,Ht as w,Tr as x,oA as y,$P as z};