@runfusion/fusion 0.4.1 → 1.0.0

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 (38) hide show
  1. package/dist/bin.js +34074 -34923
  2. package/dist/client/assets/{AgentDetailView-sy6Hg1Xr.js → AgentDetailView-dhJd4os0.js} +6 -11
  3. package/dist/client/assets/{AgentsView-DpEpW88a.js → AgentsView-CYVTv2_l.js} +3 -3
  4. package/dist/client/assets/{ChatView-BUt3C4cf.js → ChatView-ByPhfQZ6.js} +1 -1
  5. package/dist/client/assets/{DevServerView-BOyWtQJM.js → DevServerView-CD7mgC11.js} +1 -1
  6. package/dist/client/assets/{DirectoryPicker-BJyEEso5.js → DirectoryPicker-Cm0FCC9M.js} +1 -1
  7. package/dist/client/assets/{DocumentsView-Dx0M1YHw.js → DocumentsView-oB319uCj.js} +1 -1
  8. package/dist/client/assets/{InsightsView-BtXdAo7D.js → InsightsView-BHdMNnOa.js} +1 -1
  9. package/dist/client/assets/{MemoryView-kKPuqmwf.js → MemoryView-BDJMlzlM.js} +1 -1
  10. package/dist/client/assets/{NodesView-B_ZwUORz.js → NodesView-BfOlOj-Q.js} +1 -1
  11. package/dist/client/assets/{PiExtensionsManager-Db0EGr0Q.js → PiExtensionsManager-D-IznnkU.js} +2 -2
  12. package/dist/client/assets/{PluginManager-mOwWndfg.js → PluginManager-D40uAE-p.js} +1 -1
  13. package/dist/client/assets/{RoadmapsView-DbUzBLeF.js → RoadmapsView-DtgL8yl3.js} +1 -1
  14. package/dist/client/assets/{SettingsModal-TRJu_mTn.js → SettingsModal-0IyoaKEv.js} +1 -1
  15. package/dist/client/assets/SettingsModal-D1vZdAS4.js +31 -0
  16. package/dist/client/assets/{SetupWizardModal-D1bmCQrf.js → SetupWizardModal-BaQ8VkZm.js} +1 -1
  17. package/dist/client/assets/{SkillsView-Dzzpd5Md.js → SkillsView-DAvaRl37.js} +1 -1
  18. package/dist/client/assets/TodoView-BXRQSmSw.js +1 -0
  19. package/dist/client/assets/TodoView-DNi8blBB.css +1 -0
  20. package/dist/client/assets/{folder-open-BcuByk6U.js → folder-open-BJ4SvamV.js} +1 -1
  21. package/dist/client/assets/index-B7TDbn3p.css +1 -0
  22. package/dist/client/assets/index-CGW6tOaX.js +631 -0
  23. package/dist/client/assets/list-checks-CpGwz9gV.js +6 -0
  24. package/dist/client/assets/{upload-BzNbXYEj.js → upload-DJYyvab0.js} +1 -1
  25. package/dist/client/assets/{users-BvIqhSXp.js → users-ndAFpylb.js} +1 -1
  26. package/dist/client/index.html +2 -2
  27. package/dist/client/version.json +1 -1
  28. package/dist/extension.js +3262 -599
  29. package/dist/pi-claude-cli/package.json +1 -1
  30. package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +50 -17
  31. package/dist/pi-claude-cli/src/__tests__/setup-test-isolation.test.ts +30 -0
  32. package/dist/pi-claude-cli/src/__tests__/setup-test-isolation.ts +6 -0
  33. package/package.json +5 -5
  34. package/skill/fusion/references/extension-tools.md +5 -5
  35. package/skill/fusion/references/fusion-capabilities.md +5 -5
  36. package/dist/client/assets/SettingsModal-Bs_lNs5B.js +0 -31
  37. package/dist/client/assets/index-BipedNj4.css +0 -1
  38. package/dist/client/assets/index-k2c4LrUr.js +0 -616
@@ -0,0 +1,631 @@
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-BaQ8VkZm.js","assets/DirectoryPicker-Cm0FCC9M.js","assets/folder-open-BJ4SvamV.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-BMa6p24b.css","assets/SettingsModal-D1vZdAS4.js","assets/SettingsModal-0IyoaKEv.js","assets/SettingsModal-G0ESQXRD.css","assets/users-ndAFpylb.js","assets/SettingsModal-CDWvhvrd.css","assets/AgentsView-CYVTv2_l.js","assets/upload-DJYyvab0.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-oB319uCj.js","assets/DocumentsView-DV2DrCZb.css","assets/InsightsView-BHdMNnOa.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-BfOlOj-Q.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-ByPhfQZ6.js","assets/RoadmapsView-DtgL8yl3.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-DAvaRl37.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-BDJMlzlM.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-CD7mgC11.js","assets/DevServerView-ZeBGQkLI.css","assets/TodoView-BXRQSmSw.js","assets/list-checks-CpGwz9gV.js","assets/TodoView-DNi8blBB.css"])))=>i.map(i=>d[i]);
2
+ import{r as a,j as t,a as Ta,g as Qm,R as Xm,c as Tf}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 Zm=(...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 Rf=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 If=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 Gc=e=>{const n=If(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 To={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 Pf=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},$f=a.createContext({}),Df=()=>a.useContext($f),Lf=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=""}=Df()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...To,width:n??d??To.width,height:n??d??To.height,stroke:e??g,strokeWidth:f,className:Zm("lucide",p,r),...!o&&!Pf(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 Ue=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(Lf,{ref:o,iconNode:n,className:Zm(`lucide-${Rf(Gc(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Gc(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 zf=[["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=Ue("activity",zf);/**
43
+ * @license lucide-react v1.7.0 - ISC
44
+ *
45
+ * This source code is licensed under the ISC license.
46
+ * See the LICENSE file in the root directory of this source tree.
47
+ */const Ff=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],to=Ue("archive",Ff);/**
48
+ * @license lucide-react v1.7.0 - ISC
49
+ *
50
+ * This source code is licensed under the ISC license.
51
+ * See the LICENSE file in the root directory of this source tree.
52
+ */const Of=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Ga=Ue("arrow-down",Of);/**
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 Uf=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ia=Ue("arrow-left",Uf);/**
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 Bf=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Ja=Ue("arrow-right",Bf);/**
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 Hf=[["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"}]],eh=Ue("arrow-up-down",Hf);/**
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 qf=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],yi=Ue("arrow-up",qf);/**
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 Vf=[["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"}]],Wf=Ue("book-open",Vf);/**
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 Kf=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],an=Ue("bot",Kf);/**
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 Gf=[["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"}]],Al=Ue("box",Gf);/**
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 Jf=[["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"}]],Dr=Ue("brain",Jf);/**
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 Yf=[["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"}]],th=Ue("calendar",Yf);/**
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 Qf=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Xf=Ue("check-check",Qf);/**
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 Zf=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],xn=Ue("check",Zf);/**
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 eg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Lt=Ue("chevron-down",eg);/**
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 tg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],lc=Ue("chevron-left",tg);/**
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 ng=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],en=Ue("chevron-right",ng);/**
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 sg=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Ys=Ue("chevron-up",sg);/**
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 ig=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]],ss=Ue("circle-alert",ig);/**
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 ag=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],tn=Ue("circle-check-big",ag);/**
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 rg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],no=Ue("circle-dot",rg);/**
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 og=[["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"}]],Jc=Ue("circle-question-mark",og);/**
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 lg=[["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"}]],Ya=Ue("circle-x",lg);/**
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 cg=[["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"}]],dg=Ue("clipboard-list",cg);/**
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 ug=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],ji=Ue("clock",ug);/**
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 mg=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],nh=Ue("code",mg);/**
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 hg=[["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"}]],pg=Ue("columns-3",hg);/**
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 fg=[["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"}]],wi=Ue("copy",fg);/**
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 gg=[["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"}]],bg=Ue("cpu",gg);/**
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 xg=[["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"}]],vg=Ue("download",xg);/**
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 yg=[["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"}]],kg=Ue("ellipsis-vertical",yg);/**
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 jg=[["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"}]],Tl=Ue("ellipsis",jg);/**
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 wg=[["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"}]],Ng=Ue("external-link",wg);/**
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 Sg=[["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"}]],Lr=Ue("eye-off",Sg);/**
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"}]],Vi=Ue("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 Eg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}]],Ts=Ue("file-code",Eg);/**
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 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:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]],sh=Ue("file-diff",Mg);/**
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 _g=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}]],Ag=Ue("file-minus",_g);/**
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 Tg=[["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"}]],ih=Ue("file-pen",Tg);/**
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 Rg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],Ig=Ue("file-plus",Rg);/**
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 Pg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],$g=Ue("file-question-mark",Pg);/**
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 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 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Ni=Ue("file-text",Dg);/**
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 Lg=[["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"}]],zg=Ue("file-type",Lg);/**
253
+ * @license lucide-react v1.7.0 - ISC
254
+ *
255
+ * This source code is licensed under the ISC license.
256
+ * See the LICENSE file in the root directory of this source tree.
257
+ */const Fg=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],ah=Ue("file",Fg);/**
258
+ * @license lucide-react v1.7.0 - ISC
259
+ *
260
+ * This source code is licensed under the ISC license.
261
+ * See the LICENSE file in the root directory of this source tree.
262
+ */const Og=[["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"}]],Rl=Ue("folder-git-2",Og);/**
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 Ug=[["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"}]],Yc=Ue("folder-root",Ug);/**
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 Bg=[["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"}]],jn=Ue("folder",Bg);/**
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 Hg=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],zr=Ue("funnel",Hg);/**
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 qg=[["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"}]],Os=Ue("git-branch",qg);/**
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 Vg=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],Oa=Ue("git-commit-horizontal",Vg);/**
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 Wg=[["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"}]],rh=Ue("git-merge",Wg);/**
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 Kg=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],es=Ue("git-pull-request",Kg);/**
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 Gg=[["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"}]],so=Ue("globe",Gg);/**
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 Jg=[["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"}]],oh=Ue("grid-3x3",Jg);/**
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 Yg=[["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"}]],cc=Ue("grip-vertical",Yg);/**
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 Qg=[["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"}]],Xg=Ue("hard-drive",Qg);/**
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 Zg=[["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"}]],eb=Ue("heart",Zg);/**
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 tb=[["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"}]],Ua=Ue("history",tb);/**
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 nb=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],Ra=Ue("inbox",nb);/**
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 sb=[["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"}]],lh=Ue("key",sb);/**
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 ib=[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]],ab=Ue("keyboard",ib);/**
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 rb=[["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=Ue("layers",rb);/**
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 ob=[["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=Ue("layout-grid",ob);/**
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 lb=[["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"}]],Us=Ue("lightbulb",lb);/**
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 cb=[["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"}]],Wi=Ue("link",cb);/**
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 db=[["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"}]],ub=Ue("list-plus",db);/**
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 mb=[["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"}]],io=Ue("list-tree",mb);/**
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 hb=[["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"}]],Il=Ue("list",hb);/**
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 pb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],it=Ue("loader-circle",pb);/**
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 fb=[["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"}]],ao=Ue("lock",fb);/**
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 gb=[["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"}]],Ki=Ue("mail",gb);/**
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 bb=[["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"}]],Pl=Ue("map",bb);/**
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 xb=[["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"}]],ro=Ue("maximize-2",xb);/**
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 vb=[["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=Ue("message-square",vb);/**
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 yb=[["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"}]],aa=Ue("minimize-2",yb);/**
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 kb=[["path",{d:"M5 12h14",key:"1ays0h"}]],jb=Ue("minus",kb);/**
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 wb=[["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"}]],ch=Ue("monitor",wb);/**
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 Nb=[["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"}]],Sb=Ue("move",Nb);/**
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 Cb=[["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"}]],$l=Ue("package",Cb);/**
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 Eb=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]],Mb=Ue("paperclip",Eb);/**
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 _b=[["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"}]],Fs=Ue("pause",_b);/**
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 Ab=[["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"}]],qn=Ue("pencil",Ab);/**
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 Tb=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],rn=Ue("play",Tb);/**
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 Rb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],qt=Ue("plus",Rb);/**
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 Ib=[["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"}]],dh=Ue("radio",Ib);/**
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 Pb=[["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"}]],hn=Ue("refresh-cw",Pb);/**
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 $b=[["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"}]],Qc=Ue("rocket",$b);/**
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 Db=[["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"}]],Lb=Ue("rotate-ccw",Db);/**
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 zb=[["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"}]],uh=Ue("save",zb);/**
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 Fb=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Bi=Ue("search",Fb);/**
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 Ob=[["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"}]],vi=Ue("send",Ob);/**
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 Ub=[["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"}]],Fr=Ue("server",Ub);/**
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 Bb=[["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"}]],Ba=Ue("settings",Bb);/**
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 Hb=[["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"}]],qb=Ue("shield",Hb);/**
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 Vb=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]],Dn=Ue("sparkles",Vb);/**
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 Wb=[["path",{d:"M21 10.656V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.344",key:"2acyp4"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],mh=Ue("square-check-big",Wb);/**
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 Kb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ls=Ue("square",Kb);/**
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 Gb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],ns=Ue("target",Gb);/**
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 Jb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Bs=Ue("terminal",Jb);/**
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 Yb=[["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"}]],Or=Ue("text-wrap",Yb);/**
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 Qb=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],Ht=Ue("trash-2",Qb);/**
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 Xb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Zb=Ue("trending-up",Xb);/**
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 ex=[["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"}]],dc=Ue("triangle-alert",ex);/**
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 tx=[["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"}]],Xc=Ue("unlink",tx);/**
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 nx=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],Pi=Ue("user",nx);/**
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 sx=[["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"}]],hh=Ue("webhook",sx);/**
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 ix=[["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"}]],Dl=Ue("workflow",ix);/**
573
+ * @license lucide-react v1.7.0 - ISC
574
+ *
575
+ * This source code is licensed under the ISC license.
576
+ * See the LICENSE file in the root directory of this source tree.
577
+ */const ax=[["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"}]],rx=Ue("wrench",ax);/**
578
+ * @license lucide-react v1.7.0 - ISC
579
+ *
580
+ * This source code is licensed under the ISC license.
581
+ * See the LICENSE file in the root directory of this source tree.
582
+ */const ox=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Dt=Ue("x",ox);/**
583
+ * @license lucide-react v1.7.0 - ISC
584
+ *
585
+ * This source code is licensed under the ISC license.
586
+ * See the LICENSE file in the root directory of this source tree.
587
+ */const lx=[["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"}]],vn=Ue("zap",lx),Ll="fusion:version-reload";function ph(e){if(sessionStorage.getItem(Ll)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Ll,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function cx(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError/i.test(n)}function dx(e){return cx(e)?(ph(`chunk load error: ${e?.message??e}`),!0):!1}async function ux(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}let Ro=!1;async function Io(){if(!(Ro||document.visibilityState!=="visible")){Ro=!0;try{const e=await ux();e&&e!=="mogghi2q-2038053d"&&ph(`build version changed: mogghi2q-2038053d -> ${e}`)}finally{Ro=!1}}}function mx(){window.setTimeout(()=>sessionStorage.removeItem(Ll),5e3),document.addEventListener("visibilitychange",()=>{Io()}),window.addEventListener("focus",()=>{Io()}),window.setTimeout(()=>void Io(),2e3)}class oo 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),!dx(n)&&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(dc,{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 Hn({children:e,onError:n}){return t.jsx(oo,{level:"page",onError:n,children:e})}function fi({children:e,onError:n}){return t.jsx(oo,{level:"modal",onError:n,children:e})}function hx({children:e,onError:n}){return t.jsx(oo,{level:"root",onError:n,children:e})}const px="modulepreload",fx=function(e){return"/"+e},Zc={},Wt=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=fx(d),d in Zc)return;Zc[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":px,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)})},uc="fn.authToken",ed="token",gx="fn_token";let Hi,td=!1,Ur=!1;const zl="fn:auth-token-recovery-required";function bx(){try{const e=window.localStorage.getItem(uc);return e&&e.length>0?e:void 0}catch{return}}function fh(e){try{window.localStorage.setItem(uc,e)}catch{}}function xx(){if(!(td||typeof window>"u")){td=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(ed);if(!n)return;fh(n),e.searchParams.delete(ed);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Gi(){if(Hi!==void 0)return Hi;const e=xx();if(e)return Hi=e,e;const n=bx();if(n)return Hi=n,n}function vx(e){Hi=e,Ur=!1,fh(e)}function yx(){Hi=void 0,Ur=!1;try{window.localStorage.removeItem(uc)}catch{}}function nd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function kx(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function jx(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!kx(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=nd(e.protocol)===nd(n.protocol);return s&&i&&r}function wx(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 Hs(e){const n=Gi();if(!n||typeof window>"u")return e;const s=wx(e);return!s||!jx(s.parsed)?e:(s.parsed.searchParams.set(gx,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function di(e){const n=Gi();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Nx(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Sx(){typeof window>"u"||Ur||(Ur=!0,window.dispatchEvent(new CustomEvent(zl)))}async function Cx(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();Nx(i)&&Sx()}catch{}}function Ex(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Gi();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Gi(),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=>(Cx(u),u))}}class Mx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function _x(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Wn(e){return`/api${e}`}async function D(e,n={}){const s=Wn(e),i=Gi(),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")||_x(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 Mx(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function hI(){return D("/health")}function Ax(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 D(`/tasks${l}`)}async function Br(e,n){const i=Wn(H(`/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 gh(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:k,executionMode:M,priority:w}=e;return D(H("/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:k,executionMode:M,priority:w})})}function Gs(e,n,s){return D(H(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Tx(e,n,s,i,r,o,l,c){return D(H("/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 D(H(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Ix(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return D(H(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Px(e,n){return D(H(`/tasks/${e}/merge`,n),{method:"POST"})}function $x(e,n){return D(H(`/tasks/${e}/retry`,n),{method:"POST"})}function Dx(e,n){return D(H(`/tasks/${e}/duplicate`,n),{method:"POST"})}function bh(e,n){return D(H(`/tasks/${e}/pause`,n),{method:"POST"})}function Lx(e,n){return D(H(`/tasks/${e}/unpause`,n),{method:"POST"})}function zx(e,n){return D(H(`/tasks/${e}/archive`,n),{method:"POST"})}function Fx(e,n){return D(H(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Ox(e){return D(H("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Ux(e,n){return D(H(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Bx(e,n){return D(H(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Hx(e){return D(H("/config",e))}function lo(e){return D(H("/settings",e))}function mr(e,n){return D(H("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function pI(e){return D(H("/remote/settings",e))}function fI(e,n){return D(H("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function gI(e){return D(H("/remote/status",e))}function bI(e,n){return D(H("/remote/provider/activate",n),{method:"POST",body:JSON.stringify({provider:e})})}function xI(e){return D(H("/remote/tunnel/start",e),{method:"POST"})}function vI(e){return D(H("/remote/tunnel/stop",e),{method:"POST"})}function yI(e){return D(H("/remote/token/persistent/regenerate",e),{method:"POST"})}function kI(e,n){return D(H("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function xh(e,n,s){const i=new URLSearchParams;e&&i.set("format",e),i.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&i.set("ttlMs",String(s));const r=i.toString();return r?`?${r}`:""}function jI(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=xh(null,s,i);return D(H(`/remote/url${r}`,n))}function wI(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=xh(e,i,r);return D(H(`/remote/qr${o}`,s))}function NI(e){return D(H("/memory",e))}function SI(e,n){return D(H("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function CI(e){return D(H("/memory/files",e))}function EI(e,n){const s=`path=${encodeURIComponent(e)}`;return D(H(`/memory/file?${s}`,n))}function MI(e,n,s){return D(H("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function _I(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 D(H("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function AI(e){return D(H("/memory/insights",e))}function TI(e,n){return D(H("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function RI(e){return D(H("/memory/extract",e),{method:"POST"})}function II(e){return D(H("/memory/audit",e))}function PI(e){return D(H("/memory/stats",e))}function $I(e){return D(H("/memory/backend",e))}function DI(e){return D(H("/memory/install-qmd",e),{method:"POST"})}function LI(e,n){return D(H("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ra(){return D("/settings/global")}function nn(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function zI(e){return D(H("/settings/scopes",e))}function FI(e){return D(H("/settings/pi-extensions",e))}function OI(e,n){return D(H("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function UI(e,n){return D(H("/settings/test-ntfy",n),{method:"POST",body:e?JSON.stringify(e):void 0})}function BI(){return D("/pi-settings")}async function HI(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function qI(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function VI(e){return D(H("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ha(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Wn(H(`/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 qx(e,n,s){return D(H(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function sd(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=H(`/tasks/${e}/logs${r}`,n),l=await fetch(Wn(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 D(H(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Wx(e,n,s){return D(H(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Kx(e,n){return D(H(`/tasks/${e}/documents`,n))}function Gx(e,n,s){return D(H(`/tasks/${e}/documents/${n}/revisions`,s))}async function WI(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 D(H(r,n))}function KI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return D(H(r,e))}function id(e,n,s,i,r){return D(H(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Jx(e,n,s){return D(H(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Yx(e,n,s){return D(H(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Qx(e,n,s){return D(H(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Xx(e,n){return D(H(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Zx(e,n,s){return D(H(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function is(){return D("/models")}function ev(){return D("/usage")}function tv(){return D("/providers/claude-cli/status")}function nv(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function qa(){return D("/auth/status")}function sv(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function iv(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function av(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function rv(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function ov(e,n,s,i){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function lv(e,n,s,i){return D(H("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function cv(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function dv(e,n,s,i){return D(H("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function uv(e){return D(H("/git/remotes",e))}function mv(e){return D(H("/git/remotes/detailed",e))}function hv(e,n,s){return D(H("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function pv(e,n){return D(H(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function fv(e,n,s){return D(H(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function gv(e,n,s){return D(H(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function bv(e,n,s){return D(H(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function xv(e,n){return D(H(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function vv(e,n){return(await D(H("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function hr(e,n,s,i){return D(H("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function ad(e,n){return D(H(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yv(e){return D(H("/terminal/sessions",e))}function As(e){return D(H("/git/status",e))}function kv(e,n){const s=e?`?limit=${e}`:"";return D(H(`/git/commits${s}`,n))}function Hr(e,n){return D(H(`/git/commits/${e}/diff`,n))}function jv(e){return D(H("/git/commits/ahead",e))}function wv(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(H(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function pa(e){return D(H("/git/branches",e))}function Nv(e,n,s){const i=`?limit=${n}`;return D(H(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Sv(e){return D(H("/git/worktrees",e))}function Cv(e,n,s){return D(H("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function Ev(e,n){return D(H(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function rd(e,n,s){const i=n?"?force=true":"";return D(H(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function Mv(e,n){return D(H("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function _v(e){return D(H("/git/pull",e),{method:"POST"})}function Av(e){return D(H("/git/push",e),{method:"POST"})}function pr(e){return D(H("/git/stashes",e))}function Tv(e,n){return D(H("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Rv(e,n,s){return D(H(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Iv(e,n){return D(H(`/git/stashes/${e}`,n),{method:"DELETE"})}function Pv(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),D(H(`/git/diff/file?${i.toString()}`,s))}function $i(e){return D(H("/git/changes",e))}function od(e,n){return D(H("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function $v(e,n){return D(H("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function ld(e,n){return D(H("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Dv(e,n){return D(H("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Lv(e){return D(H("/workspaces",e))}function zv(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),D(`/files?${i.toString()}`)}function Fv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Ov(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Uv(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),D(`/files/search?${i.toString()}`)}function Bv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Hv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function qv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/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),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function vh(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Wv(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 D(H("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Gv(e,n,s,i){return D(H("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Jv(e,n,s){return D(H(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function yh(e,n,s){return D(H("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Yv(e,n,s){return D(H("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Qv(e,n,s){return D(H("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Xv(e,n,s){return D(H("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Fl=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Fl))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Zv(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Qa(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=Zv(e,u),f=new EventSource(Hs(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 k=x;m(k)&&v(k)});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(),Fl.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Fl.add(g),g}function cd(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 Ji(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 ey(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 ty(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>ey(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function ny(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 dd(e){return Array.isArray(e)?e.map(cd):(e.candidates??[]).map(cd)}async function sy(e){try{const n=await D(H("/dev-server/candidates",e));return dd(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(H("/dev-server/detect",e));return dd(s)}throw n}}function mc(e){return D(H("/dev-server/status",e)).then(Ji)}async function GI(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 D(H(`/dev-server/logs/history${i}`,n));return ty(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await mc(n);return ny(o.logs,e)}throw r}}function iy(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return D(H("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Ji)}function ay(e){return D(H("/dev-server/stop",e),{method:"POST"}).then(Ji)}function ry(e){return D(H("/dev-server/restart",e),{method:"POST"}).then(Ji)}async function oy(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await D(H("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Ji(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await D(H("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Ji(r)}throw i}}function JI(e){return Wn(H("/dev-server/logs/stream",e))}async function YI(e){try{return(await D(H("/devserver",e))).sessions??[]}catch{try{const n=await mc(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 QI(e,n){try{return await D(H(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await mc(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 XI(e,n){try{return await D(H(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await iy({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 ZI(e,n){try{return await D(H(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await ay(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 e4(e,n){try{return await D(H(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await ry(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 t4(e,n,s){try{const i=await D(H(`/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 oy({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function n4(e){try{return(await D(H("/devserver/detect",e))).candidates??[]}catch{try{return(await sy(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function s4(e,n){return Wn(H(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Xa(e,n,s=25e3){const i=setInterval(()=>{Ok(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function ly(e,n){return Wn(H(`/planning/${encodeURIComponent(e)}/stream`,n))}function cy(e,n,s,i){const r=ly(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Qa(r,{onOpen:()=>{c(),o=Xa(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 Za(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 dy(e){return D(Za("/routines",e))}function uy(e,n){return D(Za("/routines",n),{method:"POST",body:JSON.stringify(e)})}function ud(e,n,s){return D(Za(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function my(e,n){await D(Za(`/routines/${e}`,n),{method:"DELETE"})}function hy(e,n){return D(Za(`/routines/${e}/trigger`,n),{method:"POST"})}function md(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 D(`/activity${s}`)}function py(e){const n=H("/activity",e);return D(n,{method:"DELETE"})}function co(e){return D(H("/workflow-steps",e))}function hd(e,n){return D(H("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function fy(e,n,s){return D(H(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function gy(e,n){return D(H(`/workflow-steps/${e}`,n),{method:"DELETE"})}function pd(e,n){return D(H(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function by(e,n){return D(H(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function xy(){return D("/workflow-step-templates")}function vy(e,n){return D(H(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function er(e){return D(H("/scripts",e))}function yy(e,n,s){return D(H("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function ky(e,n){return D(H(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function kh(e,n,s){return(await D(H("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const fr={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 jh(e){if(!(e instanceof Error))return fr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?fr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?fr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:fr.NETWORK}function jy(e,n){return D(H("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function wy(e,n,s){return D(H(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ny(e,n){return Wn(H(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Sy(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Qa(Ny(e,n),{onOpen:()=>{l(),r=Xa(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 Cy(e,n,s,i){return D(H("/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 wh(e,n,s){return D(H("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function H(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Ey(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 uo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Ey(e,s,i);return D(o,r)}function oa(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 D(`/agents${i}`)}function Nh(e,n){return D(H(`/agents/${encodeURIComponent(e)}`,n))}function My(e,n){return D(H("/agents",n),{method:"POST",body:JSON.stringify(e)})}function _y(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function i4(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function a4(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function r4(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function o4(e,n){return D(H(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function l4(e,n,s){const i=`path=${encodeURIComponent(n)}`;return D(H(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function c4(e,n,s,i){return D(H(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Ay(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ty(e,n){return D(H(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function d4(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 D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function u4(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function m4(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function h4(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(H(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function p4(e,n){return D(H(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Ry(e){return D(H("/agents/stats",e))}function f4(e,n){return D(H(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function g4(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return D(`/agents/org-tree${i?`?${i}`:""}`)}function b4(e,n){return D(H(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function fd(e,n,s){return D(H(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function x4(e,n){return D(H(`/agents/${encodeURIComponent(e)}/tasks`,n))}function v4(){return D("/agents/companies")}function y4(e,n){return D(H("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function k4(e,n){return D(H("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function j4(e,n){return D(H(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function w4(e){return D(H("/backups",e))}function N4(e){return D(H("/backups",e),{method:"POST"})}function S4(e,n){const s=H("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(i)}function C4(e,n,s){return D(H("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function gd(){return D("/projects/across-nodes")}function Da(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function bd(){return D("/nodes")}function Iy(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function Py(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function $y(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Dy(e){const n=await D(`/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 E4(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=Gi();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return D(u)}function Ly(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function Sh(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function xd(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function zy(e){return D(H("/executor/stats",e))}function vd(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 D(`/activity-feed${s}`)}function Fy(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Oy(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function M4(){return D("/global-concurrency")}function _4(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Uy(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ch(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 D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function By(e){return D(H("/missions",e))}function Hy(e,n){return D(H("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Eh(e,n){return D(H(`/missions/${encodeURIComponent(e)}`,n))}function qy(e,n,s){return D(H(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Vy(e,n){return D(H(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Wy(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 D(H(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Ky(e){return D(H("/missions/health",e))}function Gy(e,n,s){return D(H(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Jy(e,n,s){return D(H(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yy(e,n){return D(H(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qy(e,n,s){return D(H(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(e,n,s){return D(H(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(e,n){return D(H(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ek(e,n){return D(H(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function tk(e,n,s){return D(H(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function nk(e,n,s){return D(H(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function sk(e,n){return D(H(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ik(e,n,s){return D(H(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function ak(e,n){return D(H(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function rk(e,n,s,i){return D(H(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ok(e,n){return D(H(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Po(e,n){return D(H(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function lk(e,n,s){return D(H(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function ck(e,n,s){return D(H(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function dk(e,n,s){return D(H(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function uk(e,n,s){return D(H(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function mk(e,n){return D(H(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function $o(e,n){return D(H(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function yd(e,n){return D(H(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function hk(e,n){return D(H(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function kd(e,n){return D(H(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function pk(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 D(H(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function fk(e,n){return D(H(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function gk(e,n){return D(H(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function bk(e,n){return D(H(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function xk(e,n){return D(H(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function vk(e,n,s){return D(H(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function yk(e,n,s){return D(H("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function kk(e,n,s,i){return D(H("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function jk(e,n,s){return D(H(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Mh(e,n,s){return D(H("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function wk(e,n,s){return D(H("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Nk(e,n,s,i){const r=Wn(H(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Qa(r,{onOpen:()=>{c(),o=Xa(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 tr(e,n,s){return H(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function nr(e,n,s){return H(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Sk(e,n){return D(tr(e,"/start",n),{method:"POST"})}function Ck(e,n,s,i){return D(tr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Ek(e,n,s,i){const r=Wn(tr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Qa(r,{onOpen:()=>{c(),o=Xa(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 Mk(e,n,s){return D(tr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function _k(e,n){return D(tr(e,"/skip",n),{method:"POST"})}function Ak(e,n){return D(nr(e,"/start",n),{method:"POST"})}function Tk(e,n,s,i){return D(nr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Rk(e,n,s,i){const r=Wn(nr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Qa(r,{onOpen:()=>{c(),o=Xa(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 Ik(e,n,s){return D(nr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Pk(e,n){return D(nr(e,"/skip",n),{method:"POST"})}async function $k(e,n){try{return await D(H(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function A4(e){return D(H("/roadmaps",e))}function T4(e,n){return D(H("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function R4(e,n){return D(H(`/roadmaps/${encodeURIComponent(e)}`,n))}function I4(e,n,s){return D(H(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function P4(e,n){return D(H(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $4(e,n,s){return D(H(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function D4(e,n,s){return D(H(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function L4(e,n){return D(H(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function z4(e,n,s){return D(H(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function F4(e,n,s){return D(H(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function O4(e,n){return D(H(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function U4(e,n,s){return D(H(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function B4(e,n,s){return D(H(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function H4(e,n,s,i){return D(H(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function q4(e,n){return D(H(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function V4(e,n,s,i){return D(H(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function W4(e,n,s){return D(H(`/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 K4(e){return D(H("/todos",e))}function G4(e,n){const s={title:e};return D(H("/todos",n),{method:"POST",body:JSON.stringify(s)})}function J4(e,n,s){const i={title:n};return D(H(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function Y4(e,n){return D(H(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Q4(e,n,s){const i={text:n};return D(H(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function X4(e,n,s){const i=n;return D(H(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function Z4(e,n){return D(H(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function eP(e,n,s){return D(H(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Yi(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function _h(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Wn(`/ai-sessions${n}`),{headers:di()});return s.ok?(await s.json()).sessions??[]:[]}async function Js(e){const n=await fetch(Wn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:di()});return n.ok?n.json():null}async function Dk(e,n){const s=await D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Lk(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function zk(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Fk(e){await fetch(Wn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:di()})}function Ok(e,n){return D(H(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Uk(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 D(`/messages/inbox${i}`)}function Bk(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 D(`/messages/outbox${i}`)}function Ah(e){return D(H("/messages/unread-count",e))}function Hk(e,n){return D(H("/messages",n),{method:"POST",body:JSON.stringify(e)})}function qk(e,n){return D(H(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Vk(e){return D(H("/messages/read-all",e),{method:"POST"})}function Wk(e,n){return D(H(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Kk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(H(i,s))}function Gk(e,n){return D(H(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function tP(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 D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function nP(e,n){return D(H(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function sP(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function iP(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 D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function aP(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function rP(e,n){return D(H(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function oP(e,n,s){return D(H(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function lP(e,n){return D(H(`/agents/${encodeURIComponent(e)}/budget`,n))}function cP(e,n){return D(H(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function dP(e){return D(H("/plugins",e))}async function uP(e,n){return D(H("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function mP(e,n){return D(H(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function hP(e,n){return D(H(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function pP(e,n){return D(H(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function fP(e,n){return D(H(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function gP(e,n,s){return D(H(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function bP(e,n){return D(H(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Jk(e){return D(H("/plugins/ui-slots",e))}async function xP(e){return(await D(H("/skills/discovered",e))).skills}async function vP(e,n,s){return D(H("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function yP(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 D(H(`/skills/catalog${r}`,s))}async function kP(e,n){return(await D(H(`/skills/${encodeURIComponent(e)}/content`,n))).content}function jP(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return D(`/chat/sessions${i?`?${i}`:""}`)}async function Yk(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 D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Qk(e,n){return D(H("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function wP(e,n,s){return D(H(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function NP(e,n){return D(H(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function jd(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 D(H(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Xk(e,n){return D(H(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Zk(e,n,s,i,r){const o=Wn(H(`/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 k=g.split(`
588
+ `);g=k.pop()||"",x&&g.length>0&&(k.push(g),g="");for(const M of k){const w=M.endsWith("\r")?M.slice(0,-1):M;if(w.startsWith("event:"))p=w.slice(6).trim();else if(w.startsWith("data:")){const I=w.slice(5);f.push(I.startsWith(" ")?I.slice(1):I)}else if(w===""){const I=f.join(`
589
+ `);u(p,I),p="",f=[]}}if(x&&p&&f.length>0){const M=f.join(`
590
+ `);u(p,M),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 SP(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 D(H(`/insights${i}`,n))}function CP(e,n){return D(H(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function EP(e="manual",n,s){return D(H("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function MP(e){return D(H("/insights/runs",e))}function _P(e,n){return D(H(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function ej({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(),R=b.current,{width:z,height:G,offsetTop:$,offsetLeft:T}=v(),j=16,W=16,K=6,B=R?.offsetWidth||Math.max(_.width,260),A=Math.min(B,Math.max(z-j*2,160)),L=R?.offsetHeight||280,X=Math.min(L,Math.max(G-W*2,160)),C=_.top-$,V=_.bottom-$,fe=_.left-T,ae=G-V,oe=C,F=ae<X&&oe>ae,de=Math.min(Math.max(fe,j),z-j-A)+T,re=F?Math.max(W+$,C-X-K+$):Math.min(V+K+$,G+$-W-X);g({top:re,left:de,width:A})},[v]),k=a.useMemo(()=>Object.entries(o).sort(([P],[_])=>P.localeCompare(_)),[o]),M=k.length>0,w=k.length+(M?1:0);a.useEffect(()=>{if(!i)return;let P=!1;return u(!0),er(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,k.length,M,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 I=a.useCallback(P=>{switch(P.key){case"ArrowDown":P.preventDefault(),m(_=>_<w-1?_+1:0);break;case"ArrowUp":P.preventDefault(),m(_=>_>0?_-1:w-1);break;case"Enter":if(P.preventDefault(),d>=0)if(d<k.length){const[_,R]=k[d];E(_,R)}else M&&d===k.length&&N();break;case"Home":P.preventDefault(),m(0);break;case"End":P.preventDefault(),m(w-1);break}},[d,w,k,M]),y=a.useCallback(()=>{r(P=>!P)},[]),E=a.useCallback((P,_)=>{n(P,_),r(!1)},[n]),N=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:y,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[t.jsx(Bs,{size:16}),t.jsx(Lt,{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:I,"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(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):k.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(Bs,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:N,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:k.map(([P,_],R)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${d===R?"highlighted":""}`,onClick:()=>E(P,_),role:"option","aria-selected":d===R,"data-testid":`quick-script-item-${P}`,children:[t.jsx(rn,{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 ${M&&d===k.length?"highlighted":""}`,onClick:N,"data-testid":"quick-scripts-manage",children:[t.jsx(Ba,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function tj(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 nj({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}=tj(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 wd=new Map,sj=6e4;function Th(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=wd.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 Jk(e);if(h||u.current)return;wd.set(m,{slots:b,expiresAt:Date.now()+sj}),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 mo({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Th(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(oo,{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 ij(){return typeof window>"u"?"desktop":window.matchMedia("(max-width: 768px)").matches?"mobile":window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches?"tablet":"desktop"}function sr(){const[e,n]=a.useState(ij);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 Rh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function aj({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(Lt,{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=Rh[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(xn,{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 Nd({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 rj({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:k,globalPaused:M,enginePaused:w,onToggleGlobalPause:I,onToggleEnginePause:y,view:E="board",onChangeView:N,showSkillsTab:P,showAgentsTab:_,searchQuery:R="",onSearchChange:z,projects:G=[],currentProject:$,onSelectProject:T,onViewAllProjects:j,projectId:W,isElectron:K=!1,mobileNavEnabled:B,availableNodes:A=[],currentNode:L,onSelectNode:X,isRemote:C=!1,experimentalFeatures:V}){const fe=sr(),ae=fe==="mobile",F=ae||fe==="tablet",de=ae&&B,[re,Z]=a.useState(!1),[ue,Ce]=a.useState(!1),[he,Ne]=a.useState(!1),[ee,we]=a.useState(!1),[Ie,qe]=a.useState(!1),[Ve,Ge]=a.useState(!1),[Ke,Qe]=a.useState(!1),[Se,Fe]=a.useState(!1),[ie,Q]=a.useState(!1),[pe,te]=a.useState(!1),[ye,ce]=a.useState({}),[Re,Ze]=a.useState(!1),at=a.useRef(null),le=a.useRef(null),U=a.useRef(null),ne=a.useRef(null),ke=a.useRef(null),_e=a.useRef(null),ge=a.useRef(!1),He=a.useRef(null),ve=a.useRef(null),$e=a.useRef(null),ze=a.useRef(null),me=a.useRef(null),Pe=a.useMemo(()=>A.filter(De=>De.type==="remote"),[A]),be=Pe.length>0,We=a.useMemo(()=>Object.entries(ye).sort(([De],[gt])=>De.localeCompare(gt)),[ye]),tt=a.useMemo(()=>!!(V?.insights||V?.roadmap||P||V?.memoryView||V?.devServerView),[V,P]);a.useEffect(()=>{ge.current=Ie},[Ie]),a.useEffect(()=>{if(!Ie||!F)return;let De=!1;return Ze(!0),er(W).then(gt=>{De||ce(gt)}).catch(()=>{De||ce({})}).finally(()=>{De||Ze(!1)}),()=>{De=!0}},[Ie,F,W]);const ct=re||R.length>0,wt=(ue||R.length>0)&&!he,Nt=(E==="board"||E==="list")&&!ae&&z&&!he&&R.length===0,It=(E==="board"||E==="list")&&!ae&&z;a.useEffect(()=>{R===""&&Ne(!1)},[R]),a.useEffect(()=>{if(!ee)return;const De=gt=>{le.current&&!le.current.contains(gt.target)&&at.current&&!at.current.contains(gt.target)&&we(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[ee]),a.useEffect(()=>{if(!ie)return;const De=gt=>{ne.current&&!ne.current.contains(gt.target)&&U.current&&!U.current.contains(gt.target)&&Q(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[ie]),a.useEffect(()=>{if(!Ve)return;const De=gt=>{He.current&&!He.current.contains(gt.target)&&Ge(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[Ve]),a.useEffect(()=>{const De=gt=>{if(gt.key==="Escape"){if(Fe(!1),Q(!1),ge.current){qe(!1);return}we(!1),Z(!1),Ge(!1),Qe(!1)}};return document.addEventListener("keydown",De),()=>document.removeEventListener("keydown",De)},[]),a.useEffect(()=>{if(!Ke)return;const De=gt=>{ve.current&&!ve.current.contains(gt.target)&&Qe(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[Ke]),a.useEffect(()=>{if(!pe)return;const De=gt=>{me.current&&!me.current.contains(gt.target)&&te(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[pe]),a.useEffect(()=>{if(!pe)return;const De=gt=>{gt.key==="Escape"&&te(!1)};return document.addEventListener("keydown",De),()=>document.removeEventListener("keydown",De)},[pe]),a.useEffect(()=>{if(!Se)return;const De=gt=>{$e.current&&!$e.current.contains(gt.target)&&ze.current&&!ze.current.contains(gt.target)&&Fe(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[Se]);const Ut=a.useCallback(()=>{Z(De=>!De)},[]),Vt=a.useCallback(()=>{Ce(!0),Ne(!1)},[]),zt=a.useCallback(()=>{Ce(!1),Ne(!0),z&&z("")},[z]),Mt=a.useCallback(()=>{we(De=>!De)},[]),xt=a.useCallback(De=>{De&&De(),we(!1),qe(!1)},[]),_t=a.useCallback(()=>{Z(!1),z&&z("")},[z]);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"})]}),ae&&G.length>=1&&T&&t.jsxs("div",{className:"mobile-project-switch",ref:ve,children:[t.jsx("button",{className:`mobile-project-switch-trigger${Ke?" mobile-project-switch-trigger--open":""}`,onClick:()=>Qe(De=>!De),title:"Switch project","aria-label":"Switch project","aria-expanded":Ke,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Lt,{size:14,className:`mobile-project-switch-chevron${Ke?" mobile-project-switch-chevron--open":""}`})}),Ke&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:G.map(De=>{const gt=$?.id===De.id,ut=Rh[De.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${gt?" mobile-project-switch-item--current":""}`,onClick:()=>{T(De),Qe(!1)},role:"option","aria-selected":gt,"data-testid":`mobile-project-switch-item-${De.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:ut||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:De.name}),t.jsx("span",{className:"mobile-project-switch-path",children:De.path.split("/").slice(-2).join("/")})]}),gt&&t.jsx(xn,{size:14,className:"mobile-project-switch-check"})]},De.id)})})]}),!F&&G.length>=1&&j&&t.jsx(aj,{projects:G,currentProject:$??null,onViewAll:j,onSelectProject:T}),be&&t.jsxs("div",{className:`header-node-selector${ae?" header-node-selector--mobile":""}`,ref:ae?void 0:He,children:[t.jsx(nj,{node:L??null,showDetails:!ae}),!ae&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Ve?" node-selector-trigger--open":""}`,onClick:()=>Ge(De=>!De),title:"Switch node","aria-label":"Switch node","aria-expanded":Ve,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(en,{size:12,className:`node-selector-chevron${Ve?" node-selector-chevron--open":""}`})}),Ve&&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),Ge(!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"})]}),Pe.map(De=>t.jsxs("button",{className:`node-selector-option${L?.id===De.id?" node-selector-option--active":""}`,onClick:()=>{X?.(De),Ge(!1)},role:"option","aria-selected":L?.id===De.id,"data-testid":`node-option-${De.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${De.status}`}),t.jsx("span",{className:"node-selector-option-label",children:De.name}),t.jsx("span",{className:"node-selector-option-status",children:De.status})]},De.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[de&&N&&(E==="board"||E==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>N("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>N("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Il,{size:16})})]}),z&&ae&&(de||E==="board"||E==="list")&&!ct&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Ut,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Bi,{size:16})}),Nt&&t.jsx("button",{className:"btn-icon",onClick:Vt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Bi,{size:16})}),ae&&de&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ss,{size:16})}),!de&&N&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>N("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>N("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list",children:t.jsx(Il,{size:16})}),_&&t.jsx("button",{className:`view-toggle-btn${E==="agents"?" active":""}`,onClick:()=>N("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":E==="agents",children:t.jsx(an,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="missions"?" active":""}`,onClick:()=>N("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":E==="missions",children:t.jsx(ns,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="chat"?" active":""}`,onClick:()=>N("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":E==="chat",children:t.jsx(li,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="documents"?" active":""}`,onClick:()=>N("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":E==="documents",children:t.jsx(Ni,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="mailbox"?" active":""}`,onClick:()=>N("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":E==="mailbox",children:t.jsx(Ki,{size:16})}),tt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:ze,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver","todos"].includes(E)?" active":""}`,onClick:()=>Fe(De=>!De),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Se,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Lt,{size:12})}),Se&&t.jsxs("div",{ref:$e,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[V?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="insights"?" active":""}`,onClick:()=>{N("insights"),Fe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Dn,{size:14}),t.jsx("span",{children:"Insights"})]}),V?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="roadmaps"?" active":""}`,onClick:()=>{N("roadmaps"),Fe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Pl,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),P&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="skills"?" active":""}`,onClick:()=>{N("skills"),Fe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(vn,{size:14}),t.jsx("span",{children:"Skills"})]}),V?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="memory"?" active":""}`,onClick:()=>{N("memory"),Fe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Dr,{size:14}),t.jsx("span",{children:"Memory"})]}),V?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="dev-server"||E==="devserver"?" active":""}`,onClick:()=>{N("devserver"),Fe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(ch,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),t.jsxs("button",{className:`view-toggle-overflow-item${E==="todos"?" active":""}`,onClick:()=>{N("todos"),Fe(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(mh,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!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(Ua,{size:16})}),!F&&!K&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Nd,{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(Us,{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(Bs,{size:16})}),!F&&x&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:x,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(jn,{size:16})}),!F&&m&&t.jsx("button",{className:"btn-icon",onClick:m,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Os,{size:16})}),!F&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Dl,{size:16})}),!F&&f&&b&&t.jsx(ej,{onOpenScripts:f,onRunScript:b,projectId:W}),!F&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:U,className:"btn-icon",onClick:()=>Q(De=>!De),title:"More actions","aria-label":"More actions","aria-expanded":ie,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Tl,{size:16})}),ie&&t.jsxs("div",{ref:ne,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),Q(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Fr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{xt(d),Q(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:me,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${M?" btn-icon--stopped":""}`,onClick:I,title:M?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:M?t.jsx(rn,{size:16}):t.jsx(ls,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${pe?" btn-icon--active":""}`,onClick:()=>te(De=>!De),title:"Engine options","aria-haspopup":"menu","aria-expanded":pe,"data-testid":"engine-control-chevron-btn",children:t.jsx(Lt,{size:12})}),pe&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${w?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{y?.(),te(!1)},role:"menuitem",title:w?"Resume scheduling":"Pause triage",disabled:!!M,"data-testid":"engine-control-pause-triage-btn",children:[w?t.jsx(rn,{size:14}):t.jsx(Fs,{size:14}),t.jsx("span",{children:w?"Resume scheduling":"Pause triage"})]})})]}),!F&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Ba,{size:16})}),t.jsx(mo,{slotId:"header-action",projectId:W}),F&&!de&&t.jsx("button",{ref:at,className:"btn-icon compact-overflow-trigger",onClick:Mt,title:"More header actions","aria-label":"More header actions","aria-expanded":ee,"aria-haspopup":"menu",children:t.jsx(Tl,{size:16})}),F&&!de&&ee&&t.jsxs("div",{ref:le,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[G.length>=1&&j&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(j),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(oh,{size:16}),t.jsx("span",{children:"Projects"})]}),x&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(x),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(jn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>xt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Us,{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:()=>xt(m),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Os,{size:16}),t.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Fr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!K&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(n),role:"menuitem",children:[t.jsx(Nd,{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:()=>xt(v),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Bs,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>qe(De=>!De),role:"menuitem","aria-expanded":Ie,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(en,{size:14,className:`mobile-overflow-chevron${Ie?" mobile-overflow-chevron--open":""}`})})]}),Ie&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Re?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):We.length>0?t.jsxs(t.Fragment,{children:[We.map(([De,gt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(De,gt),we(!1),qe(!1)},role:"menuitem","data-testid":`overflow-script-item-${De}`,children:[t.jsx(rn,{size:14}),t.jsx("span",{children:De})]},De)),f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(d),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(ji,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Ua,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),c&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(c),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Ki,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(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:()=>xt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Dl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(e),role:"menuitem",children:[t.jsx(Ba,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),It&&wt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:R,onChange:De=>z(De.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:zt,"aria-label":"Close search",children:t.jsx(Dt,{size:14})})]})}),z&&ae&&ct&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:ke,className:"header-search mobile-search-expanded",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:_e,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:R,onChange:De=>z(De.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:_t,"aria-label":"Close search",children:t.jsx(Dt,{size:14})})]})})]})}const oj={themeMode:"dark",colorTheme:"default",defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90},lj={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,remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!1,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,experimentalFeatures:{}},cj=Object.freeze(Object.keys(oj)),dj=Object.freeze(Object.keys(lj));function AP(e){return cj.includes(e)}function TP(e){return dj.includes(e)}function xe(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const RP=["off","minimal","low","medium","high"],ki=["triage","todo","in-progress","in-review","done","archived"],hc=["low","normal","high","urgent"],cs="normal",uj=["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"],Pn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},mj={triage:"Raw ideas — AI will plan 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"},Ol={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 hj(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 pj(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 fj(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 Ih({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(es,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${fj(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(no,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function gr(e,n){return`${e??"default"}:${n}`}class gj{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=gr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=gr(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=gr(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(Hs(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=gr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Sd(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:Sd(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 gi=new gj;let bj=0;function Sd(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ph(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${bj++}`);const s=a.useSyncExternalStore(o=>gi.subscribe(o),()=>gi.getSnapshot(),()=>gi.getSnapshot()),i=a.useCallback(o=>{gi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{gi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{gi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{gi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function qr(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function xj({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Ph(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=qr(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=qr(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(Ih,{prInfo:h,issueInfo:g})}const vj=a.memo(xj);vj.displayName="TaskCardBadge";const yj={sm:16,md:20,lg:24};function kj({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 Cd({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 Ed({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 jj({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 wj({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 Nj({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 Do({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 Md({size:e,color:n,label:s="Amazon Bedrock"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"bedrock-icon","aria-label":s,children:t.jsx("path",{d:"M.045 18.02c.072-.116.187-.124.348-.022 2.344 1.476 4.878 2.212 7.607 2.212 1.86 0 3.68-.398 5.453-1.198.386-.168.71-.298.972-.39.26-.092.478-.113.654-.06.176.052.263.2.263.443 0 .222-.12.453-.358.693-.96.962-2.16 1.71-3.592 2.242A12.126 12.126 0 0 1 7.297 23c-2.456 0-4.583-.665-6.378-1.992a.39.39 0 0 1-.098-.096c-.05-.078-.05-.156 0-.234zm6.609-3.26c0-.37.093-.665.282-.886.188-.222.43-.332.727-.332.282 0 .524.105.726.314.2.21.3.498.3.866v4.116c0 .382-.098.676-.294.882-.196.206-.436.31-.72.31-.294 0-.54-.108-.738-.324-.198-.216-.296-.506-.296-.868v-4.078h.014zm-2.986 2.3c0-.376.096-.672.288-.89.192-.216.434-.324.726-.324.292 0 .534.108.726.324.192.218.288.514.288.89v1.778c0 .376-.096.672-.288.89-.192.216-.434.324-.726.324-.292 0-.534-.108-.726-.324-.192-.218-.288-.514-.288-.89v-1.778zm-2.92 1.334c0-.36.09-.65.27-.868.18-.218.42-.328.722-.328s.544.11.73.328c.186.218.278.508.278.868v.444c0 .36-.092.65-.278.868-.186.218-.428.328-.73.328s-.542-.11-.722-.328c-.18-.218-.27-.508-.27-.868v-.444zM21.93 16.4c.804.456 1.39.87 1.758 1.242.368.372.552.7.552.984 0 .208-.102.37-.308.488-.206.118-.462.128-.768.032-.306-.096-.674-.316-1.104-.66a12.728 12.728 0 0 1-1.864-1.75c-1.592.644-3.342.966-5.25.966-1.354 0-2.604-.178-3.752-.534a8.103 8.103 0 0 1-.09-.032l.03.012c-.136-.048.056.022-.042-.014-.04-.016-.04-.016 0 0l.012.004-.012-.004c-.32-.122-.528-.222-.624-.3-.096-.078-.144-.178-.144-.3 0-.098.04-.186.122-.264.082-.078.19-.116.326-.116.076 0 .284.054.624.162 1.078.34 2.264.51 3.558.51 1.642 0 3.194-.286 4.658-.856a17.018 17.018 0 0 1-1.904-3.326c-.416-.94-.726-1.86-.93-2.758-.206-.898-.308-1.728-.308-2.49 0-.664.094-1.194.28-1.592.188-.396.456-.594.804-.594.2 0 .392.074.576.224.184.148.312.354.384.614.1.358.178.758.234 1.198.056.44.084.876.084 1.306 0 .898-.116 1.862-.348 2.894-.232 1.032-.614 2.11-1.146 3.234a16.217 16.217 0 0 0 1.916 1.694z",fill:n})})}function _d({size:e,color:n,label:s="xAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"xai-icon","aria-label":s,children:t.jsx("path",{d:"M2.21 3l7.964 11.386L2.13 21h1.974l6.843-7.07L17.165 21H22.1l-8.392-11.97L21.17 3h-1.974l-6.349 6.56L6.845 3z",fill:n})})}function Sj({size:e,color:n,label:s="Opencode"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"opencode-icon","aria-label":s,children:t.jsx("path",{d:"M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6z",fill:n})})}function Cj({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 Ad({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 Ej={anthropic:{component:kj,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:Cd,color:"var(--provider-openai)"},"openai-codex":{component:Cd,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ed,color:"var(--provider-gemini)"},gemini:{component:Ed,color:"var(--provider-gemini)"},ollama:{component:jj,color:"var(--text)"},github:{component:Ad,color:"var(--text)"},"github-copilot":{component:Ad,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Cj,color:"var(--provider-openrouter)"},minimax:{component:wj,color:"var(--provider-minimax)"},zai:{component:Nj,color:"var(--provider-zai)"},kimi:{component:Do,color:"var(--provider-kimi)"},moonshot:{component:Do,color:"var(--provider-kimi)"},"kimi-coding":{component:Do,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Md,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Md,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:_d,color:"var(--text)"},grok:{component:_d,color:"var(--text)",label:"xAI"},opencode:{component:Sj,color:"var(--provider-opencode)"}};function Mn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Ej[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=yj[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(bg,{size:c})})}const ks={data:new Map,pendingPromise:null,lastFetchTime:null},Mj=5e3;function Ir(e,n){return n?`${n}::${e}`:e}function _j(e,n){const s=ks.data.get(Ir(e,n));if(!(!s||Date.now()-s.timestamp>Mj))return s}function Aj(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 vv(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=xe(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,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(Ir(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(Ir(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(Ir(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ks.lastFetchTime,getBatchData:l}}const Ul=new Map,Tj=3e4;function $h(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Rj(e,n,s,i){const r=$h(e,n,s,i),o=Ul.get(r);return o?Date.now()>o.expiresAt?(Ul.delete(r),null):o.stats:null}function Ij(e,n,s,i,r){const o=$h(e,n,s,i);Ul.set(o,{stats:r,expiresAt:Date.now()+Tj})}function Pj(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 k(w=!1){if(!w){const I=Rj(e,i,b,v);if(I){x||(m(I),g(!1));return}}g(!0);try{const I=await Ch(e,b,i);x||(m(I.stats),Ij(e,i,b,v,I.stats))}catch{x||m(null)}finally{x||g(!1)}}k();let M;return u&&f&&(M=setInterval(()=>{k(!0)},u)),()=>{x=!0,M&&clearInterval(M)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const $j=new Set(["failed","stuck-killed"]);function Vr(e,n,s){if(e.column!=="in-progress"||e.status&&$j.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Dj(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Lj(e){return e==="done"||e==="skipped"}function zj(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Dh(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:zj(u,d,n),status:d?Dj(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Lj(u.status)).length;return{total:l,completed:c,items:o}}const Bl=new Map;async function Fj(e,n){const s=Bl.get(e);if(s)return s;try{const i=await Eh(e,n);return Bl.set(e,i.title),i.title}catch{return e}}const Rd=12;function Oj(e){return e.length<=Rd?e:e.slice(0,Rd-3)+"..."}const Hl=new Map;async function Uj(e,n){const s=Hl.get(e);if(s)return s;try{const i=await Nh(e,n);return Hl.set(e,i.name),i.name}catch{return e}}function Bj(e){return typeof e=="string"&&hc.includes(e)?e:cs}function Hj(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const qj=new Set(["triage","todo"]),Id=new Set(["planning","researching","executing","finalizing","merging"]),Vj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},Wj=new Set(["in-progress","done"]),Kj=3e4;function pc(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Pd(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=pc(n);if(s==null)return null;const i=Date.now();return s>i?null:s}function Gj(e){const n=pc(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Jj(e,n){return[e.createdAt].map(pc).filter(r=>r!=null).find(r=>r<=n)??null}function $d(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 Dd(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 Yj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Qj(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 Zj(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 ew(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 tw(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 nw(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 sw(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.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&tw(s.attachments,i.attachments)&&nw(s.comments,i.comments)&&Qj(s.dependencies,i.dependencies)&&Yj(s.steps,i.steps)&&Xj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&ew(s.workflowStepResults,i.workflowStepResults)&&Dd(s.prInfo,i.prInfo)&&Dd(s.issueInfo,i.issueInfo)}function iw({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),[k,M]=a.useState(!1),[w,I]=a.useState(!1),[y,E]=a.useState(e.description||""),[N,P]=a.useState(!1),[_,R]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(S=>S.status==="done"||S.status==="skipped")),[z,G]=a.useState(null),[$,T]=a.useState(null),[j,W]=a.useState(!1),[K,B]=a.useState(()=>Date.now()),A=a.useRef(null),L=a.useRef(!1),X=a.useRef(null),C=a.useRef(null),[V,fe]=a.useState(!1),{badgeUpdates:ae,subscribeToBadge:oe,unsubscribeFromBadge:F}=Ph(n),de=a.useRef(null),re=a.useRef(!1),Z=a.useCallback(S=>S instanceof Element?!!S.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{E(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!j)return;const S=q=>{C.current&&!C.current.contains(q.target)&&W(!1)};return document.addEventListener("click",S),()=>document.removeEventListener("click",S)},[j]),a.useEffect(()=>{if(!e.missionId){G(null);return}const S=Bl.get(e.missionId);if(S){G(S);return}let q=!1;return Fj(e.missionId,n).then(Ae=>{q||G(Ae)}),()=>{q=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){T(null);return}const S=Hl.get(e.assignedAgentId);if(S){T(S);return}T(null);let q=!1;return Uj(e.assignedAgentId,n).then(Ae=>{q||T(Ae)}),()=>{q=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(w&&A.current){const S=A.current;S.focus(),S.style.height="auto",S.style.height=S.scrollHeight+"px"}},[w]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){fe(!0);return}const S=X.current;if(!S)return;const q=new IntersectionObserver(([Ae])=>{fe(Ae?.isIntersecting??!0)},{rootMargin:"200px"});return q.observe(S),()=>q.disconnect()},[w,e.id]);const ue=a.useCallback(S=>{S.dataTransfer.setData("text/plain",e.id),S.dataTransfer.effectAllowed="move",x(!0)},[e.id]),Ce=a.useCallback(()=>{x(!1)},[]),he=a.useCallback(S=>S.dataTransfer.types.includes("Files"),[]),Ne=a.useCallback(S=>{he(S)&&(S.preventDefault(),S.stopPropagation(),S.dataTransfer.dropEffect="copy",M(!0))},[he]),ee=a.useCallback(S=>{he(S)&&(S.preventDefault(),S.stopPropagation(),M(!1))},[he]),we=a.useCallback(async S=>{if(!he(S))return;S.preventDefault(),S.stopPropagation(),M(!1);const q=Array.from(S.dataTransfer.files);for(const Ae of q)try{await Ha(e.id,Ae,n),r(`Attached ${Ae.name} to ${e.id}`,"success")}catch(ot){r(`Failed to attach ${Ae.name}: ${xe(ot)}`,"error")}},[e.id,he,r]),Ie=a.useCallback(()=>{w||i(e)},[e,i,w]),qe=a.useCallback(S=>{if(L.current){L.current=!1;return}Z(S.target)||Ie()},[Ie,Z]),Ve=a.useCallback(S=>{const q=S.touches[0];q&&(de.current={x:q.clientX,y:q.clientY,time:Date.now()},re.current=!1)},[]),Ge=a.useCallback(S=>{if(!de.current)return;const q=S.touches[0];if(!q)return;const Ae=Math.abs(q.clientX-de.current.x),ot=Math.abs(q.clientY-de.current.y);(Ae>Ld||ot>Ld)&&(re.current=!0)},[]),Ke=a.useCallback(S=>{if(Z(S.target)||!de.current)return;const Ae=Date.now()-de.current.time<aw,ot=!re.current;Ae&&ot&&(L.current=!0,Ie()),de.current=null,re.current=!1},[Ie,Z]),Qe=a.useCallback(async(S,q)=>{S.stopPropagation();try{const Ae=await Br(q,n);i(Ae)}catch{r(`Failed to load dependency ${q}`,"error")}},[i,r]),Se=e.status==="failed",Fe=e.paused===!0,ie=Bj(e.priority),Q=ie!==cs,pe=Vr(e,h,f),te=e.column==="triage"&&e.status==="awaiting-approval",ye=e.column==="archived",ce=!o&&!s&&!Se&&!Fe&&!pe&&!te&&(e.column==="in-progress"||Id.has(e.status)),Re=!s&&!Fe&&!w&&!ye,Ze=qj.has(e.column)&&!ce&&!Fe&&!s&&l,at=!!(e.prInfo||e.issueInfo),le=!!(e.assignedAgentId&&$===null),U=a.useMemo(()=>{const S=[];return e.modelProvider&&S.push(e.modelProvider),e.validatorModelProvider&&!S.includes(e.validatorModelProvider)&&S.push(e.validatorModelProvider),e.planningModelProvider&&!S.includes(e.planningModelProvider)&&S.push(e.planningModelProvider),S},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),ne=a.useMemo(()=>Dh(e,b),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,b]),ke=ne.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"||Pd(e)==null)return;B(Date.now());const q=window.setInterval(()=>{B(Date.now())},Kj);return()=>window.clearInterval(q)},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt]);const _e=a.useMemo(()=>{if(!Wj.has(e.column))return null;if(e.column==="in-progress"){const kt=Pd(e);if(kt==null)return null;const Ot=$d(K-kt);return Ot?{label:Ot,title:`In progress since ${new Date(kt).toLocaleString()}`,ariaLabel:`Elapsed time ${Ot}. In progress since ${new Date(kt).toLocaleString()}`}:null}const S=Gj(e);if(S==null)return null;const q=Jj(e,S);if(q==null)return null;const Ae=$d(S-q);if(!Ae)return null;const ot=new Date(S).toLocaleString();return{label:Ae,title:`Processing took ${Ae}. Completed ${ot}`,ariaLabel:`Completed processing duration ${Ae}. Completed ${ot}`}},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt,K]);a.useEffect(()=>{if(!at||!V){F(e.id);return}return oe(e.id),()=>{F(e.id)}},[at,V,oe,e.id,F]);const ge=ae.get(`${n??"default"}:${e.id}`),He=e.column==="in-progress"||e.column==="in-review",ve=a.useMemo(()=>e.steps.map(S=>`${S.name}:${S.status}`).join("|"),[e.steps]),{stats:$e}=Pj(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:V,worktree:e.worktree,stepVersion:He?ve:void 0,pollIntervalMs:He?3e4:void 0}),ze=a.useMemo(()=>_j(e.id,n),[e.id,n]),me=a.useMemo(()=>{const S=ge?.prInfo,q=ge?.timestamp,Ae=ze?.result?.prInfo,ot=ze?.timestamp?new Date(ze.timestamp).toISOString():void 0,kt=e.prInfo,Ot=e.prInfo?.lastCheckedAt??e.updatedAt;let sn=qr(S,q,kt,Ot);const Pt=q&&q>=Ot?q:Ot;return Ae&&ot&&(!Pt||ot>Pt)&&(sn=Ae),sn},[ge,ze,e.prInfo,e.updatedAt]),Pe=a.useMemo(()=>{const S=ge?.issueInfo,q=ge?.timestamp,Ae=ze?.result?.issueInfo,ot=ze?.timestamp?new Date(ze.timestamp).toISOString():void 0,kt=e.issueInfo,Ot=e.issueInfo?.lastCheckedAt??e.updatedAt;let sn=qr(S,q,kt,Ot);const Pt=q&&q>=Ot?q:Ot;return Ae&&ot&&(!Pt||ot>Pt)&&(sn=Ae),sn},[ge,ze,e.issueInfo,e.updatedAt]),be=a.useCallback(S=>{S?.stopPropagation(),!(!Ze||N)&&(I(!0),E(e.description||""))},[Ze,N,e.description]),We=a.useCallback(()=>{I(!1),E(e.description||"")},[e.description]),tt=a.useCallback(()=>y!==(e.description||""),[y,e.description]),ct=a.useCallback(async()=>{if(!(!l||N)){if(!tt()){We();return}P(!0);try{await l(e.id,{description:y.trim()||void 0}),r(`Updated ${e.id}`,"success"),I(!1)}catch(S){r(`Failed to update ${e.id}: ${xe(S)}`,"error")}finally{P(!1)}}},[l,e.id,y,N,tt,We,r]),wt=a.useCallback(S=>{S.key==="Enter"&&!S.shiftKey?(S.preventDefault(),ct()):S.key==="Escape"&&(S.preventDefault(),We())},[ct,We]),Nt=a.useCallback(()=>{setTimeout(()=>{const S=document.activeElement;S===A.current||S?.closest(".card-editing-content")||(tt()?ct():We())},0)},[tt,ct,We]),It=a.useCallback(S=>{Ze&&(S.stopPropagation(),be(S))},[Ze,be]),Ut=a.useCallback(S=>{S.stopPropagation(),be(S)},[be]),Vt=a.useCallback(S=>{E(S.target.value);const q=S.target;q.style.height="auto",q.style.height=q.scrollHeight+"px"},[]),zt=a.useCallback(S=>{S.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(q=>{r(`Failed to archive ${e.id}: ${xe(q)}`,"error")})},[r,c,e.id]),Mt=a.useCallback(S=>{S.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(q=>{r(`Failed to unarchive ${e.id}: ${xe(q)}`,"error")})},[r,u,e.id]),xt=a.useCallback(S=>{S.stopPropagation(),d&&window.confirm(`Delete ${e.id}?`)&&d(e.id).then(()=>{r(`Deleted ${e.id}`,"success")}).catch(q=>{const Ae=Zj(q);if(!Ae||Ae.dependentIds.length===0){r(`Failed to delete ${e.id}: ${xe(q)}`,"error");return}const ot=Ae.dependentIds.join(", ");window.confirm(`${e.id} is a dependency of ${ot}.
591
+
592
+ Delete anyway by removing these dependency references first?`)&&d(e.id,{removeDependencyReferences:!0}).then(()=>{r(`Deleted ${e.id} after removing dependency references`,"success")}).catch(Ot=>{r(`Failed to delete ${e.id}: ${xe(Ot)}`,"error")})})},[r,d,e.id]),_t=a.useCallback(S=>{S.stopPropagation(),m?.(e,"changes")},[e,m]),De=a.useCallback(S=>{S.stopPropagation(),R(q=>!q)},[]),gt=a.useCallback(S=>{S.stopPropagation(),e.missionId&&g&&g(e.missionId)},[e.missionId,g]),ut=a.useCallback(S=>{S.stopPropagation(),W(q=>!q)},[]),Me=a.useCallback((S,q)=>{S.stopPropagation(),W(!1),p&&p(e.id,q).then(()=>{r(`Moved ${e.id} to ${Pn[q]}`,"success")}).catch(Ae=>{r(`Failed to move ${e.id}: ${xe(Ae)}`,"error")})},[r,p,e.id]),Ye=`card${v?" dragging":""}${s?" queued":""}${ce?" agent-active":""}${Se?" failed":""}${Fe?" paused":""}${pe?" stuck":""}${te?" awaiting-approval":""}${k?" file-drop-target":""}${w?" card-editing":""}${N?" card-saving":""}`,rt=(()=>{if(e.worktree&&e.column==="in-progress"){const S=$e?.filesChanged;return S==null||S===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[S," ",S===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const S=$e?.filesChanged,q=S==null?e.modifiedFiles?.length:void 0,Ae=S??q;return Ae==null||Ae===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[Ae," ",Ae===1?"file":"files"," changed"]})]})}if(e.column==="done"){const S=$e?.filesChanged,q=e.mergeDetails?.filesChanged,Ae=S??q;if(Ae!=null&&Ae>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[Ae," ",Ae===1?"file":"files"," changed"]})]});const ot=e.modifiedFiles?.length;if(ot!=null&&ot>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[ot," ",ot===1?"file":"files"," changed"]})]})}return null})();return w?t.jsx("div",{ref:X,className:Ye,"data-id":e.id,onDoubleClick:It,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:A,className:"card-edit-desc-textarea",placeholder:"Task description",value:y,onChange:Vt,onKeyDown:wt,onBlur:Nt,disabled:N,rows:4}),N&&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:Ye,"data-id":e.id,draggable:Re,onDragStart:Re?ue:void 0,onDragEnd:Re?Ce:void 0,onDragOver:Ne,onDragLeave:ee,onDrop:we,onClick:qe,onTouchStart:Ve,onTouchMove:Ge,onTouchEnd:Ke,onDoubleClick:It,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Fe&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Fe&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${te?" awaiting-approval":""}${Id.has(e.status)?" pulsing":""}${Se?" failed":""}${pe?" stuck":""}`,children:pe?"Stuck":te?"Awaiting Approval":e.status}),pe&&(Fe||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),at&&t.jsx(Ih,{prInfo:me,issueInfo:Pe}),Q&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${ie}`,children:ie}),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:gt,title:`Mission: ${z??e.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ns,{size:11}),Oj(z??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ze&&t.jsx("button",{className:"card-edit-btn",onClick:Ut,title:"Edit task","aria-label":"Edit task",children:t.jsx(qn,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:xt,title:"Delete task","aria-label":"Delete task",children:t.jsx(Ht,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:zt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Mt,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:ut,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":j,children:["Send back",t.jsx(Lt,{size:10})]}),j&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Ol["in-progress"].filter(S=>S!=="in-review").map(S=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:q=>Me(q,S),children:Pn[S]},S))})]}),e.column==="in-review"&&p&&t.jsxs("div",{className:"card-send-back",ref:C,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ut,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":j,children:["Move",t.jsx(Lt,{size:10})]}),j&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Ol["in-review"].map(S=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:q=>Me(q,S),children:S==="done"?"Done (no merge)":Pn[S]},S))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Se&&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:Fd(e.title,zd)||Fd(e.description,zd)||e.id}),ke&&(()=>{const S=ne.completed/ne.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:`${S}%`,backgroundColor:Vj[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[ne.completed,"/",ne.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:De,"aria-expanded":_,"aria-label":_?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[ne.total," step",ne.total===1?"":"s"]}),t.jsx(Lt,{size:14,className:`card-steps-toggle-icon${_?" expanded":""}`})]}),_&&t.jsx("div",{className:"card-steps-list",children:ne.items.map(q=>{const Ae=q.source==="workflow"&&q.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${q.status}${Ae?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${q.status==="done"?" completed":""}`,children:q.name}),q.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${q.phase}`,title:"Workflow check",children:"workflow"})]},q.id)})})]})})(),(rt||_e)&&t.jsxs("div",{className:"card-footer-row",children:[rt,_e&&t.jsxs("span",{className:"card-time-indicator",title:_e.title,"aria-label":_e.ariaLabel,children:[t.jsx(ji,{size:12}),t.jsx("span",{children:_e.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(S=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:q=>void Qe(q,S),title:`Click to view ${S}`,children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}})," ",S]},S))}),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(ji,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||U.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[U.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:U.map(S=>t.jsx(Mn,{provider:S,size:"sm"},S))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${le?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(an,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:Hj($??e.assignedAgentId,15)})]})]}),t.jsx(mo,{slotId:"task-card-badge",projectId:n})]})}const Ld=10,aw=300,zd=140;function Fd(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Wr=a.memo(iw,sw);Wr.displayName="TaskCard";function rw({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(dg,{size:14}):t.jsx(Os,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(p=>t.jsx(Wr,{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(Wr,{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 Lh=a.memo(rw);Lh.displayName="WorktreeGroup";function Od(e){return e.toLowerCase().replace(/[-_./]/g,"")}function ow(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 lw(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 cw(e,n){const s=Od(e),i=Od(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&&ow(s,o)||s.length>=4&&lw(s,o,1))return!0;return!1}function dw(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=>cw(o,r))})}function wn({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,k]=a.useState(0),[M,w]=a.useState(null),[I,y]=a.useState(null),E=a.useRef(null),N=a.useRef(null),P=a.useRef(null),_=a.useRef(null),R=a.useRef(null),z=a.useMemo(()=>dw(e,b),[e,b]),G=a.useMemo(()=>z.reduce((Z,ue)=>((Z[ue.provider]??=[]).push(ue),Z),{}),[z]),$=a.useMemo(()=>{const Z=[];for(const ue of d){const Ce=ue.indexOf("/");if(Ce===-1)continue;const he=ue.slice(0,Ce),Ne=ue.slice(Ce+1),ee=z.find(we=>we.provider===he&&we.id===Ne);ee&&Z.push({model:ee,fullId:ue})}return Z},[d,z]),T=a.useMemo(()=>{const Z=Object.entries(G),ue=new Set(c);return Z.sort(([Ce],[he])=>{const Ne=ue.has(Ce),ee=ue.has(he);if(Ne&&!ee)return-1;if(!Ne&&ee)return 1;if(Ne&&ee){const we=c.indexOf(Ce),Ie=c.indexOf(he);if(we!==Ie)return we-Ie}return Ce.localeCompare(he)})},[G,c]),j=typeof h=="string"&&h.length>0,W=a.useMemo(()=>{if(!n||j&&n===h)return null;const Z=n.indexOf("/");return Z===-1?null:n.slice(0,Z)},[j,h,n]),K=a.useMemo(()=>{const Z=[];return j&&Z.push({type:"no-change",value:h,label:g}),Z.push({type:"default",value:"",label:"Use default"}),Z},[j,g,h]),B=a.useMemo(()=>{const Z=[...K];for(const{model:ue,fullId:Ce}of $)Z.push({type:"favorite",value:Ce,label:ue.name,provider:ue.provider});return T.forEach(([ue,Ce])=>{Z.push({type:"provider",value:`__group_${ue}`,label:ue,provider:ue}),Ce.forEach(he=>{Z.push({type:"model",value:`${he.provider}/${he.id}`,label:he.name,provider:he.provider})})}),Z},[$,T,K]),A=a.useMemo(()=>{if(j&&n===h)return g;if(!n)return"Use default";const Z=n.indexOf("/");if(Z===-1)return n;const ue=n.slice(0,Z),Ce=n.slice(Z+1);return e.find(Ne=>Ne.provider===ue&&Ne.id===Ce)?.name||n},[j,g,h,n,e]),L=a.useMemo(()=>B.findIndex(Z=>Z.value===n),[B,n]),X=a.useCallback(()=>{const Z=window.visualViewport;return Z&&Z.height>0&&Z.width>0?{width:Z.width,height:Z.height,offsetTop:Z.offsetTop,offsetLeft:Z.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),C=a.useCallback(()=>{const{height:Z}=X(),ue=typeof window.matchMedia=="function",Ce=ue?window.matchMedia("(max-width: 640px)").matches:!1,he=ue?window.matchMedia("(max-width: 768px)").matches:!1;return Z<=0?320:Ce?Math.min(Z*.6,360):he?Math.min(Z*.7,420):320},[X]),V=a.useCallback(()=>{const Z=N.current;if(!Z)return;const ue=Z.getBoundingClientRect(),{width:Ce,height:he,offsetTop:Ne,offsetLeft:ee}=X(),we=16,Ie=16,qe=4,Ve=C(),Ge=ue.bottom-Ne,Ke=ue.top-Ne,Qe=ue.left-ee,Se=he-Ge,Fe=Ke,ie=Math.max(Se-Ie-qe,160),Q=Math.max(Fe-Ie-qe,160),pe=Se<Ve&&Fe>Se,te=Math.max(Math.min(pe?Q:ie,Ve),160),ye=Math.min(ue.width,Ce-we*2),ce=Math.min(Math.max(Qe,we),Ce-we-ye)+ee,Re=pe?Math.max(Ie+Ne,Ke-te-qe+Ne):Math.min(Ge+qe+Ne,he+Ne-Ie-te);w({top:Re,left:ce,width:ye,maxHeight:te})},[X,C]);a.useEffect(()=>{y(document.body)},[]),a.useEffect(()=>{if(p){const Z=B.findIndex((ue,Ce)=>Ce>=(L>=0?L:0)&&ue.type!=="provider");k(Z>=0?Z:0)}},[p,B,L]),a.useEffect(()=>{if(!p)return;V();const Z=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(Z)},[p,V]),a.useEffect(()=>{if(!p)return;const Z=()=>V();window.addEventListener("resize",Z),window.addEventListener("scroll",Z,!0);const ue=window.visualViewport;return ue&&(ue.addEventListener("resize",Z),ue.addEventListener("scroll",Z)),()=>{window.removeEventListener("resize",Z),window.removeEventListener("scroll",Z,!0),ue&&(ue.removeEventListener("resize",Z),ue.removeEventListener("scroll",Z))}},[p,V]),a.useEffect(()=>{if(!p)return;const Z=ue=>{const Ce=ue.target,he=E.current?.contains(Ce),Ne=P.current?.contains(Ce);!he&&!Ne&&(f(!1),v(""))};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[p]);const fe=a.useCallback(Z=>{switch(Z.key){case"ArrowDown":if(Z.preventDefault(),!p)f(!0);else{let ue=x;for(let Ce=1;Ce<=B.length;Ce++){const he=(x+Ce)%B.length;if(B[he]?.type!=="provider"){ue=he;break}}k(ue)}break;case"ArrowUp":if(Z.preventDefault(),p){let ue=x;for(let Ce=1;Ce<=B.length;Ce++){const he=(x-Ce+B.length)%B.length;if(B[he]?.type!=="provider"){ue=he;break}}k(ue)}break;case"Enter":if(Z.preventDefault(),p){const ue=B[x];ue&&ue.type!=="provider"&&ue.type!=="favorite"&&(s(ue.value),f(!1),v(""))}else f(!0);break;case"Escape":Z.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,x,B,s]),ae=a.useCallback(Z=>{s(Z),f(!1),v("")},[s]),oe=a.useCallback(()=>{v(""),_.current?.focus()},[]),F=a.useCallback(()=>{r||f(Z=>!Z)},[r]);a.useEffect(()=>{if(p&&R.current){const Z=R.current.querySelector(`[data-index="${x}"]`);Z&&typeof Z.scrollIntoView=="function"&&Z.scrollIntoView({block:"nearest"})}},[x,p]);const de=b.length>0,re=p&&M?t.jsxs("div",{ref:P,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:fe,style:{top:`${M.top}px`,left:`${M.left}px`,width:`${M.width}px`,maxHeight:`${M.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:Z=>v(Z.target.value),onClick:Z=>Z.stopPropagation()}),de&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:oe,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[z.length," model",z.length!==1?"s":""]}),t.jsxs("div",{ref:R,className:"model-combobox-list",children:[K.map((Z,ue)=>t.jsx("div",{"data-index":ue,className:`model-combobox-option ${x===ue?"model-combobox-option--highlighted":""} ${n===Z.value?"model-combobox-option--selected":""}`,onClick:()=>ae(Z.value),onMouseEnter:()=>k(ue),role:"option","aria-selected":n===Z.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Z.label})},`${Z.type}-${Z.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:Z,fullId:ue},Ce)=>{const he=Ce+K.length,Ne=x===he,ee=n===ue;return t.jsxs("div",{"data-index":he,className:`model-combobox-option model-combobox-option--favorite ${Ne?"model-combobox-option--highlighted":""} ${ee?"model-combobox-option--selected":""}`,onClick:()=>ae(ue),onMouseEnter:()=>k(he),role:"option","aria-selected":ee,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Mn,{provider:Z.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Z.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Z.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:we=>{we.stopPropagation(),m(ue)},title:"Remove from favorites","aria-label":`Remove ${Z.name} from favorites`,children:"★"})]},ue)}),t.jsx("div",{className:"model-combobox-divider"})]}),T.map(([Z,ue])=>{const Ce=B.findIndex(ee=>ee.value===`__group_${Z}`),he=c.includes(Z),Ne=ue.filter(ee=>{const we=`${ee.provider}/${ee.id}`;return!d.includes(we)});return Ne.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":Ce,children:[t.jsx(Mn,{provider:Z,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Z}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${he?"model-combobox-optgroup-favorite--active":""}`,onClick:ee=>{ee.stopPropagation(),u(Z)},title:he?"Remove from favorites":"Add to favorites","aria-label":he?`Remove ${Z} from favorites`:`Add ${Z} to favorites`,children:"★"})]}),Ne.map(ee=>{const we=`${ee.provider}/${ee.id}`,Ie=B.findIndex(Ke=>Ke.value===we),qe=x===Ie,Ve=n===we,Ge=d.includes(we);return t.jsxs("div",{"data-index":Ie,className:`model-combobox-option ${qe?"model-combobox-option--highlighted":""} ${Ve?"model-combobox-option--selected":""}`,onClick:()=>ae(we),onMouseEnter:()=>k(Ie),role:"option","aria-selected":Ve,children:[t.jsx("span",{className:"model-combobox-option-text",children:ee.name}),t.jsx("span",{className:"model-combobox-option-id",children:ee.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ge?"model-combobox-option-favorite--active":""}`,onClick:Ke=>{Ke.stopPropagation(),m(we)},title:Ge?"Remove from favorites":"Add to favorites","aria-label":Ge?`Remove ${ee.name} from favorites`:`Add ${ee.name} to favorites`,children:Ge?"★":"☆"})]},we)})]},Z)}),z.length===0&&de&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:E,className:"model-combobox",onKeyDown:fe,children:t.jsxs("button",{ref:N,type:"button",id:o,className:"model-combobox-trigger",onClick:F,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[W&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Mn,{provider:W,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),I&&re?Ta.createPortal(re,I):null]})}function fc(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Nn(e,n){return typeof window>"u"?null:window.localStorage.getItem(fc(e,n))}function ts(e,n,s){typeof window>"u"||window.localStorage.setItem(fc(e,s),n)}function Va(e,n){typeof window>"u"||window.localStorage.removeItem(fc(e,n))}const fa="kb-quick-entry-text",uw=["image/png","image/jpeg","image/gif","image/webp"];function Lo(e,n){return e&&n?`${e}/${n}`:""}function zo(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 zh({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"&&Nn(fa,l)||""),[f,b]=a.useState(!1),[v,x]=a.useState(!1),[k,M]=a.useState(!1),w=a.useRef(null),I=a.useRef(null),y=a.useRef(!1),E=a.useRef(l),[N,P]=a.useState([]),_=a.useRef([]),[R,z]=a.useState([]),[G,$]=a.useState(!1),[T,j]=a.useState(""),[W,K]=a.useState(null),[B,A]=a.useState([]),[L,X]=a.useState(void 0),[C,V]=a.useState(!1),[fe,ae]=a.useState(!1),[oe,F]=a.useState(!1),[de,re]=a.useState(null),[Z,ue]=a.useState(void 0),[Ce,he]=a.useState(void 0),[Ne,ee]=a.useState(void 0),[we,Ie]=a.useState(void 0),[qe,Ve]=a.useState(void 0),[Ge,Ke]=a.useState(void 0),Qe=a.useRef(null),Se=a.useRef(null),Fe=a.useRef(null),ie=a.useRef(null),[Q,pe]=a.useState(null),[te,ye]=a.useState(null),ce=a.useRef(null),Re=a.useRef(null),[Ze,at]=a.useState(null),[le]=a.useState(()=>typeof document<"u"?document.body:null),[U,ne]=a.useState(!1),[ke,_e]=a.useState(null),[ge,He]=a.useState(i??[]),[ve,$e]=a.useState([]),[ze,me]=a.useState([]),[Pe,be]=a.useState(null),[We,tt]=a.useState(void 0),[ct,wt]=a.useState(!1),[Nt,It]=a.useState(!1),[Ut,Vt]=a.useState(!1),zt=a.useRef(null),Mt=a.useRef(null),[xt,_t]=a.useState(null),De=u??ve,gt=d??ze,ut=!e;a.useEffect(()=>{if(i)He(i),ne(!1),_e(null);else{let se=!1;return ne(!0),_e(null),is().then(Ee=>{se||(He(Ee.models),u||$e(Ee.favoriteProviders),d||me(Ee.favoriteModels))}).catch(Ee=>{se||_e(xe(Ee)||"Failed to load models")}).finally(()=>{se||ne(!1)}),lo(l).then(Ee=>{se||be(Ee)}).catch(()=>{}),()=>{se=!0}}},[i,u,d,l]);const Me=Lo(Z,Ce),Ye=Lo(Ne,we),rt=Lo(qe,Ge),S=!!(Z&&Ce),q=!!(Ne&&we),Ae=!!(qe&&Ge),ot=Number(S)+Number(q)+Number(Ae),kt=We?Pe?.modelPresets?.find(se=>se.id===We)?.name??"Models":ot>0?`${ot} model${ot===1?"":"s"}`:"Models",Ot=a.useCallback((se,Ee)=>{if(!se||!Ee)return"Using default";const st=ge.find(ft=>ft.provider===se&&ft.id===Ee);return st?`${st.provider}/${st.id}`:`${se}/${Ee}`},[ge]);a.useEffect(()=>{p(Nn(fa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ts(fa,g,l)},[g,l]),a.useEffect(()=>{E.current!==l&&(E.current=l,A([]),X(void 0),K(null),V(!1),pe(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{_.current=N},[N]),a.useEffect(()=>()=>{_.current.forEach(se=>URL.revokeObjectURL(se.previewUrl))},[]);const sn=a.useCallback(()=>{const se=w.current;if(!se)return;se.style.height="auto";const Ee=Math.min(se.scrollHeight,200);se.style.height=`${Ee}px`},[]);a.useEffect(()=>{v&&sn()},[g,v,sn]),a.useEffect(()=>{if(!f&&g===""&&w.current){const se=setTimeout(()=>{w.current?.focus()},0);return()=>clearTimeout(se)}},[f,g]),a.useEffect(()=>{G||j("")},[G]),a.useEffect(()=>{if(!Nt)return;const se=Ee=>{const st=Ee.target,ft=zt.current?.contains(st),bt=Mt.current?.contains(st);!ft&&!bt&&It(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[Nt]),a.useEffect(()=>{if(!oe)return;const se=Ee=>{const st=Ee.target,ft=Qe.current?.contains(st),bt=Se.current?.contains(st),on=st instanceof Element&&st.closest?.(".model-combobox-dropdown--portal")!=null;!ft&&!bt&&!on&&(F(!1),re(null))};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[oe]),a.useEffect(()=>{if(!C)return;const se=Ee=>{const st=Ee.target;Fe.current?.contains(st)||ie.current?.contains(st)||(V(!1),pe(null))};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[C]);const Pt=a.useCallback(()=>{N.forEach(se=>URL.revokeObjectURL(se.previewUrl)),P([]),I.current&&(I.current.value=""),p(""),z([]),K(null),V(!1),pe(null),ue(void 0),he(void 0),ee(void 0),Ie(void 0),Ve(void 0),Ke(void 0),tt(void 0),wt(!1),$(!1),F(!1),ye(null),re(null),It(!1),Vt(!1),x(!1),M(!1),y.current=!0,w.current&&(w.current.style.height="auto"),typeof window<"u"&&Va(fa,l)},[N,l]),zn=a.useCallback(se=>{if(!se||se.length===0)return;const Ee=[];for(let st=0;st<se.length;st++){const ft=se[st];uw.includes(ft.type)&&Ee.push({file:ft,previewUrl:URL.createObjectURL(ft)})}Ee.length>0&&P(st=>[...st,...Ee])},[]),Kn=a.useCallback(se=>{f||zn(se.clipboardData?.files)},[zn,f]),ms=a.useCallback(se=>{P(Ee=>{const st=Ee[se];return st&&URL.revokeObjectURL(st.previewUrl),Ee.filter((ft,bt)=>bt!==se)})},[]),pn=a.useCallback(async()=>{const se=g.trim();if(!(!se||f||!e)){b(!0);try{const Ee=await e({description:se,column:"triage",dependencies:R.length?R:void 0,...W?{assignedAgentId:W}:{},modelPresetId:We,modelProvider:S?Z:void 0,modelId:S?Ce:void 0,validatorModelProvider:q?Ne:void 0,validatorModelId:q?we:void 0,planningModelProvider:Ae?qe:void 0,planningModelId:Ae?Ge:void 0,...ct?{executionMode:"fast"}:{}});if(Ee&&N.length>0){const st=[];for(const ft of N)try{await Ha(Ee.id,ft.file,l)}catch{st.push(ft.file.name)}st.length>0&&n(`Failed to upload: ${st.join(", ")}`,"error")}Pt()}catch(Ee){n(xe(Ee)||"Failed to create task","error")}finally{b(!1)}}},[g,f,e,R,W,S,Z,Ce,q,Ne,we,Ae,qe,Ge,N,l,n,Pt,ct]),Fn=a.useCallback(se=>{if(se.key==="Enter"){if(se.shiftKey&&v)return;se.preventDefault(),pn()}else if(se.key==="Escape"){if(se.preventDefault(),de){re(null);return}if(oe){F(!1),ye(null);return}if(G){$(!1);return}if(Nt){It(!1);return}if(C){V(!1),pe(null);return}g.trim()&&(p(""),w.current&&(w.current.style.height="auto"),typeof window<"u"&&Va(fa,l)),x(!1),M(!1),w.current?.blur()}},[pn,g,v,G,C,oe,de,Nt,l,M]),Sn=a.useCallback(()=>{y.current&&(y.current=!1)},[]),fn=a.useCallback(()=>{c&&x(!0)},[c]),Gn=a.useCallback(se=>{z(Ee=>Ee.includes(se)?Ee.filter(st=>st!==se):[...Ee,se])},[]),dn=a.useCallback(()=>{const se=window.visualViewport;return se&&se.width>0&&se.height>0?{width:se.width,height:se.height,offsetTop:se.offsetTop,offsetLeft:se.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),At=a.useCallback(()=>{const se=Qe.current;if(!se)return;const Ee=se.getBoundingClientRect(),{width:st,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Zt=16,cn=16,Gt=4,bn=st<=768,Cn=Math.min(bn?ft*.6:ft*.5,360),gs=bn?Math.min(st-Zt*2,360):Math.max(Ee.width,240),Un=Math.min(gs,Math.max(st-Zt*2,200)),Yn=Ee.top-bt,Bn=Ee.bottom-bt,Qn=Ee.left-on,un=ft-Bn,Xn=Yn,Es=Math.max(un-cn-Gt,160),Is=Math.max(Xn-cn-Gt,160),rs=un<Cn&&Xn>un,An=Math.max(Math.min(rs?Is:Es,Cn),160),bs=Math.min(Math.max(Qn,Zt),st-Zt-Un)+on,Tn=rs?Math.max(cn+bt,Yn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);ye({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]),yn=a.useCallback(()=>{const se=zt.current?.querySelector(".refine-button");if(!se)return;const Ee=se.getBoundingClientRect(),{width:st,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Zt=8,cn=12,Gt=4,bn=Math.min(200,Math.max(ft-cn*2,160)),Cn=Math.min(200,st-Zt*2),gs=Ee.top-bt,Un=Ee.bottom-bt,Yn=Ee.left-on,Bn=ft-Un,Qn=gs,un=Bn<bn&&Qn>Bn,Xn=Math.min(Math.max(Yn,Zt),st-Zt-Cn)+on,Es=un?Math.max(cn+bt,gs-bn-Gt+bt):Math.min(Un+Gt+bt,ft+bt-cn-bn);_t({top:Es,left:Xn})},[dn]),Jn=a.useCallback(()=>{const se=ce.current;if(!se)return;const Ee=se.getBoundingClientRect(),{width:st,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Zt=16,cn=16,Gt=4,bn=st<=768,Cn=Math.min(bn?ft*.6:ft*.5,320),gs=bn?Math.min(st-Zt*2,360):Math.max(Ee.width,280),Un=Math.min(gs,Math.max(st-Zt*2,240)),Yn=Ee.top-bt,Bn=Ee.bottom-bt,Qn=Ee.left-on,un=ft-Bn,Xn=Yn,Es=Math.max(un-cn-Gt,200),Is=Math.max(Xn-cn-Gt,200),rs=un<Cn&&Xn>un,An=Math.max(Math.min(rs?Is:Es,Cn),200),bs=Math.min(Math.max(Qn,Zt),st-Zt-Un)+on,Tn=rs?Math.max(cn+bt,Yn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);at({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]),kn=a.useCallback(()=>{const se=Fe.current?.querySelector("button");if(!se)return;const Ee=se.getBoundingClientRect(),{width:st,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Zt=16,cn=16,Gt=4,bn=st<=768,Cn=Math.min(bn?ft*.6:ft*.5,320),gs=bn?Math.min(st-Zt*2,280):Math.max(Ee.width,240),Un=Math.min(gs,Math.max(st-Zt*2,200)),Yn=Ee.top-bt,Bn=Ee.bottom-bt,Qn=Ee.left-on,un=ft-Bn,Xn=Yn,Es=Math.max(un-cn-Gt,160),Is=Math.max(Xn-cn-Gt,160),rs=un<Cn&&Xn>un,An=Math.max(Math.min(rs?Is:Es,Cn),160),bs=Math.min(Math.max(Qn,Zt),st-Zt-Un)+on,Tn=rs?Math.max(cn+bt,Yn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);pe({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]);a.useEffect(()=>{if(!oe)return;const se=()=>At();window.addEventListener("resize",se),window.addEventListener("scroll",se,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",se),Ee.addEventListener("scroll",se)),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",se,!0),Ee&&(Ee.removeEventListener("resize",se),Ee.removeEventListener("scroll",se))}},[oe,At]),a.useEffect(()=>{if(!Nt)return;const se=()=>yn();window.addEventListener("resize",se),window.addEventListener("scroll",se,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",se),Ee.addEventListener("scroll",se)),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",se,!0),Ee&&(Ee.removeEventListener("resize",se),Ee.removeEventListener("scroll",se))}},[Nt,yn]),a.useEffect(()=>{if(!G)return;const se=()=>Jn();window.addEventListener("resize",se),window.addEventListener("scroll",se,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",se),Ee.addEventListener("scroll",se)),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",se,!0),Ee&&(Ee.removeEventListener("resize",se),Ee.removeEventListener("scroll",se))}},[G,Jn]),a.useEffect(()=>{if(!C)return;const se=()=>kn();window.addEventListener("resize",se),window.addEventListener("scroll",se,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",se),Ee.addEventListener("scroll",se)),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",se,!0),Ee&&(Ee.removeEventListener("resize",se),Ee.removeEventListener("scroll",se))}},[C,kn]);const _n=a.useCallback(se=>{const Ee=zo(se);Ve(Ee.provider),Ke(Ee.modelId)},[]),hs=a.useCallback(se=>{const Ee=zo(se);ue(Ee.provider),he(Ee.modelId)},[]),ps=a.useCallback(se=>{const Ee=zo(se);ee(Ee.provider),Ie(Ee.modelId)},[]),On=a.useCallback(async se=>{if(m){m(se);return}const Ee=ve,ft=Ee.includes(se)?Ee.filter(bt=>bt!==se):[se,...Ee];$e(ft);try{await nn({favoriteProviders:ft,favoriteModels:ze})}catch{$e(Ee)}},[ve,ze,m]),J=a.useCallback(async se=>{if(h){h(se);return}const Ee=ze,ft=Ee.includes(se)?Ee.filter(bt=>bt!==se):[se,...Ee];me(ft);try{await nn({favoriteProviders:ve,favoriteModels:ft})}catch{me(Ee)}},[ze,ve,h]),Le=a.useCallback(()=>{const se=g.trim();if(!se){n("Enter a description first","error");return}r?.(se),Pt()},[g,r,n,Pt]),nt=a.useCallback(()=>{const se=g.trim();if(!se){n("Enter a description first","error");return}o?.(se),Pt()},[g,o,n,Pt]),et=a.useCallback(()=>{pn()},[pn]),mt=a.useCallback(async se=>{const Ee=g.trim();if(!(!Ee||Ut)){It(!1),Vt(!0);try{const st=await kh(Ee,se,l);p(st),n("Description refined with AI","success"),w.current&&(w.current.style.height="auto",w.current.style.height=`${Math.min(w.current.scrollHeight,200)}px`)}catch(st){const ft=jh(st);n(ft,"error")}finally{Vt(!1)}}},[g,Ut,n,l]),jt=(se,Ee)=>se.length>Ee?se.slice(0,Ee)+"…":se,Tt=a.useCallback(async()=>{if(i){He(i),_e(null),ne(!1);return}ne(!0),_e(null);try{const se=await is();He(se.models),u||$e(se.favoriteProviders),d||me(se.favoriteModels)}catch(se){_e(xe(se)||"Failed to load models")}finally{ne(!1)}},[i,u,d]),gn=a.useCallback(async()=>{if(B.length>0&&L===l){V(!0),kn();return}ae(!0);try{const se=await oa(void 0,l);A(se),X(l),V(!0),kn()}catch(se){const Ee=xe(se);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),V(!1)}finally{ae(!1)}},[B.length,L,l,n,kn]),Xt=(W?B.find(se=>se.id===W):void 0)?.name??W,vt=k,dt=a.useCallback(()=>{M(se=>{const Ee=!se;return x(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${k?"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:w,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:se=>p(se.target.value),onKeyDown:Fn,onPaste:Kn,onFocus:fn,onBlur:Sn,disabled:f||ut,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":k})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:dt,"aria-expanded":k,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:k?"Collapse":"Expand",children:k?t.jsx(Ys,{size:14}):t.jsx(Lt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!vt,"aria-hidden":!vt,children:[vt&&!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:se=>se.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Us,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:nt,onMouseDown:se=>se.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(io,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:zt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ut?"refine-button--loading":""}`,onClick:()=>{It(se=>{const Ee=!se;return Ee?yn():_t(null),Ee})},disabled:!g.trim()||Ut,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),Ut?"Refining...":"Refine"]}),Nt&&le&&xt&&Ta.createPortal(t.jsxs("div",{ref:Mt,className:"refine-menu refine-menu--portal",onMouseDown:se=>se.preventDefault(),style:{position:"fixed",top:`${xt.top}px`,left:`${xt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("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:()=>mt("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:()=>mt("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:()=>mt("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"})]})]}),le)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:ce,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(se=>{const Ee=!se;return Ee?(F(!1),ye(null),re(null),V(!1),Jn()):at(null),Ee})},children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`${R.length} deps`:"Deps"]})}),G&&le&&Ze&&(()=>{const se=T.toLowerCase(),Ee=(se?s.filter(st=>st.id.toLowerCase().includes(se)||st.title&&st.title.toLowerCase().includes(se)||st.description&&st.description.toLowerCase().includes(se)):[...s]).sort((st,ft)=>{const bt=ft.createdAt.localeCompare(st.createdAt);if(bt!==0)return bt;const on=parseInt(st.id.slice(st.id.lastIndexOf("-")+1),10)||0;return(parseInt(ft.id.slice(ft.id.lastIndexOf("-")+1),10)||0)-on});return Ta.createPortal(t.jsxs("div",{ref:Re,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:T,onChange:st=>j(st.target.value),onClick:st=>st.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(st=>t.jsxs("div",{className:`dep-dropdown-item${R.includes(st.id)?" selected":""}`,onMouseDown:ft=>ft.preventDefault(),onClick:()=>Gn(st.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:st.id}),t.jsx("span",{className:"dep-dropdown-title",children:jt(st.title||st.description||st.id,60)})]},st.id))]}),le)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>I.current?.click(),children:[t.jsx(Mb,{size:12,style:{verticalAlign:"middle"}}),N.length>0?`Attach (${N.length})`:"Attach"]}),t.jsxs("button",{ref:Qe,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),V(!1),re(null),F(!0),At()},children:[t.jsx(Dr,{size:12,style:{verticalAlign:"middle"}}),kt]}),t.jsx("div",{className:"agent-trigger-wrap",ref:Fe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{C?(V(!1),pe(null)):gn()},"data-testid":"quick-entry-agent-button",children:[t.jsx(an,{size:12,style:{verticalAlign:"middle"}}),Xt?` ${Xt}`:" Agent"]})}),C&&le&&Q&&Ta.createPortal(t.jsxs("div",{ref:ie,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:se=>se.preventDefault(),style:{position:"fixed",top:`${Q.top}px`,left:`${Q.left}px`,width:`${Q.width}px`,maxHeight:Q.maxHeight?`${Q.maxHeight}px`:void 0,overflowY:Q.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(se=>se.state!=="terminated").map(se=>t.jsxs("div",{className:`dep-dropdown-item${W===se.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{K(se.id===W?null:se.id),V(!1),pe(null)},children:[t.jsx(an,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:se.role}),t.jsx("span",{className:"dep-dropdown-title",children:se.name})]},se.id)),!fe&&B.filter(se=>se.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),W&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:se=>se.preventDefault(),onClick:()=>{K(null),V(!1),pe(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),le),t.jsx("button",{type:"button",className:`btn btn-sm ${ct?"btn-primary":""}`,onClick:()=>wt(se=>!se),onMouseDown:se=>se.preventDefault(),"aria-pressed":ct,"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:et,onMouseDown:se=>se.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(uh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),N.length>0&&t.jsx("div",{className:"inline-create-previews",children:N.map((se,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:se.previewUrl,alt:se.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ms(Ee),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},se.previewUrl))}),oe&&le&&te&&Ta.createPortal(t.jsx("div",{ref:Se,className:"model-nested-menu model-nested-menu--portal",onMouseDown:se=>se.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${te.top}px`,left:`${te.left}px`,width:`${te.width}px`,maxHeight:te.maxHeight?`${te.maxHeight}px`:void 0,overflowY:te.maxHeight?"auto":void 0},children:de===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Ae?"model-menu-item--active":""}`,onClick:()=>re("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Us,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Ae?Ot(qe,Ge):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${S?"model-menu-item--active":""}`,onClick:()=>re("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:S?Ot(Z,Ce):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${q?"model-menu-item--active":""}`,onClick:()=>re("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Dr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:q?Ot(Ne,we):"Using default"}),t.jsx(en,{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:()=>re(null),"data-testid":"model-submenu-back",children:[t.jsx(Lt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[de==="plan"&&"Plan Model",de==="executor"&&"Executor Model",de==="validator"&&"Reviewer Model"]}),t.jsx(wn,{models:ge,value:de==="plan"?rt:de==="executor"?Me:Ye,onChange:de==="plan"?_n:de==="executor"?hs:ps,placeholder:"Using default",disabled:U,id:`model-${de}-select`,label:`${de} model`,favoriteProviders:De,onToggleFavorite:On,favoriteModels:gt,onToggleModelFavorite:J}),ke&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:ke}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Tt,children:"Retry"})]})]})}),le)]}),t.jsx("input",{ref:I,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:se=>{zn(se.target.files),se.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function mw(e){const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function hw(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 pw(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=hw(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:mw(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 Ud=100,Fo=50,Bd=25;function fw({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:k,onToggleCollapse:M,allTasks:w,availableModels:I,onPlanningMode:y,onSubtaskBreakdown:E,onOpenDetailWithTab:N,favoriteProviders:P,favoriteModels:_,onToggleFavorite:R,onToggleModelFavorite:z,isSearchActive:G,taskStuckTimeoutMs:$,onOpenMission:T,lastFetchTimeMs:j,workflowStepNameLookup:W}){const[K,B]=a.useState(!1),[A,L]=a.useState(Fo),[X,C]=a.useState(!1),[V,fe]=a.useState(!1),[ae,oe]=a.useState(!1),[F,de]=a.useState(!1),re=a.useRef(null),Z=pj(n.length);a.useEffect(()=>{if(!X)return;function ye(Re){re.current?.contains(Re.target)||C(!1)}function ce(Re){Re.key==="Escape"&&C(!1)}return document.addEventListener("mousedown",ye),document.addEventListener("keydown",ce),()=>{document.removeEventListener("mousedown",ye),document.removeEventListener("keydown",ce)}},[X]);const ue=e==="archived",Ce=ue&&k,he=!ue&&!G&&e!=="in-progress"&&n.length>Ud;a.useEffect(()=>{L(ye=>e==="in-progress"||ue||n.length<=Ud?Fo:Math.min(Math.max(ye,Fo),n.length))},[e,ue,n.length]);const Ne=a.useCallback(ye=>{ue||(ye.preventDefault(),ye.dataTransfer.dropEffect="move",B(!0))},[ue]),ee=a.useCallback(ye=>{ye.currentTarget.contains(ye.relatedTarget)||B(!1)},[]),we=a.useCallback(async ye=>{ye.preventDefault(),B(!1);const ce=ye.dataTransfer.getData("text/plain");if(!ce)return;const Re=n.find(Ze=>Ze.id===ce);if(!(Re&&Re.column===e))try{await r(ce,e)}catch(Ze){c(xe(Ze),"error")}},[e,r,c,n]),Ie=a.useMemo(()=>e!=="in-progress"?[]:pw(n,n,i),[e,n,i]),qe=a.useMemo(()=>he?n.slice(0,A):n,[he,n,A]),Ve=Math.max(0,n.length-qe.length),Ge=a.useCallback(()=>{L(ye=>Math.min(ye+Bd,n.length))},[n.length]),Ke=a.useCallback(async()=>{if(C(!1),!(n.length===0||!window.confirm(`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`))){fe(!0);try{const ce=await Promise.allSettled(n.map(at=>r(at.id,"triage"))),Re=ce.filter(at=>at.status==="rejected").length,Ze=ce.length-Re;Re===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${Ze} of ${ce.length} tasks; ${Re} failed`,"error")}finally{fe(!1)}}},[n,r,c]),Qe=a.useMemo(()=>n.filter(ye=>!ye.paused),[n]),Se=Qe.length,Fe=e==="todo"||e==="in-progress"||e==="in-review",ie=V||ae||F,Q=a.useCallback(async()=>{if(!(!o||(C(!1),Se===0)||!window.confirm(`Stop all ${Se} ${Pn[e].toLowerCase()} task${Se===1?"":"s"}?`))){oe(!0);try{const ce=await Promise.allSettled(Qe.map(at=>o(at.id))),Re=ce.filter(at=>at.status==="rejected").length,Ze=ce.length-Re;Re===0?c(`Stopped ${Ze} task${Ze===1?"":"s"}`,"success"):c(`Stopped ${Ze} of ${ce.length} tasks; ${Re} failed`,"error")}finally{oe(!1)}}},[o,Se,e,Qe,c]),pe=a.useCallback(async()=>{if(C(!1),!(n.length===0||!window.confirm(`Move all ${n.length} ${Pn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`))){de(!0);try{const ce=await Promise.allSettled(n.map(at=>r(at.id,"todo"))),Re=ce.filter(at=>at.status==="rejected").length,Ze=ce.length-Re;Re===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to Todo`,"success"):c(`Moved ${Ze} of ${ce.length} tasks to Todo; ${Re} failed`,"error")}finally{de(!1)}}},[n,e,r,c]),te=a.useCallback(async()=>{if(!(!x||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const ce=await x();c(`Archived ${ce.length} tasks`,"success")}catch(ce){c(xe(ce)||"Failed to archive tasks","error")}},[x,n.length,c]);return t.jsxs("div",{className:`column${K?" drag-over":""}${ue?" column-archived":""}${Ce?" column-collapsed":""}`,"data-column":e,onDragOver:Ne,onDragLeave:ee,onDrop:we,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Pn[e]}),t.jsx("span",{className:`column-count${Z?" 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:te,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(to,{size:16})}),ue&&M&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:M,title:k?"Expand archived tasks":"Collapse archived tasks","aria-label":k?"Expand archived tasks":"Collapse archived tasks",children:k?t.jsx(Lt,{size:16}):t.jsx(Ys,{size:16})}),Fe&&t.jsxs("div",{className:"column-menu",ref:re,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>C(ye=>!ye),"aria-haspopup":"menu","aria-expanded":X,"aria-label":`${Pn[e]} column actions`,title:"Column actions",disabled:ie,children:t.jsx(kg,{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 Ke(),disabled:n.length===0||V,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Q(),disabled:Se===0||ae||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":Se===0?"All tasks are already paused":`Pause ${Se} active task${Se===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void pe(),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"]})]})]})]})]})]}),!Ce&&t.jsx("p",{className:"column-desc",children:mj[e]}),!Ce&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(zh,{onCreate:u,addToast:c,tasks:w??[],availableModels:I,onPlanningMode:y,onSubtaskBreakdown:E,projectId:s,autoExpand:!1,favoriteProviders:P,favoriteModels:_,onToggleFavorite:R,onToggleModelFavorite:z}),e==="in-progress"?Ie.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Ie.map(ye=>t.jsx(Lh,{label:ye.label,activeTasks:ye.activeTasks,queuedTasks:ye.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onOpenDetailWithTab:N,taskStuckTimeoutMs:$,onOpenMission:T,lastFetchTimeMs:j,workflowStepNameLookup:W},ye.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[qe.map(ye=>t.jsx(Wr,{task:ye,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onOpenDetailWithTab:N,taskStuckTimeoutMs:$,onOpenMission:T,onMoveTask:r,lastFetchTimeMs:j,workflowStepNameLookup:W},ye.id)),he&&Ve>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ge,children:["Load ",Math.min(Bd,Ve)," more (",Ve," remaining)"]})]}),t.jsx(mo,{slotId:"board-column-footer",projectId:s})]})]})}const Fh=a.memo(fw);Fh.displayName="Column";function gw(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 bw(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Hd=new Map;function xw(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 vw({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:k="",availableModels:M,onPlanningMode:w,onSubtaskBreakdown:I,onOpenDetailWithTab:y,favoriteProviders:E,favoriteModels:N,onToggleFavorite:P,onToggleModelFavorite:_,taskStuckTimeoutMs:R,onOpenMission:z,lastFetchTimeMs:G}){const[$,T]=a.useState(!0),j=a.useRef(!1),{fetchBatch:W}=Aj(n),K=a.useRef(null),[B,A]=a.useState(Hd),L=k.trim()!=="",X=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),C=a.useCallback(()=>{T(ae=>{const oe=!ae;return!oe&&!j.current&&x&&(j.current=!0,x()),oe})},[x]),V=a.useMemo(()=>{const ae=Object.fromEntries(ki.map(de=>[de,[]]));for(const de of e)ae[de.column].push(de);const oe=X.current,F={};for(const de of ki){const re=gw(ae[de]);F[de]=bw(oe[de],re)?oe[de]:re}return X.current=F,F},[e]);a.useEffect(()=>{let ae=!1;return co(n).then(oe=>{if(ae)return;const F=new Map(oe.map(de=>[de.id,de.name]));A(de=>xw(de,F)?de:F)}).catch(()=>{ae||A(oe=>oe.size===0?oe:Hd)}),()=>{ae=!0}},[n]);const fe=a.useMemo(()=>e.filter(ae=>ae.prInfo||ae.issueInfo).map(ae=>ae.id),[e]);return a.useEffect(()=>{if(fe.length!==0)return K.current&&clearTimeout(K.current),K.current=setTimeout(()=>{const ae=[];for(let oe=0;oe<fe.length;oe+=50)ae.push(fe.slice(oe,oe+50));ae.forEach(oe=>{W(oe)})},500),()=>{K.current&&clearTimeout(K.current)}},[fe,W]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ki.map(ae=>t.jsx(Fh,{column:ae,tasks:V[ae],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:M,onOpenDetailWithTab:y,favoriteProviders:E,favoriteModels:N,onToggleFavorite:P,onToggleModelFavorite:_,isSearchActive:L,taskStuckTimeoutMs:R,onOpenMission:z,lastFetchTimeMs:G,workflowStepNameLookup:B,...ae==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:w,onSubtaskBreakdown:I}:{},...ae==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ae==="done"?{onArchiveAllDone:v}:{},...ae==="archived"?{collapsed:$,onToggleCollapse:C}:{}},ae))})})}const ga={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},qd=new Set(["planning","researching","executing","finalizing","merging"]),ql=["id","title","status","column","dependencies","progress"];function Vd(e){try{const n=Nn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>ql.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(ql)}function Wd(e){try{const n=Nn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Kd(e){try{const n=Nn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>ki.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Gd(e){try{const n=Nn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function yw(e){return e.status==="executing"||e.column==="in-progress"}function Jd(e){const n=Dh(e);return n.total===0||!yw(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function kw({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:k="",lastFetchTimeMs:M}){const[w,I]=a.useState("id"),[y,E]=a.useState("desc"),[N,P]=a.useState(null),[_,R]=a.useState(null),[z,G]=a.useState(null),T=sr()==="mobile",[j,W]=a.useState(()=>Vd(b)),[K,B]=a.useState(()=>Wd(b)),[A,L]=a.useState(()=>Kd(b));a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-list-columns",JSON.stringify([...j]),b)},[b,j]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-hide-done",K.toString(),b)},[K,b]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-list-collapsed",JSON.stringify([...A]),b)},[A,b]);const[X,C]=a.useState(!1),V=a.useRef(null),[fe,ae]=a.useState(()=>Gd(b));a.useEffect(()=>{W(Vd(b)),B(Wd(b)),L(Kd(b)),ae(Gd(b))},[b]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-selected-tasks",JSON.stringify([...fe]),b)},[b,fe]);const oe=a.useCallback(U=>{ae(ne=>{const ke=new Set(ne);return ke.has(U)?ke.delete(U):ke.add(U),ke})},[]),F=a.useCallback(()=>{ae(new Set)},[]),de=a.useCallback(U=>{W(ne=>{const ke=new Set(ne);return ke.has(U)?ke.size>1&&ke.delete(U):ke.add(U),ke})},[]);a.useEffect(()=>{if(!X)return;const U=ke=>{V.current&&!V.current.contains(ke.target)&&C(!1)},ne=ke=>{ke.key==="Escape"&&C(!1)};return document.addEventListener("mousedown",U),document.addEventListener("keydown",ne),()=>{document.removeEventListener("mousedown",U),document.removeEventListener("keydown",ne)}},[X]);const re={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Z=a.useCallback(U=>{w===U?E(ne=>ne==="asc"?"desc":"asc"):(I(U),E("asc"))},[w]),ue=a.useCallback(U=>{G(ne=>ne===U?null:U)},[]),Ce=a.useCallback(U=>{L(ne=>{const ke=new Set(ne);return ke.has(U)?ke.delete(U):ke.add(U),ke})},[]),he=a.useCallback(()=>{G(null)},[]),Ne=a.useMemo(()=>{let U=k?e.filter(ge=>ge.id.toLowerCase().includes(k.toLowerCase())||ge.title&&ge.title.toLowerCase().includes(k.toLowerCase())||ge.description.toLowerCase().includes(k.toLowerCase())):[...e];K&&!z&&(U=U.filter(ge=>ge.column!=="done"&&ge.column!=="archived"));const ke=[...z?U.filter(ge=>ge.column===z):U].sort((ge,He)=>{let ve=0;switch(w){case"id":ve=ge.id.localeCompare(He.id);break;case"title":ve=(ge.title||ge.description).localeCompare(He.title||He.description);break;case"status":ve=(ge.status||"").localeCompare(He.status||"");break;case"column":ve=ge.column.localeCompare(He.column);break}return y==="asc"?ve:-ve}),_e={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ke.forEach(ge=>_e[ge.column].push(ge)),_e},[e,k,w,y,K,z]),ee=a.useMemo(()=>Object.values(Ne).reduce((U,ne)=>U+ne.length,0),[Ne]),we=a.useMemo(()=>e.filter(U=>U.column==="done"||U.column==="archived").length,[e]),Ie=a.useMemo(()=>K?we:0,[K,we]),qe=a.useCallback(()=>{const U=Object.values(Ne).flat().filter(ne=>ne.column!=="archived").map(ne=>ne.id);ae(ne=>{if(U.every(_e=>ne.has(_e))){const _e=new Set(ne);return U.forEach(ge=>_e.delete(ge)),_e}else return new Set([...ne,...U])})},[Ne]),Ve=a.useMemo(()=>{const U=Object.values(Ne).flat().filter(ne=>ne.column!=="archived");return U.length===0?!1:U.every(ne=>fe.has(ne.id))},[Ne,fe]),Ge=a.useMemo(()=>{const U=Object.values(Ne).flat().filter(ke=>ke.column!=="archived");if(U.length===0)return!1;const ne=U.filter(ke=>fe.has(ke.id)).length;return ne>0&&ne<U.length},[Ne,fe]),[Ke,Qe]=a.useState("__no_change__"),[Se,Fe]=a.useState("__no_change__"),[ie,Q]=a.useState(!1),pe=a.useCallback(async()=>{if(fe.size===0)return;const U=Array.from(fe).filter(ke=>{const _e=e.find(ge=>ge.id===ke);return _e&&_e.column!=="archived"});if(U.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ne={taskIds:U};if(Ke!=="__no_change__")if(Ke==="")ne.modelProvider=null,ne.modelId=null;else{const ke=Ke.indexOf("/");ke!==-1&&(ne.modelProvider=Ke.slice(0,ke),ne.modelId=Ke.slice(ke+1))}if(Se!=="__no_change__")if(Se==="")ne.validatorModelProvider=null,ne.validatorModelId=null;else{const ke=Se.indexOf("/");ke!==-1&&(ne.validatorModelProvider=Se.slice(0,ke),ne.validatorModelId=Se.slice(ke+1))}if(Object.keys(ne).length===1){i("No changes to apply","info");return}Q(!0);try{const ke=await Tx(ne.taskIds,ne.modelProvider,ne.modelId,ne.validatorModelProvider,ne.validatorModelId,void 0,void 0,b);f&&ke.updated.length>0&&f(ke.updated),i(`Updated ${ke.count} task${ke.count===1?"":"s"}`,"success"),F(),Qe("__no_change__"),Fe("__no_change__")}catch(ke){i(xe(ke)||"Failed to update models","error")}finally{Q(!1)}},[fe,e,Ke,Se,b,i,F,f]),te=a.useCallback(U=>{s(U)},[s]),ye=a.useCallback((U,ne)=>{if(ne.paused){U.preventDefault();return}U.dataTransfer.setData("text/plain",ne.id),U.dataTransfer.effectAllowed="move",P(ne.id)},[]),ce=a.useCallback(()=>{P(null),R(null)},[]),Re=a.useCallback((U,ne)=>{U.preventDefault(),U.dataTransfer.dropEffect="move",R(ne)},[]),Ze=a.useCallback(()=>{R(null)},[]),at=a.useCallback(async(U,ne)=>{U.preventDefault(),R(null);const ke=U.dataTransfer.getData("text/plain");if(ke){if(ne==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(ke,ne)}catch(_e){i(xe(_e),"error")}}},[n,i]),le=U=>w!==U?t.jsx(eh,{size:14,className:"sort-icon"}):y==="asc"?t.jsx(yi,{size:14,className:"sort-icon active"}):t.jsx(Ga,{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:V,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>C(U=>!U),"aria-expanded":X,"aria-haspopup":"menu",children:[t.jsx(pg,{size:14}),"Columns"]}),X&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:ql.map(U=>{const ne=j.has(U),ke=ne&&j.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ke?" disabled":""}`,role:"menuitem",title:ke?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:ne,onChange:()=>de(U),disabled:ke}),t.jsx("span",{children:re[U]})]},U)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>B(U=>!U),"aria-pressed":K,title:K?"Show done tasks":"Hide done tasks",children:[K?t.jsx(Vi,{size:14}):t.jsx(Lr,{size:14}),K?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[z?`${ee} of ${e.length} tasks in ${Pn[z]}`:`${ee} of ${e.length} tasks`,Ie>0&&!z&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Ie," hidden)"]}),z&&t.jsx("button",{className:"btn btn-sm",onClick:he,"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(wn,{models:c,value:Ke,onChange:Qe,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(wn,{models:c,value:Se,onChange:Fe,label:"Reviewer 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:pe,disabled:ie||Ke==="__no_change__"&&Se==="__no_change__",children:ie?"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:ki.map(U=>{const ne=e.filter(He=>He.column===U).length,ke=U==="done"||U==="archived",_e=K&&ke?0:ne,ge=K&&ke&&ne>0;return t.jsxs("div",{className:`list-drop-zone${_===U?" drag-over":""}${z===U?" active":""}`,onClick:()=>ue(U),onDragOver:He=>Re(He,U),onDragLeave:Ze,onDrop:He=>at(He,U),"data-column":U,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:ga[U]}}),t.jsx("span",{className:"drop-zone-label",children:Pn[U]}),t.jsx("span",{className:"drop-zone-count",children:ge?`${_e} of ${ne}`:ne})]},U)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(zh,{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})}),ee===0?t.jsx("div",{className:"list-empty",children:k?"No tasks match your filter":"No tasks yet"}):T?t.jsx("div",{className:"list-cards",children:ki.map(U=>{if(z&&U!==z||K&&(U==="done"||U==="archived")&&!z)return null;const ne=Ne[U],ke=ne.length===0;if(k&&ke)return null;const _e=A.has(U);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${_e?" list-section-header--collapsed":""}`,onClick:()=>Ce(U),"aria-expanded":!_e,role:"button",tabIndex:0,onKeyDown:ge=>{(ge.key==="Enter"||ge.key===" ")&&(ge.preventDefault(),Ce(U))},children:[t.jsx(en,{size:14,className:`list-section-chevron${_e?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${U}`}),t.jsx("span",{className:"list-section-title",children:Pn[U]}),t.jsx("span",{className:"list-section-count",children:ne.length})]}),!_e&&t.jsx(t.Fragment,{children:ke?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ne.map(ge=>{const He=ge.status==="failed",ve=ge.paused===!0,$e=Vr(ge,x,M),ze=!r&&!He&&!ve&&!$e&&(ge.column==="in-progress"||qd.has(ge.status)),me=typeof ge.status=="string"&&ge.status.trim().length>0,Pe=!!(ge.dependencies&&ge.dependencies.length>0),be=Jd(ge),We=be.hasProgress,tt=fe.size>0;return t.jsxs("div",{className:`list-card${ze?" agent-active":""}${tt?" list-card--selectable":""}`,onClick:()=>te(ge),"data-id":ge.id,children:[tt&&t.jsx("label",{className:"list-card-checkbox",onClick:ct=>ct.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:fe.has(ge.id),onChange:ct=>{ct.stopPropagation(),oe(ge.id)},onClick:ct=>ct.stopPropagation(),disabled:ge.column==="archived","aria-label":`Select ${ge.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:ge.id}),ge.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),$e?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):me?t.jsx("span",{className:`list-status-badge list-status-badge--${ge.column}${He?" failed":""}${ze?" pulsing":""}`,children:ge.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:ge.title||ge.description})}),(Pe||We)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Pe&&t.jsxs("span",{className:"list-dep-badge",title:ge.dependencies.join(", "),children:[t.jsx(Wi,{size:12})," ",ge.dependencies.length]}),We&&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:ga[ge.column]}})}),t.jsx("span",{className:"list-progress-label",children:be.label})]})]})]},ge.id)})})]},U)})}):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:Ve,ref:U=>{U&&(U.indeterminate=Ge)},onChange:qe,"aria-label":"Select all visible tasks"})}),j.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Z("id"),children:["ID ",le("id")]}),j.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Z("title"),children:["Title ",le("title")]}),j.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Z("status"),children:["Status ",le("status")]}),j.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Z("column"),children:["Column ",le("column")]}),j.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),j.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ki.map(U=>{if(z&&U!==z||K&&(U==="done"||U==="archived")&&!z)return null;const ne=Ne[U],ke=ne.length===0;if(k&&ke)return null;const _e=A.has(U);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${_e?" list-section-header--collapsed":""}`,onClick:()=>Ce(U),"aria-expanded":!_e,children:t.jsxs("th",{colSpan:j.size+1,className:"list-section-cell",children:[t.jsx(en,{size:14,className:`list-section-chevron${_e?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${U}`}),t.jsx("span",{className:"list-section-title",children:Pn[U]}),t.jsx("span",{className:"list-section-count",children:ne.length})]})}),!_e&&t.jsx(t.Fragment,{children:ke?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:j.size+1,className:"list-empty-cell",children:"No tasks"})}):ne.map(ge=>{const He=ge.status==="failed",ve=ge.paused===!0,$e=Vr(ge,x,M),ze=!r&&!He&&!ve&&!$e&&(ge.column==="in-progress"||qd.has(ge.status)),me=N===ge.id;return t.jsxs("tr",{className:`list-row${He?" failed":""}${ve?" paused":""}${$e?" stuck":""}${ze?" agent-active":""}${me?" dragging":""}`,onClick:()=>te(ge),draggable:!ve,onDragStart:Pe=>ye(Pe,ge),onDragEnd:ce,"data-id":ge.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:fe.has(ge.id),onChange:Pe=>{Pe.stopPropagation(),oe(ge.id)},onClick:Pe=>Pe.stopPropagation(),disabled:ge.column==="archived","aria-label":`Select ${ge.id}`})}),j.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:ge.id}),j.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[ge.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:ge.title||ge.description})]})}),j.has("status")&&t.jsx("td",{className:"list-cell",children:$e?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ge.status?t.jsx("span",{className:`list-status-badge list-status-badge--${ge.column}${He?" failed":""}${ze?" pulsing":""}`,children:ge.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),j.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${ga[ge.column]}20`,color:ga[ge.column]},children:Pn[ge.column]})}),j.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:ge.dependencies&&ge.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:ge.dependencies.join(", "),children:[t.jsx(Wi,{size:12})," ",ge.dependencies.length]}):"-"}),j.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Pe=Jd(ge);return Pe.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:`${Pe.percent}%`,backgroundColor:ga[ge.column]}})}),t.jsx("span",{className:"list-progress-label",children:Pe.label})]}):"-"})()})]},ge.id)})})]},U)})})]})]})]})}const jw={active:{label:"Active",color:"var(--success)",icon:rn},paused:{label:"Paused",color:"var(--warning)",icon:Fs},errored:{label:"Error",color:"var(--color-error)",icon:ss},initializing:{label:"Initializing",color:"var(--info)",icon:it}};function ww(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 Nw(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 Sw(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 Cw({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=jw[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(w=>{w.stopPropagation(),i(e)},[i,e]),b=a.useCallback(w=>{w.stopPropagation(),r(e)},[r,e]),v=a.useCallback(w=>{if(w.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",k=e.status==="errored",M=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${k?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(jn,{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:Nw(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:M?"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:ww(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(rn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||M,title:M?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Fs,{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(Ja,{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(Ht,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const Ew=a.memo(Cw,Sw);function Mw(){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(jn,{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(tn,{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__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 _w=1e4,Yd=5;function Aw(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+=Yd){const b=e.slice(f,f+Yd),v=await Promise.allSettled(b.map(async x=>{try{return await xd(x)}catch{return null}}));if(b.forEach((x,k)=>{const M=v[k];p[x]=M.status==="fulfilled"?M.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 xd(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()},_w),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function Tw({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([]),k=a.useMemo(()=>e.map(G=>G.id),[e]),{healthMap:M,loading:w}=Aw(k),I=a.useMemo(()=>e.map(G=>({project:G,health:M[G.id]||null})),[e,M]),y=a.useMemo(()=>{let G=[...I];return u!=="all"&&(G=G.filter(({project:$})=>$.status===u)),m!==null&&(G=G.filter(({project:$})=>$.nodeId===m)),G},[I,u,m]),E=a.useMemo(()=>{const G=[...y];return G.sort(($,T)=>{let j=0;switch(g){case"name":j=$.project.name.localeCompare(T.project.name);break;case"activity":{const W=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,K=T.project.lastActivityAt||T.health?.lastActivityAt||T.project.updatedAt;j=new Date(K).getTime()-new Date(W).getTime();break}case"status":{const W={errored:0,initializing:1,paused:2,active:3};j=W[$.project.status]-W[T.project.status];break}}return f==="asc"?j:-j}),G},[y,g,f]),N=a.useMemo(()=>{const G=e.length,$=e.filter(L=>L.status==="active").length,T=e.filter(L=>L.status==="errored").length,j=new Set;e.forEach(L=>{L.nodeId&&j.add(L.nodeId)});const W=j.size||(G>0?1:0);let K=0,B=0,A=0;return Object.values(M).forEach(L=>{L&&(K+=L.activeTaskCount,B+=L.totalTasksCompleted,A+=L.inFlightAgentCount)}),{totalProjects:G,activeProjects:$,erroredProjects:T,totalNodes:W,totalActiveTasks:K,totalCompletedTasks:B,totalInFlightAgents:A}},[e,M]),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 T=$.nodeId,j=G.get(T);if(j)j.count++;else{const K=c.find(B=>B.id===T)?.name??$._sourceNodeName??"Local";G.set(T,{name:K,count:1})}}),Array.from(G.entries()).map(([$,{name:T,count:j}])=>({nodeId:$??null,name:T,count:j}))},[e,c]),R=a.useCallback(G=>{const $=[G.id,...v.filter(T=>T!==G.id)].slice(0,3);x($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(G)},[s,v]);return n||w&&e.length>0&&Object.keys(M).length===0?t.jsx(Mw,{}):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(Ra,{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(qt,{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(jn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.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:N.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(tn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),N.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",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:N.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),N.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Fr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:N.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(qt,{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(Fr,{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:T})=>t.jsxs("option",{value:G??"",children:[$," (",T,")"]},G??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(zr,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:G=>{const[$,T]=G.target.value.split("-");p($),b(T)},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(eh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:E.map(({project:G,health:$})=>{const T=c.find(W=>W.id===G.nodeId),j=T?void 0:G._sourceNodeName;return t.jsx(Ew,{project:G,health:$,node:T,nodeNameFallback:j,onSelect:R,onPause:r,onResume:o,onRemove:l},G.id)})}),E.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(zr,{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 Rw=45e3,Iw=3e3,Pw=2e3,$w=1500,Qd="fusion:sse-client-id";let Di=null;const ci=new Map;function Xd(){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 Oh(){if(!(typeof window>"u")){if(Di)return Di;try{const e=window.sessionStorage.getItem(Qd);if(e)return Di=e,e;const n=Xd();return window.sessionStorage.setItem(Qd,n),Di=n,n}catch{return Di=Xd(),Di}}}function Uh(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Bh(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function Dw(e){const n=Oh();if(!n)return e;const s=Uh(e);return!s||!Bh(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function gc(e,n){const s=Oh();if(!s)return;const i=Uh(e);if(!i||!Bh(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),Hs(`${r.pathname}${r.search}${r.hash}`)}function Lw(e){if(typeof window>"u")return;const n=gc(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 ho(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Zd(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=gc(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),$w):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function zw(e){ho(e),gc(e.url,"keepalive")&&(Zd(e),e.keepaliveTimer=window.setInterval(()=>{Zd(e)},Pw))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ci.values()))if(!s.closed){if(ho(s),Lw(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const i of Array.from(ci.values()))i.subscribers.size!==0&&(i.closed=!1,bc(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Ia(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Hh(e)},Rw)}function Hh(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),ho(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&&bc(e)},Iw)}}function bc(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Hs(Dw(e.url)));e.es=n,zw(e),n.addEventListener("open",()=>{Ia(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);Hh(e)}),n.addEventListener("message",()=>Ia(e)),n.addEventListener("heartbeat",()=>Ia(e)),qh(e),Ia(e)}function qh(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=>{Ia(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 Fw(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),ho(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ci.delete(e.url)}function qs(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),bc(s),qh(s);let r=!0;return()=>{if(!r)return;r=!1;const o=ci.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&Fw(o))}}const xc="kb-planning-last-description",vc="kb-subtask-last-description",yc="kb-mission-last-goal";function Ow(e,n){ts(xc,e,n)}function Uw(e){return Nn(xc,e)||""}function Li(e){Va(xc,e)}function Bw(e,n){ts(vc,e,n)}function Hw(e){return Nn(vc,e)||""}function Oo(e){Va(vc,e)}function qw(e,n){ts(yc,e,n)}function Vw(e){return Nn(yc,e)||""}function ai(e){Va(yc,e)}function Ww(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 Kw(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 Gw(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=Gw(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?Ww(o):void 0,h=o.question&&m!==void 0?Kw(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 eu="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(eu);if(e)return e;const n=Jw();return window.sessionStorage.setItem(eu,n),n}function po(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=Lk(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=Hs(`/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:qs("/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(zk(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const Yw="fusion:ai-session-sync",tu="fusion:ai-session-sync",Qw=3e4,Xw=6e4;function $s(){return Date.now()}function Zw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function nu(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 eN{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=Zw(),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:$s()})}broadcastUpdate(n){const s=n.timestamp??$s();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??$s();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=$s();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=$s();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=$s();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(Yw),this.channel.onmessage=s=>{const i=nu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==tu||!s.newValue))try{const i=JSON.parse(s.newValue),r=nu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=$s();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Qw)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=$s();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(tu,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:$s()});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=$s(),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>Xw;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 Ds=new eN;function la(){const e=a.useSyncExternalStore(c=>Ds.subscribe(c),()=>Ds.getSnapshot(),()=>Ds.getSnapshot());a.useEffect(()=>{Ds.requestSync()},[]);const n=a.useCallback(c=>{Ds.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Ds.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Ds.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Ds.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Ds.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Ds.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function tN(e,n){return e&&n?`${e}/${n}`:""}function nN(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 sN=["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 iN({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),[k,M]=a.useState(!1),w=a.useRef(!1),[I,y]=a.useState(""),[E,N]=a.useState(!0),[P,_]=a.useState(!1),[R,z]=a.useState(!1),[G,$]=a.useState(!1),T=a.useRef(null),j=a.useRef(null),W=a.useRef(null),K=a.useRef(null),[B,A]=a.useState(o??null),L=a.useMemo(()=>_i(),[]),{isLockedByOther:X,takeControl:C,isLoading:V}=po(e?B:null),{activeTabMap:fe,broadcastUpdate:ae,broadcastCompleted:oe,broadcastLock:F,broadcastUnlock:de,broadcastHeartbeat:re}=la(),[Z,ue]=a.useState(void 0),[Ce,he]=a.useState(void 0),[Ne,ee]=a.useState([]),[we,Ie]=a.useState(!0),[qe,Ve]=a.useState(null),[Ge,Ke]=a.useState([]),[Qe,Se]=a.useState([]),Fe=tN(Z,Ce);a.useEffect(()=>{(async()=>{try{Ie(!0);const $e=await is();ee($e.models),Ke($e.favoriteProviders),Se($e.favoriteModels)}catch($e){Ve(xe($e)||"Failed to load models")}finally{Ie(!1)}})()},[]);const ie=a.useCallback(ve=>{Ke($e=>{const ze=$e,Pe=ze.includes(ve)?ze.filter(be=>be!==ve):[ve,...ze];return nn({favoriteProviders:Pe,favoriteModels:Qe}).catch(()=>{Ke(ze)}),Pe})},[Qe]),Q=a.useCallback(ve=>{Se($e=>{const ze=$e,Pe=ze.includes(ve)?ze.filter(be=>be!==ve):[ve,...ze];return nn({favoriteProviders:Ge,favoriteModels:Pe}).catch(()=>{Se(ze)}),Pe})},[Ge]),pe=a.useCallback((ve,$e)=>{if(!ve||!$e)return"Using default";const ze=Ne.find(me=>me.provider===ve&&me.id===$e);return ze?`${ze.provider}/${ze.id}`:`${ve}/${$e}`},[Ne]),te=a.useCallback(ve=>{j.current?.close();const $e=Nk(ve,i,{onThinking:ze=>{y(me=>me+ze),ae({sessionId:ve,status:"generating",needsInput:!1,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:ze=>{_(!1),z(!1),ai(i),d({type:"question",sessionId:ve,question:ze}),y(""),M(!0),ae({sessionId:ve,status:"awaiting_input",needsInput:!0,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:ze=>{_(!1),z(!1),ai(i),d({type:"summary",sessionId:ve,summary:ze}),x(ze),y(""),M(!0),ae({sessionId:ve,status:"complete",needsInput:!1,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:ze=>{const me=ze||"Session failed while contacting the AI.";_(!1),z(!1),h(null),d({type:"error",sessionId:ve,errorMessage:me}),y(""),M(!0),W.current=ve,ae({sessionId:ve,status:"error",needsInput:!1,owningTabId:L,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),oe({sessionId:ve,status:"error"})},onComplete:()=>{_(!1),z(!1),W.current=null,oe({sessionId:ve,status:"complete"})},onConnectionStateChange:ze=>{_(ze==="reconnecting")}});j.current=$e},[oe,ae,l,i,L]),ye=a.useCallback(async ve=>{const $e=ve??l;if($e.trim()){h(null),y(""),p([]),b([]),_(!1),d({type:"loading"});try{const{sessionId:ze}=await yk($e.trim(),i,Z&&Ce?{modelProvider:Z,modelId:Ce}:void 0);W.current=ze,A(ze),ai(i),te(ze),p([])}catch(ze){_(!1),h(xe(ze)||"Failed to start interview session"),d({type:"initial"}),W.current=null,A(null)}}},[te,l,Z,Ce,i]);a.useEffect(()=>{e&&u.type==="initial"&&T.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!w.current&&u.type==="initial"){c(r);const ve=setTimeout(()=>{w.current=!0,ye(r)},0);return()=>clearTimeout(ve)}else if(e&&!r&&!w.current&&u.type==="initial"){const ve=Vw(i);ve&&c(ve)}},[e,r,u.type,ye]),a.useEffect(()=>{e||(w.current=!1,_(!1),z(!1),A(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let ve=!1;return Js(o).then($e=>{if(ve||!$e)return;const ze=Yi($e.conversationHistory);if(b(ze),A($e.id),p(ze.map(me=>me.response).filter(me=>!!(me&&typeof me=="object"&&!Array.isArray(me)))),$e.status==="awaiting_input"&&$e.currentQuestion)try{ai(i);const me=JSON.parse($e.currentQuestion);W.current=$e.id,M(!0),d({type:"question",sessionId:$e.id,question:me})}catch{h("Failed to restore session question.")}else if($e.status==="complete"&&$e.result)try{ai(i);const me=JSON.parse($e.result);W.current=$e.id,M(!0),x(me),d({type:"summary",sessionId:$e.id,summary:me})}catch{h("Failed to restore session result.")}else $e.status==="generating"?(W.current=$e.id,M(!0),$e.thinkingOutput&&y($e.thinkingOutput),d({type:"loading"}),te($e.id)):$e.status==="error"&&(W.current=$e.id,M(!0),h(null),d({type:"error",sessionId:$e.id,errorMessage:$e.error??"The session encountered an error."}))}).catch(()=>{ve||h("Failed to resume session.")}),()=>{ve=!0}},[te,e,o,u.type,i]),a.useEffect(()=>{if(!e){K.current&&(de(K.current,L),K.current=null);return}if(B&&K.current!==B){K.current&&de(K.current,L),F(B,L),K.current=B;return}!B&&K.current&&(de(K.current,L),K.current=null)},[F,de,e,B,L]),a.useEffect(()=>{if(!e||!B||K.current!==B)return;re(L);const ve=setInterval(()=>{re(L)},3e4);return()=>{clearInterval(ve)}},[re,e,B,L]),a.useEffect(()=>()=>{j.current?.close(),j.current=null,K.current&&(de(K.current,L),K.current=null)},[de,L]),a.useEffect(()=>{if(!e)return;const ve=$e=>{(u.type==="question"||u.type==="summary")&&($e.preventDefault(),$e.returnValue=""),j.current?.close()};return window.addEventListener("beforeunload",ve),()=>window.removeEventListener("beforeunload",ve)},[e,u]);const ce=a.useCallback(()=>{j.current?.close(),j.current=null,n()},[n]),Re=a.useCallback(async()=>{if(l&&qw(l,i),!(k&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(j.current?.close(),j.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await Mh(u.sessionId,i,L)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),y(""),_(!1),z(!1),M(!1),$(!1),ue(void 0),he(void 0),W.current=null,A(null),n()}},[l,k,u,n,i,L]);a.useEffect(()=>{if(!e)return;const ve=$e=>{$e.key==="Escape"&&(k?confirm("Are you sure you want to close? Your interview progress will be lost.")&&Re():Re())};return document.addEventListener("keydown",ve),()=>document.removeEventListener("keydown",ve)},[e,k,Re]);const Ze=a.useCallback(async ve=>{if(u.type!=="question")return;const{sessionId:$e}=u;h(null),p(ze=>[...ze,ve]),b(ze=>[...ze,{question:u.question,response:ve}]),d({type:"loading"}),y("");try{te($e),await kk($e,ve,i,L),M(!0)}catch(ze){j.current?.close(),j.current=null,h(xe(ze)||"Failed to submit response"),d({type:"question",sessionId:$e,question:u.question})}},[u,i,L,te]),at=a.useCallback(async()=>{if(u.type!=="error")return;const ve=u.sessionId;h(null),z(!0),y(""),d({type:"loading"}),te(ve);try{W.current=ve,A(ve),await jk(ve,i,L)}catch($e){let ze=$e;if((xe($e)||"").includes("not in an error state"))try{const Pe=await Js(ve);if(!Pe)throw new Error("Failed to refresh interview session.");const be=Yi(Pe.conversationHistory);if(b(be),p(be.map(We=>We.response).filter(We=>!!(We&&typeof We=="object"&&!Array.isArray(We)))),W.current=Pe.id,A(Pe.id),M(!0),Pe.status==="generating")y(Pe.thinkingOutput??""),d({type:"loading"}),j.current?.isConnected()||te(Pe.id);else if(Pe.status==="awaiting_input"){if(!Pe.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ai(i);const We=JSON.parse(Pe.currentQuestion);d({type:"question",sessionId:Pe.id,question:We}),j.current?.isConnected()||te(Pe.id)}else if(Pe.status==="complete"){if(!Pe.result)throw new Error("Interview session is complete but has no result.");ai(i);const We=JSON.parse(Pe.result);x(We),d({type:"summary",sessionId:Pe.id,summary:We})}else Pe.status==="error"&&d({type:"error",sessionId:Pe.id,errorMessage:Pe.error??"Retry failed. Please try again."});_(!1);return}catch(Pe){ze=Pe}j.current?.close(),j.current=null,d({type:"error",sessionId:ve,errorMessage:xe(ze)||"Retry failed. Please try again."}),_(!1)}finally{z(!1)}},[te,i,L,u]),le=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const ve=await wk(u.sessionId,v||void 0,i);s(ve),ai(i),j.current?.close(),j.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),y(""),_(!1),z(!1),M(!1),$(!1),W.current=null,A(null),n()}catch(ve){h(xe(ve)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),U=()=>u.type==="question"?Math.min(g.length+1,6):6,ne=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",ke=B?fe.get(B):null,_e=ke&&ke.tabId!==L,ge=!!(_e&&!ke.stale),He=X&&(!_e||ke.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ve=>ve.target===ve.currentTarget&&Re(),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(ns,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ne&&t.jsx("button",{className:"modal-send-to-background",onClick:ce,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Re,"aria-label":"Close",children:t.jsx(Dt,{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…"}),ge&&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(Dn,{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:T,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:ve=>c(ve.target.value),onKeyDown:ve=>{ve.key==="Enter"&&!ve.shiftKey&&l.trim()&&(ve.preventDefault(),ye())}})]}),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:sN.map((ve,$e)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(ve),children:ve.length>45?ve.slice(0,45)+"...":ve},$e))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",we&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(wn,{id:"mission-interview-modal-model",label:"Planning Model",value:Fe,onChange:ve=>{const{provider:$e,modelId:ze}=nN(ve);ue($e),he(ze)},models:Ne,disabled:we,favoriteProviders:Ge,onToggleFavorite:ie,favoriteModels:Qe,onToggleModelFavorite:Q}),qe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[qe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Ie(!0);const ve=await is();ee(ve.models),Ke(ve.favoriteProviders),Se(ve.favoriteModels),Ve(null)}catch(ve){Ve(xe(ve)||"Failed to load models")}finally{Ie(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Z&&Ce?"model-badge-custom":"model-badge-default"}`,children:pe(Z,Ce)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ye(),disabled:!l.trim(),children:[t.jsx(ns,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:I?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!E),type:"button",children:E?"Hide thinking":"Show thinking"}),E&&I&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:I})})]})]}),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 at(),disabled:R,children:[R?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:R?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Re,disabled:R,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(aN,{question:u.question,progress:U(),historyEntries:f,onSubmit:Ze}),u.type==="summary"&&v&&t.jsx(rN,{summary:v,historyEntries:f,onSummaryChange:x,onApprove:le,onStartOver:()=>{d({type:"initial"}),M(!1),x(null),p([]),b([]),A(null),j.current?.close(),j.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(ao,{size:16}),t.jsx("span",{children:He?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),He&&t.jsx("button",{type:"button",onClick:()=>{C()},disabled:V,className:"btn btn-primary session-lock-take-control",children:V?"Taking control...":"Take Control"})]})})]})]})}):null}function aN({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(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Dt,{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(Ja,{size:16,className:"icon-ml-4"})]})})]})}function rN({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((w,I)=>I))),[u,d]=a.useState(()=>{const w=new Set;return e.milestones.forEach((I,y)=>{I.slices.forEach((E,N)=>w.add(`${y}-${N}`))}),w}),m=w=>{c(I=>{const y=new Set(I);return y.has(w)?y.delete(w):y.add(w),y})},h=w=>{d(I=>{const y=new Set(I);return y.has(w)?y.delete(w):y.add(w),y})},g=(w,I)=>{const y=[...e.milestones];y[w]={...y[w],...I},s({...e,milestones:y})},p=(w,I,y)=>{const E=[...e.milestones],N=[...E[w].slices];N[I]={...N[I],...y},E[w]={...E[w],slices:N},s({...e,milestones:E})},f=(w,I,y,E)=>{const N=[...e.milestones],P=[...N[w].slices],_=[...P[I].features];_[y]={..._[y],...E},P[I]={...P[I],features:_},N[w]={...N[w],slices:P},s({...e,milestones:N})},b=w=>{const I=e.milestones.filter((y,E)=>E!==w);s({...e,milestones:I})},v=(w,I)=>{const y=[...e.milestones];y[w]={...y[w],slices:y[w].slices.filter((E,N)=>N!==I)},s({...e,milestones:y})},x=(w,I,y)=>{const E=[...e.milestones],N=[...E[w].slices];N[I]={...N[I],features:N[I].features.filter((P,_)=>_!==y)},E[w]={...E[w],slices:N},s({...e,milestones:E})},k=(w,I)=>{const y=[...e.milestones],E=[...y[w].slices];E[I]={...E[I],features:[...E[I].features,{title:"New feature",description:""}]},y[w]={...y[w],slices:E},s({...e,milestones:y})},M=e.milestones.reduce((w,I)=>w+I.slices.reduce((y,E)=>y+E.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(tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",M," 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:w=>s({...e,missionTitle:w.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:w=>s({...e,missionDescription:w.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((w,I)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(I),children:[l.has(I)?t.jsx(Lt,{size:16,className:"icon-text-secondary"}):t.jsx(en,{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:w.title,onChange:y=>g(I,{title:y.target.value}),onClick:y=>y.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:y=>{y.stopPropagation(),b(I)},title:"Remove milestone",children:t.jsx(Ht,{size:14,className:"icon-text-secondary"})})]}),l.has(I)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:w.description||"",onChange:y=>g(I,{description:y.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:w.verification||"",onChange:y=>g(I,{verification:y.target.value})})]}),w.slices.map((y,E)=>{const N=`${I}-${E}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(N),children:[u.has(N)?t.jsx(Lt,{size:14,className:"icon-text-secondary"}):t.jsx(en,{size:14,className:"icon-text-secondary"}),t.jsx($l,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:y.title,onChange:P=>p(I,E,{title:P.target.value}),onClick:P=>P.stopPropagation()}),w.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:P=>{P.stopPropagation(),v(I,E)},title:"Remove slice",children:t.jsx(Ht,{size:12,className:"icon-text-secondary"})})]}),u.has(N)&&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:y.verification||"",onChange:P=>p(I,E,{verification:P.target.value})})]}),y.features.map((P,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Al,{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:R=>f(I,E,_,{title:R.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(I,E,_),title:"Remove feature",children:t.jsx(Ht,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>k(I,E),children:[t.jsx(qt,{size:12}),"Add Feature"]})]})]},E)})]})]},I))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(ia,{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(it,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function oN({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,k]=a.useState(null),[M,w]=a.useState(""),[I,y]=a.useState(!0),[E,N]=a.useState(!1),[P,_]=a.useState(!1),R=a.useRef(null),z=a.useRef(null),G=a.useRef(null),$=a.useRef(null),[T,j]=a.useState(null),W=a.useMemo(()=>_i(),[]);po(e?T:null);const{activeTabMap:K,broadcastUpdate:B,broadcastCompleted:A,broadcastLock:L,broadcastUnlock:X,broadcastHeartbeat:C}=la(),V=i==="milestone"?Sk:Ak,fe=i==="milestone"?Ck:Tk,ae=i==="milestone"?Ek:Rk,oe=i==="milestone"?Mk:Ik,F=i==="milestone"?_k:Pk,de=i==="milestone"?"Milestone":"Slice",re=i==="milestone"?"milestone_interview":"slice_interview",Z=a.useCallback(Se=>{z.current?.close();const Fe=ae(Se,c,{onThinking:ie=>{w(Q=>Q+ie),B({sessionId:Se,status:"generating",needsInput:!1,owningTabId:W,type:re,title:o,projectId:c??null})},onQuestion:ie=>{N(!1),ue(),m({type:"question",sessionId:Se,question:ie}),w(""),B({sessionId:Se,status:"awaiting_input",needsInput:!0,owningTabId:W,type:re,title:o,projectId:c??null})},onSummary:ie=>{N(!1),ue(),m({type:"summary",sessionId:Se,summary:ie}),k(ie),w(""),B({sessionId:Se,status:"complete",needsInput:!1,owningTabId:W,type:re,title:o,projectId:c??null})},onError:ie=>{const Q=ie||"Session failed while contacting the AI.";N(!1),g(null),m({type:"error",sessionId:Se,errorMessage:Q}),w(""),G.current=Se,B({sessionId:Se,status:"error",needsInput:!1,owningTabId:W,type:re,title:o,projectId:c??null}),A({sessionId:Se,status:"error"})},onComplete:()=>{N(!1),G.current=null,A({sessionId:Se,status:"complete"})},onConnectionStateChange:ie=>{N(ie==="reconnecting")}});z.current=Fe},[A,B,ae,re,c,W,o]),ue=()=>{k(null),f([]),v([]),w("")},Ce=a.useCallback(async()=>{g(null),ue(),N(!1),m({type:"loading"});try{const{sessionId:Se}=await V(r,c);G.current=Se,j(Se),Z(Se)}catch(Se){N(!1),g(xe(Se)||`Failed to start ${de.toLowerCase()} interview`),m({type:"initial"}),G.current=null,j(null)}},[Z,c,V,r,de]),he=a.useCallback(async()=>{g(null),_(!0);try{await F(r,c),s(),m({type:"applied"})}catch(Se){g(xe(Se)||`Failed to skip ${de.toLowerCase()} interview`),_(!1)}},[s,c,F,r,de]);a.useEffect(()=>{e&&d.type==="initial"&&R.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Se=!1;return Js(u).then(Fe=>{if(Se||!Fe)return;const ie=Yi(Fe.conversationHistory);if(v(ie),j(Fe.id),f(ie.map(Q=>Q.response).filter(Q=>!!(Q&&typeof Q=="object"&&!Array.isArray(Q)))),Fe.status==="awaiting_input"&&Fe.currentQuestion)try{const Q=JSON.parse(Fe.currentQuestion);G.current=Fe.id,m({type:"question",sessionId:Fe.id,question:Q})}catch{g("Failed to restore session question.")}else if(Fe.status==="complete"&&Fe.result)try{const Q=JSON.parse(Fe.result);G.current=Fe.id,k(Q),m({type:"summary",sessionId:Fe.id,summary:Q})}catch{g("Failed to restore session result.")}else Fe.status==="generating"?(G.current=Fe.id,Fe.thinkingOutput&&w(Fe.thinkingOutput),m({type:"loading"}),Z(Fe.id)):Fe.status==="error"&&(G.current=Fe.id,g(null),m({type:"error",sessionId:Fe.id,errorMessage:Fe.error??"The session encountered an error."}))}).catch(()=>{Se||g("Failed to resume session.")}),()=>{Se=!0}},[Z,e,u,d.type]),a.useEffect(()=>{e||(N(!1),j(null))},[e]),a.useEffect(()=>{if(!(!e||!T)){if($.current!==T){$.current&&X($.current,W),L(T,W),$.current=T;return}!T&&$.current&&(X($.current,W),$.current=null)}},[L,X,e,T,W]),a.useEffect(()=>{if(!e||!T||$.current!==T)return;C(W);const Se=setInterval(()=>{C(W)},3e4);return()=>{clearInterval(Se)}},[C,e,T,W]),a.useEffect(()=>()=>{z.current?.close(),z.current=null,$.current&&(X($.current,W),$.current=null)},[X,W]);const Ne=a.useCallback(()=>{z.current?.close(),z.current=null,n()},[n]),ee=a.useCallback(async()=>{z.current?.close(),z.current=null,ue(),m({type:"initial"}),g(null),G.current=null,j(null),n()},[n]),we=a.useCallback(async Se=>{if(d.type!=="question")return;const{sessionId:Fe}=d;g(null),f(ie=>[...ie,Se]),v(ie=>[...ie,{question:d.question,response:Se}]),m({type:"loading"}),w("");try{Z(Fe),await fe(Fe,Se,c,W)}catch(ie){z.current?.close(),z.current=null,g(xe(ie)||"Failed to submit response"),m({type:"question",sessionId:Fe,question:d.question})}},[Z,c,fe,W,d]),Ie=a.useCallback(async()=>{if(d.type==="summary"){g(null),_(!0);try{await oe(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(Se){g(xe(Se)||"Failed to apply interview results"),_(!1)}}},[oe,x,s,c,d]),qe=()=>d.type==="question"?Math.min(p.length+1,6):6,Ve=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ge=T?K.get(T):null,Qe=!!(Ge&&Ge.tabId!==W&&!Ge.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Se=>Se.target===Se.currentTarget&&ee(),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(Dn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",de,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ve&&t.jsx("button",{className:"modal-send-to-background",onClick:Ne,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ee,"aria-label":"Close",children:t.jsx(Dt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),E&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Qe&&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(Dn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",de," 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 Ce(),children:[t.jsx(Dn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void he(),disabled:P,children:[P?t.jsx(it,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ee,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:M?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>y(!I),type:"button",children:I?"Hide thinking":"Show thinking"}),I&&M&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:M})})]})]}),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:ee,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(lN,{question:d.question,progress:qe(),historyEntries:b,onSubmit:we}),d.type==="summary"&&x&&t.jsx(cN,{summary:x,historyEntries:b,onSummaryChange:k,onApply:Ie,onCancel:ee,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(tn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[de," 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 lN({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(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Dt,{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(Ja,{size:16,className:"icon-ml-4"})]})})]})}function cN({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(Lt,{size:16}):t.jsx(en,{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(it,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const ba={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)"}},su={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)"}},iu={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)"}},br={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)"}},xr={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)"}},vr={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)"}},au={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)"}},dN=3;function uN(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function ru({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 ou(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Uo={title:"",description:"",status:"planning",autopilotEnabled:!1},Bo={title:"",description:"",status:"planning",dependencies:[]},Ho={title:"",description:"",status:"pending"},qo={title:"",description:"",acceptanceCriteria:"",status:"defined"},mN=3600*1e3;function Kr(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 hN(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=mN,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 pN(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 fN(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 Vo(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 Vh=["feature_triaged","feature_completed"],Wh=["slice_activated","slice_completed","milestone_completed"],Kh=["mission_started","mission_paused","mission_resumed","mission_completed"],Gh=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function lu(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Kh.includes(e);case"tasks":return Vh.includes(e);case"slices":return Wh.includes(e);case"autopilot":return Gh.includes(e);default:return!0}}function gN(e){return e==="error"||e==="warning"?"mission-event__type--error":Kh.includes(e)?"mission-event__type--state":Vh.includes(e)?"mission-event__type--task":Wh.includes(e)?"mission-event__type--slice":Gh.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function bN(e){return e.replace(/_/g," ")}function xN(e,n){return n?e==="watching"?`Watching since ${Kr(n)}`:`Last activation ${Kr(n)}`:null}function vN({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),[k,M]=a.useState(!1),[w,I]=a.useState(!1),[y,E]=a.useState(null),[N,P]=a.useState(Uo),[_,R]=a.useState(!1),[z,G]=a.useState(new Set),[$,T]=a.useState(new Set),[j,W]=a.useState(null),[K,B]=a.useState(Bo),[A,L]=a.useState(!1),[X,C]=a.useState(null),[V,fe]=a.useState(Ho),[ae,oe]=a.useState(!1),[F,de]=a.useState(null),[re,Z]=a.useState(null),[ue,Ce]=a.useState(qo),[he,Ne]=a.useState(!1),[ee,we]=a.useState(null),[Ie,qe]=a.useState(null),[Ve,Ge]=a.useState(""),[Ke,Qe]=a.useState(!1),[Se,Fe]=a.useState([]),[ie,Q]=a.useState(void 0),pe=ie??c,[te,ye]=a.useState(null),[ce,Re]=a.useState(null),[Ze,at]=a.useState(null);a.useEffect(()=>{h&&pe&&Qe(!0)},[h,pe]),a.useEffect(()=>{if(!h||pe)return;let O=!1;return _h(r).then(je=>{if(O)return;const Te=je.filter(ht=>ht.type==="mission_interview"&&(ht.status==="awaiting_input"||ht.status==="error"));Fe(Te)}).catch(je=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",je)}),()=>{O=!0}},[h,r,pe]),a.useEffect(()=>{if(!h||!d)return;let O=!1;return Js(d).then(je=>{if(!(O||!je))try{const Te=JSON.parse(je.inputPayload||"{}");Te.targetId&&Te.targetType&&ye({type:Te.targetType,id:Te.targetId,title:Te.targetTitle||je.title,resumeSessionId:d})}catch{ye({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[le,U]=a.useState(null),[ne,ke]=a.useState(new Map),[_e,ge]=a.useState(null),[He,ve]=a.useState({title:"",assertion:"",status:"pending"}),[$e,ze]=a.useState(!1),[me,Pe]=a.useState(null),[be,We]=a.useState(new Map),[tt,ct]=a.useState(new Set),[wt,Nt]=a.useState(new Set),[It,Ut]=a.useState(null),[Vt,zt]=a.useState(new Map),[Mt,xt]=a.useState(null),[_t,De]=a.useState(null),[gt,ut]=a.useState(!0),[Me,Ye]=a.useState(new Set),[rt,S]=a.useState(new Map),[q,Ae]=a.useState(null),[ot,kt]=a.useState(new Map),[Ot,sn]=a.useState(null),[Pt,zn]=a.useState(new Map),[Kn,ms]=a.useState(new Map),[pn,Fn]=a.useState("structure"),[Sn,fn]=a.useState([]),Gn=a.useRef([]),dn=a.useRef([]),At=a.useRef(null),yn=a.useRef(null),Jn=a.useRef("structure"),kn=a.useRef("all"),[_n,hs]=a.useState(!1),[ps,On]=a.useState(0),[J,Le]=a.useState("all"),[nt,et]=a.useState(new Set),mt=a.useRef(null),jt=a.useRef(null);dn.current=g,At.current=f,yn.current=Mt,Jn.current=pn,kn.current=J;const Tt=a.useCallback((O="auto")=>{const je=jt.current;if(je&&typeof je.scrollIntoView=="function"){je.scrollIntoView({block:"end",behavior:O});return}const Te=mt.current;Te&&(Te.scrollTop=Te.scrollHeight)},[]),gn=a.useCallback(()=>{const O=mt.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 ht=new Map(Te);for(const[Jt,Ct]of Object.entries(je))pN(Ct)&&ht.set(Jt,Ct);return ht})},[r]),Xt=a.useCallback(async()=>{try{x(!0);const O=await By(r);p(O),fs(O)}catch(O){i(xe(O)||"Failed to load missions","error")}finally{x(!1)}},[i,r,fs]),vt=a.useCallback(async O=>{try{M(!0);const je=await Eh(O,r);if(b(je),je.milestones.length>0){const Te=je.milestones[0].id;xt(Te),ut(!0),G(new Set([Te])),Po(Te,r).then(ht=>{ke(Jt=>{const Ct=new Map(Jt);return Ct.set(Te,ht),Ct})}).catch(()=>{}),$o(Te,r).then(ht=>{zt(Jt=>{const Ct=new Map(Jt);return Ct.set(Te,ht),Ct})}).catch(()=>{}),je.milestones[0].slices.length>0&&T(new Set([je.milestones[0].slices[0].id]))}else xt(null),De(null)}catch(je){i(xe(je)||"Failed to load mission details","error")}finally{M(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Mt){De(null);return}let O=!1;return De(null),yd(Mt,r).then(je=>{if(!O){if(!Vo(je)){De(null);return}De(je),zt(Te=>{const ht=new Map(Te);return ht.set(Mt,je.rollup),ht})}}).catch(()=>{O||De(null)}),()=>{O=!0}},[h,Mt,r]),a.useEffect(()=>{ut(!0)},[Mt]);const dt=a.useCallback(O=>{!O||O!==yn.current||yd(O,r).then(je=>{yn.current!==O||!Vo(je)||(De(je),zt(Te=>{const ht=new Map(Te);return ht.set(O,je.rollup),ht}))}).catch(()=>{})},[r]),se=a.useCallback(async(O,je)=>{const Te=je?.append??!1,ht=Te?Gn.current.length:0;Te||(hs(!0),et(new Set));try{const Jt=await Wy(O,{limit:50,offset:ht,eventType:void 0},r),Ct=Jt.events.filter(Bt=>lu(Bt.eventType,J));fn(Bt=>{if(!Te)return Ct;const Oe=new Set(Bt.map(pt=>pt.id)),Be=[...Bt];for(const pt of Ct)Oe.has(pt.id)||Be.push(pt);return Be}),On(Jt.total),Te||requestAnimationFrame(()=>{Tt("auto")})}catch(Jt){i(xe(Jt)||"Failed to load mission activity","error")}finally{Te||hs(!1)}},[i,J,r,Tt]);a.useEffect(()=>{Gn.current=Sn},[Sn]),a.useEffect(()=>{h&&(Xt(),b(null),xt(null),De(null),fn([]),On(0),Fn("structure"),Le("all"),et(new Set))},[h,Xt]);const Ee=a.useRef(null);a.useEffect(()=>{h&&u&&Ee.current!==u&&g.length>0&&(Ee.current=u,vt(u))},[h,u,g,vt]),a.useEffect(()=>{h||(Ee.current=null)},[h]),a.useEffect(()=>{!h||!f||pn!=="activity"||se(f.id)},[pn,h,se,f,J]),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(dn.current)},ht=En=>{Te();const ln=En;if(ln.data)try{const Rt=JSON.parse(ln.data);Rt?.id&&p(pi=>pi.map(ys=>ys.id===Rt.id?{...ys,...Rt}:ys))}catch{}At.current&&vt(At.current.id)},Jt=En=>{Te(),At.current&&vt(At.current.id)},Ct=()=>{Te(),At.current&&vt(At.current.id)},Bt=En=>{Te(),At.current&&vt(At.current.id)},Oe=En=>{const ln=En;if(ln.data)try{const Rt=JSON.parse(ln.data);Rt&&Rt.featureId&&(Ws(Rt.featureId),ni(Rt.featureId),Rt.milestoneId&&dt(Rt.milestoneId))}catch{}},Be=En=>{const ln=En;if(ln.data)try{const Rt=JSON.parse(ln.data);Rt&&Rt.featureId&&(Ws(Rt.featureId),ni(Rt.featureId),Rt.milestoneId&&dt(Rt.milestoneId),At.current&&vt(At.current.id))}catch{}},pt=En=>{const ln=En;if(ln.data)try{const Rt=JSON.parse(ln.data);Rt&&Rt.milestoneId&&(Y(Rt.milestoneId),dt(Rt.milestoneId))}catch{}},Yt=En=>{const ln=En;if(ln.data)try{const Rt=JSON.parse(ln.data);Rt&&Rt.milestoneId&&(ti(Rt.milestoneId),Y(Rt.milestoneId),dt(Rt.milestoneId))}catch{}};return qs(je,{events:{"mission:updated":ht,"slice:updated":Jt,"feature:updated":Ct,"milestone:updated":Bt,"mission:event":En=>{Te();const ln=At.current;if(!ln||Jn.current!=="activity")return;const Rt=gn(),pi=En;if(pi.data)try{const ys=JSON.parse(pi.data);if(!fN(ys)||ys.missionId!==ln.id||!lu(ys.eventType,kn.current))return;fn(Ks=>{const _o=Ks.filter(Ao=>Ao.id!==ys.id);return[ys,..._o].slice(0,100)}),On(Ks=>Ks+1),Rt&&requestAnimationFrame(()=>{const Ks=mt.current;Ks&&(Ks.scrollTop=0)})}catch{}},"validator-run:started":Oe,"validator-run:completed":Be,"milestone:validation:updated":pt,"assertion:created":Yt,"assertion:updated":Yt,"assertion:deleted":Yt,"assertion:linked":Yt,"assertion:unlinked":Yt,"fix-feature:created":En=>{const ln=En;if(ln.data)try{const Rt=JSON.parse(ln.data);if(Rt&&Rt.sourceFeatureId){Ws(Rt.sourceFeatureId);const pi=Rt?.feature?.sliceId,ys=At.current;if(pi&&ys){const Ks=ys.milestones.find(_o=>_o.slices.some(Ao=>Ao.id===pi));Ks&&dt(Ks.id)}At.current&&vt(At.current.id)}}catch{}}}})},[h,gn,vt,fs,r,dt]);const st=a.useCallback(()=>{I(!0),E(null),P(Uo)},[]),ft=a.useCallback(O=>{E(O.id),I(!1),P({title:O.title,description:O.description||"",status:O.status,autopilotEnabled:O.autopilotEnabled??!1})},[]),bt=a.useCallback(()=>{E(null),I(!1),P(Uo)},[]),on=a.useCallback(async()=>{if(!N.title.trim()){i("Mission title is required","error");return}try{if(R(!0),w)await Hy({title:N.title.trim(),description:N.description.trim()||void 0,autopilotEnabled:N.autopilotEnabled},r),i("Mission created","success");else if(y){const O={title:N.title.trim(),description:N.description.trim()||void 0,status:N.status,autopilotEnabled:N.autopilotEnabled};N.autopilotEnabled&&(O.autoAdvance=!0),await qy(y,O,r),i("Mission updated","success"),f?.id===y&&await vt(y)}await Xt(),bt()}catch(O){i(xe(O)||"Failed to save mission","error")}finally{R(!1)}},[N,w,y,i,Xt,vt,f,bt,r]),Zt=a.useCallback(async O=>{try{await Vy(O,r),i("Mission deleted","success"),f?.id===O&&b(null),await Xt(),U(null)}catch(je){i(xe(je)||"Failed to delete mission","error")}},[i,Xt,f,r]),cn=a.useCallback(()=>{L(!0),W(null),B(Bo)},[]),Gt=a.useCallback(O=>{W(O.id),L(!1),B({title:O.title,description:O.description||"",status:O.status,dependencies:O.dependencies})},[]),bn=a.useCallback(()=>{W(null),L(!1),B(Bo)},[]),Cn=a.useCallback(async()=>{if(!K.title.trim()){i("Milestone title is required","error");return}try{R(!0),A&&f?(await Gy(f.id,{title:K.title.trim(),description:K.description.trim()||void 0,dependencies:K.dependencies},r),i("Milestone created","success")):j&&(await Jy(j,{title:K.title.trim(),description:K.description.trim()||void 0,status:K.status,dependencies:K.dependencies},r),i("Milestone updated","success")),await vt(f.id),bn()}catch(O){i(xe(O)||"Failed to save milestone","error")}finally{R(!1)}},[K,A,j,f,i,vt,bn,N.title,r]),gs=a.useCallback(async O=>{try{await Yy(O,r),i("Milestone deleted","success"),await vt(f.id),U(null)}catch(je){i(xe(je)||"Failed to delete milestone","error")}},[i,vt,f,r]),Un=a.useCallback(O=>{xt(O),ut(!0),G(je=>{const Te=new Set(je);return!Te.has(O)?(Te.add(O),Po(O,r).then(Jt=>{ke(Ct=>{const Bt=new Map(Ct);return Bt.set(O,Jt),Bt})}).catch(()=>{}),$o(O,r).then(Jt=>{zt(Ct=>{const Bt=new Map(Ct);return Bt.set(O,Jt),Bt})}).catch(()=>{})):Te.delete(O),Te})},[r]),Yn=a.useCallback(O=>{de(O),oe(!0),C(null),fe(Ho)},[]),Bn=a.useCallback(O=>{C(O.id),oe(!1),fe({title:O.title,description:O.description||"",status:O.status})},[]),Qn=a.useCallback(()=>{C(null),oe(!1),de(null),fe(Ho)},[]),un=a.useCallback(async()=>{if(!V.title.trim()){i("Slice title is required","error");return}try{R(!0),ae&&F?(await Qy(F,{title:V.title.trim(),description:V.description.trim()||void 0},r),i("Slice created","success")):X&&(await Xy(X,{title:V.title.trim(),description:V.description.trim()||void 0,status:V.status},r),i("Slice updated","success")),await vt(f.id),Qn()}catch(O){i(xe(O)||"Failed to save slice","error")}finally{R(!1)}},[V,ae,X,F,f,i,vt,Qn,r]),Xn=a.useCallback(async O=>{try{await Zy(O,r),i("Slice deleted","success"),await vt(f.id),U(null)}catch(je){i(xe(je)||"Failed to delete slice","error")}},[i,vt,f,r]),Es=a.useCallback(async O=>{try{await ek(O,r),i("Slice activated","success"),await vt(f.id)}catch(je){i(xe(je)||"Failed to activate slice","error")}},[i,vt,f,r]),Is=a.useCallback(O=>{T(je=>{const Te=new Set(je);return Te.has(O)?Te.delete(O):Te.add(O),Te})},[]),rs=a.useCallback(O=>{we(O),Ne(!0),Z(null),Ce(qo)},[]),An=a.useCallback(O=>{Z(O.id),Ne(!1),Ce({title:O.title,description:O.description||"",acceptanceCriteria:O.acceptanceCriteria||"",status:O.status})},[]),bs=a.useCallback(()=>{Z(null),Ne(!1),we(null),Ce(qo)},[]),Tn=a.useCallback(async()=>{if(!ue.title.trim()){i("Feature title is required","error");return}try{R(!0),he&&ee?(await tk(ee,{title:ue.title.trim(),description:ue.description.trim()||void 0,acceptanceCriteria:ue.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):re&&(await nk(re,{title:ue.title.trim(),description:ue.description.trim()||void 0,acceptanceCriteria:ue.acceptanceCriteria.trim()||void 0,status:ue.status},r),i("Feature updated","success")),await vt(f.id),bs()}catch(O){i(xe(O)||"Failed to save feature","error")}finally{R(!1)}},[ue,he,re,ee,f,i,vt,bs,r]),ua=a.useCallback(async O=>{try{await sk(O,r),i("Feature deleted","success"),await vt(f.id),U(null)}catch(je){i(xe(je)||"Failed to delete feature","error")}},[i,vt,f,r]),yo=a.useCallback(async()=>{if(!Ie||!Ve.trim()){i("Task ID is required","error");return}try{await ik(Ie,Ve.trim(),r),i("Feature linked to task","success"),await vt(f.id),qe(null),Ge("")}catch(O){i(xe(O)||"Failed to link feature to task","error")}},[Ie,Ve,i,vt,f,r]),ko=a.useCallback(async O=>{try{await ak(O,r),i("Feature unlinked from task","success"),await vt(f.id)}catch(je){i(xe(je)||"Failed to unlink feature","error")}},[i,vt,f,r]),mi=a.useCallback(async O=>{try{R(!0),await rk(O,void 0,void 0,r),i("Feature triaged — task created","success"),await vt(f.id)}catch(je){i(xe(je)||"Failed to triage feature","error")}finally{R(!1)}},[i,vt,f,r]),or=a.useCallback(async O=>{at(O);try{const je=await $k(O,r);Re({featureId:O,enrichedDescription:je.description})}catch{await mi(O)}finally{at(null)}},[mi,r]),lr=a.useCallback(async()=>{ce&&(Re(null),await mi(ce.featureId))},[mi,ce]),ei=a.useCallback(()=>{Re(null)},[]),jo=a.useCallback(async O=>{try{R(!0);const je=await ok(O,r);i(`Triaged ${je.count} feature${je.count!==1?"s":""}`,"success"),await vt(f.id)}catch(je){i(xe(je)||"Failed to triage slice features","error")}finally{R(!1)}},[i,vt,f,r]),ti=a.useCallback(async O=>{try{const je=await Po(O,r);ke(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch{}},[r]),Y=a.useCallback(async O=>{try{const je=await $o(O,r);zt(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch{}},[r]),Je=a.useCallback(async O=>{if(!He.title.trim()||!He.assertion.trim()){i("Title and assertion text are required","error");return}try{R(!0),await lk(O,{title:He.title.trim(),assertion:He.assertion.trim(),status:He.status},r),i("Assertion created","success"),await ti(O),await Y(O),ze(!1),ve({title:"",assertion:"",status:"pending"})}catch(je){i(xe(je)||"Failed to create assertion","error")}finally{R(!1)}},[He,i,ti,Y,r]),lt=a.useCallback(O=>{ge(O.id),ve({title:O.title,assertion:O.assertion,status:O.status})},[]),St=a.useCallback(()=>{ge(null),ze(!1),ve({title:"",assertion:"",status:"pending"})},[]),Ms=a.useCallback(async(O,je)=>{if(!He.title.trim()||!He.assertion.trim()){i("Title and assertion text are required","error");return}try{R(!0),await ck(O,{title:He.title.trim(),assertion:He.assertion.trim(),status:He.status},r),i("Assertion updated","success"),await ti(je),await Y(je),St()}catch(Te){i(xe(Te)||"Failed to update assertion","error")}finally{R(!1)}},[He,i,ti,Y,St,r]),Rn=a.useCallback(async O=>{try{const je=await mk(O,r);We(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch{}},[r]),cr=a.useCallback(async O=>{const je=me!==O;Pe(Te=>Te===O?null:O),je&&await Rn(O)},[me,Rn]),ma=a.useCallback(O=>{Pe(O),Rn(O),requestAnimationFrame(()=>{const je=document.querySelector(`[data-mission-assertion-id="${O}"]`);je instanceof HTMLElement&&typeof je.scrollIntoView=="function"&&je.scrollIntoView({behavior:"smooth",block:"center"})})},[Rn]),wo=a.useCallback(async(O,je)=>{try{ct(Te=>new Set(Te).add(je)),await dk(O,je,r),i("Feature linked to assertion","success"),await Rn(je),Ut(null)}catch(Te){i(xe(Te)||"Failed to link feature","error")}finally{ct(Te=>{const ht=new Set(Te);return ht.delete(je),ht})}},[i,Rn,r]),No=a.useCallback(async(O,je)=>{const Te=`${O}-${je}`;try{Nt(ht=>new Set(ht).add(Te)),await uk(O,je,r),i("Feature unlinked from assertion","success"),await Rn(je)}catch(ht){i(xe(ht)||"Failed to unlink feature","error")}finally{Nt(ht=>{const Jt=new Set(ht);return Jt.delete(Te),Jt})}},[i,Rn,r]),So=a.useCallback(async O=>{try{Ye(Te=>new Set(Te).add(O)),await hk(O,r),i("Validation triggered","success");const je=await kd(O,r);S(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch(je){i(xe(je)||"Failed to trigger validation","error")}finally{Ye(je=>{const Te=new Set(je);return Te.delete(O),Te})}},[i,r]),Ws=a.useCallback(async O=>{try{const je=await kd(O,r);S(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch{}},[r]),ni=a.useCallback(async O=>{try{const je=await pk(O,{limit:10},r);kt(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch{}},[r]),si=a.useCallback(O=>{const je=At.current;if(je){for(const Te of je.milestones)for(const ht of Te.slices)if(ht.features.find(Ct=>Ct.id===O)){G(Ct=>{const Bt=new Set(Ct);return Bt.add(Te.id),Bt}),T(Ct=>{const Bt=new Set(Ct);return Bt.add(ht.id),Bt}),Ae(O),xt(Te.id),Ws(O),ni(O),requestAnimationFrame(()=>{const Ct=document.querySelector(`[data-mission-feature-id="${O}"]`);Ct instanceof HTMLElement&&typeof Ct.scrollIntoView=="function"&&Ct.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Ws,ni]),Ti=a.useCallback(async O=>{try{const je=await fk(O,r);zn(Te=>{const ht=new Map(Te);return ht.set(O,je),ht})}catch{}},[r]),Ri=a.useCallback(async O=>{q===O?Ae(null):(Ae(O),await Ws(O),await ni(O))},[q,Ws,ni]),ha=a.useCallback(async O=>{Ot===O?sn(null):(sn(O),await Ti(O))},[Ot,Ti]),Co=a.useCallback(async O=>{try{await gk(O,r),i("Mission resumed","success"),await vt(O),Xt()}catch(je){i(xe(je)||"Failed to resume mission","error")}},[i,vt,Xt,r]),Eo=a.useCallback(async O=>{try{const Te=(await bk(O,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Te} task${Te!==1?"s":""} paused)`,"success"),await vt(O),Xt()}catch(je){i(xe(je)||"Failed to stop mission","error")}},[i,vt,Xt,r]),xs=a.useCallback(async O=>{try{await xk(O,r),i("Mission started — first slice activated","success"),await vt(O),Xt()}catch(je){i(xe(je)||"Failed to start mission","error")}},[i,vt,Xt,r]),ii=a.useCallback(async(O,je)=>{try{await vk(O,{enabled:je},r),i(je?"Autopilot enabled":"Autopilot disabled","success"),await vt(O),Xt()}catch(Te){i(xe(Te)||"Failed to update autopilot","error")}},[i,vt,Xt,r]),_s=a.useCallback(O=>{Fn("structure"),xt(null),De(null),fn([]),On(0),Le("all"),et(new Set),vt(O.id)},[vt]),Ps=a.useCallback(()=>{b(null),xt(null),De(null),Fn("structure"),fn([]),On(0),Le("all"),et(new Set),Xt()},[Xt]),dr=Sn.length<ps,Ii=f?.autopilotState??"inactive",Oc=Ii==="watching"||Ii==="activating",Uc=xN(Ii,f?.lastAutopilotActivityAt),ur=a.useMemo(()=>!_t||!Mt||!Vo(_t)?null:_t.rollup.milestoneId===Mt?_t:null,[Mt,_t]),Ef=a.useMemo(()=>{const O=new Map;for(const je of ur?.validationTelemetry.validationRounds??[]){const Te=O.get(je.featureId);(!Te||je.startedAt>Te.startedAt)&&O.set(je.featureId,je)}return O},[ur]),Mf=a.useCallback(()=>{!f||_n||!dr||se(f.id,{append:!0})},[_n,dr,se,f]),_f=a.useCallback(O=>{et(je=>{const Te=new Set(je);return Te.has(O)?Te.delete(O):Te.add(O),Te})},[]),Mo=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),on())},[on]),Bc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Cn())},[Cn]),Hc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),un())},[un]),qc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Tn())},[Tn]),Af=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 Vc=t.jsxs("div",{ref:Af,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:Ps,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(lc,{size:18})}):null,t.jsx(ns,{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(Dt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(it,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):k?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(it,{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:[Oc&&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:(ba[f.status]||ba.planning).bg,color:(ba[f.status]||ba.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=>ii(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(vn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(xr[Ii]||xr.inactive).bg,color:(xr[Ii]||xr.inactive).text},"data-testid":"autopilot-state-badge",children:[Oc&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ii]})]}),Uc&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Uc})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Eo(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(ls,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Co(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(rn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xs(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>U({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Ht,{size:14})})]})]}),y===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:O=>P({...N,title:O.target.value}),onKeyDown:Mo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:O=>P({...N,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:N.status,onChange:O=>P({...N,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:N.autopilotEnabled,onChange:O=>P({...N,autopilotEnabled:O.target.checked})}),t.jsx(vn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{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 ${pn==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Fn("structure"),role:"tab","aria-selected":pn==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${pn==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Fn("activity"),role:"tab","aria-selected":pn==="activity","data-testid":"mission-tab-activity",children:["Activity (",ps,")"]})]}),pn==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(O=>{const je=ur?.rollup.milestoneId===O.id?ur:null,Te=je?.rollup??Vt.get(O.id),ht=je?.validationTelemetry.validationRounds??[],Jt=je?.fixFeatures??[],Ct=au[Te?.state??"not_started"]??au.not_started,Bt=Te&&(Te.state==="blocked"||Te.state==="failed")?je?.validationTelemetry.validationRounds.find(Oe=>Oe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Un(O.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:z.has(O.id)?t.jsx(Lt,{size:16}):t.jsx(en,{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:su[O.status].bg,color:su[O.status].text},children:O.status}),t.jsxs("span",{className:"mission-milestone__count",children:[O.slices.length," slices"]}),t.jsx(ru,{state:uN(O.interviewState)}),Te&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ct.bg,color:Ct.text},title:"Validation state",children:ou(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:()=>ye({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:Oe=>Oe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Yn(O.id),title:"Add slice",children:t.jsx(qt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Gt(O),title:"Edit milestone",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>U({type:"milestone",id:O.id}),title:"Delete milestone",children:t.jsx(Ht,{size:14})})]})]}),z.has(O.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(A||j===O.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:Oe=>B({...K,title:Oe.target.value}),onKeyDown:Bc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:Oe=>B({...K,description:Oe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),j?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,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}`:""]})]}),Bt&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Bt]}),ht.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:()=>ut(Oe=>!Oe),title:gt?"Hide validation rounds":"Show validation rounds",children:[gt?t.jsx(Lt,{size:12}):t.jsx(en,{size:12}),"Validation rounds (",ht.length,")"]}),gt&&t.jsx("div",{className:"mission-validation-rounds__list",children:ht.map(Oe=>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--${Oe.validatorStatus}`,children:Oe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Oe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Oe.implementationAttempt," · reviewer #",Oe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Oe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Oe.failedAssertionIds.map(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(Be),title:`Jump to assertion ${Be}`,children:Be},`${Oe.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:"}),Oe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Oe.generatedFixFeatureIds.map(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>si(Be),title:`Jump to fix feature ${Be}`,children:Be},`${Oe.roundId}-${Be}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Oe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Oe.blockedReason})]},Oe.roundId))})]}),Jt.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:Jt.map(Oe=>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:()=>si(Oe.id),title:`Jump to feature ${Oe.id}`,children:Oe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:br[Oe.status].bg,color:br[Oe.status].text},children:Oe.status}),Oe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Oe.loopState}`,children:Oe.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:()=>si(Oe.sourceFeatureId),title:`Jump to source feature ${Oe.sourceFeatureId}`,children:Oe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Oe.runId})]}),Oe.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:Oe.failedAssertionIds.map(Be=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(Be),title:`Jump to assertion ${Be}`,children:Be},`${Oe.id}-${Be}`))})]})]},Oe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[O.slices.map(Oe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Is(Oe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Oe.id)?t.jsx(Lt,{size:16}):t.jsx(en,{size:16})}),t.jsx($l,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Oe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:iu[Oe.status].bg,color:iu[Oe.status].text},children:Oe.status}),t.jsxs("span",{className:"mission-slice__count",children:[Oe.features?.length||0," features"]}),t.jsx(ru,{state:Oe.planState??"not_started"}),Oe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ye({type:"slice",id:Oe.id,title:Oe.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:[Oe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Es(Oe.id),title:"Activate slice",children:t.jsx(rn,{size:14})}),Oe.status==="active"&&Oe.features?.some(Be=>Be.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>jo(Oe.id),title:"Triage all features",disabled:_,children:_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(vn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>rs(Oe.id),title:"Add feature",children:t.jsx(qt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Bn(Oe),title:"Edit slice",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>U({type:"slice",id:Oe.id}),title:"Delete slice",children:t.jsx(Ht,{size:14})})]})]}),$.has(Oe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ae&&F===O.id&&!X&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:V.title,onChange:Be=>fe({...V,title:Be.target.value}),onKeyDown:Hc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:Be=>fe({...V,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:un,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),X===Oe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:V.title,onChange:Be=>fe({...V,title:Be.target.value}),onKeyDown:Hc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:V.description,onChange:Be=>fe({...V,description:Be.target.value}),rows:2}),t.jsxs("select",{value:V.status,onChange:Be=>fe({...V,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:un,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Oe.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:()=>Ri(Be.id),title:q===Be.id?"Collapse details":"Expand to show run history",children:q===Be.id?t.jsx(Lt,{size:14}):t.jsx(en,{size:14})}),t.jsx(Al,{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:br[Be.status].bg,color:br[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:()=>si(Be.generatedFromFeatureId),title:`Generated from feature: ${Be.generatedFromFeatureId}`,children:"🔗 Fix"}),(Be.loopState==="validating"||Be.loopState==="needs_fix")&&(()=>{const pt=rt.get(Be.id),Yt=Ef.get(Be.id),vs=pt?.implementationAttemptCount??Yt?.implementationAttempt??Be.implementationAttemptCount??0,hi=pt?.retryBudgetRemaining??Math.max(0,dN-vs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",vs," · ",hi," ",hi===1?"retry":"retries"," left"]})})(),Be.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>So(Be.id),title:"Validate feature",disabled:Me.has(Be.id),children:Me.has(Be.id)?t.jsx(it,{size:14,className:"spinner"}):t.jsx(Dn,{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:()=>or(Be.id),title:"Triage — create task",disabled:_||Ze===Be.id,children:Ze===Be.id?t.jsx(it,{size:14,className:"spinner"}):t.jsx(vn,{size:14})}),Be.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ko(Be.id),title:"Unlink task",children:t.jsx(Xc,{size:14})}):Be.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(Be.id),title:"Link to task",children:t.jsx(Wi,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>An(Be),title:"Edit feature",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>U({type:"feature",id:Be.id}),title:"Delete feature",children:t.jsx(Ht,{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]}),ce?.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:ce.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:lr,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ei,disabled:_,children:"Cancel"})]})]}),re===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ue.title,onChange:pt=>Ce({...ue,title:pt.target.value}),onKeyDown:qc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ue.description,onChange:pt=>Ce({...ue,description:pt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ue.acceptanceCriteria,onChange:pt=>Ce({...ue,acceptanceCriteria:pt.target.value}),rows:2}),t.jsxs("select",{value:ue.status,onChange:pt=>Ce({...ue,status:pt.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:Tn,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),q===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"})}),(ot.get(Be.id)??[]).map(pt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>ha(pt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${pt.status}`,title:pt.status,children:pt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(pt.startedAt).toLocaleString()}),pt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(pt.completedAt).getTime()-new Date(pt.startedAt).getTime())/1e3),"s"]}),pt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:pt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ot===pt.id?"Hide details":"Show details",children:Ot===pt.id?t.jsx(Lt,{size:12}):t.jsx(en,{size:12})})]}),Ot===pt.id&&Pt.get(pt.id)&&t.jsxs("div",{className:"mission-run__details",children:[pt.summary&&t.jsx("p",{className:"mission-run__summary",children:pt.summary}),pt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",pt.blockedReason]}),Pt.get(pt.id)?.failures&&Pt.get(pt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Pt.get(pt.id).failures.map(Yt=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Yt.message}),Yt.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Yt.expected]}),Yt.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Yt.actual]})]},Yt.id))]}),(!Pt.get(pt.id)?.failures||Pt.get(pt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},pt.id)),(!ot.get(Be.id)||ot.get(Be.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Be.id)),he&&ee===Oe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ue.title,onChange:Be=>Ce({...ue,title:Be.target.value}),onKeyDown:qc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ue.description,onChange:Be=>Ce({...ue,description:Be.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ue.acceptanceCriteria,onChange:Be=>Ce({...ue,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:Tn,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),!he&&(!Oe.features||Oe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Al,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Oe.id)),O.slices.length===0&&!ae&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx($l,{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:Ct.bg,color:Ct.text},children:ou(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:()=>{ze(!0),ge(null),ve({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(qt,{size:14})})]}),$e&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:He.title,onChange:Oe=>ve({...He,title:Oe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:He.assertion,onChange:Oe=>ve({...He,assertion:Oe.target.value}),rows:2}),t.jsxs("select",{value:He.status,onChange:Oe=>ve({...He,status:Oe.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:()=>Je(O.id),disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(ne.get(O.id))?ne.get(O.id):[]).map(Oe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Oe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:_e===Oe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:He.title,onChange:Be=>ve({...He,title:Be.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:He.assertion,onChange:Be=>ve({...He,assertion:Be.target.value}),rows:2}),t.jsxs("select",{value:He.status,onChange:Be=>ve({...He,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:()=>Ms(Oe.id,O.id),disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(vr[Oe.status]??vr.pending).bg,color:(vr[Oe.status]??vr.pending).text},children:Oe.status}),t.jsx("span",{className:"mission-assertion__title",children:Oe.title}),(()=>{const pt=be.get(Oe.id)?.length??0;return pt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${pt} linked feature${pt!==1?"s":""}`,children:["(",pt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>cr(Oe.id),title:"Toggle details",children:me===Oe.id?t.jsx(Lt,{size:14}):t.jsx(en,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>lt(Oe),title:"Edit assertion",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>U({type:"assertion",id:Oe.id}),title:"Delete assertion",children:t.jsx(Ht,{size:14})})]})}),me===Oe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Oe.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()=>{me!==Oe.id&&await cr(Oe.id),Ut(It===Oe.id?null:Oe.id)},title:"Link a feature",children:[t.jsx(Wi,{size:12}),"Link Feature"]})]}),It===Oe.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(Oe.id)??[]).map(Yt=>Yt.id)),pt=[];return f?.milestones.forEach(Yt=>Yt.slices.forEach(vs=>pt.push(...vs.features.filter(hi=>!Be.has(hi.id))))),pt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):pt.map(Yt=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>wo(Yt.id,Oe.id),disabled:tt.has(Oe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Yt.title}),tt.has(Oe.id)&&t.jsx(it,{size:12,className:"spinner"})]},Yt.id))})()})}),(()=>{const Be=be.get(Oe.id)??[];return Be.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Be.map(pt=>{const Yt=`${pt.id}-${Oe.id}`,vs=wt.has(Yt);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:pt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>No(pt.id,Oe.id),disabled:vs,title:"Unlink feature",children:vs?t.jsx(it,{size:12,className:"spinner"}):t.jsx(Xc,{size:12})})]},pt.id)})})()]})]})]},Oe.id)),(!ne.get(O.id)||ne.get(O.id)?.length===0)&&!$e&&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&&!A&&j===null&&t.jsxs("button",{className:"mission-add-btn",onClick:cn,children:[t.jsx(qt,{size:16}),"Add Milestone"]}),A&&j===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:O=>B({...K,title:O.target.value}),onKeyDown:Bc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:O=>B({...K,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:Cn,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),f.milestones.length===0&&!A&&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:J,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:[Sn.length," of ",ps]})]}),!_n&&dr&&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:Mf,"data-testid":"mission-activity-load-more",children:"Load more"})}),_n?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(it,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Sn.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:mt,className:"mission-events","data-testid":"mission-activity-events",children:[Sn.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 ${gN(O.eventType)}`,children:bN(O.eventType)}),t.jsx("span",{className:"mission-event__time",children:Kr(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:()=>_f(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:jt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:O=>P({...N,title:O.target.value}),onKeyDown:Mo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:O=>P({...N,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:on,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.map(O=>{const je=O,Te=f,ht=Te&&Te.id===je.id,Jt=ba[je.status]||{bg:"",text:""},Ct=je.summary,Bt=Kn.get(je.id),Oe=hN(Bt),Be=!!(Ct&&(Ct.totalMilestones>0||Ct.totalFeatures>0)),pt=Bt?.totalTasks??0,Yt=Bt?.tasksCompleted??0,vs=Bt?.tasksFailed??0,hi=Bt?.estimatedCompletionPercent??Ct?.progressPercent??0,En=Be||pt>0||vs>0||!!Bt?.lastActivityAt,ln=je.status==="active"&&(Bt?.currentMilestoneId||Bt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${ht?"mission-list__item--selected":""}`,onClick:()=>_s(O),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ns,{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(vn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Oe}`,"data-testid":`mission-health-badge-${je.id}`,"aria-label":`Mission health: ${Oe}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Jt.bg,color:Jt.text},children:je.status})]}),je.description&&t.jsx("p",{className:"mission-list__item-description",children:je.description}),ln&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",ln]}),En&&t.jsxs("div",{className:"mission-list__item-summary",children:[Be&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Ct.completedMilestones,"/",Ct.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Ct.completedFeatures,"/",Ct.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${je.id}`,children:[Yt,"/",pt," tasks"]}),vs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Rt=>{Rt.stopPropagation(),_s(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 ",Kr(Bt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Oe}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${hi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Rt=>Rt.stopPropagation(),children:[je.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Eo(je.id),title:"Stop mission",children:t.jsx(ls,{size:14})}),je.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Co(je.id),title:"Resume mission",children:t.jsx(rn,{size:14})}),je.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xs(je.id),title:"Start mission",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft(O),title:"Edit mission",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>U({type:"mission",id:je.id}),title:"Delete mission",children:t.jsx(Ht,{size:14})})]})]},je.id)}),y&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:N.title,onChange:O=>P({...N,title:O.target.value}),onKeyDown:Mo,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:N.description,onChange:O=>P({...N,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:N.status,onChange:O=>P({...N,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:N.autopilotEnabled,onChange:O=>P({...N,autopilotEnabled:O.target.checked})}),t.jsx(vn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:_,children:[_?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.length===0&&!w&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ns,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!w&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Se.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(ss,{size:16}),t.jsx("span",{children:Se.length===1?`Resume "${Se[0].title}"?`:`${Se.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Se.map(O=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{Q(O.id),Qe(!0),Fe([])},children:[O.status==="error"?t.jsx(hn,{size:14}):t.jsx(Dn,{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:()=>Qe(!0),children:[t.jsx(Dn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:st,children:[t.jsx(qt,{size:16}),"New Mission"]})]})]})]})}),le&&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 ",le.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()=>{le.type==="mission"?await Zt(le.id):le.type==="milestone"?await gs(le.id):le.type==="slice"?await Xn(le.id):le.type==="feature"&&await ua(le.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>U(null),children:"Cancel"})]})]})}),Ie&&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:Ve,onChange:O=>Ge(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:()=>Ge(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:yo,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{qe(null),Ge("")},children:"Cancel"})]})]})})]}),Wc=t.jsx(iN,{isOpen:Ke,onClose:()=>Qe(!1),onMissionCreated:()=>{Xt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:pe}),Kc=te?t.jsx(oN,{isOpen:!0,onClose:()=>ye(null),onApplied:()=>{ye(null),f&&vt(f.id)},targetType:te.type,targetId:te.id,targetTitle:te.title,missionContext:f?.title,projectId:r,resumeSessionId:te.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Vc,Wc,Kc]}):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:Vc}),Wc,Kc]})}const yr=2e3;function cu({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),k=u.trim()!==""&&g.trim().length>0&&g.length<=yr,M=a.useCallback(async()=>{if(!(!k||f)){b(!0),x(null);try{const I=m==="agent"?"user-to-agent":"system";await Hk({toId:u.trim(),toType:m,content:g.trim(),type:I,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(I){const y=xe(I)||"Failed to send message";x(y),l?.(y,"error")}finally{b(!1)}}},[k,f,u,m,g,n,i,r,l]),w=a.useCallback(I=>{d(I),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(Dt,{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:I=>w(I.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(I=>t.jsx("option",{value:I.id,children:I.name||I.id},I.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(an,{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:I=>p(I.target.value),maxLength:yr,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>yr?"over-limit":"",children:[g.length,"/",yr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(ss,{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:M,disabled:!k||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function zi(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 yN(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 kN(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 du(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function jN(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 wN({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,k]=a.useState(!1),[M,w]=a.useState(null),[I,y]=a.useState(null),[E,N]=a.useState(null),[P,_]=a.useState("inbox"),[R,z]=a.useState(null),[G,$]=a.useState([]),T=a.useMemo(()=>new Map(G.map(ee=>[ee.id,ee.name??""])),[G]),j=a.useCallback((ee,we)=>yN(ee,we,T),[T]),K=sr()==="mobile",B=!K,A=a.useCallback(async()=>{g(!0);try{const ee=await Uk({limit:50},e);l(ee),m(ee.unreadCount),s?.(ee.unreadCount)}catch{}finally{g(!1)}},[e,s]),L=a.useCallback(async()=>{g(!0);try{const ee=await Bk({limit:50},e);u(ee)}catch{}finally{g(!1)}},[e]),X=a.useCallback(async ee=>{g(!0);try{const we=await Gk(ee,e);z(we)}catch{}finally{g(!1)}},[e]),C=a.useCallback(async()=>{try{const ee=await oa(void 0,e);$(ee)}catch{}},[e]),V=a.useCallback(async()=>{try{const ee=await Ah(e);m(ee.unreadCount),s?.(ee.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?A():i==="outbox"?L():i==="agents"&&C()},[i,A,L,C]),a.useEffect(()=>{E&&X(E)},[E,X]),a.useEffect(()=>{V()},[V]),a.useEffect(()=>{C()},[C]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ee=e?`?projectId=${encodeURIComponent(e)}`:"",we=()=>{V(),i==="inbox"?A():i==="outbox"&&L(),E&&X(E)};return qs(`/api/events${ee}`,{events:{"message:sent":we,"message:received":we,"message:read":we,"message:deleted":we}})},[e,i,E,V,A,L,X]);const fe=a.useCallback(async ee=>{if(f(ee),!ee.read)try{const we=await qk(ee.id,e);we&&l(qe=>qe&&{...qe,messages:qe.messages.map(Ve=>Ve.id===we.id?we:Ve),unreadCount:Math.max(0,qe.unreadCount-1)});const Ie=Math.max(0,d-1);m(Ie),s?.(Ie)}catch{}try{const we=await Kk(ee.fromId,ee.fromType,e);v(we)}catch{v([ee])}},[e,d,s]),ae=a.useCallback(()=>{f(null),v([])},[]),oe=a.useCallback(async()=>{try{const ee=await Vk(e);m(0),s?.(0),l(we=>we&&{...we,messages:we.messages.map(Ie=>({...Ie,read:!0})),unreadCount:0}),n?.(`Marked ${ee.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),F=a.useCallback(async ee=>{try{await Wk(ee,e),f(null),v([]),i==="inbox"?A():i==="outbox"?L():E&&X(E),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,E,A,L,X,n]),de=a.useCallback(ee=>{w({id:ee.fromId,type:ee.fromType}),y({messageId:ee.id,preview:du(ee.content,120)}),k(!0)},[]),re=a.useCallback(()=>{k(!1),w(null),y(null),n?.("Message sent","success"),i==="outbox"?L():i==="agents"&&E&&X(E),V()},[i,L,E,X,n,V]),Z=a.useCallback(()=>{w(i==="agents"&&E?{id:E,type:"agent"}:null),y(null),k(!0)},[i,E]),ue=a.useCallback(()=>{k(!1),w(null),y(null)},[]),Ce=()=>!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:[K&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ae,"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:kN(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:zi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>de(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(Ht,{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(an,{size:14}):t.jsx(Pi,{size:14}),j(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(an,{size:14}):t.jsx(Pi,{size:14}),j(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(ee=>{const we=ee.metadata?.replyTo?.messageId,Ie=we?b.find(qe=>qe.id===we):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ee.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:j(ee.fromId,ee.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:zi(ee.createdAt)})]}),we&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ee.id}`,children:["↪ Replying to ",Ie?du(Ie.content,60):`message ${we}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ee.content})]},ee.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})]})]}),he=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Wo,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Ra,{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:jN(o.messages).map(ee=>t.jsxs("div",{className:`mailbox-conversation-group ${ee.unreadCount>0?"unread":""}`,onClick:()=>fe(ee.latestMessage),"data-testid":`mailbox-conversation-${ee.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.fromType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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:j(ee.fromId,ee.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:zi(ee.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.latestMessage.content.slice(0,80),ee.latestMessage.content.length>80?"…":""]})]}),ee.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ee.key}`,children:ee.unreadCount>9?"9+":ee.unreadCount})]},ee.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Wo,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(vi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ee=>t.jsxs("div",{className:"mailbox-item",onClick:()=>fe(ee),"data-testid":`mailbox-item-${ee.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.toType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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: ",j(ee.toId,ee.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:zi(ee.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.content.slice(0,80),ee.content.length>80?"…":""]})]})]},ee.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(an,{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:E??"",onChange:ee=>{N(ee.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),G.map(ee=>t.jsx("option",{value:ee.id,children:ee.name||ee.id},ee.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Z,"data-testid":"mailbox-compose-btn",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]})]}),E&&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(Ra,{size:12}),t.jsx("span",{children:"Inbox"}),R&&R.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:R.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(vi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!E&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(an,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),E&&h&&!R&&t.jsx(Wo,{}),E&&R&&P==="inbox"&&R.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ra,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),E&&R&&P==="outbox"&&R.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(vi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),E&&R&&P==="inbox"&&R.inbox.map(ee=>t.jsxs("div",{className:`mailbox-item ${ee.read?"":"unread"}`,onClick:()=>fe(ee),"data-testid":`mailbox-item-${ee.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.fromType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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:j(ee.fromId,ee.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:zi(ee.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.content.slice(0,80),ee.content.length>80?"…":""]})]})]},ee.id)),E&&R&&P==="outbox"&&R.outbox.map(ee=>t.jsxs("div",{className:"mailbox-item",onClick:()=>fe(ee),"data-testid":`mailbox-item-${ee.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ee.toType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{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: ",j(ee.toId,ee.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:zi(ee.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ee.content.slice(0,80),ee.content.length>80?"…":""]})]})]},ee.id))]})]})})]}),Ne=()=>x?t.jsx(cu,{recipient:M,replyContext:I,agents:G,projectId:e,onSend:re,onCancel:ue,addToast:n}):p?Ce():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Ki,{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(Ki,{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:Z,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:oe,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Xf,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?A():i==="outbox"?L():E&&X(E)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{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(Ra,{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(vi,{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(an,{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:he()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Ne()})]}):t.jsxs(t.Fragment,{children:[Ce(),x&&t.jsx(cu,{recipient:M,replyContext:I,agents:G,projectId:e,onSend:re,onCancel:ue,addToast:n}),!p&&!x&&he()]})})]})}function Wo(){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 NN(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const SN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,CN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,EN={};function uu(e,n){return(EN.jsx?CN:SN).test(e)}const MN=/[ \t\n\f\r]/g;function _N(e){return typeof e=="object"?e.type==="text"?mu(e.value):!1:mu(e)}function mu(e){return e.replace(MN,"")===""}class ir{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}ir.prototype.normal={};ir.prototype.property={};ir.prototype.space=void 0;function Jh(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new ir(s,i,n)}function Vl(e){return e.toLowerCase()}class as{constructor(n,s){this.attribute=s,this.property=n}}as.prototype.attribute="";as.prototype.booleanish=!1;as.prototype.boolean=!1;as.prototype.commaOrSpaceSeparated=!1;as.prototype.commaSeparated=!1;as.prototype.defined=!1;as.prototype.mustUseProperty=!1;as.prototype.number=!1;as.prototype.overloadedBoolean=!1;as.prototype.property="";as.prototype.spaceSeparated=!1;as.prototype.space=void 0;let AN=0;const Et=Ai(),mn=Ai(),Wl=Ai(),Xe=Ai(),Qt=Ai(),qi=Ai(),os=Ai();function Ai(){return 2**++AN}const Kl=Object.freeze(Object.defineProperty({__proto__:null,boolean:Et,booleanish:mn,commaOrSpaceSeparated:os,commaSeparated:qi,number:Xe,overloadedBoolean:Wl,spaceSeparated:Qt},Symbol.toStringTag,{value:"Module"})),Ko=Object.keys(Kl);class kc extends as{constructor(n,s,i,r){let o=-1;if(super(n,s),hu(this,"space",r),typeof i=="number")for(;++o<Ko.length;){const l=Ko[o];hu(this,Ko[o],(i&Kl[l])===Kl[l])}}}kc.prototype.defined=!0;function hu(e,n,s){s&&(e[n]=s)}function ca(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new kc(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Vl(i)]=i,s[Vl(o.attribute)]=i}return new ir(n,s,e.space)}const Yh=ca({properties:{ariaActiveDescendant:null,ariaAtomic:mn,ariaAutoComplete:null,ariaBusy:mn,ariaChecked:mn,ariaColCount:Xe,ariaColIndex:Xe,ariaColSpan:Xe,ariaControls:Qt,ariaCurrent:null,ariaDescribedBy:Qt,ariaDetails:null,ariaDisabled:mn,ariaDropEffect:Qt,ariaErrorMessage:null,ariaExpanded:mn,ariaFlowTo:Qt,ariaGrabbed:mn,ariaHasPopup:null,ariaHidden:mn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Qt,ariaLevel:Xe,ariaLive:null,ariaModal:mn,ariaMultiLine:mn,ariaMultiSelectable:mn,ariaOrientation:null,ariaOwns:Qt,ariaPlaceholder:null,ariaPosInSet:Xe,ariaPressed:mn,ariaReadOnly:mn,ariaRelevant:null,ariaRequired:mn,ariaRoleDescription:Qt,ariaRowCount:Xe,ariaRowIndex:Xe,ariaRowSpan:Xe,ariaSelected:mn,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 Qh(e,n){return n in e?e[n]:n}function Xh(e,n){return Qh(e,n.toLowerCase())}const TN=ca({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:qi,acceptCharset:Qt,accessKey:Qt,action:null,allow:null,allowFullScreen:Et,allowPaymentRequest:Et,allowUserMedia:Et,alt:null,as:null,async:Et,autoCapitalize:null,autoComplete:Qt,autoFocus:Et,autoPlay:Et,blocking:Qt,capture:null,charSet:null,checked:Et,cite:null,className:Qt,cols:Xe,colSpan:null,content:null,contentEditable:mn,controls:Et,controlsList:Qt,coords:Xe|qi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Et,defer:Et,dir:null,dirName:null,disabled:Et,download:Wl,draggable:mn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Et,formTarget:null,headers:Qt,height:Xe,hidden:Wl,high:Xe,href:null,hrefLang:null,htmlFor:Qt,httpEquiv:Qt,id:null,imageSizes:null,imageSrcSet:null,inert:Et,inputMode:null,integrity:null,is:null,isMap:Et,itemId:null,itemProp:Qt,itemRef:Qt,itemScope:Et,itemType:Qt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Et,low:Xe,manifest:null,max:null,maxLength:Xe,media:null,method:null,min:null,minLength:Xe,multiple:Et,muted:Et,name:null,nonce:null,noModule:Et,noValidate:Et,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:Et,optimum:Xe,pattern:null,ping:Qt,placeholder:null,playsInline:Et,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Et,referrerPolicy:null,rel:Qt,required:Et,reversed:Et,rows:Xe,rowSpan:Xe,sandbox:Qt,scope:null,scoped:Et,seamless:Et,selected:Et,shadowRootClonable:Et,shadowRootDelegatesFocus:Et,shadowRootMode:null,shape:null,size:Xe,sizes:null,slot:null,span:Xe,spellCheck:mn,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:Et,useMap:null,value:mn,width:Xe,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Qt,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:Et,declare:Et,event:null,face:null,frame:null,frameBorder:null,hSpace:Xe,leftMargin:Xe,link:null,longDesc:null,lowSrc:null,marginHeight:Xe,marginWidth:Xe,noResize:Et,noHref:Et,noShade:Et,noWrap:Et,object:null,profile:null,prompt:null,rev:null,rightMargin:Xe,rules:null,scheme:null,scrolling:mn,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:Et,disableRemotePlayback:Et,prefix:null,property:null,results:Xe,security:null,unselectable:null},space:"html",transform:Xh}),RN=ca({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:os,accentHeight: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:Qt,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:Et,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:qi,g2:qi,glyphName:qi,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:os,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:Qt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Xe,pointsAtY:Xe,pointsAtZ:Xe,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:os,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:os,rev:os,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:os,requiredFeatures:os,requiredFonts:os,requiredFormats:os,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant: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:os,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:os,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:os,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:Qh}),Zh=ca({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()}}),ep=ca({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Xh}),tp=ca({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),IN={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"},PN=/[A-Z]/g,pu=/-[a-z]/g,$N=/^data[-\w.:]+$/i;function DN(e,n){const s=Vl(n);let i=n,r=as;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&$N.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(pu,zN);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!pu.test(o)){let l=o.replace(PN,LN);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=kc}return new r(i,n)}function LN(e){return"-"+e.toLowerCase()}function zN(e){return e.charAt(1).toUpperCase()}const FN=Jh([Yh,TN,Zh,ep,tp],"html"),jc=Jh([Yh,RN,Zh,ep,tp],"svg");function ON(e){return e.join(" ").trim()}var Fi={},Go,fu;function UN(){if(fu)return Go;fu=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=`
593
+ `,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 k=1,M=1;function w($){var T=$.match(n);T&&(k+=T.length);var j=$.lastIndexOf(u);M=~j?$.length-j:M+$.length}function I(){var $={line:k,column:M};return function(T){return T.position=new y($),P(),T}}function y($){this.start=$,this.end={line:k,column:M},this.source=x.source}y.prototype.content=v;function E($){var T=new Error(x.source+":"+k+":"+M+": "+$);if(T.reason=$,T.filename=x.source,T.line=k,T.column=M,T.source=v,!x.silent)throw T}function N($){var T=$.exec(v);if(T){var j=T[0];return w(j),v=v.slice(j.length),T}}function P(){N(s)}function _($){var T;for($=$||[];T=R();)T!==!1&&$.push(T);return $}function R(){var $=I();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var T=2;h!=v.charAt(T)&&(m!=v.charAt(T)||d!=v.charAt(T+1));)++T;if(T+=2,h===v.charAt(T-1))return E("End of comment missing");var j=v.slice(2,T-2);return M+=2,w(j),v=v.slice(T),M+=2,$({type:g,comment:j})}}function z(){var $=I(),T=N(i);if(T){if(R(),!N(r))return E("property missing ':'");var j=N(o),W=$({type:p,property:b(T[0].replace(e,h)),value:j?b(j[0].replace(e,h)):h});return N(l),W}}function G(){var $=[];_($);for(var T;T=z();)T!==!1&&($.push(T),_($));return $}return P(),G()}function b(v){return v?v.replace(c,h):h}return Go=f,Go}var gu;function BN(){if(gu)return Fi;gu=1;var e=Fi&&Fi.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=s;const n=e(UN());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 Fi}var xa={},bu;function HN(){if(bu)return xa;bu=1,Object.defineProperty(xa,"__esModule",{value:!0}),xa.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 xa.camelCase=u,xa}var va,xu;function qN(){if(xu)return va;xu=1;var e=va&&va.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(BN()),s=HN();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,va=i,va}var VN=qN();const WN=Qm(VN),np=sp("end"),wc=sp("start");function sp(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 KN(e){const n=wc(e),s=np(e);if(n&&s)return{start:n,end:s}}function La(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?vu(e.position):"start"in e||"end"in e?vu(e):"line"in e||"column"in e?Gl(e):""}function Gl(e){return yu(e&&e.line)+":"+yu(e&&e.column)}function vu(e){return Gl(e&&e.start)+"-"+Gl(e&&e.end)}function yu(e){return e&&typeof e=="number"?e:1}class Ln 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=La(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}}Ln.prototype.file="";Ln.prototype.name="";Ln.prototype.reason="";Ln.prototype.message="";Ln.prototype.stack="";Ln.prototype.column=void 0;Ln.prototype.line=void 0;Ln.prototype.ancestors=void 0;Ln.prototype.cause=void 0;Ln.prototype.fatal=void 0;Ln.prototype.place=void 0;Ln.prototype.ruleId=void 0;Ln.prototype.source=void 0;const Nc={}.hasOwnProperty,GN=new Map,JN=/[A-Z]/g,YN=new Set(["table","tbody","thead","tfoot","tr"]),QN=new Set(["td","th"]),ip="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function XN(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=r1(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=a1(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?jc:FN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=ap(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function ap(e,n,s){if(n.type==="element")return ZN(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return e1(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return n1(e,n,s);if(n.type==="mdxjsEsm")return t1(e,n);if(n.type==="root")return s1(e,n,s);if(n.type==="text")return i1(e,n)}function ZN(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=jc,e.schema=r),e.ancestors.push(n);const o=op(e,n.tagName,!1),l=o1(e,n);let c=Cc(e,n);return YN.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!_N(u):!0})),rp(e,l,o,n),Sc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function e1(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)}Wa(e,n.position)}function t1(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Wa(e,n.position)}function n1(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=jc,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:op(e,n.name,!0),l=l1(e,n),c=Cc(e,n);return rp(e,l,o,n),Sc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function s1(e,n,s){const i={};return Sc(i,Cc(e,n)),e.create(n,e.Fragment,i,s)}function i1(e,n){return n.value}function rp(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function Sc(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function a1(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 r1(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=wc(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 o1(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&Nc.call(n.properties,r)){const o=c1(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&QN.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 l1(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 Wa(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 Wa(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Cc(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:GN;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=ap(e,o,l);c!==void 0&&s.push(c)}return s}function c1(e,n,s){const i=DN(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?NN(s):ON(s)),i.property==="style"){let r=typeof s=="object"?s:d1(e,String(s));return e.stylePropertyNameCase==="css"&&(r=u1(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?IN[i.property]||i.property:i.attribute,s]}}function d1(e,n){try{return WN(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Ln("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=ip+"#cannot-parse-style-attribute",r}}function op(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=uu(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=uu(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return Nc.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);Wa(e)}function Wa(e,n){const s=new Ln("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=ip+"#cannot-handle-mdx-estrees-without-createevaluater",s}function u1(e){const n={};let s;for(s in e)Nc.call(e,s)&&(n[m1(s)]=e[s]);return n}function m1(e){let n=e.replace(JN,h1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function h1(e){return"-"+e.toLowerCase()}const Jo={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},p1={};function Ec(e,n){const s=p1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return lp(e,i,r)}function lp(e,n,s){if(f1(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 ku(e.children,n,s)}return Array.isArray(e)?ku(e,n,s):""}function ku(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=lp(e[r],n,s);return i.join("")}function f1(e){return!!(e&&typeof e=="object")}const ju=document.createElement("i");function Mc(e){const n="&"+e+";";ju.innerHTML=n;const s=ju.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 wu={}.hasOwnProperty;function cp(e){const n={};let s=-1;for(;++s<e.length;)g1(n,e[s]);return n}function g1(e,n){let s;for(s in n){const r=(wu.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){wu.call(r,l)||(r[l]=[]);const c=o[l];b1(r[l],Array.isArray(c)?c:c?[c]:[])}}}function b1(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 dp(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 Vn=ui(/[A-Za-z]/),$n=ui(/[\dA-Za-z]/),x1=ui(/[#-'*+\--9=?A-Z^-~]/);function Gr(e){return e!==null&&(e<32||e===127)}const Jl=ui(/\d/),v1=ui(/[\dA-Fa-f]/),y1=ui(/[!-/:-@[-`{-~]/);function yt(e){return e!==null&&e<-2}function Kt(e){return e!==null&&(e<0||e===32)}function $t(e){return e===-2||e===-1||e===32}const fo=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 da(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&$n(e.charCodeAt(s+1))&&$n(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 Ft(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return $t(u)?(e.enter(s),c(u)):n(u)}function c(u){return $t(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const k1={tokenize:j1};function j1(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"),Ft(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 yt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const w1={tokenize:N1},Nu={tokenize:S1};function N1(e){const n=this,s=[];let i=0,r,o,l;return c;function c(M){if(i<s.length){const w=s[i];return n.containerState=w[1],e.attempt(w[0].continuation,u,d)(M)}return d(M)}function u(M){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&k();const w=n.events.length;let I=w,y;for(;I--;)if(n.events[I][0]==="exit"&&n.events[I][1].type==="chunkFlow"){y=n.events[I][1].end;break}x(i);let E=w;for(;E<n.events.length;)n.events[E][1].end={...y},E++;return ds(n.events,I+1,0,n.events.slice(w)),n.events.length=E,d(M)}return c(M)}function d(M){if(i===s.length){if(!r)return g(M);if(r.currentConstruct&&r.currentConstruct.concrete)return f(M);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Nu,m,h)(M)}function m(M){return r&&k(),x(i),g(M)}function h(M){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(M)}function g(M){return n.containerState={},e.attempt(Nu,p,f)(M)}function p(M){return i++,s.push([n.currentConstruct,n.containerState]),g(M)}function f(M){if(M===null){r&&k(),x(0),e.consume(M);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(M)}function b(M){if(M===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(M);return}return yt(M)?(e.consume(M),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(M),b)}function v(M,w){const I=n.sliceStream(M);if(w&&I.push(null),M.previous=o,o&&(o.next=M),o=M,r.defineSkip(M.start),r.write(I),n.parser.lazy[M.start.line]){let y=r.events.length;for(;y--;)if(r.events[y][1].start.offset<l&&(!r.events[y][1].end||r.events[y][1].end.offset>l))return;const E=n.events.length;let N=E,P,_;for(;N--;)if(n.events[N][0]==="exit"&&n.events[N][1].type==="chunkFlow"){if(P){_=n.events[N][1].end;break}P=!0}for(x(i),y=E;y<n.events.length;)n.events[y][1].end={..._},y++;ds(n.events,N+1,0,n.events.slice(E)),n.events.length=y}}function x(M){let w=s.length;for(;w-- >M;){const I=s[w];n.containerState=I[1],I[0].exit.call(n,e)}s.length=M}function k(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function S1(e,n,s){return Ft(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Qi(e){if(e===null||Kt(e)||Ei(e))return 1;if(fo(e))return 2}function go(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 Yl={name:"attention",resolveAll:C1,tokenize:E1};function C1(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};Su(h,-u),Su(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,go(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=Qi(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=Qi(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 Su(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const M1={name:"autolink",tokenize:_1};function _1(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 Vn(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||$n(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||$n(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||Gr(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):x1(p)?(e.consume(p),d):s(p)}function m(p){return $n(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||$n(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const ar={partial:!0,tokenize:A1};function A1(e,n,s){return i;function i(o){return $t(o)?Ft(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||yt(o)?n(o):s(o)}}const up={continuation:{tokenize:R1},exit:I1,name:"blockQuote",tokenize:T1};function T1(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 $t(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function R1(e,n,s){const i=this;return r;function r(l){return $t(l)?Ft(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(up,n,s)(l)}}function I1(e){e.exit("blockQuote")}const mp={name:"characterEscape",tokenize:P1};function P1(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 y1(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const hp={name:"characterReference",tokenize:$1};function $1(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=$n,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=v1,m):(e.enter("characterReferenceValue"),o=7,l=Jl,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===$n&&!Mc(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 Cu={partial:!0,tokenize:L1},Eu={concrete:!0,name:"codeFenced",tokenize:D1};function D1(e,n,s){const i=this,r={partial:!0,tokenize:I};let o=0,l=0,c;return u;function u(y){return d(y)}function d(y){const E=i.events[i.events.length-1];return o=E&&E[1].type==="linePrefix"?E[2].sliceSerialize(E[1],!0).length:0,c=y,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(y)}function m(y){return y===c?(l++,e.consume(y),m):l<3?s(y):(e.exit("codeFencedFenceSequence"),$t(y)?Ft(e,h,"whitespace")(y):h(y))}function h(y){return y===null||yt(y)?(e.exit("codeFencedFence"),i.interrupt?n(y):e.check(Cu,b,w)(y)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(y))}function g(y){return y===null||yt(y)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(y)):$t(y)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Ft(e,p,"whitespace")(y)):y===96&&y===c?s(y):(e.consume(y),g)}function p(y){return y===null||yt(y)?h(y):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(y))}function f(y){return y===null||yt(y)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(y)):y===96&&y===c?s(y):(e.consume(y),f)}function b(y){return e.attempt(r,w,v)(y)}function v(y){return e.enter("lineEnding"),e.consume(y),e.exit("lineEnding"),x}function x(y){return o>0&&$t(y)?Ft(e,k,"linePrefix",o+1)(y):k(y)}function k(y){return y===null||yt(y)?e.check(Cu,b,w)(y):(e.enter("codeFlowValue"),M(y))}function M(y){return y===null||yt(y)?(e.exit("codeFlowValue"),k(y)):(e.consume(y),M)}function w(y){return e.exit("codeFenced"),n(y)}function I(y,E,N){let P=0;return _;function _(T){return y.enter("lineEnding"),y.consume(T),y.exit("lineEnding"),R}function R(T){return y.enter("codeFencedFence"),$t(T)?Ft(y,z,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):z(T)}function z(T){return T===c?(y.enter("codeFencedFenceSequence"),G(T)):N(T)}function G(T){return T===c?(P++,y.consume(T),G):P>=l?(y.exit("codeFencedFenceSequence"),$t(T)?Ft(y,$,"whitespace")(T):$(T)):N(T)}function $(T){return T===null||yt(T)?(y.exit("codeFencedFence"),E(T)):N(T)}}}function L1(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 Yo={name:"codeIndented",tokenize:F1},z1={partial:!0,tokenize:O1};function F1(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Ft(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):yt(d)?e.attempt(z1,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||yt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function O1(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):yt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Ft(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):yt(l)?r(l):s(l)}}const U1={name:"codeText",previous:H1,resolve:B1,tokenize:q1};function B1(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 H1(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function q1(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)):yt(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||yt(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 V1{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&ya(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),ya(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),ya(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);ya(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);ya(this.left,s.reverse())}}}function ya(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 pp(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new V1(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,W1(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 W1(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]),k=o.pop();u.push([k,k+x.length-1]),e.splice(k,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 K1={resolve:J1,tokenize:Y1},G1={partial:!0,tokenize:Q1};function J1(e){return pp(e),e}function Y1(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):yt(c)?e.check(G1,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 Q1(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Ft(e,o,"linePrefix")}function o(l){if(l===null||yt(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 fp(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||Gr(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||yt(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||Kt(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||Gr(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 gp(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):yt(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||yt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!$t(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function bp(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):yt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Ft(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||yt(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 za(e,n){let s;return i;function i(r){return yt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):$t(r)?Ft(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const X1={name:"definition",tokenize:e0},Z1={partial:!0,tokenize:t0};function e0(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return gp.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 Kt(p)?za(e,d)(p):d(p)}function d(p){return fp(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(Z1,h,h)(p)}function h(p){return $t(p)?Ft(e,g,"whitespace")(p):g(p)}function g(p){return p===null||yt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function t0(e,n,s){return i;function i(c){return Kt(c)?za(e,r)(c):s(c)}function r(c){return bp(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return $t(c)?Ft(e,l,"whitespace")(c):l(c)}function l(c){return c===null||yt(c)?n(c):s(c)}}const n0={name:"hardBreakEscape",tokenize:s0};function s0(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return yt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const i0={name:"headingAtx",resolve:a0,tokenize:r0};function a0(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 r0(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||Kt(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||yt(m)?(e.exit("atxHeading"),n(m)):$t(m)?Ft(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||Kt(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const o0=["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"],Mu=["pre","script","style","textarea"],l0={concrete:!0,name:"htmlFlow",resolveTo:u0,tokenize:m0},c0={partial:!0,tokenize:p0},d0={partial:!0,tokenize:h0};function u0(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 m0(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:A):Vn(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):Vn(C)?(e.consume(C),r=4,i.interrupt?n:A):s(C)}function p(C){return C===45?(e.consume(C),i.interrupt?n:A):s(C)}function f(C){const V="CDATA[";return C===V.charCodeAt(c++)?(e.consume(C),c===V.length?i.interrupt?n:z:f):s(C)}function b(C){return Vn(C)?(e.consume(C),l=String.fromCharCode(C),v):s(C)}function v(C){if(C===null||C===47||C===62||Kt(C)){const V=C===47,fe=l.toLowerCase();return!V&&!o&&Mu.includes(fe)?(r=1,i.interrupt?n(C):z(C)):o0.includes(l.toLowerCase())?(r=6,V?(e.consume(C),x):i.interrupt?n(C):z(C)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(C):o?k(C):M(C))}return C===45||$n(C)?(e.consume(C),l+=String.fromCharCode(C),v):s(C)}function x(C){return C===62?(e.consume(C),i.interrupt?n:z):s(C)}function k(C){return $t(C)?(e.consume(C),k):_(C)}function M(C){return C===47?(e.consume(C),_):C===58||C===95||Vn(C)?(e.consume(C),w):$t(C)?(e.consume(C),M):_(C)}function w(C){return C===45||C===46||C===58||C===95||$n(C)?(e.consume(C),w):I(C)}function I(C){return C===61?(e.consume(C),y):$t(C)?(e.consume(C),I):M(C)}function y(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(e.consume(C),u=C,E):$t(C)?(e.consume(C),y):N(C)}function E(C){return C===u?(e.consume(C),u=null,P):C===null||yt(C)?s(C):(e.consume(C),E)}function N(C){return C===null||C===34||C===39||C===47||C===60||C===61||C===62||C===96||Kt(C)?I(C):(e.consume(C),N)}function P(C){return C===47||C===62||$t(C)?M(C):s(C)}function _(C){return C===62?(e.consume(C),R):s(C)}function R(C){return C===null||yt(C)?z(C):$t(C)?(e.consume(C),R):s(C)}function z(C){return C===45&&r===2?(e.consume(C),j):C===60&&r===1?(e.consume(C),W):C===62&&r===4?(e.consume(C),L):C===63&&r===3?(e.consume(C),A):C===93&&r===5?(e.consume(C),B):yt(C)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(c0,X,G)(C)):C===null||yt(C)?(e.exit("htmlFlowData"),G(C)):(e.consume(C),z)}function G(C){return e.check(d0,$,X)(C)}function $(C){return e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),T}function T(C){return C===null||yt(C)?G(C):(e.enter("htmlFlowData"),z(C))}function j(C){return C===45?(e.consume(C),A):z(C)}function W(C){return C===47?(e.consume(C),l="",K):z(C)}function K(C){if(C===62){const V=l.toLowerCase();return Mu.includes(V)?(e.consume(C),L):z(C)}return Vn(C)&&l.length<8?(e.consume(C),l+=String.fromCharCode(C),K):z(C)}function B(C){return C===93?(e.consume(C),A):z(C)}function A(C){return C===62?(e.consume(C),L):C===45&&r===2?(e.consume(C),A):z(C)}function L(C){return C===null||yt(C)?(e.exit("htmlFlowData"),X(C)):(e.consume(C),L)}function X(C){return e.exit("htmlFlow"),n(C)}}function h0(e,n,s){const i=this;return r;function r(l){return yt(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 p0(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(ar,n,s)}}const f0={name:"htmlText",tokenize:g0};function g0(e,n,s){const i=this;let r,o,l;return c;function c(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),u}function u(A){return A===33?(e.consume(A),d):A===47?(e.consume(A),I):A===63?(e.consume(A),M):Vn(A)?(e.consume(A),N):s(A)}function d(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,f):Vn(A)?(e.consume(A),k):s(A)}function m(A){return A===45?(e.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(e.consume(A),g):yt(A)?(l=h,W(A)):(e.consume(A),h)}function g(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?j(A):A===45?g(A):h(A)}function f(A){const L="CDATA[";return A===L.charCodeAt(o++)?(e.consume(A),o===L.length?b:f):s(A)}function b(A){return A===null?s(A):A===93?(e.consume(A),v):yt(A)?(l=b,W(A)):(e.consume(A),b)}function v(A){return A===93?(e.consume(A),x):b(A)}function x(A){return A===62?j(A):A===93?(e.consume(A),x):b(A)}function k(A){return A===null||A===62?j(A):yt(A)?(l=k,W(A)):(e.consume(A),k)}function M(A){return A===null?s(A):A===63?(e.consume(A),w):yt(A)?(l=M,W(A)):(e.consume(A),M)}function w(A){return A===62?j(A):M(A)}function I(A){return Vn(A)?(e.consume(A),y):s(A)}function y(A){return A===45||$n(A)?(e.consume(A),y):E(A)}function E(A){return yt(A)?(l=E,W(A)):$t(A)?(e.consume(A),E):j(A)}function N(A){return A===45||$n(A)?(e.consume(A),N):A===47||A===62||Kt(A)?P(A):s(A)}function P(A){return A===47?(e.consume(A),j):A===58||A===95||Vn(A)?(e.consume(A),_):yt(A)?(l=P,W(A)):$t(A)?(e.consume(A),P):j(A)}function _(A){return A===45||A===46||A===58||A===95||$n(A)?(e.consume(A),_):R(A)}function R(A){return A===61?(e.consume(A),z):yt(A)?(l=R,W(A)):$t(A)?(e.consume(A),R):P(A)}function z(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,G):yt(A)?(l=z,W(A)):$t(A)?(e.consume(A),z):(e.consume(A),$)}function G(A){return A===r?(e.consume(A),r=void 0,T):A===null?s(A):yt(A)?(l=G,W(A)):(e.consume(A),G)}function $(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||Kt(A)?P(A):(e.consume(A),$)}function T(A){return A===47||A===62||Kt(A)?P(A):s(A)}function j(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function W(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),K}function K(A){return $t(A)?Ft(e,B,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):B(A)}function B(A){return e.enter("htmlTextData"),l(A)}}const _c={name:"labelEnd",resolveAll:y0,resolveTo:k0,tokenize:j0},b0={tokenize:w0},x0={tokenize:N0},v0={tokenize:S0};function y0(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 k0(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,go(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 j0(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(b0,m,l?m:h)(g):g===91?e.attempt(x0,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(v0,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function w0(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 Kt(h)?za(e,o)(h):o(h)}function o(h){return h===41?m(h):fp(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Kt(h)?za(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?bp(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return Kt(h)?za(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 N0(e,n,s){const i=this;return r;function r(c){return gp.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 S0(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 C0={name:"labelStartImage",resolveAll:_c.resolveAll,tokenize:E0};function E0(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 M0={name:"labelStartLink",resolveAll:_c.resolveAll,tokenize:_0};function _0(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 Qo={name:"lineEnding",tokenize:A0};function A0(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Ft(e,n,"linePrefix")}}const Pr={name:"thematicBreak",tokenize:T0};function T0(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||yt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),$t(d)?Ft(e,c,"whitespace")(d):c(d))}}const Zn={continuation:{tokenize:$0},exit:L0,name:"list",tokenize:P0},R0={partial:!0,tokenize:z0},I0={partial:!0,tokenize:D0};function P0(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:Jl(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(Pr,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 Jl(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(ar,i.interrupt?s:m,e.attempt(R0,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return $t(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 $0(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(ar,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Ft(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!$t(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(I0,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Ft(e,e.attempt(Zn,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function D0(e,n,s){const i=this;return Ft(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 L0(e){e.exit(this.containerState.type)}function z0(e,n,s){const i=this;return Ft(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!$t(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const _u={name:"setextUnderline",resolveTo:F0,tokenize:O0};function F0(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 O0(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"),$t(d)?Ft(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||yt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const U0={tokenize:B0};function B0(e){const n=this,s=e.attempt(ar,i,e.attempt(this.parser.constructs.flowInitial,r,Ft(e,e.attempt(this.parser.constructs.flow,r,e.attempt(K1,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 H0={resolveAll:vp()},q0=xp("string"),V0=xp("text");function xp(e){return{resolveAll:vp(e==="text"?W0: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 vp(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 W0(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 K0={42:Zn,43:Zn,45:Zn,48:Zn,49:Zn,50:Zn,51:Zn,52:Zn,53:Zn,54:Zn,55:Zn,56:Zn,57:Zn,62:up},G0={91:X1},J0={[-2]:Yo,[-1]:Yo,32:Yo},Y0={35:i0,42:Pr,45:[_u,Pr],60:l0,61:_u,95:Pr,96:Eu,126:Eu},Q0={38:hp,92:mp},X0={[-5]:Qo,[-4]:Qo,[-3]:Qo,33:C0,38:hp,42:Yl,60:[M1,f0],91:M0,92:[n0,mp],93:_c,95:Yl,96:U1},Z0={null:[Yl,H0]},eS={null:[42,95]},tS={null:[]},nS=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:eS,contentInitial:G0,disable:tS,document:K0,flow:Y0,flowInitial:J0,insideSpan:Z0,string:Q0,text:X0},Symbol.toStringTag,{value:"Module"}));function sS(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:E(I),check:E(y),consume:k,enter:M,exit:w,interrupt:E(y,{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(R){return l=ws(l,R),v(),l[l.length-1]!==null?[]:(N(n,0),d.events=go(o,d.events,d),d.events)}function g(R,z){return aS(p(R),z)}function p(R){return iS(l,R)}function f(){const{_bufferIndex:R,_index:z,line:G,column:$,offset:T}=i;return{_bufferIndex:R,_index:z,line:G,column:$,offset:T}}function b(R){r[R.line]=R.column,_()}function v(){let R;for(;i._index<l.length;){const z=l[i._index];if(typeof z=="string")for(R=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===R&&i._bufferIndex<z.length;)x(z.charCodeAt(i._bufferIndex));else x(z)}}function x(R){m=m(R)}function k(R){yt(R)?(i.line++,i.column=1,i.offset+=R===-3?2:1,_()):R!==-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=R}function M(R,z){const G=z||{};return G.type=R,G.start=f(),d.events.push(["enter",G,d]),c.push(G),G}function w(R){const z=c.pop();return z.end=f(),d.events.push(["exit",z,d]),z}function I(R,z){N(R,z.from)}function y(R,z){z.restore()}function E(R,z){return G;function G($,T,j){let W,K,B,A;return Array.isArray($)?X($):"tokenize"in $?X([$]):L($);function L(ae){return oe;function oe(F){const de=F!==null&&ae[F],re=F!==null&&ae.null,Z=[...Array.isArray(de)?de:de?[de]:[],...Array.isArray(re)?re:re?[re]:[]];return X(Z)(F)}}function X(ae){return W=ae,K=0,ae.length===0?j:C(ae[K])}function C(ae){return oe;function oe(F){return A=P(),B=ae,ae.partial||(d.currentConstruct=ae),ae.name&&d.parser.constructs.disable.null.includes(ae.name)?fe():ae.tokenize.call(z?Object.assign(Object.create(d),z):d,u,V,fe)(F)}}function V(ae){return R(B,A),T}function fe(ae){return A.restore(),++K<W.length?C(W[K]):j}}}function N(R,z){R.resolveAll&&!o.includes(R)&&o.push(R),R.resolve&&ds(d.events,z,d.events.length-z,R.resolve(d.events.slice(z),d)),R.resolveTo&&(d.events=R.resolveTo(d.events,d))}function P(){const R=f(),z=d.previous,G=d.currentConstruct,$=d.events.length,T=Array.from(c);return{from:$,restore:j};function j(){i=R,d.previous=z,d.currentConstruct=G,d.events.length=$,c=T,_()}}function _(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function iS(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 aS(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=`
594
+ `;break}case-3:{l=`\r
595
+ `;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 rS(e){const i={constructs:cp([nS,...(e||{}).extensions||[]]),content:r(k1),defined:[],document:r(w1),flow:r(U0),lazy:{},string:r(q0),text:r(V0)};return i;function r(o){return l;function l(c){return sS(i,o,c)}}}function oS(e){for(;!pp(e););return e}const Au=/[\0\t\n\r]/g;function lS(){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(Au.lastIndex=h,d=Au.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 cS=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function dS(e){return e.replace(cS,uS)}function uS(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return dp(s.slice(o?2:1),o?16:10)}return Mc(s)||e}const yp={}.hasOwnProperty;function mS(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),hS(s)(oS(rS(s).document().write(lS()(e,n,!0))))}function hS(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(qe),autolinkProtocol:P,autolinkEmail:P,atxHeading:o(Ne),blockQuote:o(re),characterEscape:P,characterReference:P,codeFenced:o(Z),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Z,l),codeText:o(ue,l),codeTextData:P,data:P,codeFlowValue:P,definition:o(Ce),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(he),hardBreakEscape:o(ee),hardBreakTrailing:o(ee),htmlFlow:o(we,l),htmlFlowData:P,htmlText:o(we,l),htmlTextData:P,image:o(Ie),label:l,link:o(qe),listItem:o(Ge),listItemValue:g,listOrdered:o(Ve,h),listUnordered:o(Ve),paragraph:o(Ke),reference:C,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(Ne),strong:o(Qe),thematicBreak:o(Fe)},exit:{atxHeading:u(),atxHeadingSequence:I,autolink:u(),autolinkEmail:de,autolinkProtocol:F,blockQuote:u(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:fe,characterReferenceMarkerNumeric:fe,characterReferenceValue:ae,characterReference:oe,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:_,codeIndented:u(x),codeText:u(T),codeTextData:_,data:_,definition:u(),definitionDestinationString:w,definitionLabelString:k,definitionTitleString:M,emphasis:u(),hardBreakEscape:u(z),hardBreakTrailing:u(z),htmlFlow:u(G),htmlFlowData:_,htmlText:u($),htmlTextData:_,image:u(W),label:B,labelText:K,lineEnding:R,link:u(j),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:V,resourceDestinationString:A,resourceTitleString:L,resource:X,setextHeading:u(N),setextHeadingLineSequence:E,setextHeadingText:y,strong:u(),thematicBreak:u()}};kp(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(ie){let Q={type:"root",children:[]};const pe={stack:[Q],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},te=[];let ye=-1;for(;++ye<ie.length;)if(ie[ye][1].type==="listOrdered"||ie[ye][1].type==="listUnordered")if(ie[ye][0]==="enter")te.push(ye);else{const ce=te.pop();ye=r(ie,ce,ye)}for(ye=-1;++ye<ie.length;){const ce=n[ie[ye][0]];yp.call(ce,ie[ye][1].type)&&ce[ie[ye][1].type].call(Object.assign({sliceSerialize:ie[ye][2].sliceSerialize},pe),ie[ye][1])}if(pe.tokenStack.length>0){const ce=pe.tokenStack[pe.tokenStack.length-1];(ce[1]||Tu).call(pe,void 0,ce[0])}for(Q.position={start:ri(ie.length>0?ie[0][1].start:{line:1,column:1,offset:0}),end:ri(ie.length>0?ie[ie.length-2][1].end:{line:1,column:1,offset:0})},ye=-1;++ye<n.transforms.length;)Q=n.transforms[ye](Q)||Q;return Q}function r(ie,Q,pe){let te=Q-1,ye=-1,ce=!1,Re,Ze,at,le;for(;++te<=pe;){const U=ie[te];switch(U[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{U[0]==="enter"?ye++:ye--,le=void 0;break}case"lineEndingBlank":{U[0]==="enter"&&(Re&&!le&&!ye&&!at&&(at=te),le=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:le=void 0}if(!ye&&U[0]==="enter"&&U[1].type==="listItemPrefix"||ye===-1&&U[0]==="exit"&&(U[1].type==="listUnordered"||U[1].type==="listOrdered")){if(Re){let ne=te;for(Ze=void 0;ne--;){const ke=ie[ne];if(ke[1].type==="lineEnding"||ke[1].type==="lineEndingBlank"){if(ke[0]==="exit")continue;Ze&&(ie[Ze][1].type="lineEndingBlank",ce=!0),ke[1].type="lineEnding",Ze=ne}else if(!(ke[1].type==="linePrefix"||ke[1].type==="blockQuotePrefix"||ke[1].type==="blockQuotePrefixWhitespace"||ke[1].type==="blockQuoteMarker"||ke[1].type==="listItemIndent"))break}at&&(!Ze||at<Ze)&&(Re._spread=!0),Re.end=Object.assign({},Ze?ie[Ze][1].start:U[1].end),ie.splice(Ze||te,0,["exit",Re,U[2]]),te++,pe++}if(U[1].type==="listItemPrefix"){const ne={type:"listItem",_spread:!1,start:Object.assign({},U[1].start),end:void 0};Re=ne,ie.splice(te,0,["enter",ne,U[2]]),te++,pe++,at=void 0,le=!0}}}return ie[Q][1]._spread=ce,pe}function o(ie,Q){return pe;function pe(te){c.call(this,ie(te),te),Q&&Q.call(this,te)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(ie,Q,pe){this.stack[this.stack.length-1].children.push(ie),this.stack.push(ie),this.tokenStack.push([Q,pe||void 0]),ie.position={start:ri(Q.start),end:void 0}}function u(ie){return Q;function Q(pe){ie&&ie.call(this,pe),d.call(this,pe)}}function d(ie,Q){const pe=this.stack.pop(),te=this.tokenStack.pop();if(te)te[0].type!==ie.type&&(Q?Q.call(this,ie,te[0]):(te[1]||Tu).call(this,ie,te[0]));else throw new Error("Cannot close `"+ie.type+"` ("+La({start:ie.start,end:ie.end})+"): it’s not open");pe.position.end=ri(ie.end)}function m(){return Ec(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(ie){if(this.data.expectingFirstListItemValue){const Q=this.stack[this.stack.length-2];Q.start=Number.parseInt(this.sliceSerialize(ie),10),this.data.expectingFirstListItemValue=void 0}}function p(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.lang=ie}function f(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.meta=ie}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.value=ie.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.value=ie.replace(/(\r?\n|\r)$/g,"")}function k(ie){const Q=this.resume(),pe=this.stack[this.stack.length-1];pe.label=Q,pe.identifier=Rs(this.sliceSerialize(ie)).toLowerCase()}function M(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.title=ie}function w(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.url=ie}function I(ie){const Q=this.stack[this.stack.length-1];if(!Q.depth){const pe=this.sliceSerialize(ie).length;Q.depth=pe}}function y(){this.data.setextHeadingSlurpLineEnding=!0}function E(ie){const Q=this.stack[this.stack.length-1];Q.depth=this.sliceSerialize(ie).codePointAt(0)===61?1:2}function N(){this.data.setextHeadingSlurpLineEnding=void 0}function P(ie){const pe=this.stack[this.stack.length-1].children;let te=pe[pe.length-1];(!te||te.type!=="text")&&(te=Se(),te.position={start:ri(ie.start),end:void 0},pe.push(te)),this.stack.push(te)}function _(ie){const Q=this.stack.pop();Q.value+=this.sliceSerialize(ie),Q.position.end=ri(ie.end)}function R(ie){const Q=this.stack[this.stack.length-1];if(this.data.atHardBreak){const pe=Q.children[Q.children.length-1];pe.position.end=ri(ie.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Q.type)&&(P.call(this,ie),_.call(this,ie))}function z(){this.data.atHardBreak=!0}function G(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.value=ie}function $(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.value=ie}function T(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.value=ie}function j(){const ie=this.stack[this.stack.length-1];if(this.data.inReference){const Q=this.data.referenceType||"shortcut";ie.type+="Reference",ie.referenceType=Q,delete ie.url,delete ie.title}else delete ie.identifier,delete ie.label;this.data.referenceType=void 0}function W(){const ie=this.stack[this.stack.length-1];if(this.data.inReference){const Q=this.data.referenceType||"shortcut";ie.type+="Reference",ie.referenceType=Q,delete ie.url,delete ie.title}else delete ie.identifier,delete ie.label;this.data.referenceType=void 0}function K(ie){const Q=this.sliceSerialize(ie),pe=this.stack[this.stack.length-2];pe.label=dS(Q),pe.identifier=Rs(Q).toLowerCase()}function B(){const ie=this.stack[this.stack.length-1],Q=this.resume(),pe=this.stack[this.stack.length-1];if(this.data.inReference=!0,pe.type==="link"){const te=ie.children;pe.children=te}else pe.alt=Q}function A(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.url=ie}function L(){const ie=this.resume(),Q=this.stack[this.stack.length-1];Q.title=ie}function X(){this.data.inReference=void 0}function C(){this.data.referenceType="collapsed"}function V(ie){const Q=this.resume(),pe=this.stack[this.stack.length-1];pe.label=Q,pe.identifier=Rs(this.sliceSerialize(ie)).toLowerCase(),this.data.referenceType="full"}function fe(ie){this.data.characterReferenceType=ie.type}function ae(ie){const Q=this.sliceSerialize(ie),pe=this.data.characterReferenceType;let te;pe?(te=dp(Q,pe==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):te=Mc(Q);const ye=this.stack[this.stack.length-1];ye.value+=te}function oe(ie){const Q=this.stack.pop();Q.position.end=ri(ie.end)}function F(ie){_.call(this,ie);const Q=this.stack[this.stack.length-1];Q.url=this.sliceSerialize(ie)}function de(ie){_.call(this,ie);const Q=this.stack[this.stack.length-1];Q.url="mailto:"+this.sliceSerialize(ie)}function re(){return{type:"blockquote",children:[]}}function Z(){return{type:"code",lang:null,meta:null,value:""}}function ue(){return{type:"inlineCode",value:""}}function Ce(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function he(){return{type:"emphasis",children:[]}}function Ne(){return{type:"heading",depth:0,children:[]}}function ee(){return{type:"break"}}function we(){return{type:"html",value:""}}function Ie(){return{type:"image",title:null,url:"",alt:null}}function qe(){return{type:"link",title:null,url:"",children:[]}}function Ve(ie){return{type:"list",ordered:ie.type==="listOrdered",start:null,spread:ie._spread,children:[]}}function Ge(ie){return{type:"listItem",spread:ie._spread,checked:null,children:[]}}function Ke(){return{type:"paragraph",children:[]}}function Qe(){return{type:"strong",children:[]}}function Se(){return{type:"text",value:""}}function Fe(){return{type:"thematicBreak"}}}function ri(e){return{line:e.line,column:e.column,offset:e.offset}}function kp(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?kp(e,i):pS(e,i)}}function pS(e,n){let s;for(s in n)if(yp.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 Tu(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+La({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+La({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+La({start:n.start,end:n.end})+") is still open")}function fS(e){const n=this;n.parser=s;function s(i){return mS(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function gS(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 bS(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
596
+ `}]}function xS(e,n){const s=n.value?n.value+`
597
+ `:"",i={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(i.className=["language-"+r[0]]);let 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 vS(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function yS(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=da(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 wS(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function jp(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 NS(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return jp(e,n);const r={src:da(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 SS(e,n){const s={src:da(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 CS(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 ES(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return jp(e,n);const r={href:da(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 MS(e,n){const s={href:da(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 _S(e,n,s){const i=e.all(n),r=s?AS(s):wp(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:`
598
+ `}),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:`
599
+ `});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function AS(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=wp(s[i])}return n}function wp(e){const n=e.spread;return n??e.children.length>1}function TS(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 RS(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function IS(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function PS(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function $S(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=wc(n.children[1]),u=np(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 DS(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 LS(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Ru=9,Iu=32;function zS(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Pu(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Pu(n.slice(r),r>0,!1)),o.join("")}function Pu(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Ru||o===Iu;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Ru||o===Iu;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function FS(e,n){const s={type:"text",value:zS(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function OS(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const US={blockquote:gS,break:bS,code:xS,delete:vS,emphasis:yS,footnoteReference:kS,heading:jS,html:wS,imageReference:NS,image:SS,inlineCode:CS,linkReference:ES,link:MS,listItem:_S,list:TS,paragraph:RS,root:IS,strong:PS,table:$S,tableCell:LS,tableRow:DS,text:FS,thematicBreak:OS,toml:kr,yaml:kr,definition:kr,footnoteDefinition:kr};function kr(){}const Np=-1,bo=0,Fa=1,Jr=2,Ac=3,Tc=4,Rc=5,Ic=6,Sp=7,Cp=8,$u=typeof self=="object"?self:globalThis,BS=(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 bo:case Np:return s(l,r);case Fa:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Jr:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case Ac:return s(new Date(l),r);case Tc:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Rc:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Ic:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case Sp:{const{name:c,message:u}=l;return s(new $u[c](u),r)}case Cp: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 $u[o](l),r)};return i},Du=e=>BS(new Map,e)(0),Oi="",{toString:HS}={},{keys:qS}=Object,ka=e=>{const n=typeof e;if(n!=="object"||!e)return[bo,n];const s=HS.call(e).slice(8,-1);switch(s){case"Array":return[Fa,Oi];case"Object":return[Jr,Oi];case"Date":return[Ac,Oi];case"RegExp":return[Tc,Oi];case"Map":return[Rc,Oi];case"Set":return[Ic,Oi];case"DataView":return[Fa,s]}return s.includes("Array")?[Fa,s]:s.includes("Error")?[Sp,s]:[Jr,s]},jr=([e,n])=>e===bo&&(n==="function"||n==="symbol"),VS=(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]=ka(l);switch(c){case bo:{let m=l;switch(u){case"bigint":c=Cp,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([Np],l)}return r([c,m],l)}case Fa:{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 Jr:{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 qS(l))(e||!jr(ka(l[g])))&&m.push([o(g),o(l[g])]);return h}case Ac:return r([c,l.toISOString()],l);case Tc:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Rc:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(jr(ka(g))||jr(ka(p))))&&m.push([o(g),o(p)]);return h}case Ic:{const m=[],h=r([c,m],l);for(const g of l)(e||!jr(ka(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Lu=(e,{json:n,lossy:s}={})=>{const i=[];return VS(!(n||s),!!n,new Map,i)(e),i},Yr=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Du(Lu(e,n)):structuredClone(e):(e,n)=>Du(Lu(e,n));function WS(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 KS(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function GS(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||WS,i=e.options.footnoteBackLabel||KS,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=da(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 k=typeof s=="string"?s:s(u,p);typeof k=="string"&&(k={type:"text",value:k}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(k)?k:[k]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const k=v.children[v.children.length-1];k&&k.type==="text"?k.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else 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:{...Yr(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
600
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
601
+ `}]}}const xo=(function(e){if(e==null)return XS;if(typeof e=="function")return vo(e);if(typeof e=="object")return Array.isArray(e)?JS(e):YS(e);if(typeof e=="string")return QS(e);throw new Error("Expected function, string, or object as test")});function JS(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=xo(e[s]);return vo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function YS(e){const n=e;return vo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function QS(e){return vo(n);function n(s){return s&&s.type===e}}function vo(e){return n;function n(s,i,r){return!!(ZS(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function XS(){return!0}function ZS(e){return e!==null&&typeof e=="object"&&"type"in e}const Ep=[],eC=!0,Ql=!1,tC="skip";function Mp(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=xo(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=Ep,f,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=nC(s(u,m)),p[0]===Ql))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==tC)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const k=x.children[b];if(f=c(k,b,v)(),f[0]===Ql)return f;b=typeof f[1]=="number"?f[1]:b+l}}return p}}}function nC(e){return Array.isArray(e)?e:typeof e=="number"?[eC,e]:e==null?Ep:[e]}function Pc(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),Mp(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 Xl={}.hasOwnProperty,sC={};function iC(e,n){const s=n||sC,i=new Map,r=new Map,o=new Map,l={...US,...s.handlers},c={all:d,applyData:rC,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:aC,wrap:lC};return Pc(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(Xl.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=Yr(v);return x.children=c.all(m),x}return Yr(m)}return(c.options.unknownHandler||oC)(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=zu(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=zu(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function aC(e,n){e.position&&(n.position=KN(e))}function rC(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,Yr(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function oC(e,n){const s=n.data||{},i="value"in n&&!(Xl.call(s,"hProperties")||Xl.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 lC(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
602
+ `});++i<e.length;)i&&s.push({type:"text",value:`
603
+ `}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
604
+ `}),s}function zu(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Fu(e,n){const s=iC(e,n),i=s.one(e,void 0),r=GS(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
605
+ `},r),o}function cC(e,n){return e&&"run"in e?async function(s,i){const r=Fu(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Fu(s,{file:i,...e||n})}}function Ou(e){if(e)throw e}var Xo,Uu;function dC(){if(Uu)return Xo;Uu=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 Xo=function u(){var d,m,h,g,p,f,b=arguments[0],v=1,x=arguments.length,k=!1;for(typeof b=="boolean"&&(k=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),g=c(d,m),b!==g&&(k&&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(k,f,g)})):typeof g<"u"&&l(b,{name:m,newValue:g}));return b},Xo}var uC=dC();const Zo=Qm(uC);function Zl(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 mC(){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?hC(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 hC(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 Ls={basename:pC,dirname:fC,extname:gC,join:bC,sep:"/"};function pC(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');rr(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 fC(e){if(rr(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 gC(e){rr(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 bC(...e){let n=-1,s;for(;++n<e.length;)rr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":xC(s)}function xC(e){rr(e);const n=e.codePointAt(0)===47;let s=vC(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function vC(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 rr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const yC={cwd:kC};function kC(){return"/"}function ec(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function jC(e){if(typeof e=="string")e=new URL(e);else if(!ec(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 wC(e)}function wC(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 el=["history","path","basename","stem","extname","dirname"];class _p{constructor(n){let s;n?ec(n)?s={path:n}:typeof n=="string"||NC(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":yC.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<el.length;){const o=el[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)el.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ls.basename(this.path):void 0}set basename(n){nl(n,"basename"),tl(n,"basename"),this.path=Ls.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ls.dirname(this.path):void 0}set dirname(n){Bu(this.basename,"dirname"),this.path=Ls.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ls.extname(this.path):void 0}set extname(n){if(tl(n,"extname"),Bu(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=Ls.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){ec(n)&&(n=jC(n)),nl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ls.basename(this.path,this.extname):void 0}set stem(n){nl(n,"stem"),tl(n,"stem"),this.path=Ls.join(this.dirname||"",n+(this.extname||""))}fail(n,s,i){const r=this.message(n,s,i);throw r.fatal=!0,r}info(n,s,i){const r=this.message(n,s,i);return r.fatal=void 0,r}message(n,s,i){const r=new Ln(n,s,i);return this.path&&(r.name=this.path+":"+r.name,r.file=this.path),r.fatal=!1,this.messages.push(r),r}toString(n){return this.value===void 0?"":typeof this.value=="string"?this.value:new TextDecoder(n||void 0).decode(this.value)}}function tl(e,n){if(e&&e.includes(Ls.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ls.sep+"`")}function nl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Bu(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function NC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const SC=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),CC={}.hasOwnProperty;class $c extends SC{constructor(){super("copy"),this.Compiler=void 0,this.Parser=void 0,this.attachers=[],this.compiler=void 0,this.freezeIndex=-1,this.frozen=void 0,this.namespace={},this.parser=void 0,this.transformers=mC()}copy(){const n=new $c;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Zo(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(al("data",this.frozen),this.namespace[n]=s,this):CC.call(this.namespace,n)&&this.namespace[n]||void 0:n?(al("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=wr(n),i=this.parser||this.Parser;return sl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),sl("process",this.parser||this.Parser),il("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=wr(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);_C(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(),sl("processSync",this.parser||this.Parser),il("processSync",this.compiler||this.Compiler),this.process(n,r),qu("processSync","process",s),i;function r(o,l){s=!0,Ou(o),i=l}}run(n,s,i){Hu(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=wr(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),qu("runSync","run",i),r;function o(l,c){Ou(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=wr(s),r=this.compiler||this.Compiler;return il("stringify",r),Hu(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(al("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=Zo(!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];Zl(b)&&Zl(p)&&(p=Zo(!0,b,p)),i[g]=[d,p,...f]}}}}const EC=new $c().freeze();function sl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function il(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function al(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 Hu(e){if(!Zl(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function qu(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function wr(e){return MC(e)?e:new _p(e)}function MC(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function _C(e){return typeof e=="string"||AC(e)}function AC(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const TC="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Vu=[],Wu={allowDangerousHtml:!0},RC=/^(https?|ircs?|mailto|xmpp)$/i,IC=[{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 Qs(e){const n=PC(e),s=$C(e);return DC(n.runSync(n.parse(s),s),e)}function PC(e){const n=e.rehypePlugins||Vu,s=e.remarkPlugins||Vu,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Wu}:Wu;return EC().use(fS).use(s).use(cC,i).use(n)}function $C(e){const n=e.children||"",s=new _p;return typeof n=="string"&&(s.value=n),s}function DC(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||LC;for(const m of IC)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+TC+m.id,void 0);return Pc(e,d),XN(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 Jo)if(Object.hasOwn(Jo,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],b=Jo[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 LC(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||RC.test(e.slice(0,n))?e:""}function Ku(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 zC(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function FC(e,n,s){const r=xo((s||{}).ignore||[]),o=OC(n);let l=-1;for(;++l<o.length;)Mp(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,k=[];g.lastIndex=0;let M=g.exec(d.value);for(;M;){const w=M.index,I={index:M.index,input:M.input,stack:[...m,d]};let y=p(...M,I);if(typeof y=="string"&&(y=y.length>0?{type:"text",value:y}:void 0),y===!1?g.lastIndex=w+1:(f!==w&&k.push({type:"text",value:d.value.slice(f,w)}),Array.isArray(y)?k.push(...y):y&&k.push(y),f=w+M[0].length,x=!0),!g.global)break;M=g.exec(d.value)}return x?(f<d.value.length&&k.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...k)):k=[d],v+k.length}}function OC(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([UC(r[0]),BC(r[1])])}return n}function UC(e){return typeof e=="string"?new RegExp(zC(e),"g"):e}function BC(e){return typeof e=="function"?e:function(){return e}}const rl="phrasing",ol=["autolink","link","image","label"];function HC(){return{transforms:[YC],enter:{literalAutolink:VC,literalAutolinkEmail:ll,literalAutolinkHttp:ll,literalAutolinkWww:ll},exit:{literalAutolink:JC,literalAutolinkEmail:GC,literalAutolinkHttp:WC,literalAutolinkWww:KC}}}function qC(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:rl,notInConstruct:ol},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:rl,notInConstruct:ol},{character:":",before:"[ps]",after:"\\/",inConstruct:rl,notInConstruct:ol}]}}function VC(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ll(e){this.config.enter.autolinkProtocol.call(this,e)}function WC(e){this.config.exit.autolinkProtocol.call(this,e)}function KC(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 GC(e){this.config.exit.autolinkEmail.call(this,e)}function JC(e){this.exit(e)}function YC(e){FC(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,QC],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,XC]],{ignore:["link","linkReference"]})}function QC(e,n,s,i,r){let o="";if(!Ap(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!ZC(s)))return!1;const l=e2(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 XC(e,n,s,i){return!Ap(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function ZC(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 e2(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=Ku(e,"(");let o=Ku(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 Ap(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Ei(s)||fo(s))&&(!n||s!==47)}Tp.peek=c2;function t2(){this.buffer()}function n2(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function s2(){this.buffer()}function i2(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function a2(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 r2(e){this.exit(e)}function o2(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 l2(e){this.exit(e)}function c2(){return"["}function Tp(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 d2(){return{enter:{gfmFootnoteCallString:t2,gfmFootnoteCall:n2,gfmFootnoteDefinitionLabelString:s2,gfmFootnoteDefinition:i2},exit:{gfmFootnoteCallString:a2,gfmFootnoteCall:r2,gfmFootnoteDefinitionLabelString:o2,gfmFootnoteDefinition:l2}}}function u2(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Tp},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?`
606
+ `:" ")+o.indentLines(o.containerFlow(i,c.current()),n?Rp:m2))),d(),u}}function m2(e,n,s){return n===0?e:Rp(e,n,s)}function Rp(e,n,s){return(s?"":" ")+e}const h2=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ip.peek=x2;function p2(){return{canContainEols:["delete"],enter:{strikethrough:g2},exit:{strikethrough:b2}}}function f2(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:h2}],handlers:{delete:Ip}}}function g2(e){this.enter({type:"delete",children:[]},e)}function b2(e){this.exit(e)}function Ip(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 x2(){return"~"}function v2(e){return e.length}function y2(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||v2,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 k=k2(e[m][x]);if(s.alignDelimiters!==!1){const M=r(k);v[x]=M,(u[x]===void 0||M>u[x])&&(u[x]=M)}b.push(k)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Gu(i[h]);else{const b=Gu(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 k=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const M=v+"-".repeat(k)+x;s.alignDelimiters!==!1&&(k=v.length+k+x.length,k>u[h]&&(u[h]=k),p[h]=k),g[h]=M}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 k=b[h]||"";let M="",w="";if(s.alignDelimiters!==!1){const I=u[h]-(v[h]||0),y=o[h];y===114?M=" ".repeat(I):y===99?I%2?(M=" ".repeat(I/2+.5),w=" ".repeat(I/2-.5)):(M=" ".repeat(I/2),w=M):w=" ".repeat(I)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&k==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(M),x.push(k),s.alignDelimiters!==!1&&x.push(w),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(`
607
+ `)}function k2(e){return e==null?"":String(e)}function Gu(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 j2(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()),w2);return r(),l}function w2(e,n,s){return">"+(s?"":" ")+e}function N2(e,n){return Ju(e,n.inConstruct,!0)&&!Ju(e,n.notInConstruct,!1)}function Ju(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 Yu(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
608
+ `&&N2(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
609
+ `}function S2(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 C2(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 M2(e,n,s,i){const r=E2(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(C2(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,_2);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(S2(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:`
610
+ `,encode:["`"],...c.current()})),h()}return m+=c.move(`
611
+ `),o&&(m+=c.move(o+`
612
+ `)),m+=c.move(u),d(),m}function _2(e,n,s){return(s?"":" ")+e}function Dc(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 A2(e,n,s,i){const r=Dc(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?" ":`
613
+ `,...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 T2(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 Ka(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Qr(e,n,s){const i=Qi(e),r=Qi(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}}Pp.peek=R2;function Pp(e,n,s,i){const r=T2(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=Qr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Ka(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Qr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Ka(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function R2(e,n,s){return s.options.emphasis||"*"}function I2(e,n){let s=!1;return Pc(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Ql}),!!((!e.depth||e.depth<3)&&Ec(e)&&(n.options.setext||s))}function P2(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(I2(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
614
+ `,after:`
615
+ `});return h(),m(),g+`
616
+ `+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
617
+ `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
618
+ `,...o.current()});return/^[\t ]/.test(d)&&(d=Ka(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}$p.peek=$2;function $p(e){return e.value||""}function $2(){return"<"}Dp.peek=D2;function Dp(e,n,s,i){const r=Dc(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 D2(){return"!"}Lp.peek=L2;function Lp(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 L2(){return"!"}zp.peek=z2;function zp(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 z2(){return"`"}function Fp(e,n){const s=Ec(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))}Op.peek=F2;function Op(e,n,s,i){const r=Dc(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Fp(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 F2(e,n,s){return Fp(e,s)?"<":"["}Up.peek=O2;function Up(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 O2(){return"["}function Lc(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 U2(e){const n=Lc(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 B2(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 Bp(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 H2(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?B2(s):Lc(s);const c=e.ordered?l==="."?")":".":U2(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),Bp(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 q2(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 V2(e,n,s,i){const r=q2(s);let o=s.bulletCurrent||Lc(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 W2(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const K2=xo(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function G2(e,n,s,i){return(e.children.some(function(l){return K2(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}Hp.peek=Y2;function Hp(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=Qr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Ka(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Qr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Ka(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function Y2(e,n,s){return s.options.strong||"*"}function Q2(e,n,s,i){return s.safe(e.value,i)}function X2(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 Z2(e,n,s){const i=(Bp(s)+(s.options.ruleSpaces?" ":"")).repeat(X2(s));return s.options.ruleSpaces?i.slice(0,-1):i}const qp={blockquote:j2,break:Yu,code:M2,definition:A2,emphasis:Pp,hardBreak:Yu,heading:P2,html:$p,image:Dp,imageReference:Lp,inlineCode:zp,link:Op,linkReference:Up,list:H2,listItem:V2,paragraph:W2,root:G2,strong:Hp,text:Q2,thematicBreak:Z2};function eE(){return{enter:{table:tE,tableData:Qu,tableHeader:Qu,tableRow:sE},exit:{codeText:iE,table:nE,tableData:cl,tableHeader:cl,tableRow:cl}}}function tE(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 nE(e){this.exit(e),this.data.inTable=void 0}function sE(e){this.enter({type:"tableRow",children:[]},e)}function cl(e){this.exit(e)}function Qu(e){this.enter({type:"tableCell",children:[]},e)}function iE(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,aE));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function aE(e,n){return n==="|"?n:e}function rE(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
619
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table: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),k=d([x]);return k.slice(0,k.indexOf(`
620
+ `))}function u(p,f,b,v){const x=b.enter("tableCell"),k=b.enter("phrasing"),M=b.containerPhrasing(p,{...v,before:o,after:o});return k(),x(),M}function d(p,f){return y2(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("table");for(;++x<v.length;)k[x]=h(v[x],f,b);return M(),k}function h(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("tableRow");for(;++x<v.length;)k[x]=u(v[x],p,f,b);return M(),k}function g(p,f,b){let v=qp.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function oE(){return{exit:{taskListCheckValueChecked:Xu,taskListCheckValueUnchecked:Xu,paragraph:cE}}}function lE(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:dE}}}function Xu(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function cE(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 dE(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=qp.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 uE(){return[HC(),d2(),p2(),eE(),oE()]}function mE(e){return{extensions:[qC(),u2(e),f2(),rE(e),lE()]}}const hE={tokenize:vE,partial:!0},Vp={tokenize:yE,partial:!0},Wp={tokenize:kE,partial:!0},Kp={tokenize:jE,partial:!0},pE={tokenize:wE,partial:!0},Gp={name:"wwwAutolink",tokenize:bE,previous:Yp},Jp={name:"protocolAutolink",tokenize:xE,previous:Qp},Zs={name:"emailAutolink",tokenize:gE,previous:Xp},Vs={};function fE(){return{text:Vs}}let bi=48;for(;bi<123;)Vs[bi]=Zs,bi++,bi===58?bi=65:bi===91&&(bi=97);Vs[43]=Zs;Vs[45]=Zs;Vs[46]=Zs;Vs[95]=Zs;Vs[72]=[Zs,Jp];Vs[104]=[Zs,Jp];Vs[87]=[Zs,Gp];Vs[119]=[Zs,Gp];function gE(e,n,s){const i=this;let r,o;return l;function l(h){return!tc(h)||!Xp.call(i,i.previous)||zc(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return tc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(pE,m,d)(h):h===45||h===95||$n(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&&Vn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function bE(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Yp.call(i,i.previous)||zc(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(hE,e.attempt(Vp,e.attempt(Wp,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function xE(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Qp.call(i,i.previous)&&!zc(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Vn(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||Gr(h)||Kt(h)||Ei(h)||fo(h)?s(h):e.attempt(Vp,e.attempt(Wp,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function vE(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 yE(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Kp,u,c)(d):d===null||Kt(d)||Ei(d)||d!==45&&fo(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 kE(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(Kp,n,o)(l):l===null||Kt(l)||Ei(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function jE(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||Kt(c)||Ei(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Kt(c)||Ei(c)?n(c):i(c)}function o(c){return Vn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):Vn(c)?(e.consume(c),l):s(c)}}function wE(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return $n(o)?s(o):n(o)}}function Yp(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Kt(e)}function Qp(e){return!Vn(e)}function Xp(e){return!(e===47||tc(e))}function tc(e){return e===43||e===45||e===46||e===95||$n(e)}function zc(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 NE={tokenize:RE,partial:!0};function SE(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:_E,continuation:{tokenize:AE},exit:TE}},text:{91:{name:"gfmFootnoteCall",tokenize:ME},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:CE,resolveTo:EE}}}}function CE(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 ME(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||Kt(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 Kt(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 _E(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||Kt(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 Kt(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),Ft(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function AE(e,n,s){return e.check(ar,n,e.attempt(NE,n,s))}function TE(e){e.exit("gfmFootnoteDefinition")}function RE(e,n,s){const i=this;return Ft(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 IE(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,go(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=Qi(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=Qi(f);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(f)}}}class PE{constructor(){this.map=[]}add(n,s,i){$E(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 $E(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 DE(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 LE(){return{flow:{null:{name:"table",tokenize:zE,resolveAll:FE}}}}function zE(e,n,s){const i=this;let r=0,o=0,l;return c;function c(_){let R=i.events.length-1;for(;R>-1;){const $=i.events[R][1].type;if($==="lineEnding"||$==="linePrefix")R--;else break}const z=R>-1?i.events[R][1].type:null,G=z==="tableHead"||z==="tableRow"?y:u;return G===y&&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(_):yt(_)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):$t(_)?Ft(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||Kt(_)?(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,$t(_)?Ft(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):I(_)}function b(_){return $t(_)?Ft(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||yt(_)?w(_):I(_)}function x(_){return _===45?(e.enter("tableDelimiterFiller"),k(_)):I(_)}function k(_){return _===45?(e.consume(_),k):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),M):(e.exit("tableDelimiterFiller"),M(_))}function M(_){return $t(_)?Ft(e,w,"whitespace")(_):w(_)}function w(_){return _===124?f(_):_===null||yt(_)?!l||r!==o?I(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):I(_)}function I(_){return s(_)}function y(_){return e.enter("tableRow"),E(_)}function E(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),E):_===null||yt(_)?(e.exit("tableRow"),n(_)):$t(_)?Ft(e,E,"whitespace")(_):(e.enter("data"),N(_))}function N(_){return _===null||_===124||Kt(_)?(e.exit("data"),E(_)):(e.consume(_),_===92?P:N)}function P(_){return _===92||_===124?(e.consume(_),N):N(_)}}function FE(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 PE;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Zu(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=Nr(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=Nr(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=Nr(g,n,o,r,s,h)):l[1]!==0&&(h=Nr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Zu(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=DE(n.events,s))}return e}function Nr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Ui(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=Ui(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=Ui(n.events,s[2]),m=Ui(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({},Ui(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Zu(e,n,s,i,r){const o=[],l=Ui(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 Ui(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const OE={name:"tasklistCheck",tokenize:BE};function UE(){return{text:{91:OE}}}function BE(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 Kt(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 yt(u)?n(u):$t(u)?e.check({tokenize:HE},n,s)(u):s(u)}}function HE(e,n,s){return Ft(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function qE(e){return cp([fE(),SE(),IE(e),LE(),UE()])}const VE={};function Xs(e){const n=this,s=e||VE,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(qE(s)),o.push(uE()),l.push(mE(s))}const em=500,tm=100;function dl(e){return e.length>em?e.slice(-em):e}function Zp(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),k=a.useRef(n),M=a.useRef(0);(v.current!==e||x.current!==s||k.current!==n)&&(v.current=e,x.current=s,k.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 E=b.current,N=++M.current;f.current=!1;const P=e,_=s;async function R(){if(!P)return;l(!0),g(!1);try{const G=await sd(P,_,{limit:tm});if(f.current||b.current!==E||M.current!==N)return;r(dl(G.entries)),u(G.hasMore),m(G.total)}catch{if(f.current||b.current!==E||M.current!==N)return;r([]),u(!1),m(null)}finally{!f.current&&b.current===E&&M.current===N&&l(!1)}const z=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=qs(`/api/tasks/${P}/logs/stream${z}`,{events:{"agent:log":G=>{if(!(f.current||b.current!==E))try{const $=JSON.parse(G.data);r(T=>dl([...T,$])),m(T=>T!==null?T+1:null)}catch{}}}})}return R(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const I=a.useCallback(async()=>{if(!e||h)return;const E=b.current,N=i.length,P=e;g(!0);try{const _=await sd(P,s,{limit:tm,offset:N});if(f.current||b.current!==E)return;r(R=>{const z=[..._.entries,...R];return dl(z)}),u(_.hasMore),m(_.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),y=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:y,loadMore:I,hasMore:c,total:d,loadingMore:h}}function WE(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 nm={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})},ef=50;function sm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=ef}function tf(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=tf(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function GE({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=a.useRef(null),[f,b]=a.useState(!0),[v,x]=a.useState(!1),[k,M]=a.useState(!1),[w,I]=a.useState(!0),y=a.useMemo(()=>KE(e),[e]);a.useLayoutEffect(()=>{const $=d.current;if(!$)return;const T=e.length,j=m.current,W=h.current||$.scrollHeight,K=y[0]??null,B=y[y.length-1]??null,A=g.current!==K,L=p.current!==B;if(T>j)if(j===0)$.scrollTop=$.scrollHeight;else{const X=W-($.scrollTop+$.clientHeight)<=ef,C=L&&!A,V=A&&!L;if(C&&X&&($.scrollTop=$.scrollHeight),V){const fe=$.scrollHeight-W;fe>0&&($.scrollTop+=fe)}}m.current=T,h.current=$.scrollHeight,g.current=K,p.current=B,I(sm($))},[e,y]);const E=a.useCallback(()=>{const $=d.current;$&&I(sm($))},[]),N=a.useCallback(()=>{const $=d.current;$&&($.scrollTop=$.scrollHeight,I(!0))},[]),P=a.useCallback($=>{$.key==="Escape"&&v&&x(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",P),()=>{document.removeEventListener("keydown",P)}},[v,P]);const _=s?.provider&&s?.modelId,R=i?.provider&&i?.modelId,z=r?.provider&&r?.modelId,G=a.useMemo(()=>{const $=[];return _&&$.push({role:"Executor",provider:s.provider,modelId:s.modelId}),R&&$.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),z&&$.push({role:"Planning",provider:r.provider,modelId:r.modelId}),$},[_,s,R,i,z,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?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."})}):t.jsxs("div",{ref:d,className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",onScroll:E,children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[G.map($=>t.jsx(Mn,{provider:$.provider,size:"sm"},`${$.role}-${$.provider}-${$.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>M($=>!$),"aria-label":k?"Collapse model details":"Expand model details","aria-expanded":k,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:k?t.jsx(Lt,{size:14}):t.jsx(en,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b($=>!$),"aria-label":f?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":f,"data-testid":"agent-log-mode-toggle",title:f?"Show raw text":"Show formatted markdown",children:f?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x($=>!$),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(aa,{size:14}):t.jsx(ro,{size:14})})]}),k&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),_?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{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:"Reviewer:"}),R?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{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:"}),z?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),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(it,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),e.map(($,T)=>{const j=y[T]??`${tf($)}|fallback`,W=e[T-1],K=$.type==="tool"||$.type==="tool_result"||$.type==="tool_error",B=$.agent?K||!W||W.agent!==$.agent||W.type!==$.type:!1,A=B?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:WE($.timestamp)}):null,L=B?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",$.agent,"]"]}),A]}):null;return $.type==="tool"?t.jsxs("div",{className:"agent-log-tool",children:[L,"⚡ ",$.text,$.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",$.detail]})]},j):$.type==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[L,f?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:nm,children:$.text})}):$.text]},j):$.type==="tool_result"?t.jsxs("div",{className:"agent-log-tool-result",children:[L,"✓ ",$.text,$.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",$.detail]})]},j):$.type==="tool_error"?t.jsxs("div",{className:"agent-log-tool-error",children:[L,"✗ ",$.text,$.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",$.detail]})]},j):t.jsxs("div",{className:"agent-log-text",children:[L,f?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:nm,children:$.text})}):$.text]},j)}),!w&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:N,"data-testid":"agent-log-return-to-live",children:[t.jsx(Lt,{size:12}),t.jsx("span",{children:"Live"})]})]})}function Xi(e){return e??void 0}function Sr(e){return{provider:Xi(e.modelProvider),modelId:Xi(e.modelId)}}function Cr(e){return{provider:Xi(e.validatorModelProvider),modelId:Xi(e.validatorModelId)}}function Er(e){return{provider:Xi(e.planningModelProvider),modelId:Xi(e.planningModelId)}}function JE(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function YE(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 QE(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 ul(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 ml(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function hl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function XE(e,n){const i={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function ZE({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(()=>Sr(e)),[v,x]=a.useState(()=>Sr(e)),[k,M]=a.useState(()=>Cr(e)),[w,I]=a.useState(()=>Cr(e)),[y,E]=a.useState(()=>Er(e)),[N,P]=a.useState(()=>Er(e)),[_,R]=a.useState(()=>e.thinkingLevel??null),[z,G]=a.useState(()=>e.thinkingLevel??null),[$,T]=a.useState(null),j=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),is().then(he=>{o(he.models),c(he.favoriteProviders),d(he.favoriteModels)}).catch(he=>{p(he.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const W=a.useCallback(async he=>{const Ne=l,we=Ne.includes(he)?Ne.filter(Ie=>Ie!==he):[he,...Ne];c(we);try{await nn({favoriteProviders:we,favoriteModels:u})}catch{c(Ne),n("Failed to update favorites","error")}},[l,u,n]),K=a.useCallback(async he=>{const Ne=u,we=Ne.includes(he)?Ne.filter(Ie=>Ie!==he):[he,...Ne];d(we);try{await nn({favoriteProviders:l,favoriteModels:we})}catch{d(Ne),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{j.current=e.id;const he=Sr(e),Ne=Cr(e),ee=Er(e);b(he),x(he),M(Ne),I(Ne),E(ee),P(ee);const we=e.thinkingLevel??null;R(we),G(we),T(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const B=a.useMemo(()=>ml(f),[f]),A=a.useMemo(()=>ml(k),[k]),L=a.useMemo(()=>ml(y),[y]),X=a.useMemo(()=>JE(e,i),[e,i]),C=a.useMemo(()=>YE(e,i),[e,i]),V=a.useMemo(()=>QE(e,i),[e,i]),fe=$!==null,ae=a.useCallback(async(he,Ne)=>{const ee=e.id,we=v,Ie=w,qe=N;T(he);try{const Ve=s?he==="executor"?{modelProvider:Ne.provider??null,modelId:Ne.modelId??null}:he==="validator"?{validatorModelProvider:Ne.provider??null,validatorModelId:Ne.modelId??null}:{planningModelProvider:Ne.provider??null,planningModelId:Ne.modelId??null}:{modelProvider:(he==="executor"?Ne:v).provider??null,modelId:(he==="executor"?Ne:v).modelId??null,validatorModelProvider:(he==="validator"?Ne:w).provider??null,validatorModelId:(he==="validator"?Ne:w).modelId??null,planningModelProvider:(he==="planning"?Ne:N).provider??null,planningModelId:(he==="planning"?Ne:N).modelId??null},Ge=await Gs(ee,Ve);if(j.current!==ee)return;const Ke=Sr(Ge),Qe=Cr(Ge),Se=Er(Ge);x(Ke),b(Ke),I(Qe),M(Qe),P(Se),E(Se),s?.(Ge),n(XE(he,{executor:Ke,validator:Qe,planning:Se}[he]),"success")}catch(Ve){if(j.current!==ee)return;he==="executor"?b(we):he==="validator"?M(Ie):E(qe),n(xe(Ve)||"Failed to save model settings","error")}finally{j.current===ee&&T(null)}},[e.id,v,w,N,n,s]),oe=a.useCallback(he=>{const Ne=ul(he);b(Ne),!hl(Ne,v)&&ae("executor",Ne)},[v,ae]),F=a.useCallback(he=>{const Ne=ul(he);M(Ne),!hl(Ne,w)&&ae("validator",Ne)},[w,ae]),de=a.useCallback(he=>{const Ne=ul(he);E(Ne),!hl(Ne,N)&&ae("planning",Ne)},[N,ae]),re=a.useCallback(async he=>{const Ne=e.id,ee=z,we=he===""?null:he;R(we),T("thinking");try{const Ie=await Gs(Ne,{thinkingLevel:we});if(j.current!==Ne)return;const qe=Ie.thinkingLevel??null;G(qe),R(qe),s?.(Ie);const Ve=i?.defaultThinkingLevel??"off";n(qe===null?`Thinking level set to default (${Ve})`:`Thinking level set to ${qe}`,"success")}catch(Ie){if(j.current!==Ne)return;R(ee),n(xe(Ie)||"Failed to save thinking level","error")}finally{j.current===Ne&&T(null)}},[e.id,z,i,n,s]),Z=!v.provider&&!v.modelId,ue=!w.provider&&!w.modelId,Ce=!N.provider&&!N.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, project or global defaults 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),is().then(he=>{o(he.models),c(he.favoriteProviders),d(he.favoriteModels)}).catch(he=>p(he.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:Z?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(Mn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(wn,{id:"executorModel",label:"Executor Model",value:B,onChange:oe,models:r,disabled:fe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:W,favoriteModels:u,onToggleModelFavorite:K}),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:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:ue?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:[w.provider&&t.jsx(Mn,{provider:w.provider,size:"sm"}),w.provider,"/",w.modelId]})}),t.jsx(wn,{id:"validatorModel",label:"Reviewer Model",value:A,onChange:F,models:r,disabled:fe,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:W,favoriteModels:u,onToggleModelFavorite:K}),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:Ce?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",V.provider&&V.modelId?` (${V.provider}/${V.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[N.provider&&t.jsx(Mn,{provider:N.provider,size:"sm"}),N.provider,"/",N.modelId]})}),t.jsx(wn,{id:"planningModel",label:"Planning Model",value:L,onChange:de,models:r,disabled:fe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:W,favoriteModels:u,onToggleModelFavorite:K}),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:z===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:z})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:he=>re(he.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:Z&&ue&&Ce&&z===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const eM={open:t.jsx(no,{size:16}),closed:t.jsx(Ya,{size:16}),merged:t.jsx(rh,{size:16})};function tM({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,k]=a.useState(!1),[M,w]=a.useState(null),I=a.useCallback(async()=>{if(h.trim()){v(!0);try{const P=await bv(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(xe(P)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),y=a.useCallback(async()=>{if(s){k(!0);try{const P=await xv(e,n);w(P),c(P.prInfo),u("PR status refreshed","success")}catch(P){u(xe(P)||"Failed to refresh PR","error")}finally{k(!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(es,{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(es,{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(es,{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:I,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{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(qt,{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 E=eM[s.status]??t.jsx(no,{size:16}),N=M?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{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:E}),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:y,disabled:x,title:"Refresh PR status",children:t.jsx(hn,{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:N.length>0?`Waiting for: ${N.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(Ng,{size:14}),"View on GitHub"]})]})]})]})}const im=2e3;function nM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function sM(e){return e==="agent"||e==="system"}function iM({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((E,N)=>new Date(N.createdAt).getTime()-new Date(E.createdAt).getTime()),[e.comments]),v=o.length>im;async function x(){const E=o.trim();if(E){g(!0);try{const N=await Yx(e.id,E,r);l(""),n?.(N),s("Comment added","success")}catch(N){s(xe(N)||"Failed to add comment","error")}finally{g(!1)}}}async function k(E){const N=d.trim();if(N){g(!0);try{const P=await Vx(e.id,E,N,r);u(null),m(""),n?.(P),s("Comment updated","success")}catch(P){s(xe(P)||"Failed to update comment","error")}finally{g(!1)}}}async function M(E){f(E);try{const N=await Wx(e.id,E,r);n?.(N),s("Comment deleted","success")}catch(N){s(xe(N)||"Failed to delete comment","error")}finally{f(null)}}function w(E){E.key==="Enter"&&(E.ctrlKey||E.metaKey)&&(E.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(E=>{const N=E.author===i,P=c===E.id,_=sM(E.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:E.author}),t.jsx("span",{className:"detail-log-timestamp",children:nM(E)})]}),N&&!P?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(E.id),m(E.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void M(E.id),disabled:p===E.id,children:p===E.id?"Deleting…":"Delete"})]}):null]}),P?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:R=>m(R.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 k(E.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:E.text})]},E.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:E=>l(E.target.value),onKeyDown:w,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," / ",im]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function aM(e){return e?e.slice(0,7):"Unknown"}function rM({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:aM(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 nf(e){return e.split(`
621
+ `).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
622
+ `},i):t.jsx(Xm.Fragment,{children:`${s}
623
+ `},i)})}function am(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 oM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function lM({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(Ts,{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(lc,{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(en,{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(Or,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(hn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Dt,{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(Oa,{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:oM(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:nf(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(Ts,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function rm(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function cM({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),[k,M]=a.useState(!0),[w,I]=a.useState(!1),y=i==="done",E=y&&!!r?.commitSha,N=i==="in-progress"||i==="in-review"||E,P=a.useCallback(async()=>{if(!N){h(!1);return}try{h(!0),p(null);const $=await Ch(e,void 0,s),T=$.files.map(j=>({path:j.path,status:j.status,additions:j.additions,deletions:j.deletions,patch:j.patch}));c(T),d($.stats),T.length>0&&(b(new Set([T[0].path])),x(0))}catch($){p(xe($)||"Failed to load diff")}finally{h(!1)}},[e,s,N]);a.useEffect(()=>{P()},[P]);const _=$=>{b(T=>{const j=new Set(T);if(j.has($))j.delete($);else{j.add($);const W=l.findIndex(K=>K.path===$);W!==-1&&x(W)}return j})},R=$=>{if($<0||$>=l.length)return;const T=l[$].path;b(new Set([T])),x($)},z=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(ss,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!y&&!n)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{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(y&&!E){const $=r?.filesChanged,T=r?.insertions,j=r?.deletions,W=$!=null||T!=null||j!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:W?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${T??0} additions, -${j??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?y&&o&&o.length>0?t.jsxs("div",{className:"detail-section task-changes-tab",children:[y&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Oa,{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(Ts,{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:rm("unknown")}),t.jsx("span",{className:"changes-file-path",title:$,children:am($)})]})},$))})]}):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:y?"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:[y&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Oa,{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(Ts,{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:()=>z&&R(v-1),disabled:!z,title:"Previous file","aria-label":"Previous file",children:t.jsx(lc,{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&&R(v+1),disabled:!G,title:"Next file","aria-label":"Next file",children:t.jsx(en,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${k?"btn-primary":""}`,onClick:()=>M($=>!$),title:k?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Or,{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:()=>I(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(ro,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const T=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${T?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:T?t.jsx(Lt,{size:14}):t.jsx(en,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:rm($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:am($.path)}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),T&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${k?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:nf($.patch)})})})]},$.path)})}),t.jsx(lM,{isOpen:w,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>I(!1),onRefresh:P})]})}function om(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function dM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function IP(e,n){const s=dM(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 lm=["image/png","image/jpeg","image/gif","image/webp"];function uM(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 sf({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:k,selectedPresetId:M,onSelectedPresetIdChange:w,selectedWorkflowSteps:I,onWorkflowStepsChange:y,onDefaultOnApplied:E,pendingImages:N,onImagesChange:P,tasks:_,projectId:R,disabled:z=!1,addToast:G,isActive:$=!0,onAutoSaveDescription:T,onPlanningMode:j,onSubtaskBreakdown:W,onClose:K,renderBelowPrimary:B,renderBelowModelConfiguration:A,hideDependencies:L,autoExpandMoreOptionsOnSelection:X=!0,reviewLevel:C,onReviewLevelChange:V,executionMode:fe,onExecutionModeChange:ae}){const oe=(L?!1:o.length>0)||N.length>0||I.length>0||x!=="default"||(c??cs)!==cs||d!==""||h!==""||(p||"")!==""||(b||"")!==""||C!==void 0||fe==="fast",[F,de]=a.useState(!1),[re,Z]=a.useState(X?oe:!1),[ue,Ce]=a.useState(""),[he,Ne]=a.useState([]),[ee,we]=a.useState([]),[Ie,qe]=a.useState([]),[Ve,Ge]=a.useState(!1),[Ke,Qe]=a.useState(null),[Se,Fe]=a.useState([]),[ie,Q]=a.useState("idle"),[pe,te]=a.useState(!1),[ye,ce]=a.useState(!1),[Re,Ze]=a.useState(!1),at=a.useRef(null),le=a.useRef(null),U=a.useRef(null),ne=a.useRef(null),ke=a.useRef(null),_e=a.useRef(null),ge=a.useRef(null),He=a.useRef(!1),ve=a.useRef(oe),$e=a.useRef(n.trim()),ze=a.useRef(n.trim());a.useEffect(()=>{$&&(Ge(!0),is().then(S=>{Ne(S.models),we(S.favoriteProviders),qe(S.favoriteModels)}).catch(()=>{}).finally(()=>Ge(!1)),lo(R).then(S=>Qe(S)).catch(()=>Qe(null)),co(R).then(S=>Fe(S.filter(q=>q.enabled))).catch(()=>Fe([])))},[$,R]);const me=Ke?.modelPresets||[],Pe=me.find(S=>S.id===M),be=(L?!1:o.length>0)||N.length>0||I.length>0||x!=="default"||(c??cs)!==cs||d!==""||h!==""||(p||"")!==""||(b||"")!==""||C!==void 0||fe==="fast";a.useEffect(()=>{if(e!=="create"||!$||!Ke?.autoSelectModelPreset)return;const S=(Ke.defaultPresetBySize,void 0);if(S){const q=om(S);w(S.id),k("preset"),m(q.executorValue),g(q.validatorValue)}},[$,Ke,me,e]);const We=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!$||We.current||Se.length===0)return;const S=Se.filter(Ae=>Ae.defaultOn);if(S.length===0)return;We.current=!0;const q=S.map(Ae=>Ae.id);y(q),E?.(q)},[e,$,Se]),a.useEffect(()=>{$||(We.current=!1)},[$]),a.useEffect(()=>{if(!X){ve.current=be;return}be&&!ve.current&&Z(!0),ve.current=be},[be,X]),a.useEffect(()=>{re||(de(!1),Ce(""))},[re]),a.useEffect(()=>{e!=="edit"||!$||ne.current&&(ne.current.focus(),ne.current.select())},[e,$]),a.useEffect(()=>{if(!F)return;const S=q=>{le.current&&!le.current.contains(q.target)&&de(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[F]),a.useEffect(()=>{(e!=="edit"||z)&&Ze(!1)},[e,z]),a.useEffect(()=>{if(e!=="edit"){Q("idle");return}const S=n.trim();$e.current=S,ze.current=S,Q("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!T||!$)return;const S=n.trim(),q=$e.current;if(S===q||S===ze.current){_e.current&&(clearTimeout(_e.current),_e.current=null),He.current||Q("idle");return}return _e.current&&clearTimeout(_e.current),_e.current=setTimeout(async()=>{if(!He.current){He.current=!0,Q("saving");try{await T(S),ze.current=S,Q("saved"),ge.current&&clearTimeout(ge.current),ge.current=setTimeout(()=>{Q("idle"),ge.current=null},2e3)}catch{Q("idle")}finally{He.current=!1,_e.current=null}}},1500),()=>{_e.current&&(clearTimeout(_e.current),_e.current=null)}},[e,n,T,$]),a.useEffect(()=>()=>{_e.current&&clearTimeout(_e.current),ge.current&&clearTimeout(ge.current)},[]),a.useEffect(()=>{if(!pe)return;const S=q=>{at.current&&!at.current.contains(q.target)&&te(!1)};return document.addEventListener("mousedown",S),()=>document.removeEventListener("mousedown",S)},[pe]);const tt=a.useCallback(S=>{const q=S.clipboardData?.items;if(q)for(let Ae=0;Ae<q.length;Ae++){const ot=q[Ae];if(ot.type.startsWith("image/")){const kt=ot.getAsFile();if(kt&&lm.includes(kt.type)){S.preventDefault(),P([...N,{file:kt,previewUrl:URL.createObjectURL(kt)}]);return}}}},[N,P]),ct=a.useCallback(S=>{S.preventDefault();const q=S.dataTransfer.files;for(let Ae=0;Ae<q.length;Ae++){const ot=q[Ae];if(lm.includes(ot.type)){P([...N,{file:ot,previewUrl:URL.createObjectURL(ot)}]);return}}},[N,P]),wt=a.useCallback(S=>{const q=N[S];q&&URL.revokeObjectURL(q.previewUrl),P(N.filter((Ae,ot)=>ot!==S))},[N,P]),Nt=a.useCallback(S=>{l(o.includes(S)?o.filter(q=>q!==S):[...o,S])},[o,l]),It=(S,q)=>S.length>q?S.slice(0,q)+"…":S,Ut=a.useCallback(S=>{s(S.target.value);const q=S.target;q.style.height="auto",q.style.height=q.scrollHeight+"px"},[s]),Vt=a.useCallback(()=>{Ze(S=>!S)},[]),zt=a.useCallback(S=>{!Re||S.key!=="Escape"||(S.preventDefault(),S.stopPropagation(),Ze(!1))},[Re]),Mt=a.useCallback(async S=>{const q=n.trim();if(!(!q||ye)){ce(!0);try{const Ae=await kh(q,S,R);s(Ae),te(!1),G("Description refined with AI","success"),U.current&&(U.current.style.height="auto",U.current.style.height=U.current.scrollHeight+"px")}catch(Ae){const ot=jh(Ae);G(ot,"error")}finally{ce(!1)}}},[n,ye,G,s,R]),xt=a.useCallback(async S=>{const q=ee,ot=q.includes(S)?q.filter(kt=>kt!==S):[S,...q];we(ot);try{await nn({favoriteProviders:ot,favoriteModels:Ie})}catch{we(q)}},[ee,Ie]),_t=a.useCallback(async S=>{const q=Ie,ot=q.includes(S)?q.filter(kt=>kt!==S):[S,...q];qe(ot);try{await nn({favoriteProviders:ee,favoriteModels:ot})}catch{qe(q)}},[Ie,ee]),De=a.useCallback(S=>{if(S<=0)return;const q=[...I];[q[S-1],q[S]]=[q[S],q[S-1]],y(q)},[I,y]),gt=a.useCallback(S=>{if(S>=I.length-1)return;const q=[...I];[q[S],q[S+1]]=[q[S+1],q[S]],y(q)},[I,y]),ut=a.useCallback(S=>{y(I.filter(q=>q!==S))},[I,y]),Me=new Map;for(const S of Se)Me.set(S.id,{name:S.name,description:S.description});const Ye=_.filter(S=>!o.includes(S.id)).sort((S,q)=>{const Ae=q.createdAt.localeCompare(S.createdAt);if(Ae!==0)return Ae;const ot=parseInt(S.id.slice(S.id.lastIndexOf("-")+1),10)||0;return(parseInt(q.id.slice(q.id.lastIndexOf("-")+1),10)||0)-ot}),rt=ue?Ye.filter(S=>S.id.toLowerCase().includes(ue.toLowerCase())||S.title&&S.title.toLowerCase().includes(ue.toLowerCase())||S.description&&S.description.toLowerCase().includes(ue.toLowerCase())):Ye;return t.jsxs("div",{className:"task-form",onDrop:ct,onDragOver:S=>S.preventDefault(),onPaste:tt,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:ne,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:S=>r(S.target.value),disabled:z})]}),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${ie==="idle"?"":" is-visible"}`,"aria-live":"polite",children:ie==="saving"?"Saving...":ie==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Re?" description--fullscreen":""}`,ref:at,onKeyDown:zt,children:[Re&&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:Vt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(aa,{size:14})})]}),t.jsx("textarea",{ref:U,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ut,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:z||ye}),(()=>{const S=!!n.trim()&&!z;return t.jsxs(t.Fragment,{children:[!Re&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${S?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Vt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(ro,{size:14})}),S&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ye?"refine-button--loading":""}`,onClick:()=>te(q=>!q),disabled:ye,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),ye?"Refining...":"Refine"]})]})})(),pe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:S=>S.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Mt("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:()=>Mt("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:()=>Mt("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:()=>Mt("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"&&(j||W)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[j&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const S=n.trim();if(!S){G("Enter a description first","error");return}K?.(),j(S)},disabled:z||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),W&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const S=n.trim();if(!S){G("Enter a description first","error");return}K?.(),W(S)},disabled:z||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),B,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Z(S=>!S),"aria-expanded":re,"aria-controls":"task-form-more-options",disabled:z,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),re?t.jsx(Ys,{size:14}):t.jsx(Lt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${re?"":" collapsed"}`,"aria-hidden":!re,hidden:!re,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),N.length>0&&t.jsx("div",{className:"inline-create-previews",children:N.map((S,q)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:S.previewUrl,alt:S.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>wt(q),disabled:z,title:"Remove image",children:"×"})]},S.previewUrl))}),t.jsx("input",{ref:ke,type:"file",accept:"image/*",onChange:S=>{const q=S.target.files?.[0];q&&(P([...N,{file:q,previewUrl:URL.createObjectURL(q)}]),S.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ke.current?.click(),disabled:z,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),!L&&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:le,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(S=>!S),disabled:z,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:ue,onChange:S=>Ce(S.target.value),onClick:S=>S.stopPropagation()}),rt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):rt.map(S=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(S.id)?" selected":""}`,onClick:()=>Nt(S.id),onMouseDown:q=>q.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:S.id}),t.jsx("span",{className:"dep-dropdown-title",children:It(S.title||S.description||S.id,30)})]},S.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(S=>t.jsxs("span",{className:"dep-chip",children:[S,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Nt(S),disabled:z,children:"×"})]},S))})]})}),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??cs,onChange:S=>u(S.target.value),disabled:z,children:hc.map(S=>t.jsx("option",{value:S,children:S[0].toUpperCase()+S.slice(1)},S))})]}),ae&&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:S=>ae(S.target.value),disabled:z,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ve?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):he.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"?M:x,onChange:S=>{const q=S.target.value;if(q==="default"){k("default"),w(""),m(""),g("");return}if(q==="custom"){k("custom"),w("");return}const Ae=me.find(kt=>kt.id===q),ot=om(Ae);k("preset"),w(q),m(ot.executorValue),g(ot.validatorValue)},disabled:z,children:[t.jsx("option",{value:"default",children:"Use default"}),me.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,me.map(S=>t.jsx("option",{value:S.id,children:S.name},S.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),x==="preset"&&Pe?t.jsxs("small",{children:["Using preset: ",Pe.name]}):null,x==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>k("custom"),disabled:z,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(wn,{id:"executor-model",label:"Executor Model",value:d,onChange:S=>{k("custom"),w(""),m(S)},models:he,disabled:z||x==="preset",favoriteProviders:ee,onToggleFavorite:xt,favoriteModels:Ie,onToggleModelFavorite:_t})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(wn,{id:"validator-model",label:"Reviewer Model",value:h,onChange:S=>{k("custom"),w(""),g(S)},models:he,disabled:z||x==="preset",favoriteProviders:ee,onToggleFavorite:xt,favoriteModels:Ie,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(wn,{id:"planning-model",label:"Planning Model",value:p||"",onChange:S=>{k("custom"),w(""),f(S)},models:he,disabled:z||x==="preset",favoriteProviders:ee,onToggleFavorite:xt,favoriteModels:Ie,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:S=>v(S.target.value),disabled:z||x==="preset",children:[t.jsxs("option",{value:"",children:["Default (",Ke?.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"})]})]}),V&&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:S=>V(S.target.value===""?0:parseInt(S.target.value,10)),disabled:z,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"})]})]})]})]}),A,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:Se.length>0&&Se.map(S=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${S.id}`,children:[t.jsx("input",{type:"checkbox",checked:I.includes(S.id),onChange:q=>{y(q.target.checked?[...I,S.id]:I.filter(Ae=>Ae!==S.id))},disabled:z}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[S.name,uM(S.phase||"pre-merge",S.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:S.description})]})]},S.id))})]}),I.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:"}),I.map((S,q)=>{const Ae=Me.get(S);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${S}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:q+1}),t.jsx("span",{className:"workflow-step-order-name",children:Ae?.name||S}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>De(q),disabled:z||q===0,"data-testid":`workflow-step-move-up-${S}`,title:"Move up",children:t.jsx(Ys,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>gt(q),disabled:z||q===I.length-1,"data-testid":`workflow-step-move-down-${S}`,title:"Move down",children:t.jsx(Lt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ut(S),disabled:z,"data-testid":`workflow-step-remove-${S}`,title:"Remove",children:t.jsx(Dt,{size:14})})]})]},S)})]})]})]})]})}const cm={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 mM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function hM(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 pM(e){return e?new Date(e).toLocaleString():null}function fM(e){const n=e.split(`
624
+ `);return n.length<=1?e:`${n.length} lines`}function Mr(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 gM({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 bM({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),k=n.some(C=>C.status==="pending"),{entries:M}=Zp(e,!!l&&k,o);a.useEffect(()=>{let C=!1;return co(o).then(V=>{C||b(V.filter(fe=>fe.enabled))}).catch(()=>{C||b([])}),()=>{C=!0}},[o]);const w=i??[],I=a.useMemo(()=>f.map(C=>({id:C.id,name:C.name,description:C.description,phase:C.phase||"pre-merge"})),[f]),y=a.useMemo(()=>new Map(I.map(C=>[C.id,C])),[I]),E=C=>{d(V=>({...V,[C]:!V[C]}))},N=C=>{h(V=>{const fe=V[C]??"markdown";return{...V,[C]:fe==="markdown"?"plain":"markdown"}})},P=C=>{p(C)},_=()=>{p(null)};a.useEffect(()=>{if(!g)return;const C=V=>{V.key==="Escape"&&_()};return document.addEventListener("keydown",C),()=>{document.removeEventListener("keydown",C)}},[g]);const R=a.useCallback((C,V)=>{if(c){if(V){if(w.includes(C)){c(w);return}c([...w,C]);return}c(w.filter(fe=>fe!==C))}},[c,w]),z=a.useCallback(C=>{if(!c||C<=0)return;const V=[...w];[V[C-1],V[C]]=[V[C],V[C-1]],c(V)},[c,w]),G=a.useCallback(C=>{if(!c||C>=w.length-1)return;const V=[...w];[V[C],V[C+1]]=[V[C+1],V[C]],c(V)},[c,w]),$=a.useCallback(C=>{c&&c(w.filter(V=>V!==C))},[c,w]),T=n.length>0,j=w.length>0;a.useEffect(()=>{r||x(!1)},[r]);const W=a.useMemo(()=>w.map(C=>{const V=y.get(C);return{id:C,name:V?.name||C,description:V?.description||"Step definition not found.",phase:V?.phase||"pre-merge"}}),[w,y]),K=()=>!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:I.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:w.includes(C.id),onChange:V=>R(C.id,V.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[C.name,Mr(C.phase,C.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:C.description})]})]},C.id))})]}),w.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:"}),w.map((C,V)=>{const fe=y.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:V+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:()=>z(V),disabled:V===0,"data-testid":`workflow-step-move-up-${C}`,title:"Move up",children:t.jsx(Ys,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>G(V),disabled:V===w.length-1,"data-testid":`workflow-step-move-down-${C}`,title:"Move down",children:t.jsx(Lt,{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(Dt,{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(!T)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,V=n.filter(F=>F.status==="failed").length,fe=n.filter(F=>F.status==="skipped").length,ae=n.filter(F=>F.status==="pending").length,oe=[`${n.length} step${n.length!==1?"s":""}`];return C>0&&oe.push(`${C} passed`),V>0&&oe.push(`${V} failed`),fe>0&&oe.push(`${fe} skipped`),ae>0&&oe.push(`${ae} 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:oe.join(" · ")}),n.map((F,de)=>{const re=F.phase||"pre-merge",Z=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,Mr(re,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:mM(F.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[F.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",pM(F.startedAt)]}),F.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:hM(F.startedAt,F.completedAt)})]}),F.status==="pending"&&F.startedAt?t.jsx(gM,{entries:M,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:()=>E(F.workflowStepId),"data-testid":`workflow-result-toggle-${F.workflowStepId}`,children:Z?"Hide output":"Show output"}),!Z&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${F.workflowStepId}`,children:fM(F.output)}),Z&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>N(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(ro,{size:12})})]})]}),Z&&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(Qs,{remarkPlugins:[Xs],components:cm,children:F.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:F.output})})]}):null]},`${F.workflowStepId}-${de}`)})]})},A=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(xn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(qn,{size:14}),"Edit"]})}):null,L=!s&&!T&&j,X=r&&T;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[L?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:[W.length," step",W.length===1?"":"s"]})]}),A]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:W.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,Mr(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."}),K()]}):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"}),A]}),B(),K()]}),g&&(()=>{const C=n.find(ae=>ae.workflowStepId===g);if(!C)return null;const V=m[C.workflowStepId]??"markdown",fe=C.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ae=>{ae.target===ae.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}),Mr(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:()=>N(C.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:V==="markdown"?"Switch to plain text":"Switch to markdown",children:V==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Dt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${V==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:V==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:cm,children:C.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:C.output})})})]})})})()]})}const xM=/^[a-zA-Z0-9_-]{1,64}$/,vM=200;function dm(e){return e?new Date(e).toLocaleString():""}function yM(e,n=vM){return e.length<=n?e:e.substring(0,n)+"…"}function kM({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,k]=a.useState(null),[M,w]=a.useState([]),[I,y]=a.useState(!1),[E,N]=a.useState(!1),[P,_]=a.useState(""),[R,z]=a.useState(""),[G,$]=a.useState(!1),[T,j]=a.useState(null),[W,K]=a.useState(null),[B,A]=a.useState(!1),L=a.useCallback(async()=>{try{const re=await Kx(e,i);l(re)}catch(re){n(xe(re)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{L()},[L]);async function X(re){d===re.key?(m(null),g(""),f(null),v(""),k(null),w([]),A(!1)):(m(re.key),g(re.content),f(null),v(""),k(null),w([]),A(!1))}async function C(re){if(x===re)k(null),w([]);else{k(re),y(!0);try{const Z=await Gx(e,re,i);w(Z)}catch(Z){n(xe(Z)||"Failed to load revisions","error")}finally{y(!1)}}}function V(){d&&(f(d),v(h))}function fe(){f(null),v("")}async function ae(){if(!(!p||!b.trim())){$(!0);try{await id(e,p,b,{},i),f(null),v(""),await L();const re=o.find(Z=>Z.key===p);re&&g(re.content),n("Document saved","success")}catch(re){n(xe(re)||"Failed to save document","error")}finally{$(!1)}}}async function oe(){const re=P.trim(),Z=R.trim();if(!re){n("Document key is required","error");return}if(!xM.test(re)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Z){n("Content is required","error");return}$(!0);try{await id(e,re,Z,{},i),N(!1),_(""),z(""),await L(),n("Document created","success")}catch(ue){n(xe(ue)||"Failed to create document","error")}finally{$(!1)}}async function F(re){j(re);try{await Jx(e,re,i),K(null),j(null),d===re&&(m(null),g("")),x===re&&(k(null),w([])),await L(),n("Document deleted","success")}catch(Z){n(xe(Z)||"Failed to delete document","error")}finally{j(null)}}function de(re){g(re.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"}),E&&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:re=>_(re.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:R,onChange:re=>z(re.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:()=>{N(!1),_(""),z("")},disabled:G,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void oe(),disabled:G||!P.trim()||!R.trim(),children:G?"Creating…":"Create"})]})]}),o.length===0&&!E?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(re=>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:re.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",re.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:re.author}),t.jsx("span",{className:"task-document-timestamp",children:dm(re.updatedAt||re.createdAt)})]})]}),d===re.key&&p!==re.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:()=>A(Z=>!Z),"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(Qs,{remarkPlugins:[Xs],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===re.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),I?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):M.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:M.filter(Z=>Z.revision<re.revision).sort((Z,ue)=>ue.revision-Z.revision).map(Z=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>de(Z),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Z.revision]}),t.jsx("span",{className:"revision-author",children:Z.author}),t.jsx("span",{className:"revision-timestamp",children:dm(Z.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:yM(Z.content,100)})]},Z.id))})]})]}),p===re.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:Z=>v(Z.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 ae(),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(re),children:d===re.key?t.jsxs(t.Fragment,{children:[t.jsx(Ys,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Lt,{size:14})," Expand"]})}),d===re.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void C(re.key),children:[t.jsx(Ua,{size:14})," History"]}),r&&p!==re.key&&t.jsx("button",{className:"btn btn-sm",onClick:V,children:"Edit"}),r&&(W===re.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(re.key),disabled:T===re.key,children:T===re.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>K(null),disabled:T===re.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>K(re.key),children:t.jsx(Ht,{size:14})}))]})]})]},re.key))}),r&&!E&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>N(!0),children:[t.jsx(qt,{size:14})," New Document"]})]})}function _r(e){return e.toLocaleString()}function pl(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ar(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 jM(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 wM(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??""}
625
+ ${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:jM(n)}})}function NM(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 SM({tokenUsage:e,loading:n,task:s}){const i=wM(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=NM(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:Ar(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:Ar(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} (${Ar(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} (${Ar(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 ${pl(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:_r(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:_r(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:_r(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:_r(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:pl(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:pl(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}function CM(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function EM(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 MM(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 _M(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=MM(n);return i||(s?.planningProvider&&s.planningModelId?{provider:s.planningProvider,modelId:s.planningModelId}:s?.defaultProvider&&s.defaultModelId?{provider:s.defaultProvider,modelId:s.defaultModelId}:{})}function AM(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 TM(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 IM(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 um(e,n){return e.length>n?e.slice(0,n)+"…":e}function mm(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function fl(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function gl(e){return e.trim()}function PM(e){const n=e.trim();return n.length>0?n:void 0}function ja(e){return typeof e=="string"&&hc.includes(e)?e:cs}function wa(e){return e==="fast"?"fast":"standard"}const bl=200,$M=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),[k,M]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){x(e),M(!1);return}let Y=!1;return M(!0),x(null),Br(e.id,n).then(Je=>{Y||(x(Je),M(!1))}).catch(()=>{Y||M(!1)}),()=>{Y=!0}},[e.id,n]);const w=v??{...e,prompt:""},I=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt;a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{P(!1)},[e.id]);const[y,E]=a.useState("activity"),[N,P]=a.useState(!1),[_,R]=a.useState(e.attachments||[]),[z,G]=a.useState(!1),[$,T]=a.useState(e.dependencies||[]),[j,W]=a.useState(!1),[K,B]=a.useState(""),[A,L]=a.useState(null),[X,C]=a.useState([]),[V,fe]=a.useState(!1),[ae,oe]=a.useState(!1),[F,de]=a.useState(!1),[re,Z]=a.useState(!1),[ue,Ce]=a.useState(!1),[he,Ne]=a.useState(w.prompt||""),[ee,we]=a.useState(""),[Ie,qe]=a.useState(!1),[Ve,Ge]=a.useState(""),[Ke,Qe]=a.useState(!1),[Se,Fe]=a.useState(!1),[ie,Q]=a.useState(e.title||""),[pe,te]=a.useState(e.description||""),[ye,ce]=a.useState(e.dependencies||[]),[Re,Ze]=a.useState(""),[at,le]=a.useState(""),[U,ne]=a.useState(""),[ke,_e]=a.useState(""),[ge,He]=a.useState("default"),[ve,$e]=a.useState(void 0),[ze,me]=a.useState(cs),[Pe,be]=a.useState(wa(e.executionMode)),[We,tt]=a.useState(""),[ct,wt]=a.useState(e.enabledWorkflowSteps||[]),[Nt,It]=a.useState(e.sourceIssue?.provider??""),[Ut,Vt]=a.useState(e.sourceIssue?.repository??""),[zt,Mt]=a.useState(e.sourceIssue?.externalIssueId??""),[xt,_t]=a.useState(e.sourceIssue?.url??""),[De,gt]=a.useState([]),[ut,Me]=a.useState(!1),Ye=a.useRef(!1),[rt,S]=a.useState(!1),[q,Ae]=a.useState(!1),ot=a.useRef(null),kt=a.useRef(null),{getSlotsForId:Ot}=Th(n),sn=Ot("task-detail-tab");a.useEffect(()=>(Ye.current=!0,()=>{Ye.current=!1}),[]);const[Pt,zn]=a.useState(void 0),[Kn,ms]=a.useState([]),[pn,Fn]=a.useState(!1),[Sn,fn]=a.useState(e.enabledWorkflowSteps||[]);a.useEffect(()=>{Q(e.title||""),te(e.description||""),It(e.sourceIssue?.provider??""),Vt(e.sourceIssue?.repository??""),Mt(e.sourceIssue?.externalIssueId??""),_t(e.sourceIssue?.url??""),be(wa(e.executionMode)),Fe(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{fn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Y=!1;return lo(n).then(Je=>{Y||zn(Je)}).catch(()=>{}),()=>{Y=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Y=!1;return Fn(!0),by(e.id,n).then(Je=>{Y||ms(Je)}).catch(Je=>{Y||h(`Failed to load workflow results: ${xe(Je)}`,"error")}).finally(()=>{Y||Fn(!1)}),()=>{Y=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Y=n?`?projectId=${encodeURIComponent(n)}`:"",Je=lt=>{try{const St=JSON.parse(lt.data);St.id===e.id&&Array.isArray(St.workflowStepResults)&&ms(St.workflowStepResults)}catch{}};return qs(`/api/events${Y}`,{events:{"task:updated":Je}})},[f,e.id,n]),a.useEffect(()=>{j||B("")},[j]),a.useEffect(()=>{if(!e.assignedAgentId){L(null);return}const Y=X.find(lt=>lt.id===e.assignedAgentId);if(Y){L(Y);return}let Je=!1;return Nh(e.assignedAgentId,n).then(lt=>{Je||L(lt)}).catch(()=>{Je||L(null)}),()=>{Je=!0}},[e.assignedAgentId,n,X]),a.useEffect(()=>{fe(!1)},[e.id]),a.useEffect(()=>{if(!(rt||q))return;const Je=lt=>{const St=lt.target,Ms=ot.current?.contains(St),Rn=kt.current?.contains(St);!Ms&&rt&&S(!1),!Rn&&q&&Ae(!1)};return document.addEventListener("mousedown",Je),()=>document.removeEventListener("mousedown",Je)},[rt,q]),a.useEffect(()=>{if(!(rt||q))return;const Je=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),rt&&S(!1),q&&Ae(!1))};return document.addEventListener("keydown",Je),()=>document.removeEventListener("keydown",Je)},[rt,q]),a.useEffect(()=>{Ce(!1),Ne(w.prompt||""),we("")},[e.id,w.prompt]);const Gn=$M.has(e.column)&&!ut,dn=a.useCallback(()=>{if(!Gn)return;Fe(!0),Q(e.title||""),te(e.description||""),ce(e.dependencies||[]);const Y=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Je=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Ze(Y),le(Je),ne(lt),_e(e.thinkingLevel??""),He(Y||Je||lt?"custom":"default"),tt(""),wt(e.enabledWorkflowSteps||[]),be(wa(e.executionMode)),It(e.sourceIssue?.provider??""),Vt(e.sourceIssue?.repository??""),Mt(e.sourceIssue?.externalIssueId??""),_t(e.sourceIssue?.url??""),gt([]),$e(e.reviewLevel),me(ja(e.priority))},[Gn,e]),At=a.useCallback(()=>{Fe(!1),Q(e.title||""),te(e.description||""),ce(e.dependencies||[]),It(e.sourceIssue?.provider??""),Vt(e.sourceIssue?.repository??""),Mt(e.sourceIssue?.externalIssueId??""),_t(e.sourceIssue?.url??""),me(ja(e.priority)),be(wa(e.executionMode)),De.forEach(Y=>URL.revokeObjectURL(Y.previewUrl)),gt([])},[e.title,e.description,e.dependencies,e.priority,e.executionMode,De]),yn=a.useCallback(async()=>{Me(!0);try{const Y={},Je=ie.trim(),lt=pe.trim();Je&&Je!==(e.title??"")&&(Y.title=Je),lt&&lt!==(e.description??"")&&(Y.description=lt),mm(ye,e.dependencies??[])||(Y.dependencies=ye),mm(ct,e.enabledWorkflowSteps??[])||(Y.enabledWorkflowSteps=ct);const St=fl(Re),Ms=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Re!==Ms&&(Y.modelProvider=St?.provider??null,Y.modelId=St?.modelId??null);const Rn=fl(at),cr=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";at!==cr&&(Y.validatorModelProvider=Rn?.provider??null,Y.validatorModelId=Rn?.modelId??null);const ma=fl(U),wo=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";U!==wo&&(Y.planningModelProvider=ma?.provider??null,Y.planningModelId=ma?.modelId??null);const No=e.thinkingLevel??"";ke!==No&&(Y.thinkingLevel=ke!==""?ke:null);const So=e.reviewLevel;ve!==So&&(Y.reviewLevel=ve);const Ws=ja(e.priority);ze!==Ws&&(Y.priority=ze);const ni=wa(e.executionMode);Pe!==ni&&(Y.executionMode=Pe==="fast"?"fast":null);const si=gl(Nt),Ti=gl(Ut),Ri=gl(zt),ha=PM(xt);if(si.length===0&&Ti.length===0&&Ri.length===0&&!ha)e.sourceIssue&&(Y.sourceIssue=null);else{if(!si||!Ti||!Ri){h("Source issue provider, repository, and issue identifier are required","error"),Me(!1);return}const xs=Number.parseInt(Ri,10),ii=e.sourceIssue?.issueNumber??xs;if(!Number.isFinite(ii)||ii<=0){h("Source issue identifier must be numeric for new metadata","error"),Me(!1);return}const _s={provider:si,repository:Ti,externalIssueId:Ri,issueNumber:ii,...ha?{url:ha}:{}},Ps=e.sourceIssue;(!Ps||Ps.provider!==_s.provider||Ps.repository!==_s.repository||Ps.externalIssueId!==_s.externalIssueId||Ps.issueNumber!==_s.issueNumber||(Ps.url??void 0)!==_s.url)&&(Y.sourceIssue=_s)}if(Object.keys(Y).length>0){const xs=await Gs(e.id,Y,n);m?.(xs)}if(De.length>0){const xs=[];for(const ii of De)try{const _s=await Ha(e.id,ii.file,n);R(Ps=>[...Ps,_s])}catch{xs.push(ii.file.name)}xs.length>0&&h(`Failed to upload: ${xs.join(", ")}`,"error")}De.forEach(xs=>URL.revokeObjectURL(xs.previewUrl)),gt([]),h(`Updated ${e.id}`,"success"),Fe(!1)}catch(Y){h(`Failed to update ${e.id}: ${xe(Y)}`,"error")}finally{Ye.current&&Me(!1)}},[e,ie,pe,ye,Re,at,U,ke,ve,ze,Pe,ct,Nt,Ut,zt,xt,De,h,n,m]),Jn=a.useCallback(async Y=>{try{await Gs(e.id,{description:Y},n),h("Description saved","success")}catch(Je){h(`Failed to save: ${xe(Je)}`,"error")}},[e.id,h,n]),kn=a.useCallback(Y=>{Se&&(Y.key==="Escape"?(Y.preventDefault(),At()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),yn()))},[Se,At,yn]);a.useEffect(()=>{if(Se)return document.addEventListener("keydown",kn),()=>document.removeEventListener("keydown",kn)},[Se,kn]);const _n=a.useRef(null),{entries:hs,loading:ps,loadMore:On,hasMore:J,total:Le,loadingMore:nt}=Zp(e.id,f==="logs"&&y==="agent-log",n);a.useEffect(()=>{const Y=Je=>{Je.key==="Escape"&&!Se&&i()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[i,Se]);const et=a.useCallback(Y=>{Y.target===Y.currentTarget&&i()},[i]),mt=a.useCallback(async Y=>{try{await o(e.id,Y),i(),h(`Moved to ${Pn[Y]}`,"success")}catch(Je){h(xe(Je),"error")}},[e.id,o,i,h]),jt=a.useCallback(async()=>{if(confirm(`Delete ${e.id}?`))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Y){const Je=IM(Y);if(!Je||Je.dependentIds.length===0){h(xe(Y),"error");return}const lt=Je.dependentIds.join(", ");if(!confirm(`${e.id} is a dependency of ${lt}.
626
+
627
+ 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(Ms){h(xe(Ms),"error")}}},[e.id,l,i,h]),Tt=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(xe(Y),"error")}))},[e.id,c,i,h]),gn=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Y=>{h(xe(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(xe(Y),"error")}},[e.id,d,i,h]),Xt=a.useCallback(async()=>{try{e.paused?(await Lx(e.id,n),h(`Unpaused ${e.id}`,"success")):(await bh(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Y){h(xe(Y),"error")}},[e.id,e.paused,i,h]),vt=a.useCallback(async()=>{try{await Ux(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Y){h(xe(Y),"error")}},[e.id,i,h]),dt=a.useCallback(async()=>{if(confirm("Reject this plan? The specification will be discarded and regenerated."))try{await Bx(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Y){h(xe(Y),"error")}},[e.id,i,h]),se=a.useCallback(async()=>{if(confirm("Rebuild the plan for this task? The task will move to planning for replanning."))try{await Xx(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(Y){h(xe(Y),"error")}},[e.id,n,i,h]),Ee=a.useCallback(()=>{qe(!0),Ge("")},[]),st=a.useCallback(()=>{S(!1),Ae(!1)},[]),ft=a.useCallback(Y=>{st(),mt(Y)},[st]),bt=a.useCallback(Y=>{st(),Y()},[st]),on=a.useCallback(()=>{st(),Tt()},[st]),Zt=a.useCallback(()=>{qe(!1),Ge(""),Qe(!1)},[]),cn=a.useCallback(async()=>{if(!Ve.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Ve.length>2e3){h("Feedback must be 2000 characters or less","error");return}Qe(!0);try{const Y=await Zx(e.id,Ve.trim(),n);h(`Refinement task created: ${Y.id}`,"success"),i()}catch(Y){h(xe(Y),"error")}finally{Qe(!1)}},[e.id,Ve,h,i]),Gt=a.useCallback(async Y=>{G(!0);try{const Je=await Ha(e.id,Y,n);R(lt=>[...lt,Je]),h("Screenshot attached","success")}catch(Je){h(xe(Je),"error")}finally{G(!1)}},[e.id,h]),bn=a.useCallback(async Y=>{const Je=Y.target.files?.[0];Je&&(await Gt(Je),_n.current&&(_n.current.value=""))},[Gt]);a.useEffect(()=>{const Y=Je=>{const lt=Je.clipboardData?.items;if(lt)for(let St=0;St<lt.length;St++){const Ms=lt[St];if(Ms.type.startsWith("image/")){const Rn=Ms.getAsFile();if(Rn){Je.preventDefault(),Gt(Rn);return}}}};return document.addEventListener("paste",Y),()=>document.removeEventListener("paste",Y)},[Gt]);const Cn=a.useCallback(Y=>{Y.preventDefault()},[]),gs=a.useCallback(Y=>{Y.preventDefault();const Je=Y.dataTransfer.files;for(let lt=0;lt<Je.length;lt++){const St=Je[lt];if(St.type.startsWith("image/")){Gt(St);return}}},[Gt]),Un=a.useCallback(async Y=>{try{await qx(e.id,Y,n),R(Je=>Je.filter(lt=>lt.filename!==Y)),h("Attachment deleted","info")}catch(Je){h(xe(Je),"error")}},[e.id,h]),Yn=a.useCallback(async Y=>{const Je=Sn;fn(Y);try{const lt=await Gs(e.id,{enabledWorkflowSteps:Y},n);h("Workflow steps updated","success"),m?.(lt)}catch(lt){fn(Je),h(`Failed to update workflow steps: ${xe(lt)}`,"error")}},[e.id,n,Sn,m,h]),Bn=a.useCallback(async()=>{oe(!0);try{const Y=await oa(void 0,n);C(Y),fe(!0)}catch(Y){h(`Failed to load agents: ${xe(Y)}`,"error"),fe(!1)}finally{oe(!1)}},[n,h]),Qn=a.useCallback(async Y=>{try{const Je=await fd(e.id,Y,n),lt=X.find(St=>St.id===Y)??null;L(lt||(St=>St?.id===Y?St:null)),fe(!1),m?.(Je),h("Assigned agent updated","success")}catch(Je){h(`Failed to assign agent: ${xe(Je)}`,"error")}},[e.id,n,X,m,h]),un=a.useCallback(async()=>{try{const Y=await fd(e.id,null,n);L(null),fe(!1),m?.(Y),h("Agent unassigned","success")}catch(Y){h(`Failed to unassign agent: ${xe(Y)}`,"error")}},[e.id,n,m,h]),Xn=a.useCallback(async Y=>{const Je=[...$,Y];T(Je);try{await Gs(e.id,{dependencies:Je},n)}catch(lt){T($),h(xe(lt),"error")}},[e.id,$,h]),Es=a.useCallback(async(Y,Je)=>{Y.stopPropagation();const lt=$.filter(St=>St!==Je);T(lt);try{await Gs(e.id,{dependencies:lt},n)}catch(St){T($),h(xe(St),"error")}},[e.id,$,h]),Is=a.useCallback(async Y=>{try{const Je=await Br(Y,n);r(Je)}catch{h(`Failed to load dependency ${Y}`,"error")}},[r,h]),rs=a.useCallback(async Y=>{de(!0);try{await Gs(w.id,{prompt:Y},n),h("Spec updated","success"),v&&(v.prompt=Y)}catch(Je){throw h(xe(Je),"error"),Je}finally{de(!1)}},[w,v,h]),An=a.useCallback(async Y=>{Z(!0);try{await Qx(e.id,Y,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(Je){const lt=xe(Je);lt.includes("in-review")||lt.includes("done")?h("Cannot request revision: Task must be in 'todo' or 'in-progress' column.","error"):h(lt,"error")}finally{Z(!1)}},[e.id,h,i]),bs=a.useCallback(()=>{Ce(!0),Ne(w.prompt||""),we("")},[w.prompt]),Tn=a.useCallback(()=>{Ce(!1),Ne(w.prompt||""),we("")},[w.prompt]),ua=a.useCallback(async()=>{if(he===(w.prompt||"")){Tn();return}await rs(he),Ce(!1)},[he,w.prompt,rs,Tn]),yo=a.useCallback(async()=>{ee.trim()&&await An(ee.trim())},[ee,An]),ko=a.useCallback(Y=>{Y.key==="Escape"?(Y.preventDefault(),Tn()):Y.key==="Enter"&&(Y.ctrlKey||Y.metaKey)&&(Y.preventDefault(),ua())},[Tn,ua]),mi=s.filter(Y=>Y.id!==e.id&&!$.includes(Y.id)).sort((Y,Je)=>{const lt=Je.createdAt.localeCompare(Y.createdAt);if(lt!==0)return lt;const St=parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0;return(parseInt(Je.id.slice(Je.id.lastIndexOf("-")+1),10)||0)-St}),or=A?.name??e.assignedAgentId??null,lr=a.useMemo(()=>{const Y=[];return w.modelProvider&&Y.push(w.modelProvider),w.validatorModelProvider&&!Y.includes(w.validatorModelProvider)&&Y.push(w.validatorModelProvider),w.planningModelProvider&&!Y.includes(w.planningModelProvider)&&Y.push(w.planningModelProvider),Y},[w.modelProvider,w.validatorModelProvider,w.planningModelProvider]),ei=Ol[e.column]||[],jo={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},ti=e.status?jo[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",onClick:et,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg",onDragOver:Cn,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:Pn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Se&&Gn&&t.jsx("button",{className:"modal-edit-btn",onClick:dn,title:"Edit task","aria-label":"Edit task",children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&y==="agent-log"&&!Se?" detail-body--agent-log":""}`,children:[Se?t.jsx("div",{className:"modal-edit-form",children:t.jsx(sf,{mode:"edit",title:ie,onTitleChange:Q,description:pe,onDescriptionChange:te,dependencies:ye,onDependenciesChange:ce,executorModel:Re,onExecutorModelChange:Ze,validatorModel:at,onValidatorModelChange:le,planningModel:U,onPlanningModelChange:ne,thinkingLevel:ke,onThinkingLevelChange:_e,presetMode:ge,onPresetModeChange:He,selectedPresetId:We,onSelectedPresetIdChange:tt,selectedWorkflowSteps:ct,onWorkflowStepsChange:wt,pendingImages:De,onImagesChange:gt,tasks:s.filter(Y=>Y.id!==e.id),projectId:n,disabled:ut,addToast:h,isActive:Se,onAutoSaveDescription:Jn,reviewLevel:ve,onReviewLevelChange:$e,priority:ze,onPriorityChange:me,executionMode:Pe,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:Nt,onChange:Y=>It(Y.target.value),disabled:ut,"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=>Vt(Y.target.value),disabled:ut,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:zt,onChange:Y=>Mt(Y.target.value),disabled:ut,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:xt,onChange:Y=>_t(Y.target.value),disabled:ut,"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=!N&&Y.length>bl;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Je?Y.slice(0,bl)+"…":Y}),Y.length>bl&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>P(!N),children:N?"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--${ja(e.priority)}`,children:["Priority: ",ja(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})]})]}),!Se&&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"}),sn.map((Y,Je)=>{const lt=`plugin-${Je}`;return t.jsx("button",{className:`detail-tab${f===lt?" detail-tab-active":""}`,onClick:()=>b(lt),children:Y.slot.label},`plugin-tab-${Y.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(bM,{taskId:e.id,results:Kn,loading:pn,enabledWorkflowSteps:Sn,canEdit:Gn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Yn})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(ZE,{task:e,addToast:h,onTaskUpdated:m,settings:Pt})}):f==="logs"?t.jsxs("div",{className:`detail-section${y==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${y==="activity"?" log-subview-btn-active":""}`,onClick:()=>E("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${y==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>E("agent-log"),children:"Agent Log"})]}),y==="agent-log"?t.jsx(GE,{entries:hs,loading:ps,executorModel:CM(e,Pt),validatorModel:EM(e,Pt),planningModel:_M(e,hs,Pt),hasMore:J,onLoadMore:On,loadingMore:nt,totalCount:Le}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),w.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",w.log.length," activity entries."]}):null,w.log&&w.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...w.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:TM(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(cM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(iM,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(kM,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Gn}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(mo,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(SM,{tokenUsage:w.tokenUsage,loading:k,task:w})}):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(Qs,{remarkPlugins:[Xs],children:e.summary})})]}),t.jsx(rM,{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("div",{className:"detail-meta-left",children:[lr.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:lr.map(Y=>t.jsx(Mn,{provider:Y,size:"sm"},Y))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(an,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[or?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(an,{size:14}),or,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void un(),title:"Unassign agent",children:t.jsx(Dt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{V?fe(!1):Bn()},children:"Assign Agent"}),V&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ae&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ae&&X.filter(Y=>Y.state!=="terminated").map(Y=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Y.id?" selected":""}`,onClick:()=>void Qn(Y.id),children:[t.jsx(an,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Y.name}),t.jsx("span",{className:"agent-picker-role",children:Y.role})]},Y.id)),!ae&&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"}),w.steps&&w.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:w.steps.map((Y,Je)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Y.status}`,"data-tooltip":`${Y.name} (${Y.status})`,style:{backgroundColor:AM(Y.status)}},Je))}),t.jsxs("span",{className:"step-progress-label",children:[w.steps.filter(Y=>Y.status==="done").length,"/",w.steps.length," step",w.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ue&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:bs,children:"Edit"})}),ue?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:he,onChange:Y=>Ne(Y.target.value),onKeyDown:ko,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:Tn,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ua(),disabled:he===(w.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 planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:ee,onChange:Y=>we(Y.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:re,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[ee.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void yo(),disabled:!ee.trim()||re,children:re?"Requesting…":"Request AI Revision"})]})]})]}):k?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):w.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],children:w.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=Hs(`/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:()=>Un(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:_n,type:"file",accept:"image/*",onChange:bn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>_n.current?.click(),disabled:z,children:z?"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(St=>St.id===Y),lt=Je?.title||Je?.description||Y;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Is(Y),onKeyDown:St=>{(St.key==="Enter"||St.key===" ")&&(St.preventDefault(),Is(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:um(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:St=>Es(St,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:()=>{j&&B(""),W(Y=>!Y)},children:"Add Dependency"}),j&&(()=>{const Y=K.toLowerCase(),Je=Y?mi.filter(lt=>lt.id.toLowerCase().includes(Y)||lt.title&&lt.title.toLowerCase().includes(Y)||lt.description&&lt.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:K,onChange:lt=>B(lt.target.value),onClick:lt=>lt.stopPropagation()}),Je.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Je.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Xn(lt.id),W(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:um(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(tM,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Pt?.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:Se?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:At,disabled:ut,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:yn,disabled:ut,children:ut?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&w.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:vt,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:dt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!I&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:jt,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||I)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:kt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Ae(Y=>!Y),S(!1)},"aria-haspopup":"menu","aria-expanded":q,children:["Actions",t.jsx(Lt,{size:12})]}),q&&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(jt),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(Ee),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(se),children:"Respecify"}),I&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(gn),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>bt(Xt),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:ot,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:()=>{S(Y=>!Y),Ae(!1)},"aria-haspopup":"menu","aria-expanded":rt,children:["Move",t.jsx(Lt,{size:12})]}),ti?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:ti}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:on,children:"Merge & Close"})]}),rt&&t.jsxs("div",{className:"detail-move-menu",role:"menu",children:[t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ft("todo"),children:"Move to Todo"}),t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ft("in-progress"),children:"Back to In Progress"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>ft(ei[0]),disabled:ei.length===0,children:["Move to ",ei.length>0?Pn[ei[0]]:""]}),ei.length>1&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{S(Y=>!Y),Ae(!1)},"aria-haspopup":"menu","aria-expanded":rt,children:t.jsx(Lt,{size:12})}),rt&&t.jsx("div",{className:"detail-move-menu",role:"menu",children:ei.map(Y=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ft(Y),children:["Move to ",Pn[Y]]},Y))})]})]})})]})}),Ie&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Zt,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:Zt,"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:Ve,onChange:Y=>Ge(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:[Ve.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:cn,disabled:!Ve.trim()||Ke,children:Ke?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Zt,disabled:Ke,children:"Cancel"})})]})})]})})}const LM=640;function zM({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,k]=a.useState(null),[M,w]=a.useState([]),[I,y]=a.useState(null),[E,N]=a.useState(null),[P,_]=a.useState(!1),[R,z]=a.useState([]),[G,$]=a.useState(!1),[T,j]=a.useState(""),W=a.useRef(!1),[K,B]=a.useState(!1),[A,L]=a.useState("list"),X=a.useRef(null),C=new Set;for(const te of i){const ye=te.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);ye&&C.add(ye[1]);const ce=te.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);ce&&C.add(ce[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),k(null),w([]),y(null),f("issues"),N(null),_(!1),z([]),$(!0),j(""),X.current=null,W.current=!0,uv().then(te=>{if(W.current)if(z(te),$(!1),te.length===1){const ye=te[0];l(ye.owner),u(ye.repo),j(ye.name)}else te.length>1&&(l(""),u(""),j(""))}).catch(()=>{W.current&&$(!1)}),()=>{W.current=!1}},[e]);const V=a.useCallback(te=>{if(j(te),te==="")l(""),u("");else{const ye=R.find(ce=>ce.name===te);ye&&(l(ye.owner),u(ye.repo))}},[R]),fe=a.useCallback(async()=>{if(!o.trim()||!c.trim()){N("Repository must be selected");return}g(!0),N(null),v([]),k(null);try{const te=d.split(",").map(ce=>ce.trim()).filter(Boolean),ye=await ov(o.trim(),c.trim(),30,te.length>0?te:void 0);v(ye),ye.length===0&&N("No open issues found")}catch(te){N(xe(te)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),ae=a.useCallback(async()=>{if(!o.trim()||!c.trim()){N("Repository must be selected");return}g(!0),N(null),w([]),y(null);try{const te=await cv(o.trim(),c.trim(),30);w(te),te.length===0&&N("No open pull requests found")}catch(te){N(xe(te)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||P)return;const te={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};X.current?.owner===te.owner&&X.current?.repo===te.repo&&X.current?.labels===te.labels&&X.current?.tab===te.tab||(X.current=te,p==="issues"?fe():ae())},[o,c,d,p,e,h,P,fe,ae]),a.useEffect(()=>{if(!e)return;const te=ye=>{ye.key==="Escape"&&n()};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[e,n]),a.useEffect(()=>{if(!e)return;const te=()=>{B(window.innerWidth<=LM)};return te(),window.addEventListener("resize",te),()=>window.removeEventListener("resize",te)},[e]);const oe=a.useCallback(te=>{k(te),K&&L("preview")},[K]),F=a.useCallback(te=>{y(te),K&&L("preview")},[K]),de=a.useCallback(()=>{L("list")},[]),re=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;_(!0),N(null);try{const te=await lv(o.trim(),c.trim(),x,r);s(te),n()}catch(te){const ye=xe(te);ye?.includes("already imported")?N(ye):N(ye||"Failed to import issue")}finally{_(!1)}}else{if(I===null)return;_(!0),N(null);try{const te=await dv(o.trim(),c.trim(),I,r);s(te),n()}catch(te){const ye=xe(te);ye?.includes("already imported")?N(ye):N(ye||"Failed to import pull request")}finally{_(!1)}}},[p,x,I,o,c,s,n]),Z=b.find(te=>te.number===x),ue=M.find(te=>te.number===I);if(!e)return null;const Ce=R.length>0,he=R.length===1,Ne=b.filter(te=>C.has(te.html_url)).length,ee=M.filter(te=>C.has(te.html_url)).length,we=E==="No open issues found",Ie=E==="No open pull requests found",qe=p==="issues"?we:Ie,Ve=!!E&&!we&&b.length===0&&!h,Ge=!!E&&!Ie&&M.length===0&&!h,Ke=p==="issues"?Ve:Ge,Qe=h||b.length>0||we||Ve,Se=h||M.length>0||Ie||Ge,Fe=p==="issues"?Qe:Se,ie=!!E&&b.length>0&&!we,Q=!!E&&M.length>0&&!Ie,pe=p==="issues"?ie:Q;return t.jsx("div",{className:"modal-overlay open",onClick:te=>te.target===te.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"),y(null)},disabled:h||P,children:[t.jsx(no,{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"),k(null)},disabled:h||P,children:[t.jsx(es,{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(it,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):Ce?he?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:R[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[R[0].owner,"/",R[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:T,onChange:te=>V(te.target.value),disabled:h||P,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),R.map(te=>t.jsxs("option",{value:te.name,children:[te.name," (",te.owner,"/",te.repo,")"]},te.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:te=>m(te.target.value),onKeyDown:te=>te.key==="Enter"&&fe(),disabled:h||P||!Ce,"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:ae,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(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!G&&!Ce&&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"})]}),pe&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:E}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${K?"mobile":""} ${A==="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:[Ne," imported"]})]}),p==="pulls"&&M.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[M.length," pull request",M.length===1?"":"s"]}),t.jsxs("span",{children:[ee," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Fe&&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(it,{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."})]})]}),Ke&&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:E})]})}),qe&&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(te=>{const ye=C.has(te.html_url);return t.jsxs("div",{className:`issue-item ${x===te.number?"selected":""} ${ye?"imported":""}`,onClick:()=>!ye&&oe(te.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===te.number,onChange:()=>oe(te.number),disabled:ye,"aria-label":`Select issue #${te.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",te.number]}),t.jsx("span",{className:"issue-title",children:te.title})]}),te.labels.length>0&&t.jsx("span",{className:"issue-labels",children:te.labels.map(ce=>t.jsx("span",{className:"label-chip",children:ce.name},ce.name))})]}),ye&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},te.number)})}),p==="pulls"&&M.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:M.map(te=>{const ye=C.has(te.html_url);return t.jsxs("div",{className:`issue-item ${I===te.number?"selected":""} ${ye?"imported":""}`,onClick:()=>!ye&&F(te.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:I===te.number,onChange:()=>F(te.number),disabled:ye,"aria-label":`Select pull request #${te.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",te.number]}),t.jsx("span",{className:"issue-title",children:te.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[te.headBranch," → ",te.baseBranch]})]}),ye&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},te.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${K?"mobile":""} ${A==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[K&&t.jsxs("button",{className:"github-import-back-button",onClick:de,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(ia,{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"&&Z?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",Z.number]}),t.jsx("div",{className:"preview-title",children:Z.title}),t.jsx("div",{className:"preview-body",children:Z.body?Z.body.slice(0,200)+(Z.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"&&ue?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",ue.number]}),t.jsx("div",{className:"preview-title",children:ue.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",ue.headBranch," → ",ue.baseBranch]}),t.jsx("div",{className:"preview-body",children:ue.body?ue.body.slice(0,200)+(ue.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:re,disabled:(p==="issues"?x===null:I===null)||P,children:P?t.jsx(it,{size:14,className:"spin"}):"Import"})]})]})})}const FM=["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 OM(e,n){return e&&n?`${e}/${n}`:""}function UM(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 BM({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([]),[k,M]=a.useState(null),w=a.useRef(!1),I=a.useRef(!1),[y,E]=a.useState(""),[N,P]=a.useState(!0),[_,R]=a.useState(!1),[z,G]=a.useState(!1),$=a.useRef(null),T=a.useRef(null),j=a.useRef(null),[W,K]=a.useState(c??null),B=a.useMemo(()=>_i(),[]),{isLockedByOther:A,takeControl:L,isLoading:X}=po(e?W:null),{activeTabMap:C,broadcastUpdate:V,broadcastCompleted:fe,broadcastLock:ae,broadcastUnlock:oe,broadcastHeartbeat:F}=la(),[de,re]=a.useState(void 0),[Z,ue]=a.useState(void 0),[Ce,he]=a.useState([]),[Ne,ee]=a.useState(!1),[we,Ie]=a.useState(null),[qe,Ve]=a.useState([]),[Ge,Ke]=a.useState([]),Qe=a.useRef(null),Se=OM(de,Z),Fe=a.useCallback((me,Pe)=>{if(!me||!Pe)return"Using default";const be=Ce.find(We=>We.provider===me&&We.id===Pe);return be?`${be.provider}/${be.id}`:`${me}/${Pe}`},[Ce]),ie=a.useCallback(async()=>{ee(!0),Ie(null);try{const me=await is();he(me.models),Ve(me.favoriteProviders),Ke(me.favoriteModels)}catch(me){Ie(xe(me)||"Failed to load models")}finally{ee(!1)}},[]),Q=a.useCallback(me=>{Ve(Pe=>{const be=Pe,tt=be.includes(me)?be.filter(ct=>ct!==me):[me,...be];return nn({favoriteProviders:tt,favoriteModels:Ge}).catch(()=>{Ve(be)}),tt})},[Ge]),pe=a.useCallback(me=>{Ke(Pe=>{const be=Pe,tt=be.includes(me)?be.filter(ct=>ct!==me):[me,...be];return nn({favoriteProviders:qe,favoriteModels:tt}).catch(()=>{Ke(be)}),tt})},[qe]),te=a.useCallback(me=>{T.current?.close();const Pe=cy(me,l,{onThinking:be=>{E(We=>We+be),V({sessionId:me,status:"generating",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:be=>{R(!1),G(!1),Li(l),h({type:"question",session:{sessionId:me,currentQuestion:be,summary:null}}),E(""),V({sessionId:me,status:"awaiting_input",needsInput:!0,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:be=>{R(!1),G(!1),Li(l),h({type:"summary",session:{sessionId:me,currentQuestion:null,summary:be},summary:be}),M(be),E(""),V({sessionId:me,status:"complete",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:be=>{const We=be||"Session failed while contacting the AI.";R(!0),(async()=>{try{const tt=await Js(me);if(tt&&(tt.status==="generating"||tt.status==="awaiting_input")){te(me);return}}catch{}R(!1),G(!1),p(null),h(tt=>tt.type==="question"||tt.type==="summary"||tt.type==="error"?{type:"error",session:tt.session,errorMessage:We}:{type:"error",session:{sessionId:me,currentQuestion:null,summary:null},errorMessage:We}),E(""),j.current=me,V({sessionId:me,status:"error",needsInput:!1,owningTabId:B,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),fe({sessionId:me,status:"error"})})()},onComplete:()=>{R(!1),G(!1),j.current=null,fe({sessionId:me,status:"complete"})},onConnectionStateChange:be=>{R(be==="reconnecting")}});T.current=Pe},[fe,V,u,l,B]),ye=a.useCallback(async me=>{const Pe=me??u;if(Pe.trim()){p(null),E(""),x([]),b([]),R(!1),h({type:"loading"});try{const be=de&&Z?{planningModelProvider:de,planningModelId:Z}:void 0,{sessionId:We}=await Kv(Pe.trim(),l,be);j.current=We,K(We),te(We),b([])}catch(be){R(!1),p(xe(be)||"Failed to start planning session"),h({type:"initial"}),j.current=null,K(null)}}},[te,u,Z,de,l]);a.useEffect(()=>{e&&m.type==="initial"&&$.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&ie()},[e,ie]),a.useEffect(()=>{if(e&&o&&!w.current&&m.type==="initial"){d(o);const me=setTimeout(()=>{w.current=!0,ye(o)},0);return()=>clearTimeout(me)}else if(e&&!o&&!w.current&&!I.current&&m.type==="initial"){I.current=!0;const me=Uw(l);me&&d(me)}},[e,o,m.type,ye,l]),a.useEffect(()=>{if(!e||!c||m.type!=="initial")return;let me=!1;return(async()=>{try{const Pe=await Js(c);if(me||!Pe)return;j.current=c,K(c);const be=Yi(Pe.conversationHistory);if(x(be),b(be.map(We=>We.response).filter(We=>!!(We&&typeof We=="object"&&!Array.isArray(We)))),Pe.status==="awaiting_input"&&Pe.currentQuestion){Li(l);const We=JSON.parse(Pe.currentQuestion);h({type:"question",session:{sessionId:c,currentQuestion:We,summary:null}}),Pe.thinkingOutput&&E(Pe.thinkingOutput),te(c)}else if(Pe.status==="complete"&&Pe.result){Li(l);const We=JSON.parse(Pe.result);h({type:"summary",session:{sessionId:c,currentQuestion:null,summary:We},summary:We}),M(We)}else Pe.status==="generating"?(h({type:"loading"}),Pe.thinkingOutput&&E(Pe.thinkingOutput),te(c)):Pe.status==="error"&&(p(null),h({type:"error",session:{sessionId:c,currentQuestion:null,summary:null},errorMessage:Pe.error||"Session failed"}))}catch{p("Failed to resume session")}})(),()=>{me=!0}},[te,e,c,m.type,l]),a.useEffect(()=>{e||(w.current=!1,I.current=!1,R(!1),G(!1),K(null))},[e]),a.useEffect(()=>{if(!e){Qe.current&&(oe(Qe.current,B),Qe.current=null);return}if(W&&Qe.current!==W){Qe.current&&oe(Qe.current,B),ae(W,B),Qe.current=W;return}!W&&Qe.current&&(oe(Qe.current,B),Qe.current=null)},[ae,oe,e,W,B]),a.useEffect(()=>{if(!e||!W||Qe.current!==W)return;F(B);const me=setInterval(()=>{F(B)},3e4);return()=>{clearInterval(me)}},[F,e,W,B]),a.useEffect(()=>()=>{T.current?.close(),T.current=null,Qe.current&&(oe(Qe.current,B),Qe.current=null)},[oe,B]),a.useEffect(()=>{if(!e)return;const me=()=>{T.current?.close(),T.current=null};return window.addEventListener("beforeunload",me),()=>window.removeEventListener("beforeunload",me)},[e]);const ce=a.useCallback(()=>{T.current?.close(),T.current=null,n()},[n]),Re=a.useCallback(()=>{let me=null;m.type==="question"||m.type==="summary"||m.type==="error"?me=m.session.sessionId:m.type==="breakdown"?me=m.sessionId:m.type==="loading"&&(me=j.current),u&&Ow(u,l),T.current?.close(),T.current=null,me&&yh(me,l,B).catch(()=>{}),d(""),h({type:"initial"}),p(null),b([]),x([]),M(null),E(""),R(!1),G(!1),re(void 0),ue(void 0),j.current=null,K(null),n()},[u,n,l,B,m]);a.useEffect(()=>{if(!e)return;const me=Pe=>{Pe.key==="Escape"&&Re()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,Re]);const Ze=a.useCallback(async me=>{if(m.type!=="question")return;const{session:Pe}=m,be=Pe.sessionId,We=Pe.currentQuestion;if(!We){p("No active question in session");return}p(null),b(tt=>[...tt,me]),x(tt=>[...tt,{question:We,response:me}]),h({type:"loading"}),E("");try{await Gv(be,me,l,B)}catch(tt){p(xe(tt)||"Failed to submit response"),h({type:"question",session:Pe})}},[l,B,m]),at=a.useCallback(async()=>{if(m.type!=="error")return;const me=m.session;p(null),G(!0),E(""),h({type:"loading"}),te(me.sessionId);try{j.current=me.sessionId,K(me.sessionId),await Jv(me.sessionId,l,B)}catch(Pe){let be=Pe;if((xe(Pe)||"").includes("not in an error state"))try{const tt=await Js(me.sessionId);if(!tt)throw new Error("Failed to refresh planning session.");if(j.current=tt.id,K(tt.id),tt.status==="generating")E(tt.thinkingOutput??""),h({type:"loading"});else if(tt.status==="awaiting_input"){if(!tt.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const ct=JSON.parse(tt.currentQuestion);Li(l),h({type:"question",session:{sessionId:tt.id,currentQuestion:ct,summary:null}}),T.current?.isConnected()||te(tt.id)}else if(tt.status==="complete"){if(!tt.result)throw new Error("Planning session is complete but has no result.");const ct=JSON.parse(tt.result);Li(l),h({type:"summary",session:{sessionId:tt.id,currentQuestion:null,summary:ct},summary:ct}),M(ct)}else tt.status==="error"&&h({type:"error",session:{sessionId:tt.id,currentQuestion:null,summary:null},errorMessage:tt.error||"Retry failed. Please try again."});R(!1);return}catch(tt){be=tt}T.current?.close(),T.current=null,h({type:"error",session:me,errorMessage:xe(be)||"Retry failed. Please try again."}),R(!1)}finally{G(!1)}},[te,l,B,m]),le=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const me=await Yv(m.session.sessionId,k??void 0,l);s(me),Re()}catch(me){p(xe(me)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[k,m,l,s,Re]),U=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const me=await Qv(m.session.sessionId,k??void 0,l);K(me.sessionId),h({type:"breakdown",sessionId:me.sessionId,subtasks:me.subtasks,dirty:!1})}catch(me){p(xe(me)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[k,m,l]),ne=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const me=await Xv(m.sessionId,m.subtasks,l);i(me.tasks),d(""),h({type:"initial"}),p(null),b([]),x([]),M(null),E(""),re(void 0),ue(void 0),j.current=null,K(null),n()}catch(me){p(xe(me)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[m,i,n,l]),ke=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const me=f.slice(0,-1);b(me),h({type:"question",session:m.session})}},[m,f]),_e=()=>m.type==="question"?Math.min(f.length+1,3):3,ge=m.type==="loading"||m.type==="question"||m.type==="summary"||m.type==="error",He=W?C.get(W):null,ve=He&&He.tabId!==B,$e=!!(ve&&!He.stale),ze=A&&(!ve||He.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:me=>me.target===me.currentTarget&&Re(),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(Us,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ge&&t.jsx("button",{className:"modal-send-to-background",onClick:ce,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Re,"aria-label":"Close",children:t.jsx(Dt,{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…"}),$e&&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(Dn,{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:me=>d(me.target.value),onKeyDown:me=>{me.key==="Enter"&&!me.shiftKey&&u.trim()&&(me.preventDefault(),ye())}})]}),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:FM.map((me,Pe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(me),children:me.length>40?me.slice(0,40)+"...":me},Pe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Ne&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(wn,{id:"planning-modal-model",label:"Planning Model",value:Se,onChange:me=>{const{provider:Pe,modelId:be}=UM(me);re(Pe),ue(be)},models:Ce,disabled:Ne,favoriteProviders:qe,onToggleFavorite:Q,favoriteModels:Ge,onToggleModelFavorite:pe}),we&&t.jsxs("div",{className:"form-hint form-hint-error",children:[we," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{ie()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${de&&Z?"model-badge-custom":"model-badge-default"}`,children:Fe(de,Z)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ye(),disabled:!u.trim(),children:[t.jsx(Us,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:y?"AI is thinking...":"Generating next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>P(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&y&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:y})})]})]}),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 at(),disabled:z,children:[z?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:z?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Re,disabled:z,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{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(HM,{question:m.session.currentQuestion,progress:_e(),historyEntries:v,onSubmit:Ze,onBack:f.length>0?ke:void 0})}),m.type==="summary"&&k&&t.jsx(qM,{summary:k,historyEntries:v,onSummaryChange:M,tasks:r,onCreateTask:le,onBreakIntoTasks:U,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(WM,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:me=>h({...m,subtasks:me,dirty:!0}),onCreateTasks:ne,onBack:()=>{const Pe={sessionId:m.sessionId,currentQuestion:null,summary:k??null};k&&h({type:"summary",session:Pe,summary:k})}}),A&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(ao,{size:16}),t.jsx("span",{children:ze?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ze&&t.jsx("button",{type:"button",onClick:()=>{L()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function HM({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(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Dt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(ia,{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(Ja,{size:16,className:"icon-ml-4"})]})]})]})}function qM({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(tn,{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(ia,{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(it,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(io,{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(it,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function hm(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 WM({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(E=>!E.title.trim())?!0:hm(e),[e]),f=a.useCallback((E,N)=>{i(e.map(P=>P.id===E?{...P,...N}:P))},[e,i]),b=a.useCallback(()=>{i([...e,VM(e.length+1)])},[e,i]),v=a.useCallback(E=>{i(e.filter(N=>N.id!==E).map(N=>({...N,dependsOn:N.dependsOn.filter(P=>P!==E)})))},[e,i]),x=a.useCallback((E,N)=>{if(N<0||N>=e.length)return;const P=[...e],[_]=P.splice(E,1);P.splice(N,0,_),i(P)},[e,i]),k=a.useCallback(E=>N=>{c(E),N.dataTransfer.setData("text/plain",E),N.dataTransfer.effectAllowed="move"},[]),M=a.useCallback(()=>{c(null),d(null),h(null)},[]),w=a.useCallback(E=>N=>{if(N.preventDefault(),E===l)return;const P=N.currentTarget.getBoundingClientRect(),_=P.top+P.height/2,R=N.clientY<_?"before":"after";d(E),h(R)},[l]),I=a.useCallback(E=>N=>{N.preventDefault();const P=N.dataTransfer.getData("text/plain");if(!P||P===E){M();return}const _=e.findIndex(T=>T.id===P),R=e.findIndex(T=>T.id===E);if(_===-1||R===-1){M();return}const z=[...e],[G]=z.splice(_,1);let $=R;m==="after"&&_<R&&$--,m==="after"&&$++,z.splice($,0,G),i(z),M()},[e,m,i,M]),y=a.useCallback(E=>{const N=E.currentTarget.getBoundingClientRect(),P=E.clientX,_=E.clientY;(P<N.left||P>N.right||_<N.top||_>N.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(io,{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((E,N)=>{const P=l===E.id,_=u===E.id,R=["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:R,"data-testid":`subtask-item-${N}`,draggable:!s,onDragStart:k(E.id),onDragEnd:M,onDragOver:w(E.id),onDrop:I(E.id),onDragLeave:y,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(cc,{size:16}),t.jsx("strong",{children:E.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(N,N-1),disabled:s||N===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(yi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(N,N+1),disabled:s||N===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Ga,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(E.id),disabled:s,children:[t.jsx(Ht,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:z=>{g.current[N]=z},value:E.title,onChange:z=>f(E.id,{title:z.target.value}),onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),N<e.length-1&&g.current[N+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:E.description,onChange:z=>f(E.id,{description:z.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:E.suggestedSize,onChange:z=>f(E.id,{suggestedSize:z.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,N).filter(z=>z.id!==E.id).map(z=>{const G=E.dependsOn.includes(z.id);return t.jsxs("label",{className:`planning-dep-chip ${G?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:G,onChange:()=>{const $=G?E.dependsOn.filter(T=>T!==z.id):[...E.dependsOn,z.id];f(E.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:z.id}),t.jsx("span",{className:"planning-dep-title",children:z.title||"Untitled"})]},z.id)}),N===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),N>0&&e.slice(0,N).filter(z=>z.id!==E.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},E.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(qt,{size:16,className:"icon-mr-6"})," Add subtask"]}),hm(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(ia,{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(it,{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 pm(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 GM({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,k]=a.useState(!1),[M,w]=a.useState(!1),[I,y]=a.useState(s),[E,N]=a.useState(null),[P,_]=a.useState(!1),[R,z]=a.useState(null),[G,$]=a.useState(null),[T,j]=a.useState(null),W=a.useRef(null),K=a.useRef([]),B=a.useRef(!1),A=a.useRef(null),L=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,X=a.useMemo(()=>_i(),[]),{isLockedByOther:C,takeControl:V,isLoading:fe}=po(e?L:null),{activeTabMap:ae,broadcastUpdate:oe,broadcastCompleted:F,broadcastLock:de,broadcastUnlock:re,broadcastHeartbeat:Z}=la(),ue=a.useMemo(()=>d.length===0||d.some(le=>!le.title.trim())?!0:pm(d),[d]),Ce=c.type==="generating"||c.type==="editing"||c.type==="error",he=L?ae.get(L):null,Ne=he&&he.tabId!==X,ee=!!(Ne&&!he.stale),we=C&&(!Ne||he.stale),Ie=a.useCallback(()=>{I&&Bw(I,o),W.current?.close(),W.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),k(!1),w(!1),N(null),_(!1),B.current=!1},[I,o]),qe=a.useCallback(()=>{W.current?.close(),W.current=null,n()},[n]),Ve=a.useCallback(async()=>{if(!((P||c.type==="editing"||c.type==="creating")&&!confirm("Close subtask breakdown? Unsaved changes will be lost."))){if(L)try{await wh(L,o,X)}catch{}Ie(),n()}},[P,n,Ie,L,X,c.type,o]),Ge=a.useCallback(le=>{W.current?.close(),W.current=Sy(le,o,{onThinking:U=>{f(ne=>ne+U),oe({sessionId:le,status:"generating",needsInput:!1,owningTabId:X,type:"subtask",title:I.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:U=>{k(!1),w(!1),Oo(o),m(U),u({type:"editing",sessionId:le}),_(!1),oe({sessionId:le,status:"awaiting_input",needsInput:!0,owningTabId:X,type:"subtask",title:I.trim()||"Subtask breakdown",projectId:o??null})},onError:U=>{const ne=U||"Session failed while contacting the AI.";k(!1),w(!1),N(null),u({type:"error",sessionId:le,errorMessage:ne}),oe({sessionId:le,status:"error",needsInput:!1,owningTabId:X,type:"subtask",title:I.trim()||"Subtask breakdown",projectId:o??null}),F({sessionId:le,status:"error"})},onComplete:()=>{F({sessionId:le,status:"complete"})},onConnectionStateChange:U=>{k(U==="reconnecting")}})},[F,oe,I,o,X]),Ke=a.useCallback(async()=>{if(I.trim()){N(null),g([]),f(""),k(!1);try{const{sessionId:le}=await jy(I.trim(),o);u({type:"generating",sessionId:le}),Ge(le)}catch(le){N(xe(le)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Ge,I,o]);a.useEffect(()=>{if(!e){Ie();return}if(e&&s&&!B.current)y(s),B.current=!0,Ke();else if(e&&!s&&!B.current){const le=Hw(o);le&&y(le)}},[e,s,Ke,Ie]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const le=await Js(l);if(!le)return;const U=Yi(le.conversationHistory);if(g(U),le.status==="generating"||le.status==="awaiting_input")f(le.thinkingOutput??""),u({type:"generating",sessionId:l}),Ge(l);else if(le.status==="complete"&&le.result){Oo(o);const ne=JSON.parse(le.result);m(ne),u({type:"editing",sessionId:l})}else le.status==="error"&&(N(null),u({type:"error",sessionId:l,errorMessage:le.error??"Session encountered an error"}))}catch(le){N(xe(le)||"Failed to resume session")}})()},[Ge,e,l,c.type,o]),a.useEffect(()=>{if(!e){A.current&&(re(A.current,X),A.current=null);return}if(L&&A.current!==L){A.current&&re(A.current,X),de(L,X),A.current=L;return}!L&&A.current&&(re(A.current,X),A.current=null)},[de,re,e,L,X]),a.useEffect(()=>{if(!e||!L||A.current!==L)return;Z(X);const le=setInterval(()=>{Z(X)},3e4);return()=>{clearInterval(le)}},[Z,e,L,X]),a.useEffect(()=>()=>{W.current?.close(),A.current&&(re(A.current,X),A.current=null)},[re,X]),a.useEffect(()=>{if(!e)return;const le=U=>{U.key==="Escape"&&(U.preventDefault(),Ve())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[e,Ve]);const Qe=a.useCallback((le,U)=>{m(ne=>ne.map(ke=>ke.id===le?{...ke,...U}:ke)),_(!0)},[]),Se=a.useCallback(()=>{m(le=>[...le,KM(le.length+1)]),_(!0)},[]),Fe=a.useCallback(le=>{m(U=>U.filter(ne=>ne.id!==le).map(ne=>({...ne,dependsOn:ne.dependsOn.filter(ke=>ke!==le)}))),_(!0)},[]),ie=a.useCallback(le=>U=>{z(le),U.dataTransfer.setData("text/plain",le),U.dataTransfer.effectAllowed="move"},[]),Q=a.useCallback(()=>{z(null),$(null),j(null)},[]),pe=a.useCallback(le=>U=>{if(U.preventDefault(),le===R)return;const ne=U.currentTarget.getBoundingClientRect(),ke=ne.top+ne.height/2,_e=U.clientY<ke?"before":"after";$(le),j(_e)},[R]),te=a.useCallback(le=>U=>{U.preventDefault();const ne=U.dataTransfer.getData("text/plain");if(!ne||ne===le){z(null),$(null),j(null);return}m(ke=>{const _e=ke.findIndex(ze=>ze.id===ne),ge=ke.findIndex(ze=>ze.id===le);if(_e===-1||ge===-1)return ke;const He=[...ke],[ve]=He.splice(_e,1);let $e=ge;return T==="after"&&_e<ge&&$e--,T==="after"&&$e++,He.splice($e,0,ve),He}),_(!0),z(null),$(null),j(null)},[T]),ye=a.useCallback(le=>{const U=le.currentTarget.getBoundingClientRect(),ne=le.clientX,ke=le.clientY;(ne<U.left||ne>U.right||ke<U.top||ke>U.bottom)&&($(null),j(null))},[]),ce=a.useCallback((le,U)=>{U<0||U>=d.length||(m(ne=>{const ke=[...ne],[_e]=ke.splice(le,1);return ke.splice(U,0,_e),ke}),_(!0))},[d.length]),Re=a.useCallback(le=>{K.current[le+1]?.focus()},[]),Ze=a.useCallback(async()=>{if(!(!L||ue)){N(null),u({type:"creating",sessionId:L});try{const le=await Cy(L,d,r,o);i(le.tasks),Ie(),n()}catch(le){N(xe(le)||"Failed to create tasks"),u({type:"editing",sessionId:L})}}},[ue,n,i,r,o,Ie,L,d]),at=a.useCallback(async()=>{if(c.type!=="error")return;const le=c.sessionId;N(null),w(!0),f(""),u({type:"generating",sessionId:le}),Ge(le);try{await wy(le,o,X)}catch(U){let ne=U;if((xe(U)||"").includes("not in an error state"))try{const _e=await Js(le);if(!_e)throw new Error("Failed to refresh subtask session.");if(g(Yi(_e.conversationHistory)),_e.status==="generating"||_e.status==="awaiting_input")f(_e.thinkingOutput??""),u({type:"generating",sessionId:_e.id}),W.current?.isConnected()||Ge(_e.id);else if(_e.status==="complete"){if(!_e.result)throw new Error("Subtask session is complete but has no result.");Oo(o);const ge=JSON.parse(_e.result);m(ge),u({type:"editing",sessionId:_e.id}),_(!1)}else _e.status==="error"&&u({type:"error",sessionId:_e.id,errorMessage:_e.error??"Retry failed. Please try again."});k(!1);return}catch(_e){ne=_e}W.current?.close(),W.current=null,u({type:"error",sessionId:le,errorMessage:xe(ne)||"Retry failed. Please try again."}),k(!1)}finally{w(!1)}},[Ge,o,X,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:le=>le.target===le.currentTarget&&void Ve(),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(io,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ce&&t.jsx("button",{className:"modal-send-to-background",onClick:qe,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ve(),"aria-label":"Close",children:t.jsx(Dt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[E&&t.jsx("div",{className:"form-error planning-error",children:E}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ee&&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:I})]})}),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(it,{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 at(),disabled:M,children:[M?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:M?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ve(),disabled:M,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(tn,{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((le,U)=>{const ne=R===le.id,ke=G===le.id,_e=["task-detail-section","subtask-item",ne?"subtask-item-dragging":"",ke?"subtask-item-drop-target":"",ke&&T==="before"?"subtask-item-drop-before":"",ke&&T==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:_e,"data-testid":`subtask-item-${U}`,draggable:c.type!=="creating",onDragStart:ie(le.id),onDragEnd:Q,onDragOver:pe(le.id),onDrop:te(le.id),onDragLeave:ye,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(cc,{size:16}),t.jsx("strong",{children:le.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ce(U,U-1),disabled:c.type==="creating"||U===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(yi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ce(U,U+1),disabled:c.type==="creating"||U===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Ga,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Fe(le.id),disabled:c.type==="creating",children:[t.jsx(Ht,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:ge=>{K.current[U]=ge},value:le.title,onChange:ge=>Qe(le.id,{title:ge.target.value}),onKeyDown:ge=>{ge.key==="Enter"&&(ge.preventDefault(),Re(U))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:le.description,onChange:ge=>Qe(le.id,{description:ge.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:le.suggestedSize,onChange:ge=>Qe(le.id,{suggestedSize:ge.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,U).filter(ge=>ge.id!==le.id).map(ge=>{const He=le.dependsOn.includes(ge.id);return t.jsxs("label",{className:`planning-dep-chip ${He?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:He,onChange:()=>{const ve=He?le.dependsOn.filter($e=>$e!==ge.id):[...le.dependsOn,ge.id];Qe(le.id,{dependsOn:ve})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:ge.id}),t.jsx("span",{className:"planning-dep-title",children:ge.title||"Untitled"})]},ge.id)}),U===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),U>0&&d.slice(0,U).filter(ge=>ge.id!==le.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},le.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Se,disabled:c.type==="creating",children:[t.jsx(qt,{size:16,className:"icon-mr-6"})," Add subtask"]}),pm(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 Ve(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void Ze(),disabled:c.type==="creating"||ue,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(it,{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(ao,{size:16}),t.jsx("span",{children:we?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),we&&t.jsx("button",{type:"button",onClick:()=>{V()},disabled:fe,className:"btn btn-primary session-lock-take-control",children:fe?"Taking control...":"Take Control"})]})})]})]})}):null}const JM=5,YM=1e3,QM=45e3;function Tr(){return{scrollback:null,connected:null,data:[]}}function XM(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),k=a.useRef(Tr()),M=a.useCallback($=>{p.current.add($);const T=k.current;return T.data.length>0&&(T.data.forEach(j=>$(j)),T.data=[]),()=>p.current.delete($)},[]),w=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),I=a.useCallback($=>{b.current.add($);const T=k.current;return T.connected&&($(T.connected),T.connected=null),()=>b.current.delete($)},[]),y=a.useCallback($=>{v.current.add($);const T=k.current;return T.scrollback&&($(T.scrollback),T.scrollback=null),()=>v.current.delete($)},[]),E=a.useCallback($=>(x.current.add($),()=>x.current.delete($)),[]),N=a.useCallback($=>{const T=u.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:$}))},[]),P=a.useCallback(($,T)=>{const j=u.current;j?.readyState===WebSocket.OPEN&&j.send(JSON.stringify({type:"resize",cols:$,rows:T}))},[]),_=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),k.current=Tr()},[]),R=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),k.current=Tr()},[]),z=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 j=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(j+=`&projectId=${encodeURIComponent(n)}`);const W=new WebSocket(Hs(j));u.current=W,W.onopen=()=>{if(r.current!==$){W.close();return}k.current=Tr(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"ping"}))},QM)},W.onmessage=K=>{if(r.current===$)try{const B=JSON.parse(K.data),A=k.current;switch(B.type){case"data":B.data&&(p.current.size===0&&A.data.push(B.data),p.current.forEach(L=>L(B.data)));break;case"scrollback":B.data&&(A.scrollback=B.data,v.current.forEach(L=>L(B.data)));break;case"connected":B.shell&&B.cwd&&(A.connected={shell:B.shell,cwd:B.cwd},b.current.forEach(L=>L({shell:B.shell,cwd:B.cwd})));break;case"exit":B.exitCode!==void 0&&f.current.forEach(L=>L(B.exitCode));break;case"ping":W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},W.onclose=K=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(K.code===4e3||K.code===4004){i("disconnected"),K.code===4004&&x.current.forEach(L=>L());return}if(d.current++,d.current>JM){i("disconnected");return}const B=YM*Math.pow(2,d.current-1);i("reconnecting");const A=r.current;m.current=setTimeout(()=>{r.current===A&&(g.current||z())},Math.min(B,16e3))},W.onerror=()=>{}},[e,n]),G=a.useCallback(()=>{d.current=0,R(),z()},[R,z]);return a.useEffect(()=>(c&&(_(),d.current=0,i("disconnected")),e?z():i("disconnected"),R),[e,n,c,z,R,_]),{connectionStatus:s,sendInput:N,resize:P,onData:M,onExit:w,onConnect:I,onScrollback:y,reconnect:G,onSessionInvalid:E}}const af="kb-terminal-tabs",ZM=15e3,e_=15e3;function fm(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function gm(e){if(typeof window>"u")return[];try{const n=Nn(af,e);if(n)return JSON.parse(n)}catch{}return[]}function xl(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function bm(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 t_(e){const[n,s]=a.useState(()=>gm(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(gm(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{ts(af,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let I=!1;const y=h.current;return(async()=>{if(!I)try{const N=await bm(yv(e),ZM,"listTerminalSessions");if(I||y!==h.current)return;const P=new Set(N.map(_=>_.id));l(!0),s(_=>{if(I||y!==h.current)return _;const z=_.map(T=>({...T,_verified:P.has(T.sessionId)})).filter(T=>T._verified);if(z.length===0)return[];const G=z.map(({_verified:T,...j})=>j);return G.find(T=>T.isActive)?G:G.map((T,j)=>({...T,isActive:j===0}))}),r(!0)}catch(N){if(I||y!==h.current)return;const P=xl(N);P||console.warn("Failed to validate terminal sessions with server:",N),l(!P),r(!0)}})(),()=>{I=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const I=h.current,y=setTimeout(()=>{bm(hr(void 0,void 0,void 0,e),e_,"createTerminalSession").then(E=>{if(I!==h.current)return;const N={id:fm(),sessionId:E.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(P=>P.length>0?P:[...P.map(R=>({...R,isActive:!1})),N]),u(null)}).catch(E=>{if(I!==h.current)return;xl(E)||console.error(E);const N=E instanceof Error?E.message:typeof E=="string"?E:"Failed to create terminal session";u(N)})},0);return()=>clearTimeout(y)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const I=await hr(void 0,void 0,void 0,e),y={id:fm(),sessionId:I.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(E=>[...E.map(P=>({...P,isActive:!1})),y]),y},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(I=>{s(y=>{const E=y.find(R=>R.id===I);if(!E)return y;ad(E.sessionId,e).catch(R=>{console.warn(`Failed to kill terminal session ${E.sessionId}:`,R)});const N=y.findIndex(R=>R.id===I),P=E.isActive,_=y.filter(R=>R.id!==I);if(_.length===0)return[];if(P){const R=Math.min(N,_.length-1);return _.map((z,G)=>({...z,isActive:G===R}))}return _})},[]),b=a.useCallback(I=>{s(y=>{let E=!1;const N=y.map(P=>P.id===I?(E=!0,{...P,isActive:!0}):{...P,isActive:!1});return E?N:y})},[]),v=a.useCallback((I,y)=>{s(E=>E.map(N=>N.id===I?{...N,title:y}:N))},[]),x=a.useCallback(async()=>{s(E=>{const N=E.find(P=>P.isActive);return N&&ad(N.sessionId,e).catch(P=>{console.warn(`Failed to kill old session ${N.sessionId}:`,P)}),E});const I=n.find(E=>E.isActive);if(!I)return;const y=await hr(void 0,void 0,void 0,e);s(E=>E.map(N=>N.id===I.id?{...N,sessionId:y.sessionId}:N))},[n]),k=a.useCallback(async()=>{const I=n.find(y=>y.isActive);if(I)try{const y=await hr(void 0,void 0,void 0,e);s(E=>E.map(N=>N.id===I.id?{...N,sessionId:y.sessionId}:N)),u(null)}catch(y){xl(y)||console.error(y);const E=y instanceof Error?y.message:typeof y=="string"?y:"Failed to create terminal session";u(E)}},[n]),M=n.find(I=>I.isActive)??null,w=a.useCallback(()=>{u(null),h.current+=1,m(I=>I+1)},[]);return{tabs:n,activeTab:M,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:w,replaceActiveTabSession:k}}const n_=1e4,s_=[500,1500,3e3],rf="kb-terminal-font-size",Pa=14,i_=8,a_=32;function r_(e){if(!e)return"";const n=e.slice(0,1).toUpperCase();return n==="["?"\x1B":n>="A"&&n<="Z"?String.fromCharCode(n.charCodeAt(0)-64):e}function o_(e){return`\x1B${e}`}const l_=[{label:"C",key:"c",description:"SigInt"},{label:"D",key:"d",description:"EOF"},{label:"Z",key:"z",description:"Suspend"},{label:"L",key:"l",description:"Clear"},{label:"R",key:"r",description:"Reverse search"},{label:"A",key:"a",description:"Home"},{label:"E",key:"e",description:"End"},{label:"U",key:"u",description:"Kill line"},{label:"K",key:"k",description:"Kill to EOL"},{label:"W",key:"w",description:"Del word"},{label:".",key:".",description:"Last argument"}];function $a(e){return Math.min(a_,Math.max(i_,e))}function c_(){if(typeof window>"u")return Pa;try{const e=window.localStorage.getItem(rf);if(!e)return Pa;const n=Number.parseInt(e,10);return Number.isFinite(n)?$a(n):Pa}catch{return Pa}}function d_(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 u_(e){return new Promise(n=>setTimeout(n,e))}async function m_(e,n=s_){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!d_(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 u_(o)}throw s??new Error("Dynamic import failed")}function xm(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function h_(){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=p_()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let vl=null;function p_(){return vl===null&&(vl=window.innerHeight),vl}function f_({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),[k,M]=a.useState(()=>c_()),[w,I]=a.useState(!1),[y,E]=a.useState(null),N=a.useRef(null),P=a.useRef(null),_=a.useRef(null),R=a.useRef(null),z=a.useRef(!1),G=a.useRef(!1),$=a.useRef(null),T=a.useRef(()=>{}),j=a.useRef(null),W=a.useRef(0),K=a.useRef(k),B=a.useRef(null),A=a.useRef(i);W.current=f,K.current=k;const L=a.useCallback(U=>{if(U&&G.current!==U)return;const ne=R.current,ke=_.current,_e=$.current;if(!(!ne||!ke)&&!(U&&G.current!==U))try{ne.fit(),_e&&_e(ke.cols,ke.rows)}catch{}},[]);a.useEffect(()=>{e&&p(U=>U+1)},[e]),a.useEffect(()=>{if(!e||!xm())return;const U=window.visualViewport;if(!U)return;const ne=()=>{const ke=h_();b(ke),x(U.height),ke>0&&P.current?.scrollIntoView&&P.current.scrollIntoView({block:"end",behavior:"smooth"}),B.current!==null&&(cancelAnimationFrame(B.current),B.current=null);const _e=typeof G.current=="string"?G.current:void 0;B.current=requestAnimationFrame(()=>{B.current=null,L(_e)})};return ne(),U.addEventListener("resize",ne),U.addEventListener("scroll",ne),()=>{U.removeEventListener("resize",ne),U.removeEventListener("scroll",ne),B.current!==null&&(cancelAnimationFrame(B.current),B.current=null),b(0),x(null)}},[L,e]);const{tabs:X,activeTab:C,isReady:V,bootstrapError:fe,createTab:ae,closeTab:oe,setActiveTab:F,updateTabTitle:de,restartActiveTab:re,retryBootstrap:Z,replaceActiveTabSession:ue}=t_(i),{connectionStatus:Ce,sendInput:he,resize:Ne,onData:ee,onConnect:we,onExit:Ie,onScrollback:qe,reconnect:Ve,onSessionInvalid:Ge}=XM(C?.sessionId??null,i);$.current=Ne,T.current=he,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(rf,String(k))}catch{}},[k]);const Ke=a.useCallback(()=>{const U=_.current;if(U)try{R.current?.fit(),Ne(U.cols,U.rows)}catch{}},[Ne]);a.useEffect(()=>{if(!e||!V)return;const U=C?.sessionId;if(!U)return;const ne=A.current!==i;if(ne&&(A.current=i),G.current===U&&_.current&&!ne)return;_.current&&(G.current!==U||ne)&&(_.current.dispose(),_.current=null,R.current=null,G.current=!1,j.current&&(window.removeEventListener("resize",j.current),j.current=null),d(!1),h(null));let ke=!0,_e;return(async()=>{const He=m_(()=>Promise.all([Wt(()=>import("./vendor-xterm-DzcZoU0P.js").then(me=>me.x),__vite__mapDeps([0,1,2])),Wt(()=>import("./addon-fit-C7jRorKK.js").then(me=>me.a),__vite__mapDeps([3,1])),Wt(()=>import("./addon-web-links-CkJwd4cQ.js").then(me=>me.a),__vite__mapDeps([4,1]))])),ve=new Promise((me,Pe)=>{_e=setTimeout(()=>{Pe(new Error("xterm initialization timed out"))},n_)});let $e,ze;try{const[{Terminal:me},{FitAddon:Pe},{WebLinksAddon:be}]=await Promise.race([He,ve]);if(!ke||!N.current||_.current)return;$e=new me({cursorBlink:!0,cursorStyle:"block",fontSize:K.current,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}),ze=new Pe,$e.loadAddon(ze);const We=new be;if($e.loadAddon(We),!xm())try{const{WebglAddon:wt}=await Wt(async()=>{const{WebglAddon:It}=await import("./addon-webgl-BjvOw43o.js").then(Ut=>Ut.a);return{WebglAddon:It}},__vite__mapDeps([5,1])),Nt=new wt;Nt.onContextLoss(()=>{Nt.dispose()}),$e.loadAddon(Nt)}catch{}$e.open(N.current),_e&&clearTimeout(_e);const tt=N.current?.querySelector(".xterm-helper-textarea");if(tt&&tt.focus(),N.current)try{N.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{ze.fit();const wt=N.current?.querySelector(".xterm-helper-textarea");wt&&wt.focus()},50),_.current=$e,R.current=ze,G.current=U,W.current>0&&(B.current!==null&&(cancelAnimationFrame(B.current),B.current=null),B.current=requestAnimationFrame(()=>{B.current=null,L(U)})),$e.onData(wt=>{G.current===U&&T.current(wt)});const ct=()=>{if(G.current===U&&R.current&&_.current)try{R.current.fit();const{cols:wt,rows:Nt}=_.current;$.current?.(wt,Nt)}catch{}};window.addEventListener("resize",ct),j.current&&window.removeEventListener("resize",j.current),j.current=ct,d(!0),h(null)}catch(me){if(_e&&clearTimeout(_e),!ke)return;const Pe=me instanceof Error?me.message:"xterm initialization failed";h(Pe)}})(),()=>{ke=!1,_e&&clearTimeout(_e)}},[L,e,V,C?.sessionId,i]),a.useEffect(()=>{e||(_.current&&(_.current.dispose(),_.current=null),R.current=null,G.current=!1,j.current&&(window.removeEventListener("resize",j.current),j.current=null),d(!1),h(null),z.current=!1,o(null),c(null),I(!1),E(null))},[e]),a.useEffect(()=>{if(!u||!_.current||!C)return;const U=C.sessionId,ne=ve=>{G.current===U&&_.current?.write(ve)},ke=ee(ve=>{ne(ve)}),_e=qe(ve=>{ne(ve)}),ge=we(ve=>{de(C.id,ve.shell.split("/").pop()||ve.shell)}),He=Ie(ve=>{G.current===U&&(c(ve),_.current?.write(`\r
628
+ \x1B[33m[Process exited with code ${ve}]\x1B[0m\r
629
+ `))});return()=>{ke(),_e(),ge(),He()}},[u,C?.sessionId,C?.id,C,Ce,ee,qe,we,Ie,de]),a.useEffect(()=>{Ce==="connected"&&s&&z.current!==s&&C&&(z.current=s,setTimeout(()=>{he(s+`
630
+ `)},500))},[Ce,s,he,C,g]),a.useEffect(()=>{!u||!_.current||(_.current.options.fontSize=k,Ke())},[k,u,Ke]),a.useEffect(()=>{if(!e)return;const U=ne=>{if(!(!ne.ctrlKey&&!ne.metaKey)){if(ne.code==="Equal"||ne.code==="NumpadAdd"){ne.preventDefault(),M(ke=>$a(ke+1)),Ke();return}if(ne.code==="Minus"||ne.code==="NumpadSubtract"){ne.preventDefault(),M(ke=>$a(ke-1)),Ke();return}if(ne.code==="Digit0"||ne.code==="Numpad0"){ne.preventDefault(),M(Pa),Ke();return}}};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[e,Ke]),a.useEffect(()=>{if(!e)return;const U=ne=>{ne.key==="Escape"&&n()};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[e,n]),a.useEffect(()=>{Ce==="connected"&&_.current&&setTimeout(()=>{if(!_.current||!N.current)return;const U=N.current.querySelector(".xterm-helper-textarea");U&&U.focus();try{N.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[Ce]);const Qe=a.useCallback(()=>{if(!N.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;_.current?.focus();const ne=N.current.querySelector(".xterm-helper-textarea");if(!ne)return;ne.autocapitalize="off",ne.autocomplete="off",ne.autocorrect="off",ne.spellcheck=!1,ne.setAttribute("inputmode","text");try{ne.focus({preventScroll:!0})}catch{ne.focus()}const ke=ne.value.length;ne.setSelectionRange(ke,ke)},[]);a.useEffect(()=>Ge(()=>{_.current?.clear(),c(null),z.current=!1,_.current&&(_.current.dispose(),_.current=null),R.current=null,G.current=!1,j.current&&(window.removeEventListener("resize",j.current),j.current=null),d(!1),h(null),ue().catch(ne=>{console.error("Failed to replace invalid terminal session:",ne)})}),[Ge,ue]);const Se=a.useCallback(U=>{U.target===U.currentTarget&&n()},[n]),Fe=a.useCallback(()=>{_.current?.clear()},[]),ie=a.useCallback(async()=>{_.current?.clear(),c(null),z.current=!1;try{await re()}catch(U){o(xe(U)||"Failed to restart terminal session")}},[re]),Q=a.useCallback(()=>{_.current&&(_.current.dispose(),_.current=null),R.current=null,G.current=!1,j.current&&(window.removeEventListener("resize",j.current),j.current=null),h(null),d(!1)},[]),pe=a.useCallback(()=>{window.location.reload()},[]),te=a.useCallback(()=>{M(U=>$a(U+1)),Ke()},[Ke]),ye=a.useCallback(()=>{M(U=>$a(U-1)),Ke()},[Ke]),ce=a.useCallback(U=>{E(ne=>ne===U?null:U)},[]),Re=a.useCallback(U=>{if(y==="ctrl"){he(r_(U)),E(null);return}if(y==="alt"){he(o_(U)),E(null);return}he(U)},[he,y]),Ze=a.useCallback(U=>{he(U),E(null)},[he]);if(!e)return null;const at=()=>{switch(Ce){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}},le=!V||!C&&!fe||!u&&!m;return t.jsx("div",{className:"modal-overlay open",onClick:Se,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:P,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:[X.map(U=>t.jsxs("div",{className:`terminal-tab ${U.isActive?"terminal-tab--active":""}`,onClick:()=>F(U.id),title:U.title,role:"tab","aria-selected":U.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:U.title}),X.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:ne=>{ne.stopPropagation(),oe(U.id)},title:"Close tab",children:"×"})]},U.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ae,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Bs,{size:16}),at()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[Ce==="disconnected"&&C&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Ve,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(hn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:ie,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(hn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Fe,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Ht,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>I(U=>!U),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":w,children:[t.jsx(ab,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Shortcuts"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(Dt,{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:[le&&!fe&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),fe&&!C&&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: ",fe]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Z,"data-testid":"terminal-retry-btn",children:[t.jsx(hn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:pe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(hn,{size:14}),"Refresh page"]})]})]})}),m&&C&&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:Q,"data-testid":"terminal-reinit-btn",children:[t.jsx(hn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:pe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(hn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:N,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Qe,onTouchStart:Qe},C?.sessionId)]}),w&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${y==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>ce("ctrl"),"aria-pressed":y==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${y==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>ce("alt"),"aria-pressed":y==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Ze("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Ze(" "),children:"Tab"})]}),l_.map(U=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Re(U.key),title:U.description,children:U.label},U.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${Ce}`,children:[Ce==="connected"&&"Connected",Ce==="connecting"&&"Connecting...",Ce==="reconnecting"&&"Reconnecting...",Ce==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:ye,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(jb,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[k,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:te,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(qt,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Na={name:"",command:""};function vm(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function g_(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function b_({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(Na),[b,v]=a.useState(!1),[x,k]=a.useState(null),[M,w]=a.useState(null),I=a.useCallback(async()=>{try{u(!0);const T=await er(i);l(T)}catch(T){s(xe(T)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&I()},[e,I]);const y=a.useCallback(()=>{m(!0),g(null),f(Na),w(null)},[]),E=a.useCallback((T,j)=>{g(T),m(!1),f({name:T,command:j}),w(null)},[]),N=a.useCallback(()=>{g(null),m(!1),f(Na),w(null)},[]),P=a.useCallback(T=>{f(j=>({...j,name:T})),T&&!vm(T)?w("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):w(null)},[]),_=a.useCallback(async()=>{const T=p.name.trim(),j=p.command.trim();if(!T){s("Script name is required","error");return}if(!vm(T)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!j){s("Script command is required","error");return}v(!0);try{await yy(T,j,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Na),w(null),await I()}catch(W){const K=xe(W);K?.includes("already exists")?s("A script with this name already exists","error"):s(K||"Failed to save script","error")}finally{v(!1)}},[p,h,s,I,i]),R=a.useCallback(async T=>{try{await ky(T,i),s("Script deleted","success"),k(null),h===T&&(g(null),f(Na)),await I()}catch(j){s(xe(j)||"Failed to delete script","error")}},[h,s,I,i]),z=a.useCallback((T,j)=>{r&&r(T,j)},[r]);if(!e)return null;const G=d||h!==null,$=Object.entries(o).map(([T,j])=>({name:T,command:j}));return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",onClick:T=>T.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Bs,{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(it,{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:T=>P(T.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:M?"var(--color-error)":void 0}}),M&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:M}),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:T=>f(j=>({...j,command:T.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),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:N,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:b||!!M,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(it,{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:y,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(qt,{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(Bs,{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(T=>t.jsx("div",{className:"script-card","data-testid":`script-${T.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children: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:T.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:T.command,children:g_(T.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:()=>z(T.name,T.command),title:"Run script","aria-label":`Run ${T.name}`,"data-testid":`run-script-${T.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(rn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>E(T.name,T.command),title:"Edit","aria-label":`Edit ${T.name}`,"data-testid":`edit-script-${T.name}`,children:t.jsx(qt,{size:14,style:{transform:"rotate(45deg)"}})}),x===T.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>R(T.name),title:"Confirm delete","aria-label":`Confirm delete ${T.name}`,"data-testid":`confirm-delete-script-${T.name}`,style:{color:"var(--color-error)"},children:t.jsx(Ht,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>k(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${T.name}`,children:t.jsx(Dt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>k(T.name),title:"Delete","aria-label":`Delete ${T.name}`,"data-testid":`delete-script-${T.name}`,children:t.jsx(Ht,{size:14})})]})]})},T.name))})]})})]})})}function x_(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 zv(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(xe(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 v_(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(M=>{o(M),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let M=!1;async function w(){h(!0),b(null);try{const I=await Fv(e,n,i);M||(o(I.content),c(I.content),d(I.mtime))}catch(I){M||(b(xe(I)||"Failed to load file"),o(""),c(""),d(null))}finally{M||h(!1)}}return w(),()=>{M=!0}},[e,n,s,i]);const x=r!==l,k=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const M=await Ov(e,n,r,i);c(r),d(M.mtime)}catch(M){throw b(xe(M)||"Failed to save file"),M}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:k,hasChanges:x,mtime:u}}const y_=1e4;function k_(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function j_(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function w_(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 Lv(e);if(d)return;s(k_(g.project)),r(g.tasks.map(j_)),u(null)}catch(g){d||u(xe(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},y_);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function N_(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function S_(e){return e?new Date(e).toLocaleDateString():""}function ym(e,n){return e==="."?n:`${e}/${n}`}const Sa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},yl={type:null,entry:null,entryFullPath:""},C_=200,E_=500,km=10;function M_({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 k=e-b,M=n-v;k+h.width>p-x&&(k=p-x-h.width),M+h.height>f-x&&(M=f-x-h.height),k<x&&(k=x),M<x&&(M=x),c({x:k+b,y:M+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:wi,disabled:!1},{id:"move",label:"Move",icon:Sb,disabled:!1},{id:"rename",label:"Rename",icon:qn,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:to,disabled:!1}]:[{id:"download",label:"Download",icon:vg,disabled:!1}],{id:"divider",label:"",icon:wi,disabled:!0},{id:"delete",label:"Delete",icon:Ht,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 __({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 A_({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(Sa),[g,p]=a.useState(yl),[f,b]=a.useState(!1),[v,x]=a.useState(null),[k,M]=a.useState(!1),[w,I]=a.useState(null),y=a.useRef(null),E=a.useRef(null),N=a.useRef(null),P=a.useRef(!1),_=a.useCallback(()=>{y.current!==null&&(window.clearTimeout(y.current),y.current=null),E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),R=a.useCallback(()=>{_(),N.current=null,M(!1),I(null)},[_]);a.useEffect(()=>()=>{_()},[_]);const z=a.useCallback((L,X,C,V)=>{h({visible:!0,x:L,y:X,entry:C,entryFullPath:V})},[]),G=a.useCallback((L,X,C)=>{if(L.touches.length!==1)return;const V=L.touches[0];V&&(R(),N.current={x:V.clientX,y:V.clientY},E.current=window.setTimeout(()=>{M(!0),I(C)},C_),y.current=window.setTimeout(()=>{const fe=N.current;fe&&(P.current=!0,M(!1),I(null),_(),z(fe.x,fe.y,X,C))},E_))},[R,_,z]),$=a.useCallback(L=>{const X=N.current,C=L.touches[0];!X||!C||(Math.abs(C.clientX-X.x)>km||Math.abs(C.clientY-X.y)>km)&&R()},[R]),T=a.useCallback(()=>{R()},[R]);a.useEffect(()=>{if(!m.visible)return;const L=document.querySelector(".file-browser-list"),X=()=>{P.current=!1,R(),h(Sa)};return L?.addEventListener("scroll",X),()=>L?.removeEventListener("scroll",X)},[R,m.visible]),a.useEffect(()=>{if(!m.visible)return;const L=X=>{X.key==="Escape"&&(P.current=!1,h(Sa))};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[m.visible]);const j=a.useCallback((L,X)=>{L.preventDefault(),L.stopPropagation(),R(),P.current=!1,z(L.clientX,L.clientY,X,ym(n,X.name))},[R,n,z]),W=a.useCallback(L=>{if(!m.entry)return;P.current=!1;const X=m.entry,C=m.entryFullPath;if(h(Sa),L==="download"){if(!c)return;const V=vh(c,C,d);window.open(Hs(V),"_blank");return}if(L==="download-zip"){if(!c)return;const V=Wv(c,C,d);window.open(Hs(V),"_blank");return}p({type:L,entry:X,entryFullPath:C}),x(null)},[m,c,d]),K=a.useCallback(async L=>{if(!(!g.type||!g.entry||!c)){b(!0),x(null);try{switch(g.type){case"copy":await Bv(c,g.entryFullPath,L,d);break;case"move":await Hv(c,g.entryFullPath,L,d);break;case"rename":await Vv(c,g.entryFullPath,L,d);break;case"delete":await qv(c,g.entryFullPath,d);break}p(yl),u?.()}catch(X){x(xe(X)||"Operation failed")}finally{b(!1)}}},[g,c,u,d]),B=a.useCallback(()=>{p(yl),x(null)},[]),A=a.useCallback((L,X)=>{if(P.current){P.current=!1;return}m.visible||(L.type==="directory"?i(X):s(X))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(it,{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 L=n.split("/").filter(Boolean);L.pop(),i(L.length===0?".":L.join("/"))},children:[t.jsx(en,{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(L=>{const X=ym(n,L.name),C=k&&w===X;return t.jsxs("div",{className:`file-node file-node--${L.type} ${C?"file-node--long-pressing":""}`,onClick:()=>A(L,X),onContextMenu:V=>j(V,L),onTouchStart:V=>G(V,L,X),onTouchMove:$,onTouchEnd:T,onTouchCancel:T,children:[t.jsx("div",{className:"file-node-icon",children:L.type==="directory"?t.jsx(jn,{size:16}):t.jsx(ah,{size:16})}),t.jsx("div",{className:"file-node-name",children:L.name}),L.type==="file"&&L.size!==void 0&&t.jsx("div",{className:"file-node-size",children:N_(L.size)}),L.mtime&&t.jsx("div",{className:"file-node-time",children:S_(L.mtime)})]},L.name)})}),m.visible&&m.entry&&t.jsx(M_,{x:m.x,y:m.y,entry:m.entry,onAction:W,onClose:()=>{P.current=!1,h(Sa)}}),g.type&&g.entry&&t.jsx(__,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:K,onCancel:B,loading:f,error:v})]})}function T_(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function R_({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=T_(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(ih,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Vi,{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(Or,{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(Or,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],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 I_(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function P_({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(Yc,{size:14}):t.jsx(Rl,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Lt,{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(Yc,{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(Rl,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:I_(c.title)})]},c.id))]})]})]})}const $_=768,of=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),D_=new Set([...of,".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 jm(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return D_.has(n)}function L_(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return of.has(n)}function z_({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=w_(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:k,refresh:M}=x_(l,!0,i),{content:w,setContent:I,originalContent:y,loading:E,saving:N,error:P,save:_,hasChanges:R,mtime:z}=v_(l,u,!0,i);a.useEffect(()=>{c(e)},[e]),a.useEffect(()=>{const L=()=>{h(window.innerWidth<=$_)};return L(),window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[]),a.useEffect(()=>{u||p("list")},[u]),a.useEffect(()=>{const L=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),R&&!N&&_())};return document.addEventListener("keydown",L),()=>document.removeEventListener("keydown",L)},[n,R,N,_]);const G=a.useCallback(L=>{d(L),m&&p("editor")},[m]),$=a.useCallback(()=>{p("list")},[]),T=a.useCallback(()=>{I(y)},[y,I]),j=a.useCallback(L=>{c(L),d(null),p("list"),s?.(L)},[s]),K=`Files — ${a.useMemo(()=>l==="project"?"Project":o.find(L=>L.id===l)?.id??l,[l,o])}`,B=a.useMemo(()=>!u||!L_(u)?null:vh(l,u,i),[u,l,i]),A=L=>{const X=new Blob([L]).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:L=>L.stopPropagation(),children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(jn,{size:18}),t.jsx("span",{children:K}),u&&t.jsx("span",{className:"file-browser-header-path",children:u})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(P_,{currentWorkspace:l,projectName:r,workspaces:o,onSelect:j}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Dt,{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(A_,{entries:f,currentPath:b,onSelectFile:G,onNavigate:v,loading:x,error:k,onRetry:M,workspace:l,onRefresh:M,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(ia,{size:16}),t.jsx("span",{children:"Back"})]}),u,jm(u)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(zg,{size:12}),"Binary file — read only"]}),z&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(z).toLocaleString()]}),E&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!B&&R&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:T,disabled:N,children:[t.jsx(Lb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void _(),disabled:N,children:[t.jsx(uh,{size:14}),N?"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(R_,{content:w,onChange:I,filePath:u,readOnly:jm(u)})}),!B&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:A(w)}),R&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(jn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function F_(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 ev();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:xe(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 O_(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 U_(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const lf="kb-usage-hidden-windows";function wm(e){const n=Nn(lf,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function B_(e,n){ts(lf,JSON.stringify(e),n)}function cf(e,n,s){return s[e]?.includes(n)??!1}function H_({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=U_(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const x=Math.floor(v/36e5),k=Math.floor(x/24),M=x%24;k>0&&M>0?d=`resets in ${k}d ${M}h`:k>0?d=`resets in ${k}d`:x>0?d=`resets in ${x}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=m?.status==="behind",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`${s?"Show":"Hide"} ${e.label}`,"data-testid":"usage-window-hide-btn",children:s?t.jsx(Lr,{size:14}):t.jsx(Vi,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${g}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:O_(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(dc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(Zb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function q_(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":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function V_({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return null;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(Mn,{provider:q_(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name})]}),t.jsxs("div",{className:"usage-provider-actions",children:[l(),o>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",o,")"]})]})]}),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((c,u)=>{const d=cf(e.name,c.label,s);return t.jsx(H_,{window:c,viewMode:n,isHidden:d,onToggleHidden:()=>i(e.name,c.label)},`${e.name}-${c.label}-${u}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function W_(){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 K_({isOpen:e,onClose:n,projectId:s}){const{providers:i,loading:r,error:o,lastUpdated:l,refresh:c}=F_({autoRefresh:e}),[u,d]=a.useState(!1),[m,h]=a.useState("used"),[g,p]=a.useState(()=>wm(s)),f=a.useRef(null),b=a.useRef(e),v=a.useRef(!1);a.useEffect(()=>{e||(v.current=!1)},[e]),a.useEffect(()=>{i.length>0&&(v.current=!0)},[i.length]),a.useEffect(()=>{!b.current&&e&&(!l||Date.now()-l.getTime()>5e3)&&c(),b.current=e},[e,l,c]),a.useEffect(()=>{const y=Nn("kb-usage-view-mode",s);if(y==="used"||y==="remaining"){h(y);return}h("used")},[s]);const x=a.useCallback(y=>{h(y),ts("kb-usage-view-mode",y,s)},[s]);a.useEffect(()=>{p(wm(s))},[s]),a.useEffect(()=>{B_(g,s)},[g,s]);const k=a.useCallback((y,E)=>{p(N=>{if(cf(y,E,N)){const P=(N[y]??[]).filter(_=>_!==E);if(P.length===0){const{[y]:_,...R}=N;return R}return{...N,[y]:P}}return{...N,[y]:[...N[y]??[],E]}})},[]),M=a.useCallback(y=>{p(E=>{if(!E[y])return E;const{[y]:N,...P}=E;return P})},[]),w=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 I=a.useCallback(y=>{y.target===y.currentTarget&&n()},[n]);return e?t.jsx("div",{className:"modal-overlay open",onClick:I,"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:()=>x("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:()=>x("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(Dt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:f,children:(r||!v.current&&!o)&&i.length===0?t.jsx(W_,{}):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:w,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(V_,{provider:y,viewMode:m,hiddenWindows:g,onToggleWindow:k,onShowAllHidden: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:w,disabled:r||u,"data-testid":"usage-refresh-btn",children:[t.jsx(hn,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function df(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 Xr(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 G_={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},uf={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},J_={cron:th,webhook:hh,api:nh,manual:vn},Y_={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},Q_={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function X_({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(tn,{size:12}):t.jsx(Ya,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:df(n)})]})}function Z_({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"} ${Xr(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(tn,{size:12}):t.jsx(Ya,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Xr(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:uf[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:df(r)}),s?t.jsx(Ys,{size:12}):t.jsx(Lt,{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 eA({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=G_[e.trigger.type],m=J_[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}),uf[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(so,{size:10}):t.jsx(jn,{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(rn,{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(Fs,{size:14}):t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(qn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:u,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Ht,{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(ji,{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:Y_[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:Q_[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:Xr(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:Xr(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(X_,{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(Ys,{size:12}):t.jsx(Lt,{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(Z_,{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 tA({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Bs,{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(ub,{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(Dn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function kl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function nA(e){return e==="command"?{id:kl(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:kl(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:kl(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function sA({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,k]=a.useState(e.taskDescription??""),[M,w]=a.useState(e.taskColumn??"triage"),[I,y]=a.useState(e.timeoutMs),[E,N]=a.useState(e.continueOnFailure??!1),[P,_]=a.useState({}),[R,z]=a.useState([]),[G,$]=a.useState(!1),[T,j]=a.useState(null);a.useEffect(()=>{let L=!1;return $(!0),j(null),is().then(X=>{L||z(X.models)}).catch(X=>{L||j(X instanceof Error?X.message:"Failed to load models")}).finally(()=>{L||$(!1)}),()=>{L=!0}},[]);const W=a.useCallback(()=>{const L={};return i.trim()||(L.name="Step name is required"),o==="command"&&!c.trim()&&(L.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(L.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(L.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(L.modelProvider="Both model provider and model ID must be set together"),I!==void 0&&I<1e3&&(L.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(L),Object.keys(L).length===0},[i,o,c,d,x,h,p,I]),K=h&&p?`${h}/${p}`:"",B=a.useCallback(L=>{if(!L)g(""),f("");else{const X=L.indexOf("/");X!==-1&&(g(L.slice(0,X)),f(L.slice(X+1)))}},[]),A=a.useCallback(()=>{if(!W())return;const L={...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"?M: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:I||void 0,continueOnFailure:E};o!=="ai-prompt"&&delete L.prompt,o!=="create-task"&&(delete L.taskTitle,delete L.taskDescription,delete L.taskColumn),n(L)},[W,n,e,i,o,c,d,b,x,M,h,p,I,E]);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:L=>r(L.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:L=>l(L.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:L=>u(L.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:L=>m(L.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(wn,{id:`step-model-${e.id}`,label:"Model",models:R,value:K,onChange:B,placeholder:"Use default",disabled:G}),T&&t.jsx("small",{className:"field-error",children:T}),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:L=>v(L.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:L=>k(L.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:M,onChange:L=>w(L.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(wn,{id:`step-task-model-${e.id}`,label:"Model",models:R,value:K,onChange:B,placeholder:"Use default",disabled:G}),T&&t.jsx("small",{className:"field-error",children:T}),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:I??"",onChange:L=>y(L.target.value?Number(L.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:E,onChange:L=>N(L.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:A,children:"Save Step"})]})]})}function iA({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=nA(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(sA,{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(cc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(tA,{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(Ys,{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(Lt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(qn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Ht,{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(qt,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(qt,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(qt,{size:14}),"Add Create Task Step"]})]})]})}const mf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},aA={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function rA(e){const n=e.trim();for(const[s,i]of Object.entries(mf))if(i===n)return s;return"custom"}function oA(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function lA(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 cA(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 dA=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],uA=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Nm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Sm({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?cA(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":rA(c.cronExpression)),[k,M]=a.useState(c.webhookPath),[w,I]=a.useState(c.webhookSecret),[y,E]=a.useState(c.endpoint),[N,P]=a.useState(e?.executionPolicy??"queue"),[_,R]=a.useState(e?.catchUpPolicy??"run_one"),[z,G]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,T=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[j,W]=a.useState(e?.steps&&e.steps.length>0&&!$&&!T?"advanced":"simple"),[K,B]=a.useState(()=>$?"ai-prompt":T?"create-task":"command"),[A,L]=a.useState(e?.command??""),[X,C]=a.useState(e?.steps??[]),[V,fe]=a.useState(!1),[ae,oe]=a.useState(e?.timeoutMs??3e5),[F,de]=a.useState($?e.steps?.[0]?.prompt??"":""),[re,Z]=a.useState(T?e.steps?.[0]?.taskTitle??"":""),[ue,Ce]=a.useState(T?e.steps?.[0]?.taskDescription??"":""),[he,Ne]=a.useState(T?e.steps?.[0]?.taskColumn??"triage":"triage"),[ee,we]=a.useState($||T?e.steps?.[0]?.modelProvider??"":""),[Ie,qe]=a.useState($||T?e.steps?.[0]?.modelId??"":""),[Ve,Ge]=a.useState([]),[Ke,Qe]=a.useState(!1),[Se,Fe]=a.useState(null),[ie,Q]=a.useState(i??"global"),[pe,te]=a.useState({}),[ye,ce]=a.useState(!1),Re=a.useRef(!0);a.useEffect(()=>()=>{Re.current=!1},[]),a.useEffect(()=>{i&&Q(i)},[i]),a.useEffect(()=>{let be=!1;return Qe(!0),Fe(null),is().then(We=>{be||Ge(We.models)}).catch(We=>{be||Fe(We instanceof Error?We.message:"Failed to load models")}).finally(()=>{be||Qe(!1)}),()=>{be=!0}},[]);const Ze=ee&&Ie?`${ee}/${Ie}`:"",at=a.useCallback(be=>{if(!be){we(""),qe("");return}const We=be.indexOf("/");We!==-1&&(we(be.slice(0,We)),qe(be.slice(We+1)))},[]),le=a.useCallback(()=>{const be={};if(u.trim()||(be.name="Name is required"),ie==="project"&&!r&&(be.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?oA(f)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),g==="webhook"&&!k.trim()&&(be.webhookPath="Webhook path is required"),g==="api"&&!y.trim()&&(be.endpoint="API endpoint is required"),j==="simple")K==="command"&&!A.trim()&&(be.command="Command is required"),K==="ai-prompt"&&!F.trim()&&(be.prompt="Prompt is required"),K==="create-task"&&!ue.trim()&&(be.taskDescription="Task description is required"),(ee.trim()&&!Ie.trim()||!ee.trim()&&Ie.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"),V&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const We=[];X.forEach((tt,ct)=>{tt.name?.trim()||We.push(`Step ${ct+1}: Name is required`),tt.type==="command"&&!tt.command?.trim()&&We.push(`Step ${ct+1}: Command is required`),tt.type==="ai-prompt"&&!tt.prompt?.trim()&&We.push(`Step ${ct+1}: Prompt is required`),tt.type==="create-task"&&!tt.taskDescription?.trim()&&We.push(`Step ${ct+1}: Task description is required`)}),We.length>0&&(be.steps=We.join("; "))}return ae<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),te(be),Object.keys(be).length===0},[u,g,f,v,k,y,ie,r,j,K,A,F,ue,ee,Ie,X,V,ae]),U=a.useCallback(async be=>{if(be.preventDefault(),!!le()){ce(!0);try{let We=e?.scope??ie??(r?"project":"global");We==="project"&&!r&&(We="global");const tt=lA(g,f,k,w,y);let ct,wt;j==="simple"?K==="command"?ct=A.trim()||void 0:K==="ai-prompt"?wt=[{id:Nm(),type:"ai-prompt",name:u.trim(),prompt:F.trim(),modelProvider:ee.trim()||void 0,modelId:Ie.trim()||void 0}]:wt=[{id:Nm(),type:"create-task",name:u.trim(),taskTitle:re.trim()||void 0,taskDescription:ue.trim(),taskColumn:he,modelProvider:ee.trim()||void 0,modelId:Ie.trim()||void 0}]:wt=X;const Nt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:tt,command:ct,steps:wt,timeoutMs:ae,executionPolicy:N,catchUpPolicy:_,enabled:z,scope:We};await n(Nt)}finally{Re.current&&ce(!1)}}},[le,n,u,m,g,f,k,w,y,j,K,A,F,ee,Ie,re,ue,he,X,ae,N,_,z,ie,r,e?.scope,e?.agentId]),ne="routine-name-error",ke="routine-cron-error",_e="routine-webhook-error",ge="routine-endpoint-error",He="routine-command-error",ve="routine-prompt-error",$e="routine-task-description-error",ze="routine-model-error",me="routine-timeout-error",Pe=a.useCallback(be=>{x(be),be!=="custom"&&b(mf[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:U,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":!!pe.name,"aria-describedby":pe.name?ne:void 0}),pe.name&&t.jsx("small",{id:ne,className:"field-error",children:pe.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${ie==="global"?" active":""}`,onClick:()=>{Q("global"),o?.("global")},role:"radio","aria-checked":ie==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(so,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ie==="project"?" active":""}`,onClick:()=>{Q("project"),o?.("project")},role:"radio","aria-checked":ie==="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(jn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ie==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),pe.scope&&t.jsx("small",{className:"field-error",children:pe.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(th,{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(hh,{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(nh,{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(vn,{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=>Pe(be.target.value),children:Object.entries(aA).map(([be,We])=>t.jsx("option",{value:be,children:We},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":!!pe.cronExpression,"aria-describedby":pe.cronExpression?ke:void 0}),pe.cronExpression?t.jsx("small",{id:ke,className:"field-error",children:pe.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:k,onChange:be=>M(be.target.value),"aria-invalid":!!pe.webhookPath,"aria-describedby":pe.webhookPath?_e:void 0}),pe.webhookPath?t.jsx("small",{id:_e,className:"field-error",children:pe.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:w,onChange:be=>I(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:y,onChange:be=>E(be.target.value),"aria-invalid":!!pe.endpoint,"aria-describedby":pe.endpoint?ge:void 0}),pe.endpoint?t.jsx("small",{id:ge,className:"field-error",children:pe.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${j==="simple"?" active":""}`,onClick:()=>W("simple"),role:"radio","aria-checked":j==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${j==="advanced"?" active":""}`,onClick:()=>W("advanced"),role:"radio","aria-checked":j==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:j==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),j==="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${K==="command"?" active":""}`,onClick:()=>B("command"),role:"radio","aria-checked":K==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="ai-prompt"?" active":""}`,onClick:()=>B("ai-prompt"),role:"radio","aria-checked":K==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="create-task"?" active":""}`,onClick:()=>B("create-task"),role:"radio","aria-checked":K==="create-task",children:"Create Task"})]})]}),K==="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:A,onChange:be=>L(be.target.value),"aria-invalid":!!pe.command,"aria-describedby":pe.command?He:void 0}),pe.command?t.jsx("small",{id:He,className:"field-error",children:pe.command}):t.jsx("small",{children:"Shell command to execute."})]}):K==="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=>de(be.target.value),rows:3,"aria-invalid":!!pe.prompt,"aria-describedby":pe.prompt?ve:void 0}),pe.prompt?t.jsx("small",{id:ve,className:"field-error",children:pe.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(wn,{id:"routine-model",label:"Model",models:Ve,value:Ze,onChange:at,placeholder:"Use default",disabled:Ke}),Se&&t.jsx("small",{className:"field-error",children:Se}),pe.model&&t.jsx("small",{id:ze,className:"field-error",children:pe.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:re,onChange:be=>Z(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:ue,onChange:be=>Ce(be.target.value),rows:4,"aria-invalid":!!pe.taskDescription,"aria-describedby":pe.taskDescription?$e:void 0}),pe.taskDescription?t.jsx("small",{id:$e,className:"field-error",children:pe.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:he,onChange:be=>Ne(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(wn,{id:"routine-task-model",label:"Executor Model",models:Ve,value:Ze,onChange:at,placeholder:"Use default",disabled:Ke}),Se&&t.jsx("small",{className:"field-error",children:Se}),pe.model&&t.jsx("small",{id:ze,className:"field-error",children:pe.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(iA,{steps:X,onChange:C,onEditingChange:fe}),pe.steps&&t.jsx("small",{className:"field-error",children:pe.steps}),pe.stepsEditing&&t.jsx("small",{className:"field-error",children:pe.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:ae,onChange:be=>oe(Number(be.target.value)),"aria-invalid":!!pe.timeoutMs,"aria-describedby":pe.timeoutMs?me:void 0}),pe.timeoutMs?t.jsx("small",{id:me,className:"field-error",children:pe.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:N,onChange:be=>P(be.target.value),children:dA.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=>R(be.target.value),children:uA.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:z,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:ye,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:ye,children:ye?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const mA=3e4;function hA({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 R=await dy(p);l(R)}catch(R){n(xe(R)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const R=setInterval(()=>{f()},mA);return()=>clearInterval(R)},[f]),a.useEffect(()=>{const R=z=>{z.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,c]);const b=a.useCallback(R=>{R.target===R.currentTarget&&e()},[e]),v=a.useCallback(async R=>{try{await uy(R,p),n("Routine created","success"),u("list"),await f()}catch(z){n(xe(z)||"Failed to create routine","error")}},[n,f,p]),x=a.useCallback(R=>{m(R),u("edit")},[]),k=a.useCallback(async R=>{if(d)try{await ud(d.id,R,p),n("Routine updated","success"),u("list"),m(void 0),await f()}catch(z){n(xe(z)||"Failed to update routine","error")}},[d,n,f,p]),M=a.useCallback(async R=>{try{await my(R.id,p),n(`Deleted "${R.name}"`,"success"),await f()}catch(z){n(xe(z)||"Failed to delete routine","error")}},[n,f,p]),w=a.useCallback(async R=>{g(R.id);try{const{result:z}=await hy(R.id,p);z.success?n(`"${R.name}" completed successfully`,"success"):n(`"${R.name}" failed: ${z.error||"Unknown error"}`,"error"),await f()}catch(z){n(xe(z)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),I=a.useCallback(async R=>{try{await ud(R.id,{enabled:!R.enabled},p),n(`"${R.name}" ${R.enabled?"disabled":"enabled"}`,"success"),await f()}catch(z){n(xe(z)||"Failed to toggle routine","error")}},[n,f,p]),y=a.useCallback(()=>{u("list"),m(void 0)},[]),E=a.useCallback(R=>{r(R),u("list"),m(void 0)},[]),N=()=>c==="create"?t.jsx(Sm,{onSubmit:v,onCancel:y,scope:i,projectId:s}):c==="edit"&&d?t.jsx(Sm,{routine:d,onSubmit:k,onCancel:y,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(vn,{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(qt,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(R=>t.jsx(eA,{routine:R,onEdit:x,onDelete:M,onRun:w,onToggle:I,running:h===R.id},R.id))}),P=()=>N(),_=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(vn,{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(qt,{size:14}),"New Automation"]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Dt,{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:()=>E("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(so,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(jn,{size:14}),"Project"]})]})})]}),t.jsxs("div",{className:"scheduling-summary","aria-live":"polite",children:[t.jsx(vn,{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(vn,{size:14})," Routines"]})}),t.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:P()})]})})}const pA=3e4,nc=new Map,jl=new Map;function Cm(e){return e??"default"}function Em(e){const n=nc.get(e);return n?Date.now()>=n.expiresAt?(nc.delete(e),null):n:null}function fA(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 gA(e){const n=jl.get(e);if(n)return n;const s=qa().then(({providers:i,ghCli:r})=>{const l={...fA(i,r),ghCli:r,expiresAt:Date.now()+pA};return nc.set(e,l),l}).finally(()=>{jl.delete(e)});return jl.set(e,s),s}function hf(e){const n=Cm(e),s=Em(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=Cm(e),p=Em(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 gA(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 pf({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(Dt,{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 bA({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(""),[k,M]=a.useState(""),[w,I]=a.useState(""),[y,E]=a.useState(""),[N,P]=a.useState(""),[_,R]=a.useState("default"),[z,G]=a.useState(!1),[$,T]=a.useState([]),[j,W]=a.useState(!1),[K,B]=a.useState(void 0),[A,L]=a.useState(cs),[X,C]=a.useState(null),[V,fe]=a.useState([]),[ae,oe]=a.useState(!1),[F,de]=a.useState(!1),re=a.useRef(null),[Z,ue]=a.useState(!1),[Ce,he]=a.useState(""),Ne=a.useRef(null),{hasAiProvider:ee,hasGithub:we,loading:Ie}=hf(s),qe=a.useCallback(ce=>{W(!0),T(ce)},[]),Ve=a.useCallback(()=>{W(!1)},[]),Ge=a.useCallback(async()=>{if(V.length>0){oe(!0);return}de(!0);try{const ce=await oa(void 0,s);fe(ce),oe(!0)}catch(ce){const Re=xe(ce);o(Re?`Failed to load agents: ${Re}`:"Failed to load agents","error"),oe(!1)}finally{de(!1)}},[V.length,s,o]);a.useEffect(()=>{if(!ae)return;const ce=Re=>{re.current&&!re.current.contains(Re.target)&&oe(!1)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[ae]),a.useEffect(()=>{if(!Z)return;const ce=Re=>{Ne.current&&!Ne.current.contains(Re.target)&&(ue(!1),he(""))};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[Z]);const Ke=i.filter(ce=>!m.includes(ce.id)).sort((ce,Re)=>{const Ze=Re.createdAt.localeCompare(ce.createdAt);if(Ze!==0)return Ze;const at=parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0;return(parseInt(Re.id.slice(Re.id.lastIndexOf("-")+1),10)||0)-at}),Qe=Ce?Ke.filter(ce=>ce.id.toLowerCase().includes(Ce.toLowerCase())||ce.title&&ce.title.toLowerCase().includes(Ce.toLowerCase())||ce.description&&ce.description.toLowerCase().includes(Ce.toLowerCase())):Ke,Se=(ce,Re)=>ce.length>Re?ce.slice(0,Re)+"…":ce;a.useEffect(()=>{const ce=u.trim()!==""||m.length>0||g.length>0||v!==""||k!==""||w!==""||y!==""||$.length>0||X!==null||K!==void 0||A!==cs;G(ce)},[u,m,g,v,k,w,y,$,X,K,A]);const Fe=a.useCallback(()=>{z&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(ce=>URL.revokeObjectURL(ce.previewUrl)),p([]),d(""),h([]),x(""),M(""),I(""),E(""),P(""),R("default"),T([]),W(!1),C(null),oe(!1),B(void 0),L(cs),G(!1),n())},[z,n,g]),ie=a.useCallback(async()=>{const ce=u.trim();if(!(!ce||f)){b(!0);try{const Re=v.indexOf("/"),Ze=k.indexOf("/"),at=w.indexOf("/"),le=await r({title:void 0,description:ce,column:"triage",dependencies:m.length?m:void 0,enabledWorkflowSteps:j?$.length>0?$:[]:void 0,...X?{assignedAgentId:X}:{},modelPresetId:_==="preset"&&N||void 0,modelProvider:v&&Re!==-1?v.slice(0,Re):void 0,modelId:v&&Re!==-1?v.slice(Re+1):void 0,validatorModelProvider:k&&Ze!==-1?k.slice(0,Ze):void 0,validatorModelId:k&&Ze!==-1?k.slice(Ze+1):void 0,planningModelProvider:w&&at!==-1?w.slice(0,at):void 0,planningModelId:w&&at!==-1?w.slice(at+1):void 0,thinkingLevel:y!==""?y:void 0,reviewLevel:K,priority:A});if(g.length>0){const U=[];for(const ne of g)try{await Ha(le.id,ne.file,s)}catch{U.push(ne.file.name)}U.length>0&&o(`Failed to upload: ${U.join(", ")}`,"error")}g.forEach(U=>URL.revokeObjectURL(U.previewUrl)),p([]),d(""),h([]),x(""),M(""),I(""),E(""),P(""),R("default"),T([]),W(!1),C(null),oe(!1),B(void 0),L(cs),o(`Created ${le.id}`,"success"),n()}catch(Re){o(xe(Re)||"Failed to create task","error")}finally{b(!1)}}},[u,m,g,v,k,w,y,f,r,o,n,s,_,N,$,j,X,K,A]),Q=a.useCallback(ce=>{ce.key==="Escape"&&(ce.preventDefault(),Fe())},[Fe]),te=(X?V.find(ce=>ce.id===X):void 0)?.name??X,ye=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:Ne,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ue(ce=>!ce),disabled:f,"data-testid":"dep-trigger",children:m.length>0?`${m.length} selected`:"Add dependencies"}),Z&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ce,onChange:ce=>he(ce.target.value),onClick:ce=>ce.stopPropagation()}),Qe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Qe.map(ce=>t.jsxs("div",{className:`dep-dropdown-item${m.includes(ce.id)?" selected":""}`,onClick:()=>{h(m.includes(ce.id)?m.filter(Re=>Re!==ce.id):[...m,ce.id]),ue(!1),he("")},onMouseDown:Re=>Re.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ce.id}),t.jsx("span",{className:"dep-dropdown-title",children:Se(ce.title||ce.description||ce.id,30)})]},ce.id))]})]}),m.length>0&&t.jsx("div",{className:"selected-deps",children:m.map(ce=>t.jsxs("span",{className:"dep-chip",children:[ce,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(m.filter(Re=>Re!==ce)),disabled:f,children:"×"})]},ce))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:re,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ae?oe(!1):Ge()},disabled:f,"data-testid":"new-task-agent-button",children:[t.jsx(an,{size:12,style:{verticalAlign:"middle"}}),te?` ${te}`:" Assign agent"]}),ae&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ce=>ce.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&&V.filter(ce=>ce.state!=="terminated").map(ce=>t.jsxs("div",{className:`dep-dropdown-item${X===ce.id?" selected":""}`,onMouseDown:Re=>Re.preventDefault(),onClick:()=>{C(ce.id===X?null:ce.id),oe(!1)},"data-testid":`agent-option-${ce.id}`,children:[t.jsx(an,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ce.role}),t.jsx("span",{className:"dep-dropdown-title",children:ce.name})]},ce.id)),!F&&V.filter(ce=>ce.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),X&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ce=>ce.preventDefault(),onClick:()=>{C(null),oe(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Fe,onKeyDown:Q,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ce=>ce.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Fe,disabled:f,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Ie&&t.jsx(pf,{hasAiProvider:ee,hasGithub:we}),t.jsx(sf,{mode:"create",description:u,onDescriptionChange:d,dependencies:m,onDependenciesChange:h,executorModel:v,onExecutorModelChange:x,validatorModel:k,onValidatorModelChange:M,presetMode:_,onPresetModeChange:R,selectedPresetId:N,onSelectedPresetIdChange:P,selectedWorkflowSteps:$,onWorkflowStepsChange:qe,onDefaultOnApplied:Ve,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Fe,planningModel:w,onPlanningModelChange:I,thinkingLevel:y,onThinkingLevelChange:E,reviewLevel:K,onReviewLevelChange:B,priority:A,onPriorityChange:L,renderBelowPrimary:ye,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Fe,disabled:f,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ie,disabled:!u.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const xA=5e3;function vA(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 M;o?M=await vd({limit:i,projectId:n,type:s}):M=(await md({limit:i,type:s,projectId:n})).map(I=>({...I,projectId:n??"",projectName:""})),c(M),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let M;o?M=await vd({limit:i,projectId:n,type:s,since:b.current}):M=(await md({limit:i,type:s,since:b.current,projectId:n})).map(I=>({...I,projectId:n??"",projectName:""})),c(w=>[...w,...M]),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),k=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},xA),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:k,hasMore:g,loadMore:x}}const wl={"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"},yA={"task:created":t.jsx(qt,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Ja,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(hn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Dt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(tn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ya,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Ba,{size:14,className:"activity-icon settings"})};function kA(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 jA({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:k,error:M,refresh:w,hasMore:I}=vA({projectId:b,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),y=x.map(R=>({id:R.id,timestamp:R.timestamp,type:R.type,taskId:R.taskId,taskTitle:R.taskTitle,details:R.details,metadata:R.metadata,projectId:R.projectId,projectName:R.projectName})),E=async()=>{try{await py(),w(),p(!1)}catch{p(!1)}},N=R=>{i&&i(R)},P=R=>{h(R),l?.(R==="all"?void 0:R)};a.useEffect(()=>{if(!e)return;const R=z=>{z.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n,g]);const _=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:R=>{R.target===R.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children: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(Ua,{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(jn,{size:14}),t.jsxs("select",{value:m,onChange:R=>P(R.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(R=>t.jsx("option",{value:R.id,children:R.name},R.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(zr,{size:14}),t.jsxs("select",{value:u,onChange:R=>d(R.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(wl).map(([R,z])=>t.jsx("option",{value:R,children:z},R))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>w(),title:"Refresh","data-testid":"activity-refresh",children:k?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14})}),y.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Ht,{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(R=>R.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",wl[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:[M&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(ss,{size:16}),t.jsx("span",{children:M})]}),y.length===0&&!k&&!M&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Ua,{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:y.map(R=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:yA[R.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:wl[R.type]}),t.jsx("span",{className:"activity-log-entry-time",children:kA(R.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[R.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>N(R.taskId),"data-testid":"activity-task-link",children:R.taskId}),R.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:R.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:R.details})]}),R.metadata&&Object.keys(R.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof R.metadata.from=="string"&&typeof R.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[R.metadata.from," → ",R.metadata.to]}),typeof R.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${R.metadata.merged?"success":"error"}`,children:R.metadata.merged?"Merged":"Not merged"})]})]})]},R.id))}),I&&!k&&t.jsx("button",{className:"activity-log-load-more",onClick:w,"data-testid":"activity-load-more",children:"Load More"}),k&&y.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(it,{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:E,children:"Clear Log"})]})]})})]})}):null}const Ca=[{id:"status",label:"Status",icon:dh},{id:"changes",label:"Changes",icon:sh},{id:"commits",label:"Commits",icon:Oa},{id:"branches",label:"Branches",icon:Os},{id:"worktrees",label:"Worktrees",icon:Xg},{id:"stashes",label:"Stashes",icon:to},{id:"remotes",label:"Remotes",icon:rh}];function Mm({status:e}){switch(e){case"added":case"untracked":return t.jsx(Ig,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(ih,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Ag,{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($g,{size:14,className:"gm-file-icon"})}}function _m({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 wA(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 Zi(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 NA({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=wA(i),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,k]=a.useState(new Set),[M,w]=a.useState(""),[I,y]=a.useState(!1),[E,N]=a.useState(null),[P,_]=a.useState(!1),[R,z]=a.useState(null),[G,$]=a.useState(null),T=a.useRef(0),[j,W]=a.useState([]),[K,B]=a.useState(null),[A,L]=a.useState(null),[X,C]=a.useState(!1),[V,fe]=a.useState(20),[ae,oe]=a.useState(""),[F,de]=a.useState([]),[re,Z]=a.useState(""),[ue,Ce]=a.useState(""),[he,Ne]=a.useState(""),[ee,we]=a.useState(null),[Ie,qe]=a.useState([]),[Ve,Ge]=a.useState(!1),[Ke,Qe]=a.useState(null),[Se,Fe]=a.useState(null),[ie,Q]=a.useState(!1),[pe,te]=a.useState([]),[ye,ce]=a.useState([]),[Re,Ze]=a.useState(""),[at,le]=a.useState(null),[U,ne]=a.useState(null),[ke,_e]=a.useState(null),ge=a.useCallback(async()=>{if(e){u(!0),m(null);try{switch(o){case"status":{const S=await As(r);f(S);break}case"changes":{const[S,q]=await Promise.all([As(r),$i(r)]);f(S),v(q),k(new Set),$(null),N(null),z(null);break}case"commits":{const S=await kv(V,r);W(S);break}case"branches":{const[S,q]=await Promise.all([pa(r),As(r)]);de(S),f(q);break}case"worktrees":{const S=await Sv(r);te(S);break}case"stashes":{const S=await pr(r);ce(S);break}case"remotes":{const S=await As(r);f(S);break}}}catch(S){m(xe(S)||"Failed to fetch git data"),i(xe(S)||"Failed to fetch git data","error")}finally{u(!1)}}},[o,e,V,i,r]);a.useEffect(()=>{e&&ge()},[ge,e]),a.useEffect(()=>{if(!e)return;const S=q=>{if(q.key==="Escape"){n();return}if((q.key==="ArrowUp"||q.key==="ArrowDown")&&q.altKey){q.preventDefault();const Ae=Ca.findIndex(ot=>ot.id===o);q.key==="ArrowUp"&&Ae>0?l(Ca[Ae-1].id):q.key==="ArrowDown"&&Ae<Ca.length-1&&l(Ca[Ae+1].id)}};return document.addEventListener("keydown",S),()=>document.removeEventListener("keydown",S)},[e,n,o]);const He=a.useCallback(async S=>{try{await od(S,r),i(`Staged ${S.length} file(s)`,"success");const q=await $i(r);v(q),k(new Set),$(null),N(null),z(null)}catch(q){i(xe(q)||"Failed to stage files","error")}},[i,r]),ve=a.useCallback(async S=>{try{await $v(S,r),i(`Unstaged ${S.length} file(s)`,"success");const q=await $i(r);v(q),k(new Set),$(null),N(null),z(null)}catch(q){i(xe(q)||"Failed to unstage files","error")}},[i,r]),$e=a.useCallback(async S=>{if(confirm(`Discard changes to ${S.length} file(s)? This cannot be undone.`))try{await Dv(S,r),i(`Discarded changes to ${S.length} file(s)`,"success");const[q,Ae]=await Promise.all([$i(r),As(r)]);v(q),f(Ae),k(new Set),$(null),N(null),z(null)}catch(q){i(xe(q)||"Failed to discard changes","error")}},[i,r]),ze=a.useCallback(async S=>{if(S.preventDefault(),!!M.trim()){y(!0);try{const q=await ld(M.trim(),r);i(`Committed: ${q.hash}`,"success"),w("");const[Ae,ot]=await Promise.all([$i(r),As(r)]);v(Ae),f(ot),$(null),N(null),z(null)}catch(q){i(xe(q)||"Failed to commit","error")}finally{y(!1)}}},[M,i,r]),me=a.useCallback(async()=>{if(M.trim()){y(!0);try{const S=b.filter(kt=>!kt.staged).map(kt=>kt.file);S.length>0&&await od(S,r);const q=await ld(M.trim(),r);i(`Committed: ${q.hash}`,"success"),w("");const[Ae,ot]=await Promise.all([$i(r),As(r)]);v(Ae),f(ot),$(null),N(null),z(null)}catch(S){i(xe(S)||"Failed to commit","error")}finally{y(!1)}}},[M,b,i,r]),Pe=a.useCallback(async(S,q)=>{$({file:S,staged:q}),_(!0),z(null);const Ae=T.current+1;T.current=Ae;try{const ot=await Pv(S,q,r);if(T.current!==Ae)return;N(ot)}catch(ot){if(T.current!==Ae)return;const kt=xe(ot)||"Failed to load file diff";N(null),z(kt),i(kt,"error")}finally{T.current===Ae&&_(!1)}},[i,r]),be=a.useCallback(S=>{k(q=>{const Ae=new Set(q);return Ae.has(S)?Ae.delete(S):Ae.add(S),Ae})},[]),We=a.useCallback(async S=>{if(K===S){B(null),L(null);return}B(S),C(!0);try{const q=await Hr(S,r);L(q)}catch(q){i(xe(q)||"Failed to load diff","error"),L(null)}finally{C(!1)}},[K,i,r]),tt=a.useCallback(()=>{fe(S=>Math.min(S+20,100))},[]),ct=a.useMemo(()=>{if(!ae.trim())return j;const S=ae.toLowerCase();return j.filter(q=>q.message.toLowerCase().includes(S)||q.author.toLowerCase().includes(S)||q.shortHash.toLowerCase().includes(S))},[j,ae]),wt=a.useCallback(async S=>{if(S.preventDefault(),!!re.trim()){u(!0);try{await Cv(re.trim(),ue.trim()||void 0,r),i(`Created branch ${re}`,"success"),Z(""),Ce("");const q=await pa(r);de(q)}catch(q){i(xe(q)||"Failed to create branch","error")}finally{u(!1)}}},[re,ue,i,r]),Nt=a.useCallback(async S=>{u(!0);try{await Ev(S,r),i(`Switched to ${S}`,"success");const[q,Ae]=await Promise.all([As(r),pa(r)]);f(q),de(Ae)}catch(q){i(xe(q)||"Failed to checkout branch","error")}finally{u(!1)}},[i,r]),It=a.useCallback(async S=>{if(confirm(`Delete branch "${S}"?`)){u(!0);try{await rd(S,void 0,r),i(`Deleted branch ${S}`,"success");const q=await pa(r);de(q)}catch(q){if(xe(q).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await rd(S,!0,r),i(`Force deleted branch ${S}`,"success");const Ae=await pa(r);de(Ae)}catch(Ae){i(xe(Ae)||"Failed to delete branch","error")}}else i(xe(q)||"Failed to delete branch","error")}finally{u(!1)}}},[i,r]),Ut=a.useMemo(()=>{if(!he.trim())return F;const S=he.toLowerCase();return F.filter(q=>q.name.toLowerCase().includes(S))},[F,he]),Vt=a.useCallback(async S=>{if(ee===S){we(null),qe([]),Qe(null),Fe(null);return}we(S),qe([]),Qe(null),Fe(null),Ge(!0);try{const q=await Nv(S,10,r);qe(q)}catch{qe([])}finally{Ge(!1)}},[ee,r]),zt=a.useCallback(async S=>{if(Ke===S){Qe(null),Fe(null);return}Qe(S),Fe(null),Q(!0);try{const q=await Hr(S,r);Fe(q)}catch{Fe(null)}finally{Q(!1)}},[Ke,r]),Mt=a.useCallback(()=>{we(null),qe([]),Qe(null),Fe(null)},[]),xt=a.useCallback(async S=>{S.preventDefault(),le("create");try{await Tv(Re.trim()||void 0,r),i("Changes stashed","success"),Ze("");const q=await pr(r);ce(q)}catch(q){i(xe(q)||"Failed to stash changes","error")}finally{le(null)}},[Re,i,r]),_t=a.useCallback(async(S,q=!1)=>{le(`apply-${S}`);try{await Rv(S,q,r),i(q?"Stash popped":"Stash applied","success");const Ae=await pr(r);ce(Ae)}catch(Ae){i(xe(Ae)||"Failed to apply stash","error")}finally{le(null)}},[i,r]),De=a.useCallback(async S=>{if(confirm(`Drop stash@{${S}}? This cannot be undone.`)){le(`drop-${S}`);try{await Iv(S,r),i("Stash dropped","success");const q=await pr(r);ce(q)}catch(q){i(xe(q)||"Failed to drop stash","error")}finally{le(null)}}},[i,r]),gt=a.useCallback(async()=>{ne("fetch");try{const S=await Mv(void 0,r);_e(S),i(S.message||"Fetch completed",S.fetched?"success":"info");const q=await As(r);f(q)}catch(S){i(xe(S)||"Fetch failed","error")}finally{ne(null)}},[i,r]),ut=a.useCallback(async()=>{ne("pull");try{const S=await _v(r);_e(S),S.conflict?i("Merge conflict detected. Resolve manually.","error"):i(S.message||"Pull completed","success");const q=await As(r);f(q)}catch(S){i(xe(S)||"Pull failed","error")}finally{ne(null)}},[i,r]),Me=a.useCallback(async()=>{ne("push");try{const S=await Av(r);_e(S),i(S.message||"Push completed","success");const q=await As(r);f(q)}catch(S){i(xe(S)||"Push failed","error")}finally{ne(null)}},[i,r]),Ye=a.useMemo(()=>b.filter(S=>S.staged),[b]),rt=a.useMemo(()=>b.filter(S=>!S.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",onClick:S=>S.target===S.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(Rl,{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:ge,disabled:c,title:"Refresh",children:t.jsx(hn,{size:14,className:c?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Dt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Ca.map(S=>{const q=S.icon;return t.jsxs("button",{role:"tab","aria-selected":o===S.id,className:`gm-nav-item${o===S.id?" active":""}`,onClick:()=>l(S.id),children:[t.jsx(q,{size:16}),t.jsx("span",{className:"gm-nav-label",children:S.label})]},S.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[c&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),d&&!c&&t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:18}),t.jsx("span",{children:d}),t.jsx("button",{className:"btn btn-sm",onClick:ge,children:"Retry"})]}),o==="status"&&!c&&p&&t.jsx(SA,{status:p,copyToClipboard:g}),o==="changes"&&!c&&t.jsx(CA,{status:p,stagedFiles:Ye,unstagedFiles:rt,selectedFiles:x,toggleFileSelection:be,onStageFiles:He,onUnstageFiles:ve,onDiscardChanges:$e,onSelectDiffFile:Pe,selectedDiffTarget:G,changeDiff:E,loadingChangeDiff:P,changeDiffError:R,commitMessage:M,setCommitMessage:w,onCommit:ze,onStageAllAndCommit:me,committing:I}),o==="commits"&&!c&&t.jsx(EA,{commits:ct,commitSearch:ae,setCommitSearch:oe,selectedCommit:K,commitDiff:A,loadingDiff:X,onCommitClick:We,onLoadMore:tt,canLoadMore:j.length>=V&&V<100,copyToClipboard:g}),o==="branches"&&!c&&t.jsx(MA,{branches:Ut,branchSearch:he,setBranchSearch:Ne,newBranchName:re,setNewBranchName:Z,branchBase:ue,setBranchBase:Ce,onCreateBranch:wt,onCheckoutBranch:Nt,onDeleteBranch:It,loading:c,allBranches:F,selectedBranch:ee,branchCommits:Ie,loadingBranchCommits:Ve,expandedBranchCommit:Ke,branchCommitDiff:Se,loadingBranchCommitDiff:ie,onSelectBranch:Vt,onBranchCommitClick:zt,onCloseBranchDetails:Mt}),o==="worktrees"&&!c&&t.jsx(_A,{worktrees:pe}),o==="stashes"&&!c&&t.jsx(AA,{stashes:ye,stashMessage:Re,setStashMessage:Ze,onCreateStash:xt,onApplyStash:_t,onDropStash:De,stashLoading:at}),o==="remotes"&&!c&&t.jsx(TA,{status:p,remoteLoading:U,lastRemoteResult:ke,onFetch:gt,onPull:ut,onPush:Me,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function SA({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(Os,{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(wi,{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(ss,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{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(yi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Ga,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(tn,{size:12}),"Up to date"]})]})]})]})]})}function CA({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 k=s.filter(w=>i.has(`unstaged:${w.file}`)),M=n.filter(w=>i.has(`staged:${w.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(Os,{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:[k.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(k.map(w=>w.file)),title:"Stage selected",children:[t.jsx(qt,{size:12})," Stage (",k.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(k.map(w=>w.file)),title:"Discard selected",children:t.jsx(Ya,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(w=>w.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(w=>{const I=d?.file===w.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${I?" active":""}`,onClick:()=>u(w.file,!1),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),u(w.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:y=>y.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${w.file}`),onChange:()=>r(`unstaged:${w.file}`)})}),t.jsx(Mm,{status:w.status}),t.jsx("span",{className:"gm-file-name",title:w.file,children:w.file}),t.jsx(_m,{status:w.status}),t.jsx("button",{className:"gm-icon-btn",onClick:y=>{y.stopPropagation(),o([w.file])},title:"Stage file",children:t.jsx(qt,{size:12})})]},`unstaged:${w.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:[M.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(M.map(w=>w.file)),title:"Unstage selected",children:["Unstage (",M.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(w=>w.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(w=>{const I=d?.file===w.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${I?" active":""}`,onClick:()=>u(w.file,!0),role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),u(w.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:y=>y.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${w.file}`),onChange:()=>r(`staged:${w.file}`)})}),t.jsx(Mm,{status:w.status}),t.jsx("span",{className:"gm-file-name",title:w.file,children:w.file}),t.jsx(_m,{status:w.status}),t.jsx("button",{className:"gm-icon-btn",onClick:y=>{y.stopPropagation(),l([w.file])},title:"Unstage file",children:t.jsx(Dt,{size:12})})]},`staged:${w.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(sh,{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(it,{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:w=>f(w.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(it,{size:14,className:"spin"}):t.jsx(vi,{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 EA({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(Bi,{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:Zi(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(wi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{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 MA({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:k,onBranchCommitClick:M,onCloseBranchDetails:w}){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(Bi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:I=>s(I.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:I=>r(I.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:I=>l(I.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(I=>t.jsx("option",{value:I.name,children:I.name},I.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(qt,{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(I=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${I.isCurrent?" current":""}${g===I.name?" selected":""}`,onClick:()=>k(I.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[I.isCurrent&&t.jsx(xn,{size:14,className:"gm-current-icon"}),I.name]}),I.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",I.remote]}),I.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Zi(I.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!I.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:y=>{y.stopPropagation(),u(I.name)},disabled:m,title:"Checkout",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:y=>{y.stopPropagation(),d(I.name)},disabled:m,title:"Delete",children:t.jsx(Ht,{size:14})})]})})]}),g===I.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(Oa,{size:14}),"Commits on ",I.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:w,title:"Close","data-testid":"close-branch-details",children:t.jsx(Dt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(it,{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(y=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>M(y.hash),"data-testid":`branch-commit-${y.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:y.shortHash}),t.jsx("span",{className:"gm-commit-message",title:y.message,children:y.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:y.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(y.date)}),y.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===y.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{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"})})]},y.hash))})]})]},I.name))})]})}function _A({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(Os,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function AA({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(it,{size:14,className:"spin"}):t.jsx(to,{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(Os,{size:12}),c.branch]}),t.jsx("span",{children:Zi(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(it,{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(it,{size:14,className:"spin"}):t.jsx(Ht,{size:14})})]})]},c.index))})]})}function TA({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=Q=>{try{return new URL(Q).hostname}catch{return Q.replace(/^git@/,"").split(":")[0]||Q}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[v,x]=a.useState(""),[k,M]=a.useState(""),[w,I]=a.useState(null),[y,E]=a.useState(""),[N,P]=a.useState(""),[_,R]=a.useState(!1),[z,G]=a.useState([]),[$,T]=a.useState(!1),[j,W]=a.useState(null),[K,B]=a.useState([]),[A,L]=a.useState(!1),[X,C]=a.useState(null),V=m.find(Q=>Q.name===j),[fe,ae]=a.useState(null),[oe,F]=a.useState(null),[de,re]=a.useState(!1),[Z,ue]=a.useState(null),[Ce,he]=a.useState(null),[Ne,ee]=a.useState(!1);a.useEffect(()=>{we()},[]),a.useEffect(()=>{e&&e.ahead>0?Ie():e&&e.ahead===0&&G([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!j&&W(m[0].name)},[m]),a.useEffect(()=>{j?qe(j):(B([]),C(null))},[j]),a.useEffect(()=>{j&&!m.find(Q=>Q.name===j)&&W(m.length>0?m[0].name:null)},[m,j]);const we=async()=>{p(!0);try{const Q=await mv(c);h(Q)}catch(Q){l(xe(Q)||"Failed to load remotes","error")}finally{p(!1)}},Ie=async()=>{T(!0);try{const Q=await jv(c);G(Q)}catch{G([])}finally{T(!1)}},qe=async Q=>{L(!0),C(null);try{const pe=await wv(Q,void 0,10,c);B(pe)}catch(pe){C(xe(pe)||"Failed to load remote commits"),B([])}finally{L(!1)}},Ve=async Q=>{if(Q.preventDefault(),!(!v.trim()||!k.trim())){b("add");try{await hv(v.trim(),k.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),M(""),R(!1),await we()}catch(pe){l(xe(pe)||"Failed to add remote","error")}finally{b(null)}}},Ge=async Q=>{if(confirm(`Are you sure you want to remove remote '${Q}'?`)){b(`remove-${Q}`);try{await pv(Q,c),l(`Remote '${Q}' removed`,"success"),await we()}catch(pe){l(xe(pe)||"Failed to remove remote","error")}finally{b(null)}}},Ke=async Q=>{if(N.trim()){b(`rename-${Q}`);try{await fv(Q,N.trim(),c),l(`Remote renamed to '${N.trim()}'`,"success"),I(null),P(""),await we()}catch(pe){l(xe(pe)||"Failed to rename remote","error")}finally{b(null)}}},Qe=async Q=>{if(y.trim()){b(`url-${Q}`);try{await gv(Q,y.trim(),c),l("Remote URL updated","success"),I(null),E(""),await we()}catch(pe){l(xe(pe)||"Failed to update remote URL","error")}finally{b(null)}}},Se=a.useCallback(async(Q,pe)=>{if(pe==="ahead"){if(fe===Q){ae(null),F(null);return}ae(Q),F(null),re(!0);try{const te=await Hr(Q);F(te)}catch{F(null)}finally{re(!1)}}else{if(Z===Q){ue(null),he(null);return}ue(Q),he(null),ee(!0);try{const te=await Hr(Q);he(te)}catch{he(null)}finally{ee(!1)}}},[fe,Z]),Fe=Q=>{I(`url-${Q.name}`),E(Q.pushUrl||Q.fetchUrl)},ie=Q=>{I(`name-${Q.name}`),P(Q.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:()=>R(!_),disabled:f!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(Dt,{size:14}):t.jsx(qt,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ve,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:Q=>x(Q.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:k,onChange:Q=>M(Q.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()||!k.trim()||f==="add",children:[f==="add"?t.jsx(it,{size:12,className:"spin"}):t.jsx(qt,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Q=>t.jsxs("div",{className:`gm-remote-selector-item${j===Q.name?" selected":""}`,onClick:()=>W(Q.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[Q.name,Q.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(Q.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:pe=>{pe.stopPropagation(),Ge(Q.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Ht,{size:14})})]},Q.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[j&&V?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:j}),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(yi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(Ga,{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(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(it,{size:14,className:"spin"}):t.jsx(es,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(it,{size:14,className:"spin"}):t.jsx(yi,{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:"}),w===`url-${j}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:y,onChange:Q=>E(Q.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Qe(j),disabled:f===`url-${j}`,children:f===`url-${j}`?t.jsx(it,{size:12,className:"spin"}):t.jsx(xn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{I(null),E("")},title:"Cancel",children:t.jsx(Dt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:V.fetchUrl,children:V.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(V.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(wi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Fe(V),disabled:f!==null,title:"Edit remote URL",children:t.jsx(qn,{size:14})})]})]}),V.pushUrl&&V.pushUrl!==V.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:V.pushUrl,children:V.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(V.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(wi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:w===`name-${j}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:Q=>P(Q.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ke(j),disabled:f===`rename-${j}`,children:f===`rename-${j}`?t.jsx(it,{size:12,className:"spin"}):t.jsx(xn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{I(null),P("")},title:"Cancel",children:t.jsx(Dt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ie(V),disabled:f!==null,title:"Edit remote name",children:t.jsx(qn,{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(yi,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:14,className:"spin"}),"Loading..."]}):z.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:z.map(Q=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Se(Q.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:Q.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Q.message,children:Q.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Q.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(Q.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:fe===Q.hash?t.jsx(Lt,{size:14}):t.jsx(en,{size:14})})]}),fe===Q.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:de?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):oe?t.jsxs(t.Fragment,{children:[Q.message&&t.jsx("div",{className:"gm-commit-message-full",children:Q.message}),oe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:oe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:oe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Q.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(dh,{size:14}),"Recent commits on ",j]})}),A?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:14,className:"spin"}),"Loading commits..."]}):X?t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:14}),X]}):K.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",j,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:K.map(Q=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Se(Q.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:Q.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Q.message,children:Q.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Q.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(Q.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Z===Q.hash?t.jsx(Lt,{size:14}):t.jsx(en,{size:14})})]}),Z===Q.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Ne?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):Ce?t.jsxs(t.Fragment,{children:[Q.message&&t.jsx("div",{className:"gm-commit-message-full",children:Q.message}),Ce.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Ce.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Ce.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Q.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 Ea={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function RA(e,n){return e&&n?`${e}/${n}`:""}function IA(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 PA(e){switch(e){case"file-text":return Ni;case"check-circle":return tn;case"shield":return qb;case"zap":return vn;case"eye":return Vi;case"globe":return so;case"layout-grid":return Ci;default:return tn}}function $A(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 DA({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),[k,M]=a.useState(Ea),[w,I]=a.useState(!1),[y,E]=a.useState(!1),[N,P]=a.useState(null),[_,R]=a.useState(null),[z,G]=a.useState({}),[$,T]=a.useState([]),j=a.useCallback(async()=>{try{d(!0);const F=await co(i);o(F)}catch(F){s(xe(F)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),W=a.useCallback(async()=>{try{const F=await er(i);G(F||{})}catch{}},[i]),K=a.useCallback(async()=>{try{const F=await is();T(F.models||[])}catch{}},[]),B=a.useCallback(async()=>{try{h(!0);const F=await xy();c(F.templates)}catch(F){s(xe(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(j(),B(),W(),K())},[e,j,B,W,K]);const A=a.useCallback(()=>{x(!0),b(null),M(Ea)},[]),L=a.useCallback(F=>{b(F.id),x(!1),M({name:F.name,description:F.description,mode:F.mode||"prompt",phase:F.phase||"pre-merge",prompt:F.prompt,scriptName:F.scriptName||"",enabled:F.enabled,defaultOn:F.defaultOn||!1,modelProvider:F.modelProvider||"",modelId:F.modelId||""})},[]),X=a.useCallback(()=>{b(null),x(!1),M(Ea)},[]),C=a.useCallback(async()=>{if(!k.name.trim()||!k.description.trim()){s("Name and description are required","error");return}I(!0);try{const F=k.mode==="prompt"&&k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:k.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const de={name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"&&k.prompt.trim()||void 0,scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...F};await hd(de,i),s("Workflow step created","success")}else f&&(await fy(f,{name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"?k.prompt:"",scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn,...F},i),s("Workflow step updated","success"));x(!1),b(null),M(Ea),await j()}catch(F){s(xe(F)||"Failed to save workflow step","error")}finally{I(!1)}},[k,v,f,s,j]),V=a.useCallback(async F=>{try{await gy(F,i),s("Workflow step deleted","success"),P(null),f===F&&(b(null),M(Ea)),await j()}catch(de){s(xe(de)||"Failed to delete workflow step","error")}},[f,s,j]),fe=a.useCallback(async()=>{if(!(!f&&!v)&&k.mode==="prompt"){if(v){if(!k.name.trim()||!k.description.trim()){s("Name and description are required before refining","error");return}I(!0);try{const F=k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:{},de={name:k.name.trim(),description:k.description.trim(),mode:"prompt",prompt:k.prompt.trim()||void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...F},re=await hd(de,i);x(!1),b(re.id),E(!0);const Z=await pd(re.id,i);M(ue=>({...ue,prompt:Z.prompt})),s("Prompt refined with AI","success"),await j()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{I(!1),E(!1)}return}if(f){E(!0);try{const F=await pd(f,i);M(de=>({...de,prompt:F.prompt})),s("Prompt refined with AI","success"),await j()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{E(!1)}}}},[f,v,k,s,j]),ae=a.useCallback(async F=>{R(F.id);try{await vy(F.id,i),s(`Added ${F.name} workflow step`,"success"),await j(),p("my-steps")}catch(de){const re=xe(de);re?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(re||"Failed to add workflow step from template","error")}finally{R(null)}},[s,j]);if(!e)return null;const oe=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:[!oe&&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(Wf,{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"&&!oe&&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:()=>L(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(qn,{size:14})}),N===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>V(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>P(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Dt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>P(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(Ht,{size:14})})]})]})},F.id))})]}),g==="templates"&&!oe&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(it,{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 de=PA(F.icon),re=$A(F.category),Z=_===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(de,{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:re,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:()=>ae(F),disabled:Z,"data-testid":`add-template-${F.id}`,children:Z?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(qt,{size:12}),"Add"]})})]})]})},F.id)})})}),oe&&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:k.name,onChange:F=>M(de=>({...de,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:k.description,onChange:F=>M(de=>({...de,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 ${k.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(li,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${k.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Bs,{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 ${k.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${k.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:k.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),k.mode==="prompt"&&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:!k.description.trim()||y,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[y?t.jsx(it,{size:12,className:"spin"}):t.jsx(Dn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:k.prompt,onChange:F=>M(de=>({...de,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),k.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"}),k.modelProvider&&k.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>M(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Dt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:k.modelProvider&&k.modelId?`Using ${k.modelProvider}/${k.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(wn,{models:$,value:RA(k.modelProvider,k.modelId),onChange:F=>{const de=IA(F);M(re=>({...re,modelProvider:de.provider,modelId:de.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),k.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(z).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:k.scriptName,onChange:F=>M(de=>({...de,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(z).map(([F,de])=>t.jsxs("option",{value:F,children:[F," (",de,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:k.enabled,onChange:F=>M(de=>({...de,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:k.defaultOn,onChange:F=>M(de=>({...de,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:w,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:C,disabled:w||!k.name.trim()||!k.description.trim()||k.mode==="script"&&!k.scriptName.trim(),"data-testid":"save-workflow-step",children:w?"Saving...":v?"Create":"Save"})]})]})]})]})}),!oe&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:A,"data-testid":"add-workflow-step",children:[t.jsx(qt,{size:14}),"Add Workflow Step"]})})]})})}const LA=36e5,zA=3e5,Nl=[{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 FA(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)?LA:Math.max(zA,Math.round(e))}function PP(e){if(Nl.some(s=>s.value===e))return[...Nl];const n={value:e,label:`${FA(e)} (custom)`};return[...Nl,n].sort((s,i)=>s.value-i.value)}const UA=4,BA=5*6e4;function HA(e){const n=OA(e?.heartbeatIntervalMs);return Math.max(n*UA,BA)}function qA(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 VA(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=qA(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(ls,{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(Fs,{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(an,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=HA(o);return u>d?{label:"Unresponsive",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(eb,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ma=[{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 WA({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 j=Nn("fn-agent-view",i);return j==="board"||j==="list"?j:"list"});a.useEffect(()=>{const j=Nn("fn-agent-view",i);if(j==="board"||j==="list"){x(j);return}x("list")},[i]),a.useEffect(()=>{ts("fn-agent-view",v,i)},[i,v]);const[k,M]=a.useState(null),w=a.useRef(null),I=a.useMemo(()=>f==="all"?r.filter(j=>j.state!=="terminated"):r,[r,f]),y=a.useCallback(async()=>{c(!0);try{const W=await oa(f!=="all"?{state:f}:void 0,i);o(W)}catch(j){s(`Failed to load agents: ${xe(j)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&y()},[e,y]),a.useEffect(()=>{if(!e)return;const j=setInterval(()=>{y()},3e4);return()=>{clearInterval(j)}},[e,y]);const E=async()=>{if(m.trim())try{await My({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),y()}catch(j){s(`Failed to create agent: ${xe(j)}`,"error")}},N=async(j,W)=>{try{await Ay(j,W,i),s(`Agent state updated to ${W}`,"success"),y()}catch(K){s(`Failed to update state: ${xe(K)}`,"error")}},P=async(j,W)=>{if(confirm(`Delete agent "${W}"? This cannot be undone.`))try{await Ty(j,i),s(`Agent "${W}" deleted`,"success"),y()}catch(K){s(`Failed to delete agent: ${xe(K)}`,"error")}},_=async(j,W)=>{const K=r.find(B=>B.id===j);if(K){if(K.role===W){M(null);return}try{await _y(j,{role:W},i),s(`Agent role updated to ${Ma.find(B=>B.value===W)?.label??W}`,"success"),M(null),y()}catch(B){s(`Failed to update role: ${xe(B)}`,"error")}}},R=(j,W)=>{j.key==="Escape"&&M(null)},z=j=>Ma.find(W=>W.value===j)?.label??j,G=j=>Ma.find(W=>W.value===j)?.icon??"◆",$=j=>VA(j),T=j=>j.color==="var(--state-active-text)"?"active":j.color==="var(--state-paused-text)"?"paused":j.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:j=>j.target===j.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(an,{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(Il,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void y(),title:"Refresh",disabled:l,children:t.jsx(hn,{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(zr,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:j=>b(j.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(qt,{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:j=>h(j.target.value),onKeyDown:j=>j.key==="Enter"&&E(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:j=>p(j.target.value),children:Ma.map(j=>t.jsxs("option",{value:j.value,children:[j.icon," ",j.label]},j.value))}),t.jsx("button",{className:"btn btn--primary",onClick:()=>void E(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:I.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(an,{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"?I.map(j=>{const W=$(j),K=T(W);return t.jsxs("div",{className:"agent-board-card","data-state":j.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:G(j.role)}),t.jsx("span",{className:"agent-board-badge","data-state":j.state,children:j.state}),t.jsx("span",{className:"agent-board-health","data-health":K,title:W.label,children:W.icon})]}),t.jsx("div",{className:"agent-board-name",title:j.name,children:j.name}),t.jsx("div",{className:"agent-board-id",children:j.id}),t.jsxs("div",{className:"agent-board-actions",children:[j.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"active"),title:"Activate",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:t.jsx(Ht,{size:14})})]}),j.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"paused"),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),j.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"active"),title:"Resume",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),j.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"paused"),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),j.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"active"),title:"Retry",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),j.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:t.jsx(Ht,{size:14})})]})]},j.id)}):I.map(j=>{const W=$(j),K=T(W);return t.jsxs("div",{className:"agent-card","data-state":j.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[k===j.id?t.jsx("select",{ref:w,className:"select agent-role-select",value:j.role,onChange:B=>void _(j.id,B.target.value),onKeyDown:B=>R(B,j.id),onBlur:()=>M(null),autoFocus:!0,children:Ma.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:()=>M(j.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&M(j.id)},children:G(j.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:j.name}),t.jsx("span",{className:"agent-id text-secondary",children:j.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":j.state,children:j.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":K,title:W.label,children:[W.icon,!W.stateDerived&&` ${W.label}`]}),t.jsx("span",{className:"badge text-secondary",children:z(j.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[j.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:j.taskId})]}),j.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(j.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[j.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"active"),title:"Activate",children:[t.jsx(rn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:[t.jsx(Ht,{size:14})," Delete"]})]}),j.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"paused"),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),j.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"active"),title:"Resume",children:[t.jsx(rn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),j.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"paused"),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),j.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void N(j.id,"active"),title:"Retry",children:[t.jsx(rn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void N(j.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),j.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void N(j.id,"active"),title:"Start",children:[t.jsx(rn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(j.id,j.name),title:"Delete",children:[t.jsx(Ht,{size:14})," Delete"]})]})]})]},j.id)})})]})]})}):null}function KA({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 tv();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 k=await nv(x);d.current&&u({kind:k.enabled?"enabled":"disabled",restartRequired:k.restartRequired}),n?.(k.enabled),await m()}catch(k){d.current&&u({kind:"error",message:k instanceof Error?k.message:String(k)})}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(it,{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(Mn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(GA,{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(Am,{status:i,authenticated:e}),c&&t.jsx(Tm,{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(Mn,{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(Am,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Tm,{action:c})]})}function GA({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 Am({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(it,{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 Tm({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."]})}function JA(e){return e.match(/\bcode\s+([A-Z0-9]+(?:-[A-Z0-9]+)+)\b/i)?.[1]??null}function Rm({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=JA(e),o=a.useCallback(async()=>{const l=r??e;try{await navigator.clipboard.writeText(l),i(!0),setTimeout(()=>i(!1),2e3)}catch{}},[r,e]);return t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((l,c,u)=>t.jsxs("span",{children:[l,c<u.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:o,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(xn,{size:12}):t.jsx(wi,{size:12})})]})]},c))}):e})}const Mi="fusion_model_onboarding_state",ea=[],ta=[],Zr=!1,eo=!1,na={},YA=void 0,oi=["ai-setup","github","project-setup","first-task"],QA={"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??YA;return{...e,completedSteps:e.completedSteps??ea,skippedSteps:e.skippedSteps??ta,dismissed:e.dismissed??Zr,completed:e.completed??eo,stepData:e.stepData??na,...n?{postOnboardingDismissedAt:n}:{}}}function Rr(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:ea,skippedSteps:ta,dismissed:Zr,completed:eo,stepData:na};try{localStorage.setItem(Mi,JSON.stringify(s))}catch{}return}try{const s=us(),i=new Date().toISOString(),r=n.completed??eo;let o=n.dismissed??Zr;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??ea,c=n.skippedSteps??s?.skippedSteps??ta,u={...s?.stepData??na};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 ZA(e){if(!(typeof window>"u"))try{const n=us(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:ea,skippedSteps:[e],dismissed:Zr,completed:eo,stepData:na};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 Im(){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:ea,skippedSteps:ta,dismissed:!1,completed:!0,stepData:na};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function sa(){const e=us();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function eT(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ea,skippedSteps:ta,dismissed:!1,completed:!1,stepData:na,postOnboardingDismissedAt:n};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function ff(){const e=us();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function tT(){const e=us();return!e||sa()?!1:e.currentStep!=="complete"}function nT(){const e=us();if(!e||sa()||e.currentStep==="complete")return null;const n=e.currentStep,s=QA[n]??aT(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function sT(){const e=us();return e?e.skippedSteps:ta}function iT(e){const n=us();return!n||!n.stepData?null:n.stepData[e]??null}function aT(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const gf="fusion_onboarding_events",Pm="fusion_onboarding_session_id",rT=200,oT=50;function js(e,n={}){if(!(typeof window>"u"))try{const s=cT(),i=mT(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:lT()},o=uT([...s,r]);dT(o)}catch{}}function lT(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Pm);if(e)return e;const n=$m();return sessionStorage.setItem(Pm,n),n}catch{return $m()}}function $m(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function cT(){try{const e=localStorage.getItem(gf);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(hT):[]}catch{return[]}}function dT(e){try{localStorage.setItem(gf,JSON.stringify(e))}catch{}}function uT(e){const n=[...e];for(;n.length>rT;)n.splice(0,oT);return n}function mT(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function hT(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 pT={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"}}},bf={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:"..."}},fT={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Dm={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 sc(e){if(Dm[e])return Dm[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 Sl=["anthropic","openai","google","gemini","ollama"],gT=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],bT={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"},xT={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function ic(e){return bT[e]??e}function Lm(e){const n=ic(e),s=gT.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function zm(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Lm(e.id),i=Lm(n.id);if(s!==i)return s-i;const r=ic(e.id),o=ic(n.id);if(r!==o)return r.localeCompare(o);const l=xT[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 vT(e,n){const s=n.trim();if(!s)return"API key is required";const i=bf[e]??fT;return i.pattern.test(s)?null:`${sc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const xf={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"},yT={description:"AI provider — connect to start using AI models",apiKeyInfo:xf};function ac(e){return pT[e]??yT}function kT(e){return ac(e.id).apiKeyInfo??xf}function zs({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(en,{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 jT({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 wT({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=bf[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(zs,{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(zs,{summary:"Advanced setup details",children:f})]})}const NT=150;function ST({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??sT(),[p,f]=a.useState(!0),[b,v]=a.useState(m),[x,k]=a.useState(h),[M,w]=a.useState(g),[I,y]=a.useState(!1),[E,N]=a.useState(""),[P,_]=a.useState(!1),[R,z]=a.useState(null),[G,$]=a.useState(null),[T,j]=a.useState([]),[W,K]=a.useState(void 0),[B,A]=a.useState(!0),[L,X]=a.useState(null),[C,V]=a.useState({}),[fe,ae]=a.useState([]),[oe,F]=a.useState(""),[de,re]=a.useState(!1),[Z,ue]=a.useState({}),[Ce,he]=a.useState({}),[Ne,ee]=a.useState({}),we=a.useRef({}),Ie=a.useRef(null),qe=a.useRef(null),[Ve,Ge]=a.useState({}),[Ke,Qe]=a.useState(()=>us()?.stepData?.github?.skipped===!0),Se=a.useRef(0),Fe=a.useRef(l),ie=a.useRef(!1),Q=u?.currentStep,pe=!!u&&u.currentStep!=="complete",[te,ye]=a.useState(()=>us()?.stepData?.["ai-setup"]?.skippedProviders??{}),ce=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Re=ce.findIndex(J=>J.key===b),Ze=b==="complete"?ce.length:Re;a.useEffect(()=>{b!=="complete"&&Rr(b,{completedSteps:x,skippedSteps:M})},[b,x,M]),a.useEffect(()=>{ie.current||(ie.current=!0,js("onboarding:wizard-opened",{source:pe?"resume":"initial",resumedFromStep:Q}))},[pe,Q]),a.useEffect(()=>{const J=Fe.current!=null,Le=l!=null;!J&&Le&&y(!0),Le||y(!1),Fe.current=l},[l]);const at=a.useRef(m);a.useEffect(()=>{if(at.current==="ai-setup"&&b!=="ai-setup"&&!T.some(Le=>Le.id!=="github"&&Le.authenticated)){const Le={};for(const nt of T)nt.id!=="github"&&!nt.authenticated&&!te[nt.id]&&(Le[nt.id]=!0);if(Object.keys(Le).length>0){const nt={...te,...Le};ye(nt),Rr(b,{stepData:{"ai-setup":{skippedProviders:nt}}})}}at.current=b},[b,T,te]);const le=a.useCallback(async()=>{try{const{providers:J,ghCli:Le}=await qa();j(J),K(Le),V(nt=>{const et={};for(const[mt,jt]of Object.entries(nt)){const Tt=J.find(gn=>gn.id===mt);Tt&&!Tt.authenticated&&(et[mt]=jt)}return Object.keys(et).length===Object.keys(nt).length?nt:et}),ye(nt=>{const et={...nt};for(const mt of J)mt.authenticated&&et[mt.id]&&delete et[mt.id];return Object.keys(et).length===Object.keys(nt).length?nt:et})}catch{}},[]),U=a.useRef(!1);a.useEffect(()=>{U.current&&le(),U.current=b!=="ai-setup"},[b,le]);const ne=T.find(J=>J.id==="github"),ke=!!ne,_e=ne?.authenticated??!1,ge=W?.authenticated??!1,He=_e||ge,ve=!_e&&ge,$e=a.useCallback(J=>{if(J.authenticated)return"connected";const Le=Ve?.[J.id];return Le==="timeout"||Le==="failed"?"retry":te[J.id]?"skipped":"not-connected"},[Ve,te]);function ze({status:J}){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:et}=Le[J];return t.jsx("span",{"data-testid":"provider-status-badge",className:et,"data-status":J,children:nt})}const me=a.useCallback(()=>{if(He)return"connected";const J=Ve.github;return J==="pending"?"pending":J==="failed"||J==="timeout"?"failed":Ke?"skipped":"not-connected"},[He,Ve,Ke]);function Pe({status:J}){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:et}=Le[J];return t.jsx("span",{"data-testid":"github-status-badge",className:et,"data-status":J,children:nt})}const be=a.useCallback(async()=>{try{const J=await is();ae(J.models)}catch{}},[]),We=a.useCallback(async()=>{try{const J=await ra();if(J.defaultProvider&&J.defaultModelId){const Le=`${J.defaultProvider}/${J.defaultModelId}`;F(Le)}}catch{}},[]);a.useEffect(()=>{Promise.all([le(),be(),We()]).finally(()=>A(!1))},[le,be,We]),a.useEffect(()=>{const J=iT("ai-setup");if(J?.loginOutcomes){const Le=J.loginOutcomes,nt={};for(const[et,mt]of Object.entries(Le))mt!=="pending"&&(nt[et]=mt);Object.keys(nt).length>0&&Ge(nt)}},[]);const tt=a.useCallback((J,Le)=>{Rr(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[J]:Le}}}})},[b,x]);a.useEffect(()=>{const J=Object.entries(Ve).filter(([Le,nt])=>nt!=="pending");for(const[Le,nt]of J)tt(Le,nt)},[Ve,tt]),a.useEffect(()=>()=>{qe.current&&clearInterval(qe.current),Object.values(we.current).forEach(clearTimeout),we.current={}},[]);const ct=a.useCallback(J=>{Qe(J),Rr(b,{completedSteps:x,stepData:{github:{skipped:J}}})},[b,x]),wt=a.useCallback(J=>J==="complete"?-1:oi.indexOf(J),[]),Nt=a.useCallback(()=>{k(Le=>[...new Set([...Le,b])]),w(Le=>Le.filter(nt=>nt!==b)),js("onboarding:step-completed",{step:b}),b==="github"&&!_e&&ct(!1);const J=wt(b);J>=0&&J<oi.length-1&&v(oi[J+1])},[b,_e,ct,wt]),It=a.useCallback(()=>{w(Le=>[...new Set([...Le,b])]),ZA(b),js("onboarding:step-skipped",{step:b}),b==="github"&&!_e&&ct(!0);const J=wt(b);J>=0&&J<oi.length-1&&v(oi[J+1])},[b,_e,ct,wt]),Ut=a.useCallback(()=>{const J=b;k(nt=>nt.filter(et=>et!==J)),w(nt=>nt.filter(et=>et!==J)),J==="github"&&!_e&&ct(!1);const Le=wt(b);Le>0&&v(oi[Le-1])},[b,_e,ct,wt]),Vt=a.useCallback(()=>{It()},[It]),zt=a.useCallback(async J=>{Ge(Le=>{const nt=Le[J];if(nt&&nt!=="pending"){const{[J]:et,...mt}=Le;return mt}return Le}),V(Le=>{if(!(J in Le))return Le;const nt={...Le};return delete nt[J],nt}),Ge(Le=>({...Le,[J]:"pending"})),X(J),Se.current=0;try{const{url:Le,instructions:nt}=await sv(J);nt?.trim()&&V(et=>({...et,[J]:nt})),window.open(Hs(Le),"_blank"),qe.current=setInterval(async()=>{if(Se.current++,Se.current>=NT){qe.current&&(clearInterval(qe.current),qe.current=null),X(null),Ge(et=>({...et,[J]:"timeout"})),V(et=>{if(!(J in et))return et;const mt={...et};return delete mt[J],mt}),n("Login timed out. Please try again.","warning");return}try{const{providers:et,ghCli:mt}=await qa();j(et),K(mt),et.find(Tt=>Tt.id===J)?.authenticated&&(qe.current&&(clearInterval(qe.current),qe.current=null),X(null),Ge(Tt=>({...Tt,[J]:"success"})),V(Tt=>{if(!(J in Tt))return Tt;const gn={...Tt};return delete gn[J],gn}),J==="github"&&ct(!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"),Ge(et=>({...et,[J]:"failed"}))):(n(Le instanceof Error?Le.message:"Login failed","error"),Ge(et=>({...et,[J]:"failed"}))),X(null),V(et=>{if(!(J in et))return et;const mt={...et};return delete mt[J],mt})}},[n,ct]),Mt=a.useCallback(J=>{qe.current&&(clearInterval(qe.current),qe.current=null),X(null),Se.current=0,Ge(Le=>({...Le,[J]:"cancelled"})),V(Le=>{if(!(J in Le))return Le;const nt={...Le};return delete nt[J],nt})},[]),xt=a.useCallback((J,Le)=>{ue(et=>({...et,[J]:Le}));const nt=we.current[J];nt&&(clearTimeout(nt),delete we.current[J]),he(et=>{if(!et[J])return et;const mt={...et};return delete mt[J],mt}),ee(et=>{if(!et[J])return et;const mt={...et};return delete mt[J],mt})},[]),_t=a.useCallback(()=>{const J=Ie.current;if(!J)return;const Le=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof J.scrollTo=="function"){J.scrollTo({top:0,behavior:Le?"auto":"smooth"});return}}catch{}J.scrollTop=0},[]),De=a.useCallback(async(J,Le)=>{const nt=(Le??Z[J]??"").trim(),et=vT(J,nt);if(et){he(jt=>({...jt,[J]:et}));return}const mt=we.current[J];mt&&(clearTimeout(mt),delete we.current[J]),X(J),he(jt=>{const Tt={...jt};return delete Tt[J],Tt}),ee(jt=>{if(!jt[J])return jt;const Tt={...jt};return delete Tt[J],Tt});try{await av(J,nt),await le(),_t(),ue(jt=>{const Tt={...jt};return delete Tt[J],Tt}),he(jt=>{if(!jt[J])return jt;const Tt={...jt};return delete Tt[J],Tt}),ee(jt=>({...jt,[J]:"✓ Key saved"})),we.current[J]=setTimeout(()=>{ee(jt=>{if(!jt[J])return jt;const Tt={...jt};return delete Tt[J],Tt}),delete we.current[J]},3e3),n("API key saved","success")}catch(jt){const Tt=jt instanceof TypeError&&jt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":jt instanceof Error?jt.message:"Failed to save API key";he(gn=>({...gn,[J]:Tt})),ee(gn=>{if(!gn[J])return gn;const fs={...gn};return delete fs[J],fs}),n(Tt,"error")}finally{X(null)}},[Z,n,le,_t]),gt=a.useCallback(async J=>{X(J);try{await rv(J),await le(),n("API key removed","success")}catch(Le){n(Le instanceof Error?Le.message:"Failed to clear API key","error")}finally{X(null)}},[n,le]),ut=a.useCallback(async J=>{X(J);try{await iv(J),await le(),n("Logged out","success")}catch(Le){n(Le instanceof Error?Le.message:"Logout failed","error")}finally{X(null)}},[n,le]),Me=a.useCallback(J=>{F(J)},[]),Ye=a.useCallback(async()=>{try{const J={modelOnboardingComplete:!0};if(oe){const Le=oe.indexOf("/"),nt=Le!==-1?oe.slice(0,Le):void 0,et=Le!==-1?oe.slice(Le+1):oe,mt=fe.find(jt=>jt.id===et);mt?(J.defaultProvider=mt.provider,J.defaultModelId=mt.id):nt&&et&&(J.defaultProvider=nt,J.defaultModelId=et)}await nn(J),Im()}catch{}},[oe,fe,nn,Im]),rt=a.useCallback(async()=>{const J=[...new Set([...x,"first-task"])];re(!0);try{await Ye(),js("onboarding:completed",{completedSteps:J,skippedSteps:M}),k(J),w(Le=>Le.filter(nt=>nt!=="first-task")),v("complete")}finally{re(!1)}},[Ye,x,M]),S=a.useCallback(async()=>{if(!s)return;const J=E.trim();if(!J){z("Please enter a task description.");return}z(null),_(!0);let Le=!1;try{const nt=await gh({description:J},s);$(nt),y(!0),js("onboarding:first-task-created",{taskId:nt?.id}),n("Task created","success"),Le=!0}catch(nt){const et=nt instanceof Error?nt.message:"Something went wrong creating your task. Please try again.";z(et),n(et,"error")}finally{_(!1)}Le&&Ye()},[s,E,n,Ye]),q=a.useCallback(async()=>{re(!0);try{await Ye()}finally{re(!1)}js("onboarding:open-new-task",{}),r?.()},[Ye,r]),Ae=a.useCallback(async()=>{if(He){re(!0);try{await Ye()}finally{re(!1)}f(!1),e(),js("onboarding:open-github-import",{}),o?.()}},[Ye,He,e,o]),ot=a.useCallback(async()=>{js("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:M}),re(!0);try{await nn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[b,x,M,e]),kt=a.useCallback(()=>{js("onboarding:finished",{}),f(!1),e()},[e]),Ot=a.useCallback(()=>{const J=l??G;J&&(Ye(),c?.(J),e())},[l,G,Ye,c,e]),sn=a.useCallback(()=>{Ye(),e()},[Ye,e]);if(!p)return null;const Pt=me(),zn=T.filter(J=>J.id!=="github"),Kn=[...zn].sort(zm),ms=Kn.some(J=>!J.type||J.type==="oauth"),pn=Kn.some(J=>J.type==="api_key"),Fn=zn.filter(J=>J.authenticated),Sn=Fn.length>0,fn=!!s,Gn=b==="github"&&!Sn,dn=(()=>{if(!oe)return"";const J=oe.indexOf("/"),Le=J===-1?void 0:oe.slice(0,J),nt=J===-1?oe:oe.slice(J+1),et=fe.find(mt=>mt.id===nt&&(!Le||mt.provider===Le));return et?.name?et.name:Le?`${sc(Le)} ${nt}`:oe})(),At=[];if(fn?At.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):At.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Sn){const J=sc(Fn[0]?.id??"");At.push({label:"AI Provider",status:"connected",detail:`${J} connected — AI agents can work on tasks`})}else zn.length>0&&zn.some(J=>te[J.id])?At.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):At.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});He?At.push({label:"GitHub",status:"connected",detail:ve?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ke||Ke?At.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):At.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),dn&&At.push({label:"Default Model",status:"connected",detail:dn});const yn=l??G,Jn=yn?.description?.split(`
631
+ `)[0]?.trim()||yn?.title||"",kn=new Set(Sl),_n=Kn.filter(J=>kn.has(J.id)).sort((J,Le)=>{const nt=Sl.indexOf(J.id),et=Sl.indexOf(Le.id);return nt!==et?nt-et:zm(J,Le)}),hs=Kn.filter(J=>J.authenticated&&!kn.has(J.id)),ps=Kn.filter(J=>!J.authenticated&&!kn.has(J.id)),On=J=>{if(J.id==="claude-cli"&&J.type==="cli")return t.jsx(KA,{authenticated:J.authenticated,onToggled:()=>{le()}},J.id);if(J.type==="api_key"){const Le=ac(J.id),nt=kT(J);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${J.id}`,className:`onboarding-provider-card${J.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${J.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:J.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(lh,{size:14,className:"onboarding-provider-key-icon"}),J.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Le.description}),t.jsx(ze,{status:$e(J)}),J.authenticated&&J.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",J.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(wT,{provider:J,apiKeyInfo:nt,inputValue:Z[J.id]??"",isSaving:L===J.id,error:Ce[J.id],success:Ne[J.id],isConnected:J.authenticated,onInputChange:xt,onSave:De,onClear:gt})})]},J.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${J.id}`,className:`onboarding-provider-card${J.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${J.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:J.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:J.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:ac(J.id).description}),t.jsx(ze,{status:$e(J)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:L===J.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:J.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Mt(J.id),children:"Cancel"})]}):J.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ut(J.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>zt(J.id),children:"Login"})}),L===J.id&&C[J.id]&&t.jsx(Rm,{instructions:C[J.id],"data-testid":`onboarding-login-instructions-${J.id}`}),Ve[J.id]==="timeout"&&L!==J.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ve[J.id]==="failed"&&L!==J.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},J.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(vn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(es,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Qc,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Qc,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ot,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Dt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:ce.map((J,Le)=>{const nt=Ze>Le,et=x.includes(J.key)&&nt,mt=M.includes(J.key)&&!x.includes(J.key)&&nt,jt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Le>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Le<=Ze?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===J.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>v(J.key),"aria-label":`Go back to ${J.label}`,title:`Review ${J.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Le+1}),t.jsx("span",{className:"step-label",children:J.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===J.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Le+1}),t.jsx("span",{className:"step-label",children:J.label})]})]},J.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Ie,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&&T.length>0&&(()=>{const J=T.filter(jt=>jt.id!=="github"&&jt.authenticated).length,Le=T.filter(jt=>jt.id!=="github").length,nt=Object.keys(te).filter(jt=>!T.find(Tt=>Tt.id===jt)?.authenticated).length;if(Le===0)return null;let et="onboarding-provider-summary",mt="";return J>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${J} of ${Le} provider${Le!==1?"s":""} connected`):nt>0?(et+=" onboarding-provider-summary--skipped",mt=`${nt} provider${nt!==1?"s":""} skipped`):(et+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:et,"data-testid":"provider-summary",children:mt})})(),t.jsx(zs,{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."})}),T.length>0&&!T.some(J=>J.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(it,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):T.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"}),_n.length>0?t.jsx("div",{className:"model-onboarding-providers",children:_n.map(J=>On(J))}):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(J=>On(J))})]}),t.jsx(zs,{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(J=>On(J))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),ms&&t.jsx(zs,{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."})}),pn&&t.jsx(zs,{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(zs,{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(wn,{models:fe,value:oe,onChange:Me,placeholder:"Select a default model…",label:"Default model"})}),oe&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",fe.find(J=>J.id===oe)?.name??oe]})})]})]}),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"})]})}),Gn&&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(zs,{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."})}),ke?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(es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Pe,{status:Pt})})]}),_e&&(L==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ut("github"),children:"Disconnect"}))]}),(Pt==="not-connected"||Pt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[L==="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:()=>Mt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>zt("github"),children:[t.jsx(es,{size:16}),"Connect"]}),L==="github"&&C.github&&t.jsx(Rm,{instructions:C.github,"data-testid":"onboarding-login-instructions-github"})]}),Pt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:ve?"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."}),Pt==="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:()=>zt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Vt,children:"Skip for now"})]})]}),Pt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Pt==="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:()=>zt("github"),children:"Connect anyway"})})]}),Pt==="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(es,{size:48,className:"optional-icon"}),ve?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."}),fn?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(zs,{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."}),I&&yn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(tn,{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:yn.id}),Jn&&t.jsx("p",{className:"onboarding-task-created__description",children:Jn}),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:Ot,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:sn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[fn?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:E,onChange:J=>{N(J.target.value),z(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:S,disabled:P,"data-testid":"onboarding-first-task-submit",children:P?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),R&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:R}),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(jT,{items:At}),fn&&t.jsxs(t.Fragment,{children:[t.jsx(zs,{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:q,disabled:de,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(qt,{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${He?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Ae,disabled:de||!He,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(es,{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"}),!He&&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(tn,{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:ot,disabled:de,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:It,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Nt,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:It,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Nt,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:Nt,disabled:!fn,children:"Next →"})]}),b==="first-task"&&!I&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ut,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:rt,disabled:de,children:de?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:kt,children:[t.jsx(tn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function vf({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 CT=a.lazy(()=>Wt(()=>import("./SetupWizardModal-BaQ8VkZm.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),ET=a.lazy(()=>Wt(()=>import("./SettingsModal-D1vZdAS4.js"),__vite__mapDeps([11,1,12,13,14,0,2,15])).then(e=>({default:e.SettingsModal})));function MT(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Wt(()=>import("./SettingsModal-D1vZdAS4.js"),__vite__mapDeps([11,1,12,13,14,0,2,15]))},{timeout:1500})}function _T({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,k=a.useCallback(()=>{c.openNewTask()},[c]),M=a.useCallback(()=>{c.openGitHubImport()},[c]),w=a.useCallback(y=>{v(null),c.closeModelOnboarding(),c.openDetailTask(y)},[c]),I=a.useCallback(async y=>{const E=await d.handleModalCreate(y);return c.modelOnboardingOpen&&v(E),E},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{MT()},[]),t.jsxs(t.Fragment,{children:[c.detailTask&&t.jsx(fi,{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(fi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(ET,{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(zM,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(fi,{children:t.jsx(BM,{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(fi,{children:t.jsx(GM,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(f_,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(b_,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(z_,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(K_,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e}),c.schedulesOpen&&t.jsx(hA,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(fi,{children:t.jsx(bA,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:I,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(jA,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:y=>{const E=n.find(N=>N.id===y);E&&c.openDetailTask(E)}}),t.jsx(fi,{children:t.jsx(NA,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(fi,{children:t.jsx(DA,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(WA,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(CT,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(ST,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:M,firstCreatedTask:b,onViewTask:w}),t.jsx(vf,{toasts:o,onRemove:l})]})}function AT({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 rc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function TT(e,n){if(n==="ready")return"done";const s=rc.findIndex(r=>r.id===n),i=rc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function RT({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:rc.map(n=>{const s=TT(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(it,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const IT=5e3;function PT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function $T(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++,Vr(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 DT(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 zy(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()},IT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=$T(e,s,i),f=PT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const LT={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},zT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function FT({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}=la(),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 k of e){const M=g.get(k.id),w=[k.status,k.updatedAt,M?.tabId??k.lockedByTab??"",M?.stale?"stale":"fresh"].join("|"),I=m.current.get(k.id);I&&I!==w&&v.add(k.id),x.set(k.id,w)}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(it,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Jc,{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=LT[v.type],k=v.status==="generating",M=v.status==="awaiting_input",w=v.status==="error",I=g.get(v.id),y=I?.tabId??v.lockedByTab??null,E=!!(y&&y!==p&&!I?.stale),N=c.has(v.id);return t.jsxs("div",{className:`background-tasks-indicator__item${N?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:N?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:N?"translateY(-1px)":void 0},onClick:()=>{E&&!window.confirm("This session is active in another tab. Open anyway?")||(i(v),l(!1))},children:[w?t.jsx(ss,{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:[w?"Failed":zT[v.type],k&&" — generating...",M&&!E&&" — needs input",M&&E&&" — active in another tab"]})]}),k&&t.jsx(it,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),M&&!E&&t.jsx(Jc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),M&&E&&t.jsx(ao,{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(Dt,{size:12})})]},v.id)})})]})]})}function OT(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 UT(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:rn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Fs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:vn}}}function BT({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}=DT(e,n,s,u),[f,b]=a.useState(!1),v=a.useMemo(()=>UT(h.executorState),[h.executorState]),x=a.useMemo(()=>OT(h.lastActivityAt),[h.lastActivityAt]),k=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(dc,{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(FT,{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(M=>!M),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(jn,{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(ji,{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(k,{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 HT={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},qT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},xi=new Set;function VT({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(xi.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of xi){const x=f.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(xi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!xi.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=>{xi.add(f),l()},g=f=>{xi.delete(f.id),l(),n(f)},p=()=>{for(const f of c)xi.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(ss,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Dt,{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=HT[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(ss,{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":qT[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(Dt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function WT({onResume:e}){const n=nT();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(Dn,{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(rn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function KT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=sa(),i=ff(),[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[M,w]=await Promise.all([qa(),ra()]);if(x)return;const I=M.providers??[],y=I.find(R=>R.id==="github"),N=!I.some(R=>R.id!=="github"&&R.authenticated),P=!w.defaultProvider&&!w.defaultModelId,_=y?!y.authenticated:!1;h({needsAiProvider:N,needsDefaultModel:P,needsGitHub:_})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const g=a.useCallback(()=>{eT(),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:vn}),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:lh}),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:es}),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(Us,{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 k=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(ss,{size:14,"aria-hidden":!0}),t.jsx(k,{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(Dt,{size:16,"aria-hidden":!0})})]})}function GT({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 Cl(e){return e>99?"99+":String(e)}function JT({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:k,onRunScript:M,projectId:w,onViewAllProjects:I,showSkillsTab:y,experimentalFeatures:E}){const N=sr(),[P,_]=a.useState(!1),[R,z]=a.useState(!1),[G,$]=a.useState({}),[T,j]=a.useState(!1),W=a.useMemo(()=>Object.entries(G).sort(([oe],[F])=>oe.localeCompare(F)),[G]);a.useEffect(()=>{if(!R)return;let oe=!1;return j(!0),er(w).then(F=>{oe||$(F)}).catch(()=>{oe||$({})}).finally(()=>{oe||j(!1)}),()=>{oe=!0}},[R,w]);const K=a.useCallback(()=>_(!1),[]),B=a.useCallback(oe=>{K(),oe?.()},[K]);if(a.useEffect(()=>{if(!P)return;const oe=F=>{F.key==="Escape"&&_(!1)};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[P]),N!=="mobile"||i)return null;const A=x>0&&v?v:b,L=!!E?.roadmap,X=!!y,C=L&&(!X||e==="roadmaps"),V=X&&(!L||e!=="roadmaps"),fe=X&&!V,ae=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"||e==="roadmaps"&&!C||e==="skills"&&!V;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(an,{}),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(ns,{}),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(Ki,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Cl(c)})]}),V&&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(vn,{}),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(Pl,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ae?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>_(oe=>!oe),children:[t.jsx(Tl,{}),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:K}),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(Ki,{}),t.jsx("span",{children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Cl(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(Os,{}),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(Bs,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>z(oe=>!oe),"aria-expanded":R,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(en,{size:14,className:`mobile-more-chevron${R?" mobile-more-chevron--open":""}`})})]}),R&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:T?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):W.length>0?t.jsxs(t.Fragment,{children:[W.map(([oe,F])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${oe}`,onClick:()=>{M&&M(oe,F),K(),z(!1)},children:[t.jsx(rn,{size:14}),t.jsx("span",{children:oe})]},oe)),h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{K(),z(!1),h()},children:[t.jsx(Ts,{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:()=>{K(),z(!1),h()},children:[t.jsx(Ts,{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(jn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>B(A),children:[t.jsx(Us,{}),t.jsx("span",{children:"Planning"}),x>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Cl(x)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>B(d),children:[t.jsx(Dl,{}),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(ji,{}),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(GT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>B(k),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(I),children:[t.jsx(oh,{}),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(vn,{}),t.jsx("span",{children:"Skills"})]}),L&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>B(()=>n("roadmaps")),children:[t.jsx(Pl,{}),t.jsx("span",{children:"Roadmaps"})]}),E?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>B(()=>n("insights")),children:[t.jsx(Dn,{}),t.jsx("span",{children:"Insights"})]}),E?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>B(()=>n("memory")),children:[t.jsx(Dr,{}),t.jsx("span",{children:"Memory"})]}),E?.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(ch,{size:14}),t.jsx("span",{children:"Dev Server"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>B(()=>n("todos")),children:[t.jsx(mh,{size:14}),t.jsx("span",{children:"Todos"})]}),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(Ba,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function YT({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(an,{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 Fc="__fn_agent__";function yf(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Fm(e,n,s){const i=typeof e=="string"?e.trim():"",r=yf(n,s),o=i||(r.modelProvider&&r.modelId?Fc:"");return o?{agentId:o,...r}:null}function El(e,n,s){const i=yf(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function QT(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 Om(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:QT(e.metadata),createdAt:e.createdAt}}function XT(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([]),[k,M]=a.useState(""),w=a.useRef(null),I=a.useRef(!1),y=a.useRef(""),E=a.useRef(""),N=a.useRef(null);a.useEffect(()=>{y.current=k},[k]);const P=a.useCallback(async B=>{const A={agentId:B.agentId};return B.modelProvider&&B.modelId&&(A.modelProvider=B.modelProvider,A.modelId=B.modelId),(await Qk(A,e)).session},[e]),_=a.useCallback(async(B,A,L)=>{const X=Fm(B,A,L);if(!X)return;const C=El(X.agentId,X.modelProvider,X.modelId);o(!0);try{const{session:V}=await Yk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},e);if(V)i(V),E.current=C;else{const fe=await P(X);i(fe),E.current=C}}catch(V){console.error("[useQuickChat] Failed to initialize session:",V),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,P]),R=a.useCallback(async()=>{if(s){d(!0);try{const B=await jd(s.id,{limit:50},e);c(B.messages.map(Om))}catch(B){console.error("[useQuickChat] Failed to load messages:",B)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?R():c([])},[s,R]);const z=a.useCallback(async()=>{if(s){d(!0);try{const B=await jd(s.id,{limit:50},e);c(B.messages.map(Om))}catch(B){console.error("[useQuickChat] Failed to reload messages:",B)}finally{d(!1)}}},[s,e]),G=a.useCallback(async(B,A,L)=>{const X=Fm(B,A,L);if(!X)return;const C=El(X.agentId,X.modelProvider,X.modelId);if(N.current=X,w.current&&(w.current.close(),w.current=null),p(""),b(""),x([]),h(!1),C===E.current&&s){await z();return}c([]),E.current=C,await _(X.agentId,X.modelProvider,X.modelId)},[_,z,s]),$=a.useCallback(async(B,A)=>{await G(Fc,B,A)},[G]),T=a.useCallback(async()=>{const B=N.current;if(!B)return;const A=El(B.agentId,B.modelProvider,B.modelId);w.current&&(w.current.close(),w.current=null),p(""),b(""),x([]),h(!1),c([]),o(!0);try{const L=await P(B);i(L),E.current=A}catch(L){console.error("[useQuickChat] Failed to start a fresh session:",L),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,P]),j=a.useCallback(()=>{s&&(I.current=!0,w.current?.close(),w.current=null,Xk(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),W=a.useCallback(()=>{y.current="",M("")},[]),K=a.useCallback(B=>{if(!s||!B.trim())return;if(m){y.current=B,M(B);return}I.current=!1,w.current&&(w.current.close(),w.current=null);const L={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:B,createdAt:new Date().toISOString()};c(ae=>[...ae,L]),p(""),b(""),x([]),h(!0);let X="",C="",V=[];const fe={onThinking:ae=>{C+=ae,b(C)},onText:ae=>{X+=ae,p(X)},onToolStart:ae=>{V=[...V,{toolName:ae.toolName,args:ae.args,isError:!1,status:"running"}],x(V)},onToolEnd:ae=>{const oe=[...V];for(let F=oe.length-1;F>=0;F--){const de=oe[F];if(de?.toolName===ae.toolName&&de.status==="running"){oe[F]={...de,status:"completed",isError:ae.isError,result:ae.result},V=oe,x(oe);return}}V=[...oe,{toolName:ae.toolName,isError:ae.isError,result:ae.result,status:"completed"}],x(V)},onDone:ae=>{const oe={id:ae.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:C||void 0,toolCalls:V.length>0?V:void 0,createdAt:new Date().toISOString()};c(de=>[...de,oe]),p(""),b(""),x([]),h(!1),w.current=null;const F=y.current.trim();F&&(y.current="",M(""),K(F))},onError:ae=>{if(p(""),b(""),x([]),h(!1),w.current=null,console.error("[useQuickChat] Stream error:",ae),n?.("Failed to get response","error"),!I.current){const oe=y.current.trim();oe&&(y.current="",M(""),K(oe))}z()}};w.current=Zk(s.id,B,fe,e)},[s,m,e,n,z]);return a.useEffect(()=>()=>{w.current&&(w.current.close(),w.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:k,sendMessage:K,stopStreaming:j,clearPendingMessage:W,switchSession:G,startModelChat:$,startFreshSession:T,loadMessages:R,reloadMessages:z}),[s,r,l,u,m,g,f,v,k,K,j,W,G,$,T,R,z])}function ZT(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 oa({...f,...g,includeEphemeral:g?.includeEphemeral??b},e),x=Array.from(new Map(v.map(k=>[k.id,k])).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 qs(`/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||!hj(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function eR({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(ah,{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 tR=200;function nR(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((y,E)=>{if(E<0||E>y.length){r(!1);return}const N=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=E-1;P>=0;P--){if(y[P]==="#")if(P===0){const _=y.slice(P+1,E);u(P),l(_),f(0),r(!0);return}else{const _=y[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const R=y.slice(P+1,E);u(P),l(R),f(0),r(!0);return}r(!1);return}if(!N(y[P])){r(!1);return}}r(!1)},[]),k=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),M=a.useCallback(async y=>{if(!y.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const E=await Uv(y,s,n);m(E.files),f(0)}catch(E){E.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M(o)},tR),()=>{b.current&&clearTimeout(b.current)}},[o,i,M]);const w=a.useCallback((y,E)=>{if(!i||c<0)return E;const N=E.slice(0,c),P=E.slice(c+1),_=P.match(/[\s]|$/),R=_?_.index:P.length,z=P.slice(R);return`${N}#${y.path}${z}`},[i,c]),I=a.useCallback((y,E)=>{if(!i||d.length===0)return!1;switch(y.key){case"ArrowDown":return y.preventDefault(),f(N=>Math.min(N+1,d.length-1)),!0;case"ArrowUp":return y.preventDefault(),f(N=>Math.max(N-1,0)),!0;case"Enter":case"Tab":return d[p]?(y.preventDefault(),!0):!1;case"Escape":return y.preventDefault(),k(),!0;default:return!1}},[i,d,p,k]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:x,selectFile:w,dismissMention:k,handleKeyDown:I}}const sR={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"},iR={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function aR(e){return`${e.name?.trim()||e.id} (${e.role})`}function rR(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 oR(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 $r(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function lR(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}=${$r(r,50)}`}).join(", ")}function cR(e){if(e===void 0)return null;if(typeof e=="string")return $r(e,200);try{return $r(JSON.stringify(e),200)}catch{return $r(String(e),200)}}function Um(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(rx,{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=lR(s.args),c=cR(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 dR={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 uR(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 mR(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,k=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,w=window.innerWidth-v-x,I=window.innerHeight-v-x-k-M;return{x:Math.max(x,Math.min(w,b.x)),y:Math.max(x,Math.min(I,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 k=u.current.x-v,M=u.current.y-x,w=m({x:k,y:M});o(w)}},[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 hR({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=ZT(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?Me=>{r?.(typeof Me=="function"?Me(p):Me)}:h,[b,v]=a.useState("agent"),[x,k]=a.useState(""),[M,w]=a.useState([]),[I,y]=a.useState(!1),[E,N]=a.useState(""),[P,_]=a.useState(""),[R,z]=a.useState(""),[G,$]=a.useState(!1),[T,j]=a.useState(0),[W,K]=a.useState(-1),[B,A]=a.useState(()=>new Set),[,L]=a.useState(!1),[X,C]=a.useState({top:0,left:0}),V=nR({projectId:e}),fe=a.useCallback(Me=>{if(!Me||!V.mentionActive)return;const Ye=Me.getBoundingClientRect();C({top:Ye.top-260,left:Ye.left+8})},[V.mentionActive]),ae=a.useRef(!1),oe=a.useRef(!1),F=a.useRef(""),de=a.useRef(0),re=a.useRef(null),{position:Z,isDragging:ue,handlePointerDown:Ce,handlePointerMove:he,handlePointerUp:Ne}=mR(e,ae),{activeSession:ee,messages:we,isStreaming:Ie,streamingText:qe,streamingThinking:Ve,streamingToolCalls:Ge,sessionsLoading:Ke,messagesLoading:Qe,sendMessage:Se,stopStreaming:Fe,pendingMessage:ie,clearPendingMessage:Q,switchSession:pe,startModelChat:te,startFreshSession:ye}=XT(e,n),ce=a.useRef(null),Re=a.useRef(null),Ze=a.useRef(null),at=a.useRef(null),le=a.useMemo(()=>rR(E),[E]),U=a.useMemo(()=>M.find(Me=>`${Me.provider}/${Me.id}`===E)??null,[M,E]),ne=a.useMemo(()=>oR(U,le),[U,le]),ke=a.useMemo(()=>b==="model"?le?`${Fc}::${le.modelProvider}/${le.modelId}`:"":x?`${x}::`:"",[b,le,x]),_e=b==="agent"?!!x:!!le;a.useEffect(()=>{if(d.length===0){k(""),v("model");return}d.some(Ye=>Ye.id===x)||k(d[0]?.id??"")},[d,x]),a.useEffect(()=>{!p||oe.current||(oe.current=!0,y(!0),is().then(Me=>{const Ye=Me.models??[];if(w(Ye),d.length===0&&Ye.length>0&&!E){const rt=Ye[0];rt&&N(`${rt.provider}/${rt.id}`)}}).catch(Me=>{console.error("[QuickChatFAB] Failed to load models:",Me),w([])}).finally(()=>{y(!1)}))},[p,d.length,E]),a.useEffect(()=>{if(!p){F.current="";return}if(!ke){F.current="";return}if(ke!==F.current){if(F.current=ke,b==="model"&&le){te(le.modelProvider,le.modelId);return}b==="agent"&&x&&pe(x)}},[p,b,le,x,ke,te,pe]),a.useEffect(()=>{p||($(!1),z(""),K(-1))},[p]);const ge=a.useCallback(Me=>{k(Me)},[]),He=a.useCallback(Me=>{N(Me)},[]),ve=a.useCallback(()=>{!_e||Ke||ye()},[_e,Ke,ye]),$e=a.useMemo(()=>d.find(Me=>Me.id===x)??null,[d,x]),ze=a.useMemo(()=>{const Me=R.trim().toLowerCase();return Me?d.filter(Ye=>Ye.name.toLowerCase().includes(Me)):d},[d,R]),me=a.useMemo(()=>{const Me=new Map;for(const Ye of d)Me.set(Ye.name.toLowerCase(),Ye);return Me},[d]);a.useEffect(()=>{j(0)},[R,G]),a.useEffect(()=>()=>{re.current!==null&&(window.clearTimeout(re.current),re.current=null)},[]),a.useEffect(()=>{if(!p)return;const Me=rt=>{const S=rt.target;ce.current?.contains(S)||Re.current?.contains(S)||S.closest(".model-combobox-dropdown--portal")||f(!1)},Ye=rt=>{rt.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Ye),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Ye)}},[p,f]),a.useEffect(()=>{if(!p)return;const Me=Ze.current;Me&&(Me.scrollTop=Me.scrollHeight)},[we,qe,Ve,p]);const Pe=a.useMemo(()=>b==="agent"?$e?`Message ${$e.name||$e.id}`:"Select an agent to start chatting":ne?`Message ${ne}`:"Select a model to start chatting",[b,$e,ne]),be=!_e||!ee||Ke,We=ie.length>50?`${ie.slice(0,50)}…`:ie,tt=a.useCallback(()=>{const Me=P.trim();!Me||be||(_(""),$(!1),z(""),K(-1),Se(Me))},[Se,be,P]),ct=a.useCallback((Me,Ye)=>{const rt=uR(Me,Ye);if(rt){$(!0),z(rt.filter),K(rt.start);return}$(!1),z(""),K(-1)},[]),wt=a.useCallback(Me=>{const Ye=at.current;if(!Ye||W<0)return;const rt=Ye.selectionStart??de.current,S=Ye.selectionEnd??rt,q=Math.max(rt,S),Ae=Math.min(W,q),kt=`${`@${Me.name.replace(/\s+/g,"_")}`} `,Ot=P.slice(0,Ae)+kt+P.slice(q),sn=Ae+kt.length;_(Ot),$(!1),z(""),j(0),K(-1),window.requestAnimationFrame(()=>{at.current&&(at.current.focus(),at.current.setSelectionRange(sn,sn))})},[W,P]),Nt=a.useCallback(Me=>{const Ye=Me.target.value,rt=Me.target.selectionStart??Ye.length;de.current=rt,_(Ye),ct(Ye,rt),V.detectMention(Ye,rt),L(V.mentionActive),V.mentionActive&&fe(Me.target)},[ct,V,fe]),It=a.useCallback(()=>{re.current!==null&&window.clearTimeout(re.current),re.current=window.setTimeout(()=>{$(!1),z(""),K(-1),L(!1),V.dismissMention(),re.current=null},120)},[V]),Ut=a.useCallback(()=>{re.current!==null&&(window.clearTimeout(re.current),re.current=null)},[]),Vt=a.useCallback(Me=>{const Ye=Me.currentTarget,rt=Ye.selectionStart??Ye.value.length;de.current=rt,ct(Ye.value,rt),V.detectMention(Ye.value,rt),L(V.mentionActive),V.mentionActive&&fe(Ye)},[ct,V,fe]),zt=a.useCallback(Me=>{Me.key!=="Escape"&&Vt(Me)},[Vt]),Mt=a.useCallback(Me=>{const Ye=/@([\w-]+)/g,rt=[];let S=0,q=Ye.exec(Me);for(;q;){const[Ae,ot=""]=q,kt=q.index;kt>S&&rt.push(Me.slice(S,kt));const Ot=ot.replace(/_/g," ").toLowerCase(),sn=me.get(Ot);sn?rt.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",sn.name.replace(/\s+/g,"_")]},`${sn.id}-${kt}`)):rt.push(Ae),S=kt+Ae.length,q=Ye.exec(Me)}return S<Me.length&&rt.push(Me.slice(S)),rt.length===0?Me:rt},[me]),xt=a.useCallback(Me=>{A(Ye=>{const rt=new Set(Ye);return rt.has(Me)?rt.delete(Me):rt.add(Me),rt})},[]),_t=a.useCallback((Me,Ye=!1)=>Ye?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Me}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Qs,{remarkPlugins:[Xs],components:dR,children:Me})}),[]),De=a.useCallback(Me=>{if(de.current=Me.currentTarget.selectionStart??de.current,V.mentionActive&&V.files.length>0){if(V.handleKeyDown(Me,P),Me.key==="Enter"||Me.key==="Tab"){const Ye=V.files[V.selectedIndex];if(Ye){const rt=V.selectFile(Ye,P);_(rt),V.dismissMention(),L(!1)}}return}if(G&&Me.key==="ArrowDown"){Me.preventDefault(),ze.length>0&&j(Ye=>(Ye+1)%ze.length);return}if(G&&Me.key==="ArrowUp"){Me.preventDefault(),ze.length>0&&j(Ye=>Ye===0?ze.length-1:Ye-1);return}if(G&&Me.key==="Enter"){Me.preventDefault();const Ye=ze[T]??ze[0];Ye&&wt(Ye);return}if(G&&Me.key==="Escape"){Me.preventDefault(),Me.stopPropagation(),$(!1),z(""),K(-1);return}Me.key!=="Enter"||Me.shiftKey||(Me.preventDefault(),tt())},[G,ze,T,wt,tt,V,P]),gt=a.useCallback(()=>{if(ae.current){ae.current=!1;return}f(Me=>!Me)},[f]),ut=Z.y+60;return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Re,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ue?"true":"false",style:{right:Z.x,bottom:Z.y},onPointerDown:Ce,onPointerMove:he,onPointerUp:Ne,onClick:gt,children:t.jsx(li,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:ce,"data-testid":"quick-chat-panel",style:{right:Z.x,bottom:ut},children:[t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{style:iR,children:[t.jsx("h3",{children:"Quick Chat"}),ne&&t.jsx("span",{style:sR,"data-testid":"quick-chat-model-tag",title:ne,children:ne})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:ve,disabled:!_e||Ke,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(Dt,{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"),N("")},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"),k("")},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:Me=>ge(Me.target.value),"data-testid":"quick-chat-agent-select",children:d.map(Me=>t.jsx("option",{value:Me.id,children:aR(Me)},Me.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(wn,{id:"quick-chat-model-override",models:M,value:E,onChange:He,label:"Select model override",placeholder:I?"Loading models…":"Select a model",disabled:I||M.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:Ke||Qe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):we.length===0&&!qe&&!Ve&&!Ie?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[we.map(Me=>{const Ye=Me.role==="user",rt=!Ye&&B.has(Me.id);return t.jsxs("div",{className:`quick-chat-panel-message ${Ye?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${Me.id}`,children:[Ye?t.jsx("p",{children:Mt(Me.content)}):t.jsxs(t.Fragment,{children:[_t(Me.content,rt),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${rt?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":rt?"Show rendered markdown":"Show plain text",onClick:()=>xt(Me.id),children:rt?t.jsx(Lr,{size:12}):t.jsx(Vi,{size:12})})]}),Um(Me.toolCalls,!0)]},Me.id)}),Ie&&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:[qe?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:_t(qe,B.has("__streaming__"))}),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${B.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":B.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>xt("__streaming__"),children:B.has("__streaming__")?t.jsx(Lr,{size:12}):t.jsx(Vi,{size:12})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ve?"Thinking…":"Connecting…"}),Um(Ge,!0),Ve&&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:Ve})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:at,type:"text",value:P,onChange:Nt,onKeyDown:De,onKeyUp:zt,onClick:Vt,onBlur:It,onFocus:Ut,placeholder:Pe,disabled:be,"data-testid":"quick-chat-input"}),t.jsx(YT,{agents:d,filter:R,highlightedIndex:T,visible:G,onSelect:wt,position:"above"}),t.jsx(eR,{visible:V.mentionActive&&!G,position:X,files:V.files,selectedIndex:V.selectedIndex,onSelect:Me=>{const Ye=V.selectFile(Me,P);_(Ye),V.dismissMention(),L(!1),at.current?.focus()},loading:V.loading}),ie&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${We}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Q,children:"×"})]})]}),Ie?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:Fe,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ls,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void tt(),disabled:be||P.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(vi,{size:16})})]})]})]})}function _a(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Bm(e){return e.status==="generating"||e.status==="awaiting_input"}function Aa(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}=la(),d=a.useCallback(()=>{_h(e).then(p=>{const f=p.filter(v=>{const x=_a(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:x<=k?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of f)b.set(v.id,_a(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,k=i.current.get(v.sessionId)??0;if(x<k)continue;const M=r.current.get(v.sessionId);if(M!==void 0&&x<=M)continue;if(M!==void 0&&x>M&&!Aa(v.status)&&r.current.delete(v.sessionId),Aa(v.status)){b.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,x);continue}const w=b.get(v.sessionId),I=v.type??w?.type,y=v.title??w?.title;if(!w&&(!I||!y))continue;const E={id:v.sessionId,type:I??"planning",status:v.status,title:y??"AI Session",projectId:v.projectId??w?.projectId??e??null,lockedByTab:v.owningTabId??w?.lockedByTab??null,updatedAt:v.updatedAt??w?.updatedAt??new Date(x).toISOString()},N=b.get(v.sessionId);(!N||N.status!==E.status||N.title!==E.title||N.type!==E.type||N.projectId!==E.projectId||N.lockedByTab!==E.lockedByTab||N.updatedAt!==E.updatedAt)&&(b.set(v.sessionId,E),i.current.set(v.sessionId,x),f=!0)}return f?[...b.values()].sort((v,x)=>_a(x.updatedAt)-_a(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const x=JSON.parse(v.data),k=_a(x.updatedAt)||Date.now();s(M=>{const w=i.current.get(x.id)??0;if(k<w)return M;const I=r.current.get(x.id);if(I!==void 0&&k<=I)return M;if(I!==void 0&&k>I&&!Aa(x.status)&&r.current.delete(x.id),i.current.set(x.id,k),Aa(x.status))return M.filter(E=>E.id!==x.id);const y=M.findIndex(E=>E.id===x.id);if(y>=0){const E=[...M];return E[y]=x,E}return Bm(x)?[x,...M]:M}),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:k}),Aa(x.status)&&c({sessionId:x.id,status:x.status,timestamp:k})}catch{}},b=v=>{try{const x=JSON.parse(v.data);s(k=>k.filter(M=>M.id!==x)),i.current.delete(x),r.current.delete(x)}catch{}};return qs(`/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(w=>w.id===p)?.type,v=_i();let x=!1,k=!1;if(b==="planning")try{await yh(p,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${p}: locked by another tab`))}else if(b==="subtask")try{await wh(p,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${p}: locked by another tab`))}else if(b==="mission_interview")try{await Mh(p,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${p}: locked by another tab`))}if(k)return;x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const M=Date.now();r.current.set(p,M),i.current.set(p,Math.max(i.current.get(p)??0,M)),c({sessionId:p,status:"complete",timestamp:M});try{await Fk(p)}catch{}s(w=>w.filter(I=>I.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Bm(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 In(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 Hm(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function fR(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,k=a.useCallback(async T=>{const j=++m.current,W=n,K=T?.searchQueryOverride??s,B=T?.includeArchivedOverride??u.current;try{const A=await Ax(void 0,void 0,W,K,B);if(m.current!==j||n!==W)return;o(A.map(In)),f.current=Date.now()}catch{if(m.current!==j||n!==W)return;if(T?.clearOnError){o([]);return}o(A=>A)}},[n,s]);p.current=k;const M=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const T=setTimeout(()=>{k({searchQueryOverride:s})},300);return()=>clearTimeout(T)},[s]),a.useEffect(()=>{k({clearOnError:!0});const T=()=>{if(document.visibilityState!=="visible")return;const j=Date.now();j-h.current<x||(h.current=j,k())};return document.addEventListener("visibilitychange",T),()=>{document.removeEventListener("visibilitychange",T)}},[k]),a.useEffect(()=>{if(i===!1)return;const T=b.current,j=n?`?projectId=${encodeURIComponent(n)}`:"",W=()=>b.current!==T;let K=!0;const B=fe=>{if(W())return;const ae=In(JSON.parse(fe.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(oe=>oe.some(F=>F.id===ae.id)?oe:[...oe,ae])},A=fe=>{if(W())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ae,to:oe}=JSON.parse(fe.data),F=In(ae);o(de=>de.map(re=>re.id===F.id?{...F,column:oe}:re)),f.current=Date.now()},L=fe=>{if(W())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ae=In(JSON.parse(fe.data));o(oe=>oe.map(F=>{if(F.id!==ae.id||Hm(ae.updatedAt,F.updatedAt)<0)return F;if(F.column===ae.column)return ae;const re=Hm(F.columnMovedAt,ae.columnMovedAt);return F.columnMovedAt&&!ae.columnMovedAt?{...ae,column:F.column,columnMovedAt:F.columnMovedAt}:re>0?{...ae,column:F.column,columnMovedAt:F.columnMovedAt}:ae})),f.current=Date.now()},X=fe=>{if(W())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ae=In(JSON.parse(fe.data));o(oe=>oe.filter(F=>F.id!==ae.id))},C=fe=>{if(W())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ae}=JSON.parse(fe.data),oe=In(ae);o(F=>F.map(de=>de.id===oe.id?{...oe,column:"done"}:de))},V=qs(`/api/events${j}`,{events:{"task:created":B,"task:moved":A,"task:updated":L,"task:deleted":X,"task:merged":C},onReconnect:()=>{K&&(W()||p.current())}});return()=>{K=!1,V()}},[n,i]);const w=a.useCallback(async T=>{const j=In(await gh(T,n));return o(W=>W.some(K=>K.id===j.id)?W:[...W,j]),j},[n]),I=a.useCallback(async(T,j)=>In(await Rx(T,j,n)),[n]),y=a.useCallback(async T=>In(await bh(T,n)),[n]),E=a.useCallback(async T=>In(await Ix(T,n)),[n]),N=a.useCallback(async T=>Px(T,n),[n]),P=a.useCallback(async T=>In(await $x(T,n)),[n]),_=a.useCallback(async T=>{const j=In(await Dx(T,n));return o(W=>W.some(K=>K.id===j.id)?W:[...W,j]),j},[n]),R=a.useCallback(async(T,j)=>{const W=d.current.find(B=>B.id===T),K=W?{...W,...j,updatedAt:new Date().toISOString()}:void 0;K&&o(B=>B.map(A=>A.id===T?K:A));try{const B=In(await Gs(T,j,n));return o(A=>A.map(L=>L.id===T?B:L)),B}catch(B){throw W&&o(A=>A.map(L=>L.id===T?W:L)),B}},[n]),z=a.useCallback(async T=>{const j=In(await zx(T,n));return o(W=>W.map(K=>K.id===T?j:K)),j},[n]),G=a.useCallback(async T=>{const j=In(await Fx(T,n));return o(W=>W.map(K=>K.id===T?j:K)),j},[n]),$=a.useCallback(async()=>{const j=(await Ox(n)).map(In);return o(W=>W.map(K=>j.find(A=>A.id===K.id)||K)),j},[n]);return{tasks:r,createTask:w,moveTask:I,pauseTask:y,deleteTask:E,mergeTask:N,retryTask:P,duplicateTask:_,updateTask:R,archiveTask:z,unarchiveTask:G,archiveAllDone:$,loadArchivedTasks:M,includeArchived:l,lastFetchTimeMs:f.current}}const gR=5e3,bR=1e3;function xR(){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 gd();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 gd(),k=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${k}`),Da("[useProjects]",k),g||(n(v),o(null))}catch(v){const k=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${k}`),Da("[useProjects]",k),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<bR||(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()},gR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Ly(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Uy(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await Sh(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 vR=1e4,yR=1e3;function kR(){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 bd();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 bd();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<yR||(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()},vR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await Iy(p);return n(b=>[...b,f]),f},[]),m=a.useCallback(async(p,f)=>{const b=await Py(p,f);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await $y(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 jR="kb-dashboard-current-project";function wR(e){return e??"local"}function NR(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=wR(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ra();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(k=>k.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(jR);if(x){const k=JSON.parse(x);k?.id&&e.some(w=>w.id===k.id)&&(r(k),c.current=!0,d.current={...d.current,[m]:k.id},await nn({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,nn({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,nn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,nn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const kf=a.createContext(null);function SR({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()},[]),Xm.createElement(kf.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function CR(){const e=a.useContext(kf);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const jf="kb-dashboard-theme-mode",wf="kb-dashboard-color-theme",Nf=[...uj],oc="theme-data",Ml="theme-data.css";function ER(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Ml}`:e.replace(/\/[^/]+$/,`/${Ml}`):`/${Ml}`}const Ns=typeof window<"u",MR=Ns?a.useLayoutEffect:a.useEffect;function Sf(e){return e==="dark"||e==="light"||e==="system"}function qm(){if(!Ns)return"dark";try{const e=localStorage.getItem(jf);if(Sf(e))return e}catch{}return"dark"}function Vm(){if(!Ns)return"default";try{const e=localStorage.getItem(wf);if(e&&Nf.includes(e))return e}catch{}return"default"}function Wm(e){if(Ns)try{localStorage.setItem(jf,e)}catch{}}function Km(e){if(Ns)try{localStorage.setItem(wf,e)}catch{}}function _R(e,n){return e==="system"?n?"dark":"light":e}function AR(e,n,s){if(!Ns)return;const i=_R(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Gm(){if(!Ns)return;const e=ER(),n=document.getElementById(oc);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=oc,document.head.appendChild(s)}function Jm(){if(!Ns)return;const e=document.getElementById(oc);e&&e.remove()}function TR(){const[e,n]=a.useState(()=>qm()),[s,i]=a.useState(()=>Vm()),[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 ra().then(b=>{f||(Sf(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),qm()!==b.themeMode&&Wm(b.themeMode)),b.colorTheme&&Nf.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Vm()!==b.colorTheme&&Km(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)},[]),MR(()=>{AR(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ns||r||(s!=="default"?Gm():Jm())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Wm(f),nn({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),Km(f),f!=="default"?Gm():Jm(),nn({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 RR(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),[k,M]=a.useState("definition"),[w,I]=a.useState(!1),[y,E]=a.useState(void 0),[N,P]=a.useState(!1),[_,R]=a.useState(!1),[z,G]=a.useState(!1),[$,T]=a.useState(!1),[j,W]=a.useState(void 0),[K,B]=a.useState(!1),[A,L]=a.useState("project"),[X,C]=a.useState(!1),[V,fe]=a.useState(!1),[ae,oe]=a.useState(!1),[F,de]=a.useState(!1),[re,Z]=a.useState(!1),[ue,Ce]=a.useState(!1),[he,Ne]=a.useState(!1),ee=!!(v||w||s||r||m||$||K||X||V||ae||re||F||z||N||_||ue||he),we=a.useCallback(()=>i(!0),[]),Ie=a.useCallback(()=>i(!1),[]),qe=a.useCallback(()=>o(!0),[]),Ve=a.useCallback(ut=>{c(ut),o(!0)},[]),Ge=a.useCallback(()=>{const ut=n[0];ut&&(d(ut.id),o(!0))},[n]),Ke=a.useCallback(ut=>{d(ut),o(!0)},[]),Qe=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),Se=a.useCallback(ut=>{p(ut),h(!0)},[]),Fe=a.useCallback(ut=>{b(ut),h(!0)},[]),ie=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),Q=a.useCallback((ut,Me="definition")=>{x(ut),M(Me)},[]),pe=a.useCallback(ut=>{x(ut),M("changes")},[]),te=a.useCallback(ut=>{x(Me=>Me&&{...Me,...ut})},[]),ye=a.useCallback(()=>{x(null)},[]),ce=a.useCallback(ut=>{E(ut),I(!0)},[]),Re=a.useCallback(()=>{I(!1),E(void 0)},[]),Ze=a.useCallback(()=>P(!0),[]),at=a.useCallback(()=>P(!1),[]),le=a.useCallback(()=>R(!0),[]),U=a.useCallback(()=>R(!1),[]),ne=a.useCallback(()=>G(!0),[]),ke=a.useCallback(()=>G(!1),[]),_e=a.useCallback(()=>{T(ut=>!ut)},[]),ge=a.useCallback(()=>{T(!1),W(void 0)},[]),He=a.useCallback(()=>B(!0),[]),ve=a.useCallback(()=>B(!1),[]),$e=a.useCallback(ut=>{L(ut)},[]),ze=a.useCallback(()=>C(!0),[]),me=a.useCallback(()=>C(!1),[]),Pe=a.useCallback(()=>fe(!0),[]),be=a.useCallback(()=>fe(!1),[]),We=a.useCallback(()=>oe(!0),[]),tt=a.useCallback(()=>oe(!1),[]),ct=a.useCallback(()=>de(!0),[]),wt=a.useCallback(()=>de(!1),[]),Nt=a.useCallback(()=>Z(!0),[]),It=a.useCallback(()=>Z(!1),[]),Ut=a.useCallback(async(ut,Me)=>{Z(!1),W(Me),T(!0)},[]),Vt=a.useCallback(()=>Ce(!0),[]),zt=a.useCallback(()=>Ce(!1),[]),Mt=a.useCallback(()=>Ne(!0),[]),xt=a.useCallback(()=>Ne(!1),[]),_t=a.useCallback((ut,Me)=>{Me(`Created ${ut.id} from planning mode`,"success"),o(!1),c(null)},[]),De=a.useCallback((ut,Me)=>{const Ye=ut.map(rt=>rt.id).join(", ");Me(`Created ${Ye} from planning mode`,"success"),o(!1),c(null)},[]),gt=a.useCallback((ut,Me)=>{const Ye=ut.map(rt=>rt.id).join(", ");Me(`Created ${Ye} 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:k,settingsOpen:w,settingsInitialSection:y,schedulesOpen:N,githubImportOpen:_,usageOpen:z,terminalOpen:$,terminalInitialCommand:j,filesOpen:K,fileBrowserWorkspace:A,activityLogOpen:X,gitManagerOpen:V,workflowStepsOpen:ae,agentsOpen:F,scriptsOpen:re,setupWizardOpen:ue,modelOnboardingOpen:he,anyModalOpen:ee,openNewTask:we,closeNewTask:Ie,openPlanning:qe,openPlanningWithInitialPlan:Ve,resumePlanning:Ge,openPlanningWithSession:Ke,closePlanning:Qe,openSubtaskBreakdown:Se,openSubtaskWithSession:Fe,closeSubtask:ie,openDetailTask:Q,openDetailWithChangesTab:pe,updateDetailTask:te,closeDetailTask:ye,openSettings:ce,closeSettings:Re,openSchedules:Ze,closeSchedules:at,openGitHubImport:le,closeGitHubImport:U,openUsage:ne,closeUsage:ke,toggleTerminal:_e,closeTerminal:ge,openFiles:He,closeFiles:ve,setFileWorkspace:$e,openActivityLog:ze,closeActivityLog:me,openGitManager:Pe,closeGitManager:be,openWorkflowSteps:We,closeWorkflowSteps:tt,openAgents:ct,closeAgents:wt,openScripts:Nt,closeScripts:It,runScript:Ut,openSetupWizard:Vt,closeSetupWizard:zt,openModelOnboarding:Mt,closeModelOnboarding:xt,onPlanningTaskCreated:_t,onPlanningTasksCreated:De,onSubtaskTasksCreated:gt}}function IR(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,k]=a.useState({}),[M,w]=a.useState(!1),[I,y]=a.useState(!1),[E,N]=a.useState(!1),[P,_]=a.useState(!1),R=a.useCallback(async()=>{const[j,W]=await Promise.allSettled([Hx(e),lo(e)]);if(j.status==="fulfilled"&&(s(j.value.maxConcurrent),r(j.value.rootDir)),W.status==="fulfilled"){const K=W.value;l(!!K.autoMerge),u(!!K.globalPause),m(!!K.enginePaused),v(!!K.prAuthAvailable),g(K.taskStuckTimeoutMs),f(K.showQuickChatFAB===!0),k(K.experimentalFeatures??{});const B=K.experimentalFeatures??{};w(B.insights===!0),y(B.roadmap===!0),N(B.memoryView===!0),_(B.devServerView===!0||B.devServer===!0)}},[e]);a.useEffect(()=>{R()},[R]);const z=a.useCallback(async()=>{const j=!o;l(j);try{await mr({autoMerge:j},e)}catch{l(!j)}},[o,e]),G=a.useCallback(async()=>{const j=!c;u(j);try{await mr({globalPause:j,globalPauseReason:j?"manual":void 0},e)}catch{u(!j)}},[c,e]),$=a.useCallback(async()=>{const j=!d;m(j);try{await mr({enginePaused:j},e)}catch{m(!j)}},[d,e]),T=a.useCallback(async()=>{const j=!p;f(j);try{await mr({showQuickChatFAB:j},e)}catch{f(!j)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:x,insightsEnabled:M,roadmapEnabled:I,memoryEnabled:E,devServerEnabled:P,toggleAutoMerge:z,toggleGlobalPause:G,toggleEnginePause:$,toggleShowQuickChatFAB:T,refresh:R}}function PR(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,Br(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 $R(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{is().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 nn({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 nn({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 DR({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;qa().then(({providers:l})=>{const c=l.some(d=>d.authenticated);if(l.length>0&&!c||l.length>0&&c)return ra().then(d=>{const m=!!(d.defaultProvider&&d.defaultModelId);(d.modelOnboardingComplete===!1||d.modelOnboardingComplete===void 0)&&(!c||!m)&&!sa()?r=!0:!c&&!sa()&&(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 LR=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Ym(e){return e!==null&&LR.includes(e)}function zR(e){return e==="devserver"?"dev-server":e}function FR(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=Nn("kb-dashboard-task-view");return Ym(x)?x:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Nn("kb-dashboard-task-view",r?.id);if(Ym(x)){const k=!f.current&&x==="devserver";p(k?"devserver":zR(x))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ts("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"],k=x.indexOf(u),M=x[(k+1)%x.length];d(M)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function OR(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(N=>{n(N),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(N=>{h(),n(N),i("project"),u(`Project ${N.name} registered successfully`,"success"),o()},[h,n,i,u,o]),k=a.useCallback(()=>{g()},[g]),M=a.useCallback(async N=>{try{await Fy(N.id),u(`Project ${N.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${N.name}`,"error")}},[u,o]),w=a.useCallback(async N=>{try{await Oy(N.id),u(`Project ${N.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${N.name}`,"error")}},[u,o]),I=a.useCallback(async N=>{try{await Sh(N.id),u(`Project ${N.name} removed`,"success"),r?.id===N.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${N.name}`,"error")}},[r,s,i,u,o]),y=a.useCallback(async N=>{try{await l(N)}catch{u("Failed to update favorites","error")}},[l,u]),E=a.useCallback(async N=>{try{await c(N)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:k,handlePauseProject:M,handleResumeProject:w,handleRemoveProject:I,handleToggleFavorite:y,handleToggleModelFavorite:E}}function UR(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 BR(e){return uo("/health",{nodeId:e})}async function HR(e){return uo("/projects",{nodeId:e})}async function qR(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),uo(`/tasks?${i.toString()}`,{nodeId:e})}async function VR(e,n){return uo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function $P(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function DP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function LP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function zP(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function WR(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 k=[BR(e),HR(e)];s&&(k.push(qR(e,s,i)),k.push(VR(e,s)));const M=await Promise.allSettled(k);if(x.signal.aborted)return;const w=M[0],I=M[1];if(w.status==="rejected"){p(`Failed to fetch node health: ${w.reason}`),h(!1);return}if(d(w.value),I.status==="rejected"){p(`Failed to fetch projects: ${I.reason}`),h(!1);return}if(o(I.value),s&&M[2]){const y=M[2];if(y.status==="rejected"){p(`Failed to fetch tasks: ${y.reason}`),h(!1);return}y.status==="fulfilled"&&c(y.value)}h(!1)}catch(k){x.signal.aborted||(p(k instanceof Error?k.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 KR(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 qs(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 GR="fusion-dashboard-current-node",Cf=a.createContext(null);function JR({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 ra();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(GR);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(l.current=b.id,await nn({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,nn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(Cf.Provider,{value:d,children:e})}function YR(){const e=a.useContext(Cf);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function QR({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&&(vx(l),window.location.reload())},[n]),o=a.useCallback(()=>{yx(),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 XR=a.lazy(()=>Wt(()=>import("./AgentsView-CYVTv2_l.js").then(e=>e.A),__vite__mapDeps([16,1,17,8,18])).then(e=>({default:e.AgentsView}))),ZR=a.lazy(()=>Wt(()=>import("./DocumentsView-oB319uCj.js"),__vite__mapDeps([19,1,0,2,20])).then(e=>({default:e.DocumentsView}))),eI=a.lazy(()=>Wt(()=>import("./InsightsView-BHdMNnOa.js"),__vite__mapDeps([21,1,14,0,2,22])).then(e=>({default:e.InsightsView}))),tI=a.lazy(()=>Wt(()=>import("./NodesView-BfOlOj-Q.js"),__vite__mapDeps([23,1,17,0,2,24])).then(e=>({default:e.NodesView}))),nI=a.lazy(()=>Wt(()=>import("./ChatView-ByPhfQZ6.js"),__vite__mapDeps([25,1,0,2])).then(e=>({default:e.ChatView}))),sI=a.lazy(()=>Wt(()=>import("./RoadmapsView-DtgL8yl3.js"),__vite__mapDeps([26,1,0,2,27])).then(e=>({default:e.RoadmapsView}))),iI=a.lazy(()=>Wt(()=>import("./SkillsView-DAvaRl37.js"),__vite__mapDeps([28,1,0,2,29])).then(e=>({default:e.SkillsView}))),aI=a.lazy(()=>Wt(()=>import("./MemoryView-BDJMlzlM.js"),__vite__mapDeps([30,1,12,13,0,2,31])).then(e=>({default:e.MemoryView}))),rI=a.lazy(()=>Wt(()=>import("./DevServerView-CD7mgC11.js"),__vite__mapDeps([32,1,0,2,33])).then(e=>({default:e.DevServerView}))),oI=a.lazy(()=>Wt(()=>import("./TodoView-BXRQSmSw.js"),__vite__mapDeps([34,1,35,0,2,36])).then(e=>({default:e.TodoView})));function lI(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Wt(()=>import("./AgentsView-CYVTv2_l.js").then(n=>n.A),__vite__mapDeps([16,1,17,8,18])),Wt(()=>import("./DocumentsView-oB319uCj.js"),__vite__mapDeps([19,1,0,2,20])),Wt(()=>import("./InsightsView-BHdMNnOa.js"),__vite__mapDeps([21,1,14,0,2,22])),Wt(()=>import("./NodesView-BfOlOj-Q.js"),__vite__mapDeps([23,1,17,0,2,24])),Wt(()=>import("./ChatView-ByPhfQZ6.js"),__vite__mapDeps([25,1,0,2])),Wt(()=>import("./RoadmapsView-DtgL8yl3.js"),__vite__mapDeps([26,1,0,2,27])),Wt(()=>import("./SkillsView-DAvaRl37.js"),__vite__mapDeps([28,1,0,2,29])),Wt(()=>import("./MemoryView-BDJMlzlM.js"),__vite__mapDeps([30,1,12,13,0,2,31])),Wt(()=>import("./DevServerView-CD7mgC11.js"),__vite__mapDeps([32,1,0,2,33])),Wt(()=>import("./TodoView-BXRQSmSw.js"),__vite__mapDeps([34,1,35,0,2,36]))})}const _l="kb-setup-warning-dismissed";function cI(){const{toasts:e,addToast:n,removeToast:s}=CR(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{lI()},[]);const{projects:r,loading:o,error:l,refresh:c}=xR(),{nodes:u}=kR(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=YR(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:x}=NR(r,{nodeId:m}),{hasAiProvider:k,hasGithub:M,loading:w,hasWarnings:I}=hf(f?.id);a.useEffect(()=>{if(m&&!d&&u.length>0){const dt=u.find(se=>se.id===m);if(dt){g(dt);return}}m&&u.length>0&&(u.some(se=>se.id===m)||p())},[m,d,u,g,p]);const[y,E]=a.useState(""),N=WR(m,{projectId:f?.id,searchQuery:y||void 0});KR(m);const P=h&&N.projects.length>0?N.projects:r,{themeMode:_,colorTheme:R,setThemeMode:z,setColorTheme:G}=TR(),{sessions:$,generating:T,needsInput:j,planningSessions:W,dismissSession:K}=pR(f?.id),B=$.filter(dt=>dt.status==="awaiting_input"||dt.status==="error"),A=RR({projectId:f?.id,planningSessions:W}),{viewMode:L,setViewMode:X,taskView:C,handleChangeTaskView:V}=FR({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:f,projectsLength:r.length,setupWizardOpen:A.setupWizardOpen,openSetupWizard:A.openSetupWizard,themeMode:_,setThemeMode:z}),fe=a.useCallback(dt=>{dt==="missions"&&(ne(void 0),_e(void 0),He(void 0)),V(dt)},[V]),ae=C==="board"||C==="list",{tasks:oe,createTask:F,moveTask:de,pauseTask:re,deleteTask:Z,mergeTask:ue,retryTask:Ce,updateTask:he,duplicateTask:Ne,archiveTask:ee,unarchiveTask:we,archiveAllDone:Ie,loadArchivedTasks:qe,lastFetchTimeMs:Ve}=fR({...f?{projectId:f.id}:{},searchQuery:y||void 0,sseEnabled:ae}),[Ge,Ke]=a.useState(!1),Qe=a.useRef(performance.now()),Se=a.useRef(!1),Fe=a.useRef(!1),ie=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!Se.current){Se.current=!0;const dt=`projects loaded at ${Math.round(performance.now()-Qe.current)}ms from mount`;console.log(`[App] ${dt}`),Da("[App]",dt)}if(!x&&!Fe.current){Fe.current=!0;const dt=`current-project resolved at ${Math.round(performance.now()-Qe.current)}ms from mount`;console.log(`[App] ${dt}`),Da("[App]",dt)}},[o,x]),a.useEffect(()=>{if(Ge||o||x)return;const dt=performance.now(),se=window.setTimeout(()=>{const Ee=`dashboard ready at ${Math.round(performance.now()-Qe.current)}ms from mount (settle delay=${Math.round(performance.now()-dt)}ms)`;console.log(`[App] ${Ee}`),Da("[App]",Ee),Ke(!0)},200);return()=>{window.clearTimeout(se)}},[Ge,o,x]);const pe=sr()==="mobile",[te,ye]=a.useState(0),ce=a.useCallback(()=>{Ah(f?.id).then(dt=>{ye(dt.unreadCount)}).catch(dt=>{console.warn("[App] Failed to fetch mailbox unread count:",dt)})},[f?.id]);a.useEffect(()=>{ce();const dt=new URLSearchParams;f?.id&&dt.set("projectId",f.id);const se=dt.size>0?`?${dt.toString()}`:"";return qs(`/api/events${se}`,{events:{"message:sent":ce,"message:received":ce,"message:read":ce,"message:deleted":ce}})},[f?.id,ce]);const[Re,Ze]=a.useState(!1),[at,le]=a.useState(!1),[U,ne]=a.useState(void 0),[ke,_e]=a.useState(void 0),[ge,He]=a.useState(void 0),[ve,$e]=a.useState(!1),[ze,me]=a.useState(!1),[Pe,be]=a.useState(()=>Nn(_l,f?.id)==="true");a.useEffect(()=>{be(Nn(_l,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const dt=()=>{me(!0)};return window.addEventListener(zl,dt),()=>{window.removeEventListener(zl,dt)}},[]);const We=a.useCallback(()=>{ts(_l,"true",f?.id),be(!0)},[f?.id]),{maxConcurrent:tt,autoMerge:ct,globalPaused:wt,enginePaused:Nt,taskStuckTimeoutMs:It,showQuickChatFAB:Ut,prAuthAvailable:Vt,experimentalFeatures:zt,insightsEnabled:Mt,roadmapEnabled:xt,memoryEnabled:_t,devServerEnabled:De,toggleAutoMerge:gt,toggleGlobalPause:ut,toggleEnginePause:Me,refresh:Ye}=IR(f?.id),rt=zt.skillsView===!0,S=zt.nodesView===!0,q=!0;a.useEffect(()=>{Object.keys(zt).length!==0&&(C==="insights"&&!Mt&&V("board"),C==="roadmaps"&&!xt&&V("board"),C==="memory"&&!_t&&V("board"),(C==="devserver"||C==="dev-server")&&!De&&V("board"))},[C,Mt,xt,zt,V,q,_t,De]),a.useEffect(()=>{Re&&!S&&Ze(!1)},[Re,S]);const{availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn}=$R();DR({projectId:f?.id,openModelOnboarding:A.openModelOnboarding,openSettings:A.openSettings});const{handleSelectProject:Pt,handleViewAllProjects:zn,handleOpenSettings:Kn,handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn,handlePauseProject:Sn,handleResumeProject:fn,handleRemoveProject:Gn,handleToggleFavorite:dn,handleToggleModelFavorite:At}=OR({setCurrentProject:b,clearCurrentProject:v,setViewMode:X,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn,addToast:n,openSettings:A.openSettings,openSetupWizard:A.openSetupWizard,closeSetupWizard:A.closeSetupWizard,closeModelOnboarding:A.closeModelOnboarding}),{handleDetailClose:yn}=PR({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:A.openDetailTask,closeTaskDetail:A.closeDetailTask}),{handleBoardQuickCreate:Jn,handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On}=UR({createTask:F,onPlanningTaskCreated:A.onPlanningTaskCreated,onPlanningTasksCreated:A.onPlanningTasksCreated,onSubtaskTasksCreated:A.onSubtaskTasksCreated,addToast:n}),J=a.useCallback((dt,se)=>{if(se==="changes"){A.openDetailWithChangesTab(dt);return}A.openDetailTask(dt,se)},[A]),Le=a.useCallback(()=>{S&&Ze(dt=>!dt)},[S]),nt=a.useCallback(()=>{A.setFileWorkspace("project"),A.openFiles()},[A]),et=a.useCallback(async()=>{le(!0);try{await c()}finally{le(!1)}},[c]),mt=a.useCallback(dt=>{_e(dt),ne(void 0),V("missions")},[V]),jt=a.useCallback(dt=>{dt.type==="planning"?A.openPlanningWithSession(dt.id):dt.type==="subtask"?A.openSubtaskWithSession(dt.id):dt.type==="mission_interview"?(_e(void 0),ne(dt.id),He(void 0),V("missions")):(dt.type==="milestone_interview"||dt.type==="slice_interview")&&(ne(void 0),_e(void 0),He(dt.id),V("missions"))},[V,A]),Tt=a.useCallback(()=>{for(const dt of B)K(dt.id)},[K,B]),gn=!o&&!x&&r.length===0&&!f&&!!l,fs=()=>gn?t.jsx(AT,{errorMessage:l??"Failed to fetch projects",isRetrying:at,onRetry:et}):Re?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(tI,{addToast:n,onClose:()=>Ze(!1)})})})}):L==="overview"?t.jsx(Hn,{children:t.jsx(Tw,{projects:r,loading:o,onSelectProject:Pt,onAddProject:ms,onPauseProject:Sn,onResumeProject:fn,onRemoveProject:Gn,nodes:u})}):C==="skills"?rt?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(iI,{addToast:n,projectId:f?.id,onClose:()=>V("board")})})}):(V("board"),null):C==="chat"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(nI,{addToast:n,projectId:f?.id})})}):C==="mailbox"?t.jsx(Hn,{children:t.jsx(wN,{projectId:f?.id,addToast:n,onUnreadCountChange:ye})}):C==="roadmaps"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(sI,{addToast:n,projectId:f?.id})})}):C==="missions"?t.jsx(Hn,{children:t.jsx(vN,{isInline:!0,isOpen:!0,onClose:()=>{_e(void 0),ne(void 0),He(void 0),V("board")},addToast:n,projectId:f?.id,onSelectTask:dt=>{const se=oe.find(Ee=>Ee.id===dt);se&&A.openDetailTask(se)},availableTasks:oe.map(dt=>({id:dt.id,title:dt.title})),resumeSessionId:U,targetMissionId:ke,milestoneSliceResumeSessionId:ge,onMilestoneSliceResumeFetchError:()=>He(void 0)})}):C==="agents"&&q?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(XR,{addToast:n,projectId:f?.id})})}):C==="documents"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(ZR,{projectId:f?.id,addToast:n,onOpenDetail:A.openDetailTask})})}):C==="insights"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(eI,{projectId:f?.id,addToast:n,onClose:()=>V("board")})})}):C==="memory"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(aI,{addToast:n,projectId:f?.id})})}):C==="todos"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(oI,{addToast:n,projectId:f?.id})})}):C==="devserver"||C==="dev-server"?t.jsx(Hn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(rI,{addToast:n,projectId:f?.id})})}):C==="board"?t.jsx(Hn,{children:t.jsx(vw,{tasks:h&&N.tasks.length>0?N.tasks:oe,projectId:f?.id,maxConcurrent:tt,onMoveTask:de,onPauseTask:re,onOpenDetail:A.openDetailTask,addToast:n,onQuickCreate:Jn,onNewTask:A.openNewTask,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,autoMerge:ct,onToggleAutoMerge:gt,globalPaused:wt,onUpdateTask:he,onArchiveTask:ee,onUnarchiveTask:we,onDeleteTask:Z,onArchiveAllDone:Ie,onLoadArchivedTasks:qe,searchQuery:y,availableModels:Ae,onOpenDetailWithTab:J,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:At,taskStuckTimeoutMs:It,onOpenMission:mt,lastFetchTimeMs:Ve})}):t.jsx(Hn,{children:t.jsx(kw,{tasks:h&&N.tasks.length>0?N.tasks:oe,projectId:f?.id,onMoveTask:de,onOpenDetail:A.openDetailTask,addToast:n,globalPaused:wt,onNewTask:A.openNewTask,onQuickCreate:Jn,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:At,taskStuckTimeoutMs:It,searchQuery:y,lastFetchTimeMs:Ve})});if(!Ge)return t.jsxs(t.Fragment,{children:[t.jsx(RT,{stage:ie}),t.jsx(vf,{toasts:e,onRemove:s})]});const Xt=!A.modelOnboardingOpen&&tT(),vt=!A.modelOnboardingOpen&&!Xt&&sa()&&!ff();return t.jsxs(t.Fragment,{children:[t.jsx(rj,{isElectron:i,onOpenSettings:Kn,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:W.length,onOpenUsage:A.openUsage,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>fe("mailbox"),mailboxUnreadCount:te,onOpenSchedules:A.openSchedules,onOpenGitManager:A.openGitManager,onOpenNodes:Le,showNodesButton:S,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenScripts:A.openScripts,onRunScript:A.runScript,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,filesOpen:A.filesOpen,globalPaused:wt,enginePaused:Nt,onToggleGlobalPause:ut,onToggleEnginePause:Me,view:C,onChangeView:L==="project"&&f?fe:void 0,showSkillsTab:rt,showAgentsTab:q,searchQuery:y,onSearchChange:E,projects:P,currentProject:f,onSelectProject:Pt,onViewAllProjects:zn,projectId:f?.id,mobileNavEnabled:pe,availableNodes:u,currentNode:d,onSelectNode:dt=>{dt===null?p():g(dt)},isRemote:h,experimentalFeatures:{insights:Mt,roadmap:xt,memoryView:_t,devServer:De,devServerView:De}}),L==="project"&&f&&!Re&&C!=="missions"&&!A.isPlanningOpen&&t.jsx(VT,{sessions:B,onResumeSession:jt,onDismissSession:K,onDismissAll:Tt}),L==="project"&&f&&Xt&&t.jsx(WT,{onResume:A.openModelOnboarding}),L==="project"&&f&&vt&&t.jsx(KT,{onOpenModelOnboarding:A.openModelOnboarding,onOpenSettings:dt=>A.openSettings(dt)}),L==="project"&&f&&!w&&I&&!Pe&&t.jsx(pf,{hasAiProvider:k,hasGithub:M,onDismiss:We}),t.jsx("div",{className:`project-content${L==="project"&&f?" project-content--with-footer":""}${pe?" project-content--with-mobile-nav":""}`,children:fs()}),L==="project"&&f&&!Re&&t.jsx(BT,{tasks:h&&N.tasks.length>0?N.tasks:oe,projectId:f.id,taskStuckTimeoutMs:It,backgroundSessions:$,backgroundGenerating:T,backgroundNeedsInput:j,onOpenBackgroundSession:jt,onDismissBackgroundSession:K,lastFetchTimeMs:Ve,currentProjectPath:f.path,onOpenProjectDirectory:nt}),t.jsx(JT,{view:C,onChangeView:L==="project"&&f?fe:()=>{},footerVisible:L==="project"&&!!f,modalOpen:A.anyModalOpen,onOpenSettings:Kn,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>fe("mailbox"),mailboxUnreadCount:te,onOpenGitManager:A.openGitManager,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenSchedules:A.openSchedules,onOpenScripts:A.openScripts,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:W.length,onOpenUsage:A.openUsage,onViewAllProjects:zn,onRunScript:A.runScript,projectId:f?.id,showSkillsTab:rt,experimentalFeatures:{insights:Mt,roadmap:xt,memoryView:_t,devServer:De,devServerView:De}}),L==="project"&&f&&C!=="chat"&&C!=="mailbox"&&C!=="insights"&&C!=="devserver"&&C!=="dev-server"&&t.jsx(hR,{projectId:f.id,addToast:n,showFAB:Ut,open:ve,onOpenChange:$e,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:At}),t.jsx(_T,{projectId:f?.id,tasks:oe,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:A,projectActions:{handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn},taskHandlers:{handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On},taskOperations:{moveTask:de,deleteTask:Z,mergeTask:ue,retryTask:Ce,duplicateTask:Ne},deepLink:{handleDetailClose:yn},settings:{prAuthAvailable:Vt,themeMode:_,colorTheme:R,setThemeMode:z,setColorTheme:G},onSettingsClose:()=>{A.closeSettings(),Ye()},onReopenOnboarding:()=>{A.closeSettings(),A.openModelOnboarding()}}),t.jsx(QR,{open:ze})]})}function dI(){return t.jsx(SR,{children:t.jsx(JR,{children:t.jsx(cI,{})})})}Ex();mx();Tf.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(hx,{children:t.jsx(dI,{})})}));"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{KI as $,Ss as A,an as B,tn as C,en as D,rn as E,Ni as F,so as G,Nl as H,Ht as I,Fs as J,Lt as K,it as L,VA as M,_y as N,zA as O,Mn as P,FA as Q,hn as R,Bi as S,dc as T,Ay as U,Ty as V,h4 as W,Dt as X,WI as Y,vn as Z,Wt as _,ts as a,V4 as a$,Br as a0,Fv as a1,Lr as a2,Vi as a3,ia as a4,Qs as a5,Xs as a6,Ys as a7,SP as a8,MP as a9,wP as aA,NP as aB,Xk as aC,Zk as aD,nR as aE,sr as aF,lc as aG,YT as aH,eR as aI,ls as aJ,vi as aK,li as aL,rx as aM,A4 as aN,R4 as aO,T4 as aP,I4 as aQ,P4 as aR,$4 as aS,D4 as aT,L4 as aU,z4 as aV,F4 as aW,O4 as aX,U4 as aY,B4 as aZ,H4 as a_,EP as aa,CP as ab,_P as ac,Dn as ad,ss as ae,Zb as af,Us as ag,Ng as ah,to as ai,ji as aj,LP as ak,$P as al,DP as am,zP as an,Fr as ao,qb as ap,Ba as aq,vg as ar,qn as as,uh as at,kR as au,xR as av,jP as aw,jd as ax,Va as ay,Qk as az,j4 as b,sv as b$,W4 as b0,q4 as b1,xn as b2,cc as b3,wi as b4,yP as b5,vP as b6,kP as b7,EI as b8,CI as b9,sy as bA,GI as bB,aa as bC,ro as bD,ch as bE,G4 as bF,J4 as bG,Y4 as bH,Q4 as bI,X4 as bJ,Z4 as bK,eP as bL,K4 as bM,Gi as bN,Ly as bO,vx as bP,yx as bQ,Wf as bR,x_ as bS,zI as bT,M4 as bU,hI as bV,qa as bW,w4 as bX,pI as bY,gI as bZ,mv as b_,SI as ba,MI as bb,DI as bc,LI as bd,II as be,AI as bf,TI as bg,RI as bh,_I as bi,NI as bj,PI as bk,R_ as bl,QI as bm,YI as bn,s4 as bo,JI as bp,XI as bq,ZI as br,e4 as bs,t4 as bt,oy as bu,n4 as bv,mc as bw,iy as bx,ay as by,ry as bz,Ue as c,hP as c$,Hs as c0,iv as c1,av as c2,rv as c3,UI as c4,N4 as c5,S4 as c6,C4 as c7,AP as c8,TP as c9,sd as cA,eb as cB,lP as cC,f4 as cD,d4 as cE,m4 as cF,u4 as cG,x4 as cH,b4 as cI,ih as cJ,l4 as cK,o4 as cL,LA as cM,p4 as cN,Ya as cO,GE as cP,a4 as cQ,i4 as cR,Ov as cS,r4 as cT,c4 as cU,cP as cV,dP as cW,Lb as cX,$l as cY,gP as cZ,bP as c_,_4 as ca,fI as cb,jn as cc,A_ as cd,KA as ce,Rm as cf,mo as cg,bI as ch,xI as ci,vI as cj,yI as ck,kI as cl,jI as cm,wI as cn,om as co,RP as cp,IP as cq,$I as cr,tP as cs,sP as ct,rP as cu,iP as cv,nP as cw,aP as cx,oP as cy,Nh as cz,y4 as d,mP as d0,pP as d1,uP as d2,fP as d3,E4 as d4,BI as d5,FI as d6,OI as d7,qI as d8,VI as d9,HI as da,k4 as e,xP as f,Nn as g,is as h,oa as i,wn as j,My as k,v4 as l,ZT as m,lo as n,mr as o,xe as p,hj as q,g4 as r,qs as s,Il as t,nn as u,Os as v,qt as w,zr as x,OA as y,PP as z};