@runfusion/fusion 0.9.4 → 0.10.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 (40) hide show
  1. package/dist/bin.js +1382 -557
  2. package/dist/client/assets/{AgentDetailView-5W1q48YS.js → AgentDetailView-BtpZ4jxh.js} +1 -1
  3. package/dist/client/assets/{AgentsView-DcEnemu0.js → AgentsView-Dxdtt0Bm.js} +3 -3
  4. package/dist/client/assets/ChatView-Bra9fNAG.js +1 -0
  5. package/dist/client/assets/{DevServerView-LOrDrAYm.js → DevServerView-UkgjEw9-.js} +1 -1
  6. package/dist/client/assets/{DirectoryPicker-Bgp6PCbu.js → DirectoryPicker-Cls4HWxP.js} +1 -1
  7. package/dist/client/assets/{DocumentsView-CNbnZ7Q3.js → DocumentsView-BRBUPFVA.js} +1 -1
  8. package/dist/client/assets/{InsightsView-CmJwV-ZC.js → InsightsView-BRDqHCLb.js} +1 -1
  9. package/dist/client/assets/{MemoryView-Bwi5p79s.js → MemoryView-DvTrwFnQ.js} +1 -1
  10. package/dist/client/assets/{NodesView-1pZii99I.js → NodesView-C4Ffl_o0.js} +1 -1
  11. package/dist/client/assets/{PiExtensionsManager-CokhM-MB.js → PiExtensionsManager-CeI1syeZ.js} +3 -3
  12. package/dist/client/assets/{PluginManager-cHaGKMgY.js → PluginManager-BgeoYhLk.js} +1 -1
  13. package/dist/client/assets/{ResearchView-CQDI2y7Q.js → ResearchView-fmEOm4A2.js} +1 -1
  14. package/dist/client/assets/{RoadmapsView-BTo3BT0I.js → RoadmapsView-DNb4x75S.js} +1 -1
  15. package/dist/client/assets/SettingsModal-CDPDmHhd.css +1 -0
  16. package/dist/client/assets/{SettingsModal-D5slUUsC.js → SettingsModal-CRMr4tL6.js} +1 -1
  17. package/dist/client/assets/SettingsModal-D1xq0WZm.js +31 -0
  18. package/dist/client/assets/{SetupWizardModal-1qSn8Yl0.js → SetupWizardModal-tF8B_aG_.js} +1 -1
  19. package/dist/client/assets/{SkillsView-CY3I5OYc.js → SkillsView-uyl47gSf.js} +1 -1
  20. package/dist/client/assets/{TodoView-B1GDwwhR.js → TodoView-CbzDtV53.js} +1 -1
  21. package/dist/client/assets/{folder-open-DPESt6bg.js → folder-open-DPpmGJ-v.js} +1 -1
  22. package/dist/client/assets/{index-2_pvFDiN.css → index-BqK6TvSa.css} +1 -1
  23. package/dist/client/assets/index-DyXZm9QN.js +656 -0
  24. package/dist/client/assets/{list-checks-D7D9kx7Y.js → list-checks-D62pw1I8.js} +1 -1
  25. package/dist/client/assets/{star-C59_6aNu.js → star-B8EbxNgI.js} +1 -1
  26. package/dist/client/assets/{upload-1I0eQddJ.js → upload-CpnLno9z.js} +1 -1
  27. package/dist/client/assets/{users-DH50eBCX.js → users-B_C_0qzA.js} +1 -1
  28. package/dist/client/index.html +2 -2
  29. package/dist/client/version.json +1 -1
  30. package/dist/extension.js +1025 -358
  31. package/dist/pi-claude-cli/index.ts +31 -5
  32. package/dist/pi-claude-cli/package.json +1 -1
  33. package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +90 -0
  34. package/dist/pi-claude-cli/src/__tests__/provider.test.ts +13 -3
  35. package/dist/pi-claude-cli/src/process-manager.ts +65 -0
  36. package/package.json +1 -1
  37. package/dist/client/assets/ChatView-CTc6mP8y.js +0 -1
  38. package/dist/client/assets/SettingsModal-EEQwF0Ql.js +0 -31
  39. package/dist/client/assets/SettingsModal-FfIAhzcJ.css +0 -1
  40. package/dist/client/assets/index-DNIrnlpO.js +0 -656
@@ -1,656 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-1qSn8Yl0.js","assets/DirectoryPicker-Bgp6PCbu.js","assets/folder-open-DPESt6bg.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-EEQwF0Ql.js","assets/SettingsModal-D5slUUsC.js","assets/SettingsModal-FfIAhzcJ.css","assets/users-DH50eBCX.js","assets/star-C59_6aNu.js","assets/SettingsModal-9HS8MnmW.css","assets/AgentsView-DcEnemu0.js","assets/upload-1I0eQddJ.js","assets/AgentsView-MotzGhZJ.css","assets/DocumentsView-CNbnZ7Q3.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-CmJwV-ZC.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-CQDI2y7Q.js","assets/ResearchView-BVJFgfat.css","assets/NodesView-1pZii99I.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-CTc6mP8y.js","assets/RoadmapsView-BTo3BT0I.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-CY3I5OYc.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-Bwi5p79s.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-LOrDrAYm.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-B1GDwwhR.js","assets/list-checks-D7D9kx7Y.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
2
- import{r as a,j as t,R as xo,a as ca,g as Gh,c as Mg}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 Jh=(...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 Ag=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 Rg=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 zd=e=>{const n=Rg(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 ml={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
28
- * @license lucide-react v1.7.0 - ISC
29
- *
30
- * This source code is licensed under the ISC license.
31
- * See the LICENSE file in the root directory of this source tree.
32
- */const Tg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Pg=a.createContext({}),Ig=()=>a.useContext(Pg),$g=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=""}=Ig()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...ml,width:n??d??ml.width,height:n??d??ml.height,stroke:e??g,strokeWidth:f,className:Jh("lucide",p,r),...!o&&!Tg(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 Be=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement($g,{ref:o,iconNode:n,className:Jh(`lucide-${Ag(zd(e))}`,`lucide-${e}`,i),...r}));return s.displayName=zd(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 Dg=[["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"}]],zs=Be("activity",Dg);/**
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 Lg=[["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"}]],Lo=Be("archive",Lg);/**
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 zg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],wr=Be("arrow-down",zg);/**
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 Og=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ca=Be("arrow-left",Og);/**
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 Fg=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Nr=Be("arrow-right",Fg);/**
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 Ug=[["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"}]],Yh=Be("arrow-up-down",Ug);/**
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 Bg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Di=Be("arrow-up",Bg);/**
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 Hg=[["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"}]],qg=Be("book-open",Hg);/**
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 Vg=[["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"}]],Sn=Be("bot",Vg);/**
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 Wg=[["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"}]],jc=Be("box",Wg);/**
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 Kg=[["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"}]],vo=Be("brain",Kg);/**
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 Gg=[["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"}]],Qh=Be("calendar",Gg);/**
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 Jg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Yg=Be("check-check",Jg);/**
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 Qg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Bn=Be("check",Qg);/**
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 Xg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Yt=Be("chevron-down",Xg);/**
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 Zg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],zo=Be("chevron-left",Zg);/**
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 eb=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],kn=Be("chevron-right",eb);/**
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 tb=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],mi=Be("chevron-up",tb);/**
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 nb=[["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"}]],hs=Be("circle-alert",nb);/**
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 sb=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],wn=Be("circle-check-big",sb);/**
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 ib=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Oo=Be("circle-dot",ib);/**
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 ab=[["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"}]],kc=Be("circle-question-mark",ab);/**
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 rb=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],ob=Be("circle-stop",rb);/**
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 lb=[["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"}]],Sr=Be("circle-x",lb);/**
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 cb=[["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"}]],db=Be("clipboard-list",cb);/**
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 ub=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],wi=Be("clock",ub);/**
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 mb=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Xh=Be("code",mb);/**
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 hb=[["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"}]],pb=Be("columns-3",hb);/**
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 fb=[["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"}]],zi=Be("copy",fb);/**
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 gb=[["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"}]],bb=Be("cpu",gb);/**
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 xb=[["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"}]],vb=Be("download",xb);/**
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 yb=[["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"}]],jb=Be("ellipsis-vertical",yb);/**
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 kb=[["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"}]],wc=Be("ellipsis",kb);/**
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 wb=[["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"}]],Nb=Be("external-link",wb);/**
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 Sb=[["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"}]],Nc=Be("eye-off",Sb);/**
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 Cb=[["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"}]],ha=Be("eye",Cb);/**
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 Eb=[["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"}]],Ws=Be("file-code",Eb);/**
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 _b=[["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"}]],Sc=Be("file-diff",_b);/**
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 Mb=[["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"}]],Ab=Be("file-minus",Mb);/**
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 Rb=[["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"}]],Zh=Be("file-pen",Rb);/**
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 Tb=[["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"}]],Pb=Be("file-plus",Tb);/**
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 Ib=[["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"}]],$b=Be("file-question-mark",Ib);/**
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 Db=[["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"}]],Oi=Be("file-text",Db);/**
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 Lb=[["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"}]],zb=Be("file-type",Lb);/**
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 Ob=[["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"}]],ep=Be("file",Ob);/**
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 Fb=[["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"}]],Cc=Be("folder-git-2",Fb);/**
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 Ub=[["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"}]],Od=Be("folder-root",Ub);/**
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 Bb=[["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"}]],Wn=Be("folder",Bb);/**
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 Hb=[["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"}]],yo=Be("funnel",Hb);/**
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 qb=[["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"}]],Js=Be("git-branch",qb);/**
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 Vb=[["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"}]],Cr=Be("git-commit-horizontal",Vb);/**
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 Wb=[["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"}]],tp=Be("git-merge",Wb);/**
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 Kb=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],Ns=Be("git-pull-request",Kb);/**
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 Gb=[["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"}]],Fo=Be("globe",Gb);/**
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 Jb=[["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"}]],np=Be("grid-3x3",Jb);/**
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 Yb=[["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"}]],id=Be("grip-vertical",Yb);/**
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 Qb=[["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"}]],Xb=Be("hard-drive",Qb);/**
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 Zb=[["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"}]],ex=Be("heart",Zb);/**
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 tx=[["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"}]],hr=Be("history",tx);/**
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 nx=[["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"}]],ir=Be("inbox",nx);/**
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 sx=[["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"}]],sp=Be("key",sx);/**
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 ix=[["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"}]],ax=Be("keyboard",ix);/**
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 rx=[["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"}]],Fi=Be("layers",rx);/**
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 ox=[["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"}]],Ui=Be("layout-grid",ox);/**
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 lx=[["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"}]],ii=Be("lightbulb",lx);/**
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 cx=[["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"}]],pa=Be("link",cx);/**
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 dx=[["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"}]],ux=Be("list-plus",dx);/**
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 mx=[["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"}]],Uo=Be("list-tree",mx);/**
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 hx=[["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"}]],Ec=Be("list",hx);/**
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 px=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=Be("loader-circle",px);/**
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 fx=[["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"}]],Bo=Be("lock",fx);/**
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 gx=[["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"}]],fa=Be("mail",gx);/**
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 bx=[["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"}]],_c=Be("map",bx);/**
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 xx=[["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"}]],Ho=Be("maximize-2",xx);/**
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 vx=[["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"}],["path",{d:"M12 8v6",key:"1ib9pf"}],["path",{d:"M9 11h6",key:"1fldmi"}]],yx=Be("message-square-plus",vx);/**
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 jx=[["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"}]],ji=Be("message-square",jx);/**
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 kx=[["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"}]],Er=Be("minimize-2",kx);/**
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 wx=[["path",{d:"M5 12h14",key:"1ays0h"}]],Nx=Be("minus",wx);/**
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 Sx=[["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"}]],pr=Be("monitor",Sx);/**
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 Cx=[["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"}]],Ex=Be("move",Cx);/**
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 _x=[["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"}]],Mc=Be("package",_x);/**
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 Mx=[["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"}]],ip=Be("paperclip",Mx);/**
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 Ax=[["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"}]],Ks=Be("pause",Ax);/**
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 Rx=[["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"}]],us=Be("pencil",Rx);/**
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 Tx=[["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"}]],Cn=Be("play",Tx);/**
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 Px=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],ln=Be("plus",Px);/**
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 Ix=[["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"}]],ap=Be("radio",Ix);/**
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 $x=[["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"}]],Pn=Be("refresh-cw",$x);/**
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 Dx=[["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"}]],Fd=Be("rocket",Dx);/**
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 Lx=[["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"}]],zx=Be("rotate-ccw",Lx);/**
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 Ox=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]],Fx=Be("rotate-cw",Ox);/**
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 Ux=[["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"}]],rp=Be("save",Ux);/**
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 Bx=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],yi=Be("search",Bx);/**
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 Hx=[["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"}]],$i=Be("send",Hx);/**
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 qx=[["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=Be("server",qx);/**
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 Vx=[["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"}]],lr=Be("settings",Vx);/**
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 Wx=[["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"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]],Kx=Be("shield-alert",Wx);/**
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 Gx=[["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"}]],Jx=Be("shield",Gx);/**
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 Yx=[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]],Qx=Be("skull",Yx);/**
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 Xx=[["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"}]],rs=Be("sparkles",Xx);/**
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 Zx=[["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"}]],op=Be("square-check-big",Zx);/**
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 ev=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],ws=Be("square",ev);/**
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 tv=[["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"}]],vs=Be("target",tv);/**
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 nv=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],di=Be("terminal",nv);/**
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 sv=[["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"}]],jo=Be("text-wrap",sv);/**
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 iv=[["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"}]],on=Be("trash-2",iv);/**
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 av=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],rv=Be("trending-up",av);/**
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 ov=[["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"}]],ad=Be("triangle-alert",ov);/**
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 lv=[["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"}]],Ud=Be("unlink",lv);/**
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 cv=[["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"}]],ea=Be("user",cv);/**
588
- * @license lucide-react v1.7.0 - ISC
589
- *
590
- * This source code is licensed under the ISC license.
591
- * See the LICENSE file in the root directory of this source tree.
592
- */const dv=[["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"}]],lp=Be("webhook",dv);/**
593
- * @license lucide-react v1.7.0 - ISC
594
- *
595
- * This source code is licensed under the ISC license.
596
- * See the LICENSE file in the root directory of this source tree.
597
- */const uv=[["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"}]],Ac=Be("workflow",uv);/**
598
- * @license lucide-react v1.7.0 - ISC
599
- *
600
- * This source code is licensed under the ISC license.
601
- * See the LICENSE file in the root directory of this source tree.
602
- */const mv=[["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"}]],Bd=Be("wrench",mv);/**
603
- * @license lucide-react v1.7.0 - ISC
604
- *
605
- * This source code is licensed under the ISC license.
606
- * See the LICENSE file in the root directory of this source tree.
607
- */const hv=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Kt=Be("x",hv);/**
608
- * @license lucide-react v1.7.0 - ISC
609
- *
610
- * This source code is licensed under the ISC license.
611
- * See the LICENSE file in the root directory of this source tree.
612
- */const pv=[["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=Be("zap",pv),Rc="fusion:version-reload",Tc="fusion:version-update";function fv(){try{if(sessionStorage.getItem(Tc))return sessionStorage.removeItem(Tc),!0}catch{}return!1}function cp(e){if(sessionStorage.getItem(Rc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Rc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function gv(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 bv(e){return gv(e)?(cp(`chunk load error: ${e?.message??e}`),!0):!1}async function xv(){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 hl=!1;async function pl(){if(!(hl||document.visibilityState!=="visible")){hl=!0;try{const e=await xv();if(e&&e!=="molf2rkt-e94c1494"){try{sessionStorage.setItem(Tc,"1")}catch{}cp(`build version changed: molf2rkt-e94c1494 -> ${e}`)}}finally{hl=!1}}}function vv(){window.setTimeout(()=>sessionStorage.removeItem(Rc),5e3),document.addEventListener("visibilitychange",()=>{pl()}),window.addEventListener("focus",()=>{pl()}),window.setTimeout(()=>void pl(),2e3)}class qo 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),!bv(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(ad,{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 is({children:e,onError:n}){return t.jsx(qo,{level:"page",onError:n,children:e})}function Ri({children:e,onError:n}){return t.jsx(qo,{level:"modal",onError:n,children:e})}function yv({children:e,onError:n}){return t.jsx(qo,{level:"root",onError:n,children:e})}const jv="modulepreload",kv=function(e){return"/"+e},Hd={},dn=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=kv(d),d in Hd)return;Hd[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":jv,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)})},rd="fn.authToken",qd="token",wv="fn_token";let ua,Vd=!1,ko=!1;const Pc="fn:auth-token-recovery-required";function Nv(){try{const e=window.localStorage.getItem(rd);return e&&e.length>0?e:void 0}catch{return}}function dp(e){try{window.localStorage.setItem(rd,e)}catch{}}function Sv(){if(!(Vd||typeof window>"u")){Vd=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(qd);if(!n)return;dp(n),e.searchParams.delete(qd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ga(){if(ua!==void 0)return ua;const e=Sv();if(e)return ua=e,e;const n=Nv();if(n)return ua=n,n}function Cv(e){ua=e,ko=!1,dp(e)}function Ev(){ua=void 0,ko=!1;try{window.localStorage.removeItem(rd)}catch{}}function Wd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function _v(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Mv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!_v(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Wd(e.protocol)===Wd(n.protocol);return s&&i&&r}function Av(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 ai(e){const n=ga();if(!n||typeof window>"u")return e;const s=Av(e);return!s||!Mv(s.parsed)?e:(s.parsed.searchParams.set(wv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function hi(e){const n=ga();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Rv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Tv(){typeof window>"u"||ko||(ko=!0,window.dispatchEvent(new CustomEvent(Pc)))}async function Pv(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();Rv(i)&&Tv()}catch{}}function Iv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ga();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ga(),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=>(Pv(u),u))}}class $v extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function Dv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function fs(e){return`/api${e}`}async function D(e,n={}){const s=fs(e),i=ga(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),hi(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")||Dv(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 $v(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function jI(){return D("/health")}function kI(){return D("/updates/check")}function Lv(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 gr(e,n){const i=fs(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:hi({"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 up(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:S,priority:j,source:A}=e;return D(W("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:S,priority:j,source:A})})}function si(e,n,s){return D(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function zv(e,n,s,i,r,o,l,c,u){return D(W("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Ov(e,n,s){return D(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Fv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return D(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Uv(e,n){return D(W(`/tasks/${e}/merge`,n),{method:"POST"})}function Bv(e,n){return D(W(`/tasks/${e}/retry`,n),{method:"POST"})}function Hv(e,n){return D(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function mp(e,n){return D(W(`/tasks/${e}/pause`,n),{method:"POST"})}function qv(e,n){return D(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function Vv(e,n){return D(W(`/tasks/${e}/archive`,n),{method:"POST"})}function Wv(e,n){return D(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Kv(e){return D(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Gv(e,n){return D(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Jv(e,n){return D(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Yv(e){return D(W("/config",e))}function Vo(e){return D(W("/settings",e))}function Hr(e,n){return D(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Qv(e){return D(W("/update-check",e))}function wI(e){return D(W("/remote/settings",e))}function NI(e,n){return D(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function SI(e){return D(W("/remote/status",e))}function CI(e){return D(W("/remote/install-cloudflared",e),{method:"POST"})}function EI(e){return D(W("/remote/tunnel/start",e),{method:"POST"})}function _I(e){return D(W("/remote/tunnel/stop",e),{method:"POST"})}function MI(e){return D(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function AI(e,n){return D(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function hp(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 RI(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=hp(null,s,i);return D(W(`/remote/url${r}`,n))}function TI(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=hp(e,i,r);return D(W(`/remote/qr${o}`,s))}function PI(e){return D(W("/memory",e))}function II(e,n){return D(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function $I(e){return D(W("/memory/files",e))}function DI(e,n){const s=`path=${encodeURIComponent(e)}`;return D(W(`/memory/file?${s}`,n))}function LI(e,n,s){return D(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function zI(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(W("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function OI(e){return D(W("/memory/dream",e),{method:"POST"})}function FI(e){return D(W("/memory/insights",e))}function UI(e,n){return D(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function BI(e){return D(W("/memory/extract",e),{method:"POST"})}function HI(e){return D(W("/memory/audit",e))}function qI(e){return D(W("/memory/stats",e))}function VI(e){return D(W("/memory/backend",e))}function WI(e){return D(W("/memory/install-qmd",e),{method:"POST"})}function KI(e,n){return D(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Wi(){return D("/settings/global")}function fn(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function GI(e){return D(W("/settings/scopes",e))}function JI(e){return D(W("/settings/pi-extensions",e))}function YI(e,n){return D(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function QI(e,n,s){return D(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function XI(){return D("/pi-settings")}async function ZI(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function e$(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function t$(e){return D(W("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function br(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(fs(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:hi(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Xv(e,n,s){return D(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Kd(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=W(`/tasks/${e}/logs${r}`,n),l=await fetch(fs(o),{headers:hi()});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 Zv(e,n,s,i){return D(W(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function ey(e,n,s){return D(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function ty(e,n){return D(W(`/tasks/${e}/documents`,n))}function ny(e,n,s){return D(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function n$(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(W(r,n))}function s$(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return D(W(r,e))}function Gd(e,n,s,i,r){return D(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function sy(e,n,s){return D(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function iy(e,n,s){return D(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function ay(e,n,s){return D(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ry(e,n){return D(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function oy(e,n,s){return D(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ps(){return D("/models")}function ly(){return D("/usage")}function cy(){return D("/providers/claude-cli/status")}async function i$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/hermes/status${n}`)}async function a$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await D(`/providers/hermes/profiles${n}`)).profiles??[]}async function r$(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/openclaw/status${n}`)}async function o$(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),D(`/providers/paperclip/status?${n.toString()}`)}async function l$(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await D(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function c$(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await D(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function d$(e){return D("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function u$(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return D(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function m$(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await D(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function h$(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await D(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function p$(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return D(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function dy(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function uy(){const n=(await D("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function my(e){return D("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function f$(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return D(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function g$(e){return D(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function hy(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return my({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function xr(){return D("/auth/status")}function py(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function fy(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function gy(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function by(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function xy(e,n,s,i){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function vy(e,n,s,i){return D(W("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function yy(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function jy(e,n,s,i){return D(W("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ky(e){return D(W("/git/remotes",e))}function wy(e){return D(W("/git/remotes/detailed",e))}function Ny(e,n,s){return D(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Sy(e,n){return D(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Cy(e,n,s){return D(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Ey(e,n,s){return D(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function _y(e,n,s){return D(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function My(e,n){return D(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Ay(e,n){return(await D(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function qr(e,n,s,i){return D(W("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Jd(e,n){return D(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Ry(e){return D(W("/terminal/sessions",e))}function qs(e){return D(W("/git/status",e))}function Ty(e,n){const s=e?`?limit=${e}`:"";return D(W(`/git/commits${s}`,n))}function wo(e,n){return D(W(`/git/commits/${e}/diff`,n))}function Py(e){return D(W("/git/commits/ahead",e))}function Iy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Oa(e){return D(W("/git/branches",e))}function $y(e,n,s){const i=`?limit=${n}`;return D(W(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Dy(e){return D(W("/git/worktrees",e))}function Ly(e,n,s){return D(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function zy(e,n){return D(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Yd(e,n,s){const i=n?"?force=true":"";return D(W(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function Oy(e,n){return D(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Fy(e){return D(W("/git/pull",e),{method:"POST"})}function Uy(e){return D(W("/git/push",e),{method:"POST"})}function Vr(e){return D(W("/git/stashes",e))}function By(e,n){return D(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Hy(e,n,s){return D(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function qy(e,n){return D(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function Vy(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),D(W(`/git/diff/file?${i.toString()}`,s))}function ta(e){return D(W("/git/changes",e))}function Qd(e,n){return D(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Wy(e,n){return D(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Xd(e,n){return D(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Ky(e,n){return D(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Gy(e){return D(W("/workspaces",e))}function Jy(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 Yy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Qy(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 Xy(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 Zy(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 ej(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 tj(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 nj(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 pp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function sj(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function ij(e,n,s){return D(W("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function aj(e,n,s,i){return D(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function rj(e,n,s){return D(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function oj(e,n,s){return D(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function fp(e,n,s){return D(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function lj(e,n,s){return D(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function cj(e,n,s){return D(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function dj(e,n,s){return D(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Ic=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Ic))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function uj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function _r(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=uj(e,u),f=new EventSource(ai(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))f.addEventListener(b,x=>{const y=x;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),Ic.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Ic.add(g),g}function Zd(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 ba(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 mj(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 hj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>mj(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function pj(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 eu(e){return Array.isArray(e)?e.map(Zd):(e.candidates??[]).map(Zd)}async function fj(e){try{const n=await D(W("/dev-server/candidates",e));return eu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(W("/dev-server/detect",e));return eu(s)}throw n}}function od(e){return D(W("/dev-server/status",e)).then(ba)}async function b$(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(W(`/dev-server/logs/history${i}`,n));return hj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await od(n);return pj(o.logs,e)}throw r}}function gj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return D(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(ba)}function bj(e){return D(W("/dev-server/stop",e),{method:"POST"}).then(ba)}function xj(e){return D(W("/dev-server/restart",e),{method:"POST"}).then(ba)}async function vj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await D(W("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return ba(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await D(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return ba(r)}throw i}}function x$(e){return fs(W("/dev-server/logs/stream",e))}async function v$(e){try{return(await D(W("/devserver",e))).sessions??[]}catch{try{const n=await od(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 y$(e,n){try{return await D(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await od(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 j$(e,n){try{return await D(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await gj({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 k$(e,n){try{return await D(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await bj(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 w$(e,n){try{return await D(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await xj(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 N$(e,n,s){try{const i=await D(W(`/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 vj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function S$(e){try{return(await D(W("/devserver/detect",e))).candidates??[]}catch{try{return(await fj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function C$(e,n){return fs(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Mr(e,n,s=25e3){const i=setInterval(()=>{Zk(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function yj(e,n){return fs(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function jj(e,n,s,i){const r=yj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Ar(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 kj(e){return D(Ar("/routines",e))}function wj(e,n){return D(Ar("/routines",n),{method:"POST",body:JSON.stringify(e)})}function tu(e,n,s){return D(Ar(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Nj(e,n){await D(Ar(`/routines/${e}`,n),{method:"DELETE"})}function Sj(e,n){return D(Ar(`/routines/${e}/trigger`,n),{method:"POST"})}function nu(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 Cj(e){const n=W("/activity",e);return D(n,{method:"DELETE"})}function Wo(e){return D(W("/workflow-steps",e))}function su(e,n){return D(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Ej(e,n,s){return D(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _j(e,n){return D(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function iu(e,n){return D(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Mj(e,n){return D(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Aj(){return D("/workflow-step-templates")}function Rj(e,n){return D(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function vr(e){return D(W("/scripts",e))}function Tj(e,n,s){return D(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Pj(e,n){return D(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function gp(e,n,s){return(await D(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Wr={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 bp(e){if(!(e instanceof Error))return Wr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Wr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Wr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Wr.NETWORK}function Ij(e,n){return D(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function $j(e,n,s){return D(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Dj(e,n){return fs(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Lj(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=_r(Dj(e,n),{onOpen:()=>{l(),r=Mr(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 zj(e,n,s,i){return D(W("/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 xp(e,n,s){return D(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Oj(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 Ko(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Oj(e,s,i);return D(o,r)}function Ea(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 vp(e,n){return D(W(`/agents/${encodeURIComponent(e)}`,n))}function Fj(e,n){return D(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Uj(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function E$(e,n){return D(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function _$(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function M$(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function A$(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function R$(e,n){return D(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function T$(e,n,s){const i=`path=${encodeURIComponent(n)}`;return D(W(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function P$(e,n,s,i){return D(W(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Bj(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Hj(e,n){return D(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function I$(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 $$(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function D$(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function L$(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function z$(e,n){return D(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function qj(e){return D(W("/agents/stats",e))}function O$(e,n){return D(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function F$(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 U$(e,n){return D(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function au(e,n,s){return D(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function B$(e,n){return D(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function H$(){return D("/agents/companies")}function q$(e,n){return D(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function V$(e,n){return D(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function W$(e,n){return D(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function K$(e){return D(W("/backups",e))}function G$(e){return D(W("/backups",e),{method:"POST"})}function J$(e,n){const s=W("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(i)}function Y$(e,n,s){return D(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function ru(){return D("/projects/across-nodes")}function cr(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function No(){return D("/nodes")}function Vj(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function Wj(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Kj(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Gj(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 Q$(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=ga();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return D(u)}function Jj(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function yp(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function ou(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function Yj(e){return D(W("/executor/stats",e))}function Qj(e){return D(W("/system-stats",e))}function Xj(e){return D(W("/kill-vitest",e),{method:"POST"})}function lu(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 Zj(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function ek(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function X$(){return D("/global-concurrency")}function Z$(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function tk(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function jp(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 nk(e){return D(W("/missions",e))}function sk(e,n){return D(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function kp(e,n){return D(W(`/missions/${encodeURIComponent(e)}`,n))}function ik(e,n,s){return D(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ak(e,n){return D(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rk(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(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function ok(e){return D(W("/missions/health",e))}function lk(e,n,s){return D(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function ck(e,n,s){return D(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function dk(e,n){return D(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function uk(e,n,s){return D(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function mk(e,n,s){return D(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hk(e,n){return D(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function pk(e,n){return D(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function fk(e,n,s){return D(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function gk(e,n,s){return D(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function bk(e,n){return D(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xk(e,n,s){return D(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function vk(e,n){return D(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function yk(e,n,s,i){return D(W(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function jk(e,n){return D(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function fl(e,n){return D(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function kk(e,n,s){return D(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function wk(e,n,s){return D(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Nk(e,n,s){return D(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Sk(e,n,s){return D(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Ck(e,n){return D(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function gl(e,n){return D(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function cu(e,n){return D(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function Ek(e,n){return D(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function du(e,n){return D(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function _k(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(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function Mk(e,n){return D(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function Ak(e,n){return D(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function Rk(e,n){return D(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function Tk(e,n){return D(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Pk(e,n,s){return D(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Ik(e,n,s){return D(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function $k(e,n,s,i){return D(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Dk(e,n,s){return D(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function wp(e,n,s){return D(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Lk(e,n,s){return D(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function zk(e,n,s,i){const r=fs(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Rr(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Tr(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Ok(e,n){return D(Rr(e,"/start",n),{method:"POST"})}function Fk(e,n,s,i){return D(Rr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Uk(e,n,s,i){const r=fs(Rr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Bk(e,n,s){return D(Rr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Hk(e,n){return D(Rr(e,"/skip",n),{method:"POST"})}function qk(e,n){return D(Tr(e,"/start",n),{method:"POST"})}function Vk(e,n,s,i){return D(Tr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Wk(e,n,s,i){const r=fs(Tr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=_r(r,{onOpen:()=>{c(),o=Mr(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 Kk(e,n,s){return D(Tr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Gk(e,n){return D(Tr(e,"/skip",n),{method:"POST"})}async function Jk(e,n){try{return await D(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function eD(e){return D(W("/roadmaps",e))}function tD(e,n){return D(W("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function nD(e,n){return D(W(`/roadmaps/${encodeURIComponent(e)}`,n))}function sD(e,n,s){return D(W(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function iD(e,n){return D(W(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function aD(e,n,s){return D(W(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function rD(e,n,s){return D(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oD(e,n){return D(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function lD(e,n,s){return D(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function cD(e,n,s){return D(W(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function dD(e,n){return D(W(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function uD(e,n,s){return D(W(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function mD(e,n,s){return D(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function hD(e,n,s,i){return D(W(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function pD(e,n){return D(W(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function fD(e,n,s,i){return D(W(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function gD(e,n,s){return D(W(`/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 bD(e){return D(W("/todos",e))}function xD(e,n){const s={title:e};return D(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function vD(e,n,s){const i={title:n};return D(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function yD(e,n){return D(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function jD(e,n,s){const i={text:n};return D(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function kD(e,n,s){const i=n;return D(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function wD(e,n){return D(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ND(e,n,s){return D(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function xa(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function ld(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(fs(`/ai-sessions${n}`),{headers:hi()});return s.ok?(await s.json()).sessions??[]:[]}async function ui(e){const n=await fetch(fs(`/ai-sessions/${encodeURIComponent(e)}`),{headers:hi()});return n.ok?n.json():null}async function Yk(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 Qk(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Xk(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Np(e){await fetch(fs(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:hi()})}function Zk(e,n){return D(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function ew(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 tw(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 Sp(e){return D(W("/messages/unread-count",e))}function nw(e,n){return D(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function sw(e,n){return D(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function iw(e){return D(W("/messages/read-all",e),{method:"POST"})}function aw(e,n){return D(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rw(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(W(i,s))}function ow(e,n){return D(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function SD(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 CD(e,n){return D(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function ED(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 _D(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 MD(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function AD(e,n){return D(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function RD(e,n,s){return D(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function TD(e,n){return D(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function PD(e,n){return D(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function ID(e){return D(W("/plugins",e))}async function $D(e,n){return D(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function DD(e,n){return D(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function LD(e,n){return D(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function zD(e,n){return D(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function OD(e,n){return D(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function FD(e,n,s){return D(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function UD(e,n){return D(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function lw(e){return D(W("/plugins/ui-slots",e))}async function BD(e){return D(W("/plugins/runtimes",e))}async function HD(e){return(await D(W("/skills/discovered",e))).skills}async function qD(e,n,s){return D(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function VD(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(W(`/skills/catalog${r}`,s))}async function WD(e,n){return(await D(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function KD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return D(`/chat/sessions${i?`?${i}`:""}`)}async function cw(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 dw(e,n){return D(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function GD(e,n,s){return D(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function JD(e,n){return D(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function uu(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(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function uw(e,n){return D(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function mw(e,n,s,i,r,o){const l=fs(W(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let u=!1;const d=(m,h)=>{if(!(!m||!h))switch(m){case"thinking":try{s.onThinking?.(JSON.parse(h))}catch{s.onThinking?.(h)}break;case"text":try{s.onText?.(JSON.parse(h))}catch{s.onText?.(h)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(h))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const g=JSON.parse(h);s.onError?.(g.message||g)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(i)&&i.length>0,h=m?(()=>{const S=new FormData;return S.append("content",n),i.forEach(j=>S.append("attachments",j)),S})():JSON.stringify({content:n}),g=await fetch(l,{method:"POST",headers:m?hi():hi({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!g.ok){const S=await g.text();let j=`Request failed: ${g.status}`;try{j=JSON.parse(S).error||j}catch{}s.onError?.(j);return}if(!g.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=g.body.getReader(),f=new TextDecoder;let b="",v="",x=[];const y=(S,j=!1)=>{b+=S;const A=b.split(`
613
- `);b=A.pop()||"",j&&b.length>0&&(A.push(b),b="");for(const w of A){const _=w.endsWith("\r")?w.slice(0,-1):w;if(_.startsWith("event:"))v=_.slice(6).trim();else if(_.startsWith("data:")){const C=_.slice(5);x.push(C.startsWith(" ")?C.slice(1):C)}else if(_===""){const C=x.join(`
614
- `);d(v,C),v="",x=[]}}if(j&&v&&x.length>0){const w=x.join(`
615
- `);d(v,w),v="",x=[]}};for(;;){const{done:S,value:j}=await p.read();if(S){y(f.decode(),!0);break}y(f.decode(j,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){u||s.onError?.("Connection aborted");return}if(u)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{u=!0,c.abort()},isConnected:()=>!u}}function YD(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(W(`/insights${i}`,n))}function QD(e,n){return D(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function XD(e="manual",n,s){return D(W("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function ZD(e){return D(W("/insights/runs",e))}function eL(e,n){return D(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function tL(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const i=s.size>0?`?${s.toString()}`:"";return D(W(`/research/runs${i}`,n))}function nL(e,n){return D(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function sL(e,n){return D(W(`/research/runs/${encodeURIComponent(e)}`,n))}function iL(e,n){return D(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function aL(e,n){return D(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function rL(e,n,s){return D(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function oL(e,n,s){return D(W(`/research/runs/${encodeURIComponent(e)}/create-task`,s),{method:"POST",body:JSON.stringify(n)})}function lL(e,n,s){return D(W(`/research/runs/${encodeURIComponent(e)}/attach-task`,s),{method:"POST",body:JSON.stringify(n)})}function hw(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 pw({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}=hw(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]})]})}function fw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Bi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=fw(e);return t.jsxs("span",{className:`node-health-dot${i?" node-health-dot--compact":""}${s?` ${s}`:""}`,title:r,"aria-label":`Node status: ${r}`,children:[t.jsx("span",{className:`status-dot status-dot--${e}`}),n?t.jsx("span",{className:"node-health-dot__label",children:r}):null]})}const mu=new Map,gw=6e4;function Cp(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=mu.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 lw(e);if(h||u.current)return;mu.set(m,{slots:b,expiresAt:Date.now()+gw}),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 Go({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Cp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(qo,{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 bw(){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 Pr(){const[e,n]=a.useState(bw);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}function _a(e){return e.replace(/\\/g,"/")}function cd(e){return e.replace(/[\\/]+$/g,"")}function dd(e){const n=_a(cd(e));return n?n.split("/").filter(Boolean):[]}function ud(e){const n=_a(cd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Ep(e,n){const s=dd(e);return s.length===0?_a(e):s.slice(-2).join("/")}function xw(e){const n=_a(cd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function vw(e,n){return!e||e==="."?n:[...dd(e),n].join("/")}function yw(e){const n=dd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function cL(e){const n=_a(e),s=n.match(/^([A-Za-z]:)(?:\/(.*))?$/);if(s){const r=`${s[1]}/`,o=(s[2]??"").split("/").filter(Boolean),l=[{label:s[1],path:r}];for(let c=0;c<o.length;c+=1)l.push({label:o[c],path:`${r}${o.slice(0,c+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const _p={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function jw({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(Yt,{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=_p[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:Ep(u.path)})]}),d&&t.jsx(Bn,{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 hu({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 kw({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:g,showNodesButton:p,onOpenWorkflowSteps:f,onOpenScripts:b,onRunScript:v,onToggleTerminal:x,onOpenFiles:y,filesOpen:S,globalPaused:j,enginePaused:A,onToggleGlobalPause:w,onToggleEnginePause:_,view:C="board",onChangeView:L,showSkillsTab:E,showAgentsTab:T,searchQuery:F="",onSearchChange:K,projects:$=[],currentProject:R,onSelectProject:I,onViewAllProjects:H,projectId:J,isElectron:Z=!1,mobileNavEnabled:N,availableNodes:z=[],currentNode:P,onSelectNode:k,isRemote:U=!1,experimentalFeatures:V}){const pe=Pr(),ve=pe==="mobile",he=ve||pe==="tablet",O=ve&&N,[ue,te]=a.useState(!1),[me,oe]=a.useState(!1),[be,ae]=a.useState(!1),[Ee,$e]=a.useState(!1),[He,ot]=a.useState(!1),[Je,et]=a.useState(!1),[st,Oe]=a.useState(!1),[Ue,re]=a.useState(!1),[Ne,ee]=a.useState(!1),[Ae,Fe]=a.useState(!1),[fe,_e]=a.useState(!1),[ze,Xe]=a.useState({}),[je,ce]=a.useState(!1),[Re,ge]=a.useState(-1),[Me,Ge]=a.useState(null),[Pe,pt]=a.useState({}),[Y,le]=a.useState(!1),ye=a.useRef(null),nt=a.useRef(null),X=a.useRef(null),Qe=a.useRef(null),lt=a.useRef(null),ft=a.useRef(null),Mt=a.useRef(!1),yt=a.useRef(null),ht=a.useRef(null),St=a.useRef(null),zt=a.useRef(null),It=a.useRef(null),Rt=a.useRef(null),$t=a.useRef(null),Ot=a.useRef(null),Vt=a.useRef(!1),Dt=a.useMemo(()=>z.filter(we=>we.type==="remote"),[z]),Ft=Dt.length>0,Ct=a.useMemo(()=>Object.entries(ze).sort(([we],[it])=>we.localeCompare(it)),[ze]),Nt=Ct.length>0,Tt=Ct.length+(Nt?1:0),Zt=a.useMemo(()=>Object.entries(Pe).sort(([we],[it])=>we.localeCompare(it)),[Pe]),Ut=a.useMemo(()=>!!(V?.researchView||V?.todoView||V?.insights||V?.roadmap||E||V?.memoryView||V?.devServerView||!O),[V,E,O]),B=a.useCallback(()=>{const we=window.visualViewport;return we&&we.width>0&&we.height>0?{width:we.width,height:we.height,offsetTop:we.offsetTop,offsetLeft:we.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),xe=a.useCallback(()=>{const we=$t.current;if(!we)return;const it=we.getBoundingClientRect(),un=Ot.current,{width:Nn,height:Tn,offsetTop:Ce,offsetLeft:Ye}=B(),dt=16,vt=16,Qt=6,bn=un?.offsetWidth||Math.max(it.width,260),Jt=Math.min(bn,Math.max(Nn-dt*2,160)),Xt=un?.offsetHeight||280,_n=Math.min(Xt,Math.max(Tn-vt*2,160)),sn=it.top-Ce,ls=it.bottom-Ce,cs=it.right-Ye,cn=Tn-ls,kt=sn,G=cn<_n&&kt>cn,De=Math.min(Math.max(cs-Jt,dt),Nn-dt-Jt)+Ye,tt=G?Math.max(vt+Ce,sn-_n-Qt+Ce):Math.min(ls+Qt+Ce,Tn+Ce-vt-_n);Ge({top:tt,left:De,width:Jt})},[B]),Ie=a.useCallback((we,it)=>{v?.(we,it),_e(!1),ge(-1)},[v]),M=a.useCallback(()=>{b?.(),_e(!1),ge(-1)},[b]),ne=a.useCallback(we=>{switch(we.key){case"ArrowDown":we.preventDefault(),Tt>0&&ge(it=>it<Tt-1?it+1:0);break;case"ArrowUp":we.preventDefault(),Tt>0&&ge(it=>it>0?it-1:Tt-1);break;case"Enter":if(we.preventDefault(),Re>=0)if(Re<Ct.length){const[it,un]=Ct[Re];Ie(it,un)}else Nt&&Re===Ct.length&&M();break;case"Home":we.preventDefault(),Tt>0&&ge(0);break;case"End":we.preventDefault(),Tt>0&&ge(Tt-1);break}},[M,Ie,Re,Ct,Nt,Tt]);a.useEffect(()=>{Mt.current=He},[He]),a.useEffect(()=>{Vt.current=fe},[fe]),a.useEffect(()=>{if(!He||!he)return;let we=!1;return le(!0),vr(J).then(it=>{we||pt(it)}).catch(()=>{we||pt({})}).finally(()=>{we||le(!1)}),()=>{we=!0}},[He,he,J]),a.useEffect(()=>{if(!fe||he)return;let we=!1;return ce(!0),vr(J).then(it=>{we||Xe(it)}).catch(()=>{we||Xe({})}).finally(()=>{we||ce(!1)}),()=>{we=!0}},[fe,he,J]),a.useEffect(()=>{if(!fe)return;const we=it=>{Rt.current&&!Rt.current.contains(it.target)&&_e(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[fe]),a.useEffect(()=>{if(!fe)return;const we=it=>{it.key==="Escape"&&(_e(!1),$t.current?.focus())};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[fe]),a.useEffect(()=>{if(fe){ge(-1);const we=window.setTimeout(()=>Ot.current?.focus(),0);return()=>window.clearTimeout(we)}Ge(null)},[fe]),a.useEffect(()=>{if(!fe)return;const we=requestAnimationFrame(()=>{xe()});return()=>cancelAnimationFrame(we)},[fe,je,Ct.length,Nt,xe]),a.useEffect(()=>{if(!fe)return;const we=()=>xe();window.addEventListener("resize",we),window.addEventListener("scroll",we,!0);const it=window.visualViewport;return it&&(it.addEventListener("resize",we),it.addEventListener("scroll",we)),()=>{window.removeEventListener("resize",we),window.removeEventListener("scroll",we,!0),it&&(it.removeEventListener("resize",we),it.removeEventListener("scroll",we))}},[fe,xe]),a.useEffect(()=>{he&&(_e(!1),ge(-1))},[he]);const Le=ue||F.length>0,ut=(me||F.length>0)&&!be,bt=(C==="board"||C==="list")&&!ve&&K&&!be&&F.length===0,Pt=(C==="board"||C==="list")&&!ve&&K;a.useEffect(()=>{F===""&&ae(!1)},[F]),a.useEffect(()=>{if(!Ee)return;const we=it=>{nt.current&&!nt.current.contains(it.target)&&ye.current&&!ye.current.contains(it.target)&&$e(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ee]),a.useEffect(()=>{if(!Ne)return;const we=it=>{Qe.current&&!Qe.current.contains(it.target)&&X.current&&!X.current.contains(it.target)&&ee(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ne]),a.useEffect(()=>{if(!Je)return;const we=it=>{yt.current&&!yt.current.contains(it.target)&&et(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Je]),a.useEffect(()=>{const we=it=>{if(it.key==="Escape"){if(re(!1),ee(!1),Mt.current){ot(!1);return}if(Vt.current){_e(!1),$t.current?.focus();return}$e(!1),te(!1),et(!1),Oe(!1)}};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[]),a.useEffect(()=>{if(!st)return;const we=it=>{ht.current&&!ht.current.contains(it.target)&&Oe(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[st]),a.useEffect(()=>{if(!Ae)return;const we=it=>{It.current&&!It.current.contains(it.target)&&Fe(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ae]),a.useEffect(()=>{if(!Ae)return;const we=it=>{it.key==="Escape"&&Fe(!1)};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[Ae]),a.useEffect(()=>{if(!Ue)return;const we=it=>{St.current&&!St.current.contains(it.target)&&zt.current&&!zt.current.contains(it.target)&&re(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ue]);const At=a.useCallback(()=>{te(we=>!we)},[]),nn=a.useCallback(()=>{oe(!0),ae(!1)},[]),zn=a.useCallback(()=>{oe(!1),ae(!0),K&&K("")},[K]),hn=a.useCallback(()=>{$e(we=>!we)},[]),en=a.useCallback(we=>{we&&we(),$e(!1),ot(!1)},[]),On=a.useCallback(()=>{te(!1),K&&K("")},[K]);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"})]}),ve&&$.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:ht,children:[t.jsx("button",{className:`mobile-project-switch-trigger${st?" mobile-project-switch-trigger--open":""}`,onClick:()=>Oe(we=>!we),title:"Switch project","aria-label":"Switch project","aria-expanded":st,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Yt,{size:14,className:`mobile-project-switch-chevron${st?" mobile-project-switch-chevron--open":""}`})}),st&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:$.map(we=>{const it=R?.id===we.id,un=_p[we.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${it?" mobile-project-switch-item--current":""}`,onClick:()=>{I(we),Oe(!1)},role:"option","aria-selected":it,"data-testid":`mobile-project-switch-item-${we.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:un||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:we.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Ep(we.path)})]}),it&&t.jsx(Bn,{size:14,className:"mobile-project-switch-check"})]},we.id)})})]}),!he&&$.length>=1&&H&&t.jsx(jw,{projects:$,currentProject:R??null,onViewAll:H,onSelectProject:I}),Ft&&t.jsxs("div",{className:`header-node-selector${ve?" header-node-selector--mobile":""}`,ref:ve?void 0:yt,children:[t.jsx(pw,{node:P??null,showDetails:!ve}),!ve&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Je?" node-selector-trigger--open":""}`,onClick:()=>et(we=>!we),title:"Switch node","aria-label":"Switch node","aria-expanded":Je,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(kn,{size:12,className:`node-selector-chevron${Je?" node-selector-chevron--open":""}`})}),Je&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${U?"":" node-selector-option--active"}`,onClick:()=>{k?.(null),et(!1)},role:"option","aria-selected":!U,"data-testid":"node-option-local",children:[t.jsx(Bi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Dt.map(we=>t.jsxs("button",{className:`node-selector-option${P?.id===we.id?" node-selector-option--active":""}`,onClick:()=>{k?.(we),et(!1)},role:"option","aria-selected":P?.id===we.id,"data-testid":`node-option-${we.id}`,children:[t.jsx(Bi,{status:we.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:we.name}),t.jsx("span",{className:"node-selector-option-status",children:we.status})]},we.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[O&&L&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Ec,{size:16})})]}),K&&ve&&(O||C==="board"||C==="list")&&!Le&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:At,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(yi,{size:16})}),bt&&t.jsx("button",{className:"btn-icon",onClick:nn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(yi,{size:16})}),ve&&O&&o&&t.jsx("button",{className:"btn-icon",onClick:we=>o(we.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(zs,{size:16})}),!O&&L&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>L("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>L("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(Ec,{size:16})}),T&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>L("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(Sn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>L("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(vs,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>L("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(ji,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>L("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Oi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>L("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(fa,{size:16})}),Ut&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:zt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||V?.todoView&&C==="todos"?" active":""}`,onClick:()=>re(we=>!we),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ue,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Yt,{size:12})}),Ue&&t.jsxs("div",{ref:St,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[V?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="research"?" active":""}`,onClick:()=>{L("research"),re(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(yi,{size:14}),t.jsx("span",{children:"Research"})]}),V?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{L("insights"),re(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(rs,{size:14}),t.jsx("span",{children:"Insights"})]}),V?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{L("roadmaps"),re(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(_c,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),E&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{L("skills"),re(!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${C==="memory"?" active":""}`,onClick:()=>{L("memory"),re(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(vo,{size:14}),t.jsx("span",{children:"Memory"})]}),V?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{L("devserver"),re(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),V?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="todos"?" active":""}`,onClick:()=>{L("todos"),re(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(op,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!he&&o&&t.jsx("button",{className:"btn-icon",onClick:we=>o(we.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(zs,{size:16})}),!he&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(pr,{size:16})}),!he&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(hr,{size:16})}),!he&&!Z&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(hu,{size:16})}),!he&&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(ii,{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})]}),!he&&t.jsxs("div",{className:"terminal-split-btn",ref:Rt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(di,{size:16})}),b&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:$t,className:`btn-icon terminal-split-btn__chevron${fe?" btn-icon--active":""}`,onClick:()=>_e(we=>!we),title:"Scripts","aria-haspopup":"listbox","aria-expanded":fe,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Yt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${fe?" rotate":""}`})}),fe&&t.jsx("div",{ref:Ot,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:ne,"data-testid":"quick-scripts-dropdown",style:Me?{position:"fixed",top:`${Me.top}px`,left:`${Me.left}px`,width:`${Me.width}px`,right:"auto"}:void 0,children:je?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ct.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(di,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:M,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ct.map(([we,it],un)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Re===un?"highlighted":""}`,onClick:()=>Ie(we,it),role:"option","aria-selected":Re===un,"data-testid":`quick-script-item-${we}`,children:[t.jsx(Cn,{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:we}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:it,children:it.length>50?`${it.slice(0,50)}...`:it})]})]},we))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Nt&&Re===Ct.length?"highlighted":""}`,onClick:M,"data-testid":"quick-scripts-manage",children:[t.jsx(lr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!he&&y&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Wn,{size:16})}),!he&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Js,{size:16})}),!he&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Ac,{size:16})}),!he&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:X,className:"btn-icon",onClick:()=>ee(we=>!we),title:"More actions","aria-label":"More actions","aria-expanded":Ne,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(wc,{size:16})}),Ne&&t.jsxs("div",{ref:Qe,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),ee(!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:()=>{en(m),ee(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(wi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:It,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${j?" btn-icon--stopped":""}`,onClick:w,title:j?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:j?t.jsx(Cn,{size:16}):t.jsx(ws,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Ae?" btn-icon--active":""}`,onClick:()=>Fe(we=>!we),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ae,"data-testid":"engine-control-chevron-btn",children:t.jsx(Yt,{size:12})}),Ae&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${A?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{_?.(),Fe(!1)},role:"menuitem",title:A?"Resume scheduling":"Pause triage",disabled:!!j,"data-testid":"engine-control-pause-triage-btn",children:[A?t.jsx(Cn,{size:14}):t.jsx(Ks,{size:14}),t.jsx("span",{children:A?"Resume scheduling":"Pause triage"})]})})]}),!he&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(lr,{size:16})}),t.jsx(Go,{slotId:"header-action",projectId:J}),he&&!O&&t.jsx("button",{ref:ye,className:"btn-icon compact-overflow-trigger",onClick:hn,title:"More header actions","aria-label":"More header actions","aria-expanded":Ee,"aria-haspopup":"menu",children:t.jsx(wc,{size:16})}),he&&!O&&Ee&&t.jsxs("div",{ref:nt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[$.length>=1&&H&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(H),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(np,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Wn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>en(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(ii,{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"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Js,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(fr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Z&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(n),role:"menuitem",children:[t.jsx(hu,{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:()=>en(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(di,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>ot(we=>!we),role:"menuitem","aria-expanded":He,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(kn,{size:14,className:`mobile-overflow-chevron${He?" mobile-overflow-chevron--open":""}`})})]}),He&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Y?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Zt.length>0?t.jsxs(t.Fragment,{children:[Zt.map(([we,it])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(we,it),$e(!1),ot(!1)},role:"menuitem","data-testid":`overflow-script-item-${we}`,children:[t.jsx(Cn,{size:14}),t.jsx("span",{children:we})]},we)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>en(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ws,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>en(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ws,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(wi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(hr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(fa,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:we=>en(()=>o(we.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(zs,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Ac,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>en(e),role:"menuitem",children:[t.jsx(lr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Pt&&ut&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(yi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:we=>K(we.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:zn,"aria-label":"Close search",children:t.jsx(Kt,{size:14})})]})}),K&&ve&&Le&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:lt,className:"header-search mobile-search-expanded",children:[t.jsx(yi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:ft,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:we=>K(we.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:On,"aria-label":"Close search",children:t.jsx(Kt,{size:14})})]})})]})}const ww={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","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!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,researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchWebSearchProvider:"none",researchSearxngUrl:void 0,researchBraveApiKey:void 0,researchGoogleSearchApiKey:void 0,researchGoogleSearchCx:void 0,researchTavilyApiKey:void 0,researchGitHubEnabled:!1,researchLocalDocsEnabled:!0,researchMaxSearchResults:10,researchFetchTimeoutMs:3e4,researchUserAgent:"FusionResearchBot/1.0"},Nw={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",requirePrApproval:!1,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,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:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,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,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,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:!0,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,researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2,experimentalFeatures:{}},Sw=Object.freeze(Object.keys(ww)),Cw=Object.freeze(Object.keys(Nw));function dL(e){return Sw.includes(e)}function uL(e){return Cw.includes(e)}function ke(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Ew(e){return!!(e?.provider&&e?.modelId)}function Ni(...e){for(const n of e)if(Ew(n))return{provider:n.provider,modelId:n.modelId};return{}}function Jo(e){return Ni({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function _w(e){return Ni({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Jo(e))}function Mw(e){return Ni({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Jo(e))}function Aw(e){return Ni({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Jo(e))}function mL(e){return Ni({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Jo(e))}function Mp(e,n){return Ni({provider:e.modelProvider,modelId:e.modelId},_w(n))}function Ap(e,n){return Ni({provider:e.validatorModelProvider,modelId:e.validatorModelId},Aw(n))}function Rp(e,n){return Ni({provider:e.planningModelProvider,modelId:e.planningModelId},Mw(n))}const hL=["off","minimal","low","medium","high"],Li=["triage","todo","in-progress","in-review","done","archived"],md=["low","normal","high","urgent"],Ss="normal",Rw=["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"],Dn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},Tw={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"},$c={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Pw(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 Iw(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 $w({isOpen:e,options:n,onConfirm:s,onCancel:i}){const r=a.useRef(null);return a.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,i]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:i,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:i,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const Tp=a.createContext(null);function Dw({children:e}){const[n,s]=a.useState([]),i=a.useRef([]),r=a.useCallback(d=>{s(m=>{const h=d(m);return i.current=h,h})},[]),o=a.useCallback(d=>new Promise(m=>{r(h=>[...h,{options:d,resolve:m}])}),[r]),l=a.useCallback(d=>{const m=i.current[0];m&&(m.resolve(d),r(h=>h.slice(1)))},[r]),c=n[0]??null,u=a.useMemo(()=>({confirm:o}),[o]);return xo.createElement(Tp.Provider,{value:u},e,xo.createElement($w,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ys(){const e=a.useContext(Tp);return e||{confirm:async n=>!1}}function Lw(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 Pp({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(Ns,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${Lw(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Oo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Kr(e,n){return`${e??"default"}:${n}`}class zw{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=Kr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Kr(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=Kr(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(ai(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=Kr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:pu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:pu(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 Ti=new zw;let Ow=0;function pu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ip(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Ow++}`);const s=a.useSyncExternalStore(o=>Ti.subscribe(o),()=>Ti.getSnapshot(),()=>Ti.getSnapshot()),i=a.useCallback(o=>{Ti.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Ti.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Ti.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Ti.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function So(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function Fw({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Ip(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=So(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=So(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(Pp,{prInfo:h,issueInfo:g})}const Uw=a.memo(Fw);Uw.displayName="TaskCardBadge";const Bw={sm:16,md:20,lg:24};function Hw({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 fu({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 Xs({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 qw({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 gu({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 Vw({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 bl({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 bu({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 xu({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 vu({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 Fa({size:e,color:n,label:s="Qwen"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"qwen-icon","aria-label":s,children:[t.jsx("circle",{cx:"11",cy:"12",r:"7.5",stroke:n,strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M14 15 L21 22",stroke:n,strokeWidth:"2.6",strokeLinecap:"round"})]})}function yu({size:e,color:n,label:s="LM Studio"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"lmstudio-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"4.5",fill:n}),t.jsx("text",{x:"12",y:"16",textAnchor:"middle",fontFamily:"-apple-system, system-ui, sans-serif",fontSize:"9.5",fontWeight:"700",fill:"var(--provider-icon-contrast)",letterSpacing:"-0.4",children:"LM"})]})}function xl({size:e,color:n,label:s="Hugging Face"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"huggingface-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"9",fill:n}),t.jsx("circle",{cx:"8.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("circle",{cx:"15.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("path",{d:"M7.5 14.5 Q12 18.5 16.5 14.5",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.6",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M3.5 16 Q5 13.5 7 14.5 M20.5 16 Q19 13.5 17 14.5",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})]})}function ju({size:e,color:n,label:s="Mistral 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":"mistral-icon","aria-label":s,children:t.jsx("path",{d:"M2 4h3v16H2zM7 4h3v12H7zM12 4h3v16h-3zM17 4h3v8h-3zM7 16h3v4H7zM17 8h3v12h-3z",fill:n})})}function vl({size:e,color:n,label:s="Azure"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"azure-icon","aria-label":s,children:t.jsx("path",{d:"M10.4 3.2 4.5 16.6l3.5.5L13 6 9.6 19.5h9.9zM3 19.5l4.6.6 8.6-1.7-7-1.6z",fill:n})})}function Ww({size:e,color:n,label:s="Cerebras"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cerebras-icon","aria-label":s,children:[t.jsx("path",{d:"M19.5 6.5A8.5 8.5 0 1 0 19.5 17.5",stroke:n,strokeWidth:"2.4",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M16.5 9A4.6 4.6 0 1 0 16.5 15",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"}),t.jsx("circle",{cx:"11",cy:"12",r:"1.6",fill:n})]})}function Kw({size:e,color:n,label:s="Groq"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"groq-icon","aria-label":s,children:t.jsx("path",{d:"M14 2 4 13h6l-2 9 10-11h-6z",fill:n})})}function ku({size:e,color:n,label:s="Vercel"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"vercel-icon","aria-label":s,children:t.jsx("path",{d:"M12 2 22 21H2z",fill:n})})}function yl({size:e,color:n,label:s="Fireworks AI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"fireworks-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"2.4",fill:n}),t.jsx("circle",{cx:"12",cy:"3.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"12",cy:"20.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"3.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"20.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"6",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"6",cy:"18",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"18",r:"1.2",fill:n}),t.jsx("path",{d:"M12 5.5v3M12 15.5v3M5.5 12h3M15.5 12h3",stroke:n,strokeWidth:"1.4",strokeLinecap:"round"})]})}function Gw({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 wu({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 jl({size:e,color:n,label:s="Hermes"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:[t.jsx("rect",{x:"30",y:"10",width:"4",height:"46",rx:"2",fill:n}),t.jsx("path",{d:"M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round"}),t.jsx("path",{d:"M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.8"}),t.jsx("circle",{cx:"32",cy:"10",r:"4",fill:n})]})}function Nu({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function kl({size:e,color:n,label:s="Paperclip"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:t.jsx("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",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function Su({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 Jw={anthropic:{component:Hw,color:"var(--provider-anthropic)"},"claude-cli":{component:Su,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:Su,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:fu,color:"var(--provider-openai)"},"openai-codex":{component:fu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Xs,color:"var(--provider-gemini)"},gemini:{component:Xs,color:"var(--provider-gemini)"},"google-antigravity":{component:Xs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Xs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Xs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Xs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Xs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Xs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Xs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Xs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:qw,color:"var(--text)"},github:{component:wu,color:"var(--text)"},"github-copilot":{component:wu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Gw,color:"var(--provider-openrouter)"},minimax:{component:gu,color:"var(--provider-minimax)"},"minimax-cn":{component:gu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Vw,color:"var(--provider-zai)"},kimi:{component:bl,color:"var(--provider-kimi)"},moonshot:{component:bl,color:"var(--provider-kimi)"},"kimi-coding":{component:bl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:bu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:bu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:xu,color:"var(--text)"},grok:{component:xu,color:"var(--text)",label:"xAI"},opencode:{component:vu,color:"var(--provider-opencode)"},"opencode-go":{component:vu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Fa,color:"var(--provider-qwen)"},"qwen-ai":{component:Fa,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Fa,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Fa,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Fa,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:yu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:yu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:xl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:xl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:xl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:ju,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:ju,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:vl,color:"var(--provider-azure)"},"azure-openai":{component:vl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:vl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:yl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:yl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:yl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Ww,color:"var(--provider-cerebras)"},groq:{component:Kw,color:"var(--provider-groq)"},vercel:{component:ku,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:ku,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:jl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:jl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:jl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:Nu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:Nu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:kl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:kl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:kl,color:"var(--provider-paperclip)",label:"Paperclip"}};function Ln({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Jw[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=Bw[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(bb,{size:c})})}const Is={data:new Map,pendingPromise:null,lastFetchTime:null},Yw=5e3;function fo(e,n){return n?`${n}::${e}`:e}function Qw(e,n){const s=Is.data.get(fo(e,n));if(!(!s||Date.now()-s.timestamp>Yw))return s}function Xw(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 Ay(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=ke(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=Is.data.get(fo(g,e));return p&&p.timestamp>d})&&Is.lastFetchTime&&Is.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Is.pendingPromise){s(!0);try{await Is.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Is.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))Is.data.set(fo(f,e),{result:b,timestamp:p});Is.lastFetchTime=p}catch{}finally{Is.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Is.data.get(fo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Is.lastFetchTime,getBatchData:l}}const Dc=new Map,Zw=3e4;function $p(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function eN(e,n,s,i){const r=$p(e,n,s,i),o=Dc.get(r);return o?Date.now()>o.expiresAt?(Dc.delete(r),null):o.stats:null}function tN(e,n,s,i,r){const o=$p(e,n,s,i);Dc.set(o,{stats:r,expiresAt:Date.now()+Zw})}function nN(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const b=f?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(j=!1){if(!j){const A=eN(e,i,b,v);if(A){x||(m(A),g(!1));return}}g(!0);try{const A=await jp(e,b,i);x||(m(A.stats),tN(e,i,b,v,A.stats))}catch{x||m(null)}finally{x||g(!1)}}y();let S;return u&&f&&(S=setInterval(()=>{y(!0)},u)),()=>{x=!0,S&&clearInterval(S)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const sN=new Set(["failed","stuck-killed"]);function Co(e,n,s){if(e.column!=="in-progress"||e.status&&sN.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function iN(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function aN(e){return e==="done"||e==="skipped"}function rN(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Dp(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:rN(u,d,n),status:d?iN(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>aN(u.status)).length;return{total:l,completed:c,items:o}}function oN(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 Lp(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??""}
616
- ${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:oN(n)}})}function lN(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of Lp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Lc=new Map;async function cN(e,n){const s=Lc.get(e);if(s)return s;try{const i=await kp(e,n);return Lc.set(e,i.title),i.title}catch{return e}}const Cu=12;function dN(e){return e.length<=Cu?e:e.slice(0,Cu-3)+"..."}const zc=new Map;async function uN(e,n){const s=zc.get(e);if(s)return s;try{const i=await vp(e,n);return zc.set(e,i.name),i.name}catch{return e}}function mN(e){return typeof e=="string"&&md.includes(e)?e:Ss}function hN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const pN=new Set(["triage","todo"]),Eu=new Set(["planning","researching","executing","finalizing","merging"]),_u=new Set(["merging","merging-pr"]),fN={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},gN=new Set(["in-progress","in-review","done"]),bN=3e4;function Hi(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function xN(e){const n=Hi(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Mu(e,n){const s=Hi(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Gr(e,n){const s=Hi(e.executionStartedAt);if(s==null)return null;const i=Hi(e.executionCompletedAt),r=i!=null&&i>=s?i:n;return Math.max(0,r-s)}function vN(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let i=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=Hi(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=Hi(o.completedAt);if(u==null||u<l)continue;c=u}else c=Math.max(l,n);i+=c-l,r+=1}return r>0?i:null}function Jr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:lN(e.log),i=vN(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Au(e){if(!Number.isFinite(e)||e<0)return"";if(e<6e4)return"<1m";const n=Math.floor(e/6e4);if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function yN(e){if(!Number.isFinite(e)||e<0||e===0)return"";const n=Math.ceil(e/6e4);if(n<59)return`${n}m`;const s=Math.ceil(e/36e5);return s<24?`${s}h`:`${Math.ceil(e/864e5)}d`}function Ru(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 jN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function kN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function wN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function NN(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 SN(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 CN(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 EN(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 _N(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.onRetryTask===n.onRetryTask&&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.timedExecutionMs===i.timedExecutionMs&&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&&CN(s.attachments,i.attachments)&&EN(s.comments,i.comments)&&kN(s.dependencies,i.dependencies)&&jN(s.steps,i.steps)&&wN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&SN(s.workflowStepResults,i.workflowStepResults)&&Ru(s.prInfo,i.prInfo)&&Ru(s.issueInfo,i.issueInfo)}function MN({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:g,onOpenMission:p,onMoveTask:f,lastFetchTimeMs:b,workflowStepNameLookup:v}){const[x,y]=a.useState(!1),[S,j]=a.useState(!1),[A,w]=a.useState(!1),[_,C]=a.useState(e.description||""),[L,E]=a.useState(!1),[T,F]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(M=>M.status==="done"||M.status==="skipped")),[K,$]=a.useState(null),[R,I]=a.useState(null),[H,J]=a.useState(!1),[Z,N]=a.useState(!1),[z,P]=a.useState(()=>Date.now()),k=a.useRef(null),U=a.useRef(!1),V=a.useRef(null),pe=a.useRef(null),[ve,se]=a.useState(!1),{badgeUpdates:he,subscribeToBadge:O,unsubscribeFromBadge:ue}=Ip(n),{confirm:te}=Ys(),me=a.useRef(null),oe=a.useRef(!1),be=a.useCallback(M=>M instanceof Element?!!M.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!H)return;const M=ne=>{pe.current&&!pe.current.contains(ne.target)&&J(!1)};return document.addEventListener("click",M),()=>document.removeEventListener("click",M)},[H]),a.useEffect(()=>{if(!e.missionId){$(null);return}const M=Lc.get(e.missionId);if(M){$(M);return}let ne=!1;return cN(e.missionId,n).then(Le=>{ne||$(Le)}),()=>{ne=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const M=zc.get(e.assignedAgentId);if(M){I(M);return}I(null);let ne=!1;return uN(e.assignedAgentId,n).then(Le=>{ne||I(Le)}),()=>{ne=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(A&&k.current){const M=k.current;M.focus(),M.style.height="auto",M.style.height=M.scrollHeight+"px"}},[A]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){se(!0);return}const M=V.current;if(!M)return;const ne=new IntersectionObserver(([Le])=>{se(Le?.isIntersecting??!0)},{rootMargin:"200px"});return ne.observe(M),()=>ne.disconnect()},[A,e.id]);const ae=a.useCallback(M=>{M.dataTransfer.setData("text/plain",e.id),M.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ee=a.useCallback(()=>{y(!1)},[]),$e=a.useCallback(M=>M.dataTransfer.types.includes("Files"),[]),He=a.useCallback(M=>{$e(M)&&(M.preventDefault(),M.stopPropagation(),M.dataTransfer.dropEffect="copy",j(!0))},[$e]),ot=a.useCallback(M=>{$e(M)&&(M.preventDefault(),M.stopPropagation(),j(!1))},[$e]),Je=a.useCallback(async M=>{if(!$e(M))return;M.preventDefault(),M.stopPropagation(),j(!1);const ne=Array.from(M.dataTransfer.files);for(const Le of ne)try{await br(e.id,Le,n),r(`Attached ${Le.name} to ${e.id}`,"success")}catch(ut){r(`Failed to attach ${Le.name}: ${ke(ut)}`,"error")}},[e.id,$e,r]),et=a.useCallback(()=>{A||i(e)},[e,i,A]),st=a.useCallback(M=>{if(U.current){U.current=!1;return}be(M.target)||et()},[et,be]),Oe=a.useCallback(M=>{const ne=M.touches[0];ne&&(me.current={x:ne.clientX,y:ne.clientY,time:Date.now()},oe.current=!1)},[]),Ue=a.useCallback(M=>{if(!me.current)return;const ne=M.touches[0];if(!ne)return;const Le=Math.abs(ne.clientX-me.current.x),ut=Math.abs(ne.clientY-me.current.y);(Le>Tu||ut>Tu)&&(oe.current=!0)},[]),re=a.useCallback(M=>{if(be(M.target)||!me.current)return;const Le=Date.now()-me.current.time<AN,ut=!oe.current;Le&&ut&&(U.current=!0,et()),me.current=null,oe.current=!1},[et,be]),Ne=a.useCallback(async(M,ne)=>{M.stopPropagation();try{const Le=await gr(ne,n);i(Le)}catch{r(`Failed to load dependency ${ne}`,"error")}},[i,r]),ee=e.status==="failed",Ae=e.paused===!0,Fe=mN(e.priority),fe=Fe!==Ss,_e=Co(e,g,b),ze=e.column==="triage"&&e.status==="awaiting-approval",Xe=e.column==="archived",je=!o&&!s&&!ee&&!Ae&&!_e&&!ze&&(e.column==="in-progress"||Eu.has(e.status)),ce=!s&&!Ae&&!A&&!Xe,Re=pN.has(e.column)&&!je&&!Ae&&!s&&l,ge=!!(e.prInfo||e.issueInfo),Me=!!(e.assignedAgentId&&R===null),Ge=a.useMemo(()=>{const M=[];return e.modelProvider&&M.push(e.modelProvider),e.validatorModelProvider&&!M.includes(e.validatorModelProvider)&&M.push(e.validatorModelProvider),e.planningModelProvider&&!M.includes(e.planningModelProvider)&&M.push(e.planningModelProvider),M},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Pe=a.useMemo(()=>Dp(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),pt=Pe.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const M=e.status!=null&&_u.has(e.status);if(!M&&e.column==="in-progress"){const Le=Gr(e,Date.now()),ut=Mu(e,Date.now()),bt=Jr(e,Date.now());if(Le==null&&ut==null&&bt==null)return}if(!M&&e.column==="in-review"){const Le=Gr(e,Date.now()),ut=Jr(e,Date.now());if(Le==null&&ut==null)return}P(Date.now());const ne=window.setInterval(()=>{P(Date.now())},bN);return()=>window.clearInterval(ne)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Y=a.useMemo(()=>{if(!gN.has(e.column))return null;if(e.status!=null&&_u.has(e.status)){const Pt=Hi(e.updatedAt);if(Pt!=null){const At=Math.max(0,z-Pt),nn=Au(At);if(nn)return{label:nn,title:`Merging ${nn}`,ariaLabel:`Merging ${nn}`}}}if(e.column==="in-progress"){const Pt=Gr(e,z)??Mu(e,z)??Jr(e,z);if(Pt==null)return null;const At=Au(Pt);return At?{label:At,title:`In progress ${At}`,ariaLabel:`In progress ${At}`}:null}const ne=Gr(e,z)??Jr(e,z);if(ne==null)return null;const Le=yN(ne);if(!Le)return null;const ut=xN(e);if(ut==null)return{label:Le,title:`Execution time ${Le}`,ariaLabel:`Execution time ${Le}`};const bt=new Date(ut).toLocaleString();return{label:Le,title:`Execution time ${Le}. Completed ${bt}`,ariaLabel:`Execution time ${Le}. Completed ${bt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,z]);a.useEffect(()=>{if(!ge||!ve){ue(e.id);return}return O(e.id),()=>{ue(e.id)}},[ge,ve,O,e.id,ue]);const le=he.get(`${n??"default"}:${e.id}`),ye=e.column==="in-progress"||e.column==="in-review",nt=a.useMemo(()=>e.steps.map(M=>`${M.name}:${M.status}`).join("|"),[e.steps]),{stats:X}=nN(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:ve,worktree:e.worktree,stepVersion:ye?nt:void 0,pollIntervalMs:ye?3e4:void 0}),Qe=a.useMemo(()=>Qw(e.id,n),[e.id,n]),lt=a.useMemo(()=>{const M=le?.prInfo,ne=le?.timestamp,Le=Qe?.result?.prInfo,ut=Qe?.timestamp?new Date(Qe.timestamp).toISOString():void 0,bt=e.prInfo,Pt=e.prInfo?.lastCheckedAt??e.updatedAt;let At=So(M,ne,bt,Pt);const nn=ne&&ne>=Pt?ne:Pt;return Le&&ut&&(!nn||ut>nn)&&(At=Le),At},[le,Qe,e.prInfo,e.updatedAt]),ft=a.useMemo(()=>{const M=le?.issueInfo,ne=le?.timestamp,Le=Qe?.result?.issueInfo,ut=Qe?.timestamp?new Date(Qe.timestamp).toISOString():void 0,bt=e.issueInfo,Pt=e.issueInfo?.lastCheckedAt??e.updatedAt;let At=So(M,ne,bt,Pt);const nn=ne&&ne>=Pt?ne:Pt;return Le&&ut&&(!nn||ut>nn)&&(At=Le),At},[le,Qe,e.issueInfo,e.updatedAt]),Mt=a.useCallback(M=>{M?.stopPropagation(),!(!Re||L)&&(w(!0),C(e.description||""))},[Re,L,e.description]),yt=a.useCallback(()=>{w(!1),C(e.description||"")},[e.description]),ht=a.useCallback(()=>_!==(e.description||""),[_,e.description]),St=a.useCallback(async()=>{if(!(!l||L)){if(!ht()){yt();return}E(!0);try{await l(e.id,{description:_.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(M){r(`Failed to update ${e.id}: ${ke(M)}`,"error")}finally{E(!1)}}},[l,e.id,_,L,ht,yt,r]),zt=a.useCallback(M=>{M.key==="Enter"&&!M.shiftKey?(M.preventDefault(),St()):M.key==="Escape"&&(M.preventDefault(),yt())},[St,yt]),It=a.useCallback(()=>{setTimeout(()=>{const M=document.activeElement;M===k.current||M?.closest(".card-editing-content")||(ht()?St():yt())},0)},[ht,St,yt]),Rt=a.useCallback(M=>{Re&&(M.stopPropagation(),Mt(M))},[Re,Mt]),$t=a.useCallback(M=>{M.stopPropagation(),Mt(M)},[Mt]),Ot=a.useCallback(M=>{C(M.target.value);const ne=M.target;ne.style.height="auto",ne.style.height=ne.scrollHeight+"px"},[]),Vt=a.useCallback(M=>{M.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(ne=>{r(`Failed to archive ${e.id}: ${ke(ne)}`,"error")})},[r,c,e.id]),Dt=a.useCallback(M=>{M.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(ne=>{r(`Failed to unarchive ${e.id}: ${ke(ne)}`,"error")})},[r,u,e.id]),Ft=a.useCallback(async M=>{if(M.stopPropagation(),!(!d||!await te({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(Le){const ut=NN(Le);if(!ut||ut.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ke(Le)}`,"error");return}const bt=ut.dependentIds.join(", ");if(!await te({title:"Force Delete Task",message:`${e.id} is a dependency of ${bt}.
617
-
618
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await d(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(At){r(`Failed to delete ${e.id}: ${ke(At)}`,"error")}}},[r,te,d,e.id]),Ct=a.useCallback(M=>{M.stopPropagation(),h?.(e,"changes")},[e,h]),Nt=a.useCallback(M=>{M.stopPropagation(),F(ne=>!ne)},[]),Tt=a.useCallback(M=>{M.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Zt=a.useCallback(M=>{M.stopPropagation(),J(ne=>!ne)},[]),Ut=a.useCallback((M,ne)=>{M.stopPropagation(),J(!1),f&&f(e.id,ne).then(()=>{r(`Moved ${e.id} to ${Dn[ne]}`,"success")}).catch(Le=>{r(`Failed to move ${e.id}: ${ke(Le)}`,"error")})},[r,f,e.id]),B=a.useCallback(async M=>{if(M.stopPropagation(),!(!m||Z)){N(!0);try{await m(e.id)}catch(ne){r(`Failed to retry ${e.id}: ${ke(ne)}`,"error")}finally{N(!1)}}},[r,Z,m,e.id]),xe=`card${x?" dragging":""}${s?" queued":""}${je?" agent-active":""}${ee?" failed":""}${Ae?" paused":""}${_e?" stuck":""}${ze?" awaiting-approval":""}${S?" file-drop-target":""}${A?" card-editing":""}${L?" card-saving":""}`,Ie=(()=>{if(e.column==="in-progress"){const M=X?.filesChanged,ne=M==null||M===0?e.modifiedFiles?.length:void 0,Le=M!=null&&M>0?M:ne;return Le==null||Le===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(Wn,{size:12}),t.jsxs("span",{children:[Le," ",Le===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const M=X?.filesChanged,ne=M==null||M===0?e.modifiedFiles?.length:void 0,Le=M!=null&&M>0?M:ne;return Le==null||Le===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(Wn,{size:12}),t.jsxs("span",{children:[Le," ",Le===1?"file":"files"," changed"]})]})}if(e.column==="done"){const M=X?.filesChanged,ne=e.mergeDetails?.filesChanged,Le=M??ne;if(Le!=null&&Le>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(Wn,{size:12}),t.jsxs("span",{children:[Le," ",Le===1?"file":"files"," changed"]})]});const ut=e.modifiedFiles?.length;if(ut!=null&&ut>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ct,disabled:!h,children:[t.jsx(Wn,{size:12}),t.jsxs("span",{children:[ut," ",ut===1?"file":"files"," changed"]})]})}return null})();return A?t.jsx("div",{ref:V,className:xe,"data-id":e.id,onDoubleClick:Rt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:k,className:"card-edit-desc-textarea",placeholder:"Task description",value:_,onChange:Ot,onKeyDown:zt,onBlur:It,disabled:L,rows:4}),L&&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:V,className:xe,"data-id":e.id,draggable:ce,onDragStart:ce?ae:void 0,onDragEnd:ce?Ee:void 0,onDragOver:He,onDragLeave:ot,onDrop:Je,onClick:st,onTouchStart:Oe,onTouchMove:Ue,onTouchEnd:re,onDoubleClick:Rt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Ae&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Ae&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ze?" awaiting-approval":""}${Eu.has(e.status)?" pulsing":""}${ee?" failed":""}${_e?" stuck":""}`,children:_e?"Stuck":ze?"Awaiting Approval":e.status}),_e&&(Ae||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),ge&&t.jsx(Pp,{prInfo:lt,issueInfo:ft}),fe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Fe}`,children:Fe}),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:Tt,title:`Mission: ${K??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(vs,{size:11}),dN(K??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Re&&t.jsx("button",{className:"card-edit-btn",onClick:$t,title:"Edit task","aria-label":"Edit task",children:t.jsx(us,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:Ft,title:"Delete task","aria-label":"Delete task",children:t.jsx(on,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Vt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Dt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&f&&t.jsxs("div",{className:"card-send-back",ref:pe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Zt,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":H,children:["Send back",t.jsx(Yt,{size:10})]}),H&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:$c["in-progress"].filter(M=>M!=="in-review").map(M=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ne=>Ut(ne,M),children:Dn[M]},M))})]}),e.column==="in-review"&&f&&t.jsxs("div",{className:"card-send-back",ref:pe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Zt,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":H,children:["Move",t.jsx(Yt,{size:10})]}),H&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:$c["in-review"].map(M=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ne=>Ut(ne,M),children:M==="done"?"Done (no merge)":Dn[M]},M))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ee&&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}),m&&t.jsxs("button",{type:"button",className:"btn btn-sm card-error-retry-btn",onClick:B,disabled:Z,children:[t.jsx(Fx,{size:12}),Z?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Iu(e.title,Pu)||Iu(e.description,Pu)||e.id}),pt&&(()=>{const M=Pe.completed/Pe.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:`${M}%`,backgroundColor:fN[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Pe.completed,"/",Pe.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Nt,"aria-expanded":T,"aria-label":T?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Pe.total," step",Pe.total===1?"":"s"]}),t.jsx(Yt,{size:14,className:`card-steps-toggle-icon${T?" expanded":""}`})]}),T&&t.jsx("div",{className:"card-steps-list",children:Pe.items.map(ne=>{const Le=ne.source==="workflow"&&ne.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${ne.status}${Le?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${ne.status==="done"?" completed":""}`,children:ne.name}),ne.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${ne.phase}`,title:"Workflow check",children:"workflow"})]},ne.id)})})]})})(),(Ie||Y)&&t.jsxs("div",{className:"card-footer-row",children:[Ie,Y&&t.jsxs("span",{className:"card-time-indicator",title:Y.title,"aria-label":Y.ariaLabel,children:[t.jsx(wi,{size:12}),t.jsx("span",{children:Y.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(M=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:ne=>void Ne(ne,M),title:`Click to view ${M}`,children:[t.jsx(pa,{size:12,style:{verticalAlign:"middle"}})," ",M]},M))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Fi,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(wi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Ge.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ge.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ge.map(M=>t.jsx(Ln,{provider:M,size:"sm"},M))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Me?" card-agent-badge--loading":""}`,title:`Assigned to ${R??e.assignedAgentId}`,children:[t.jsx(Sn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:hN(R??e.assignedAgentId,15)})]})]}),t.jsx(Go,{slotId:"task-card-badge",projectId:n})]})}const Tu=10,AN=300,Pu=140;function Iu(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Eo=a.memo(MN,_N);Eo.displayName="TaskCard";function RN({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p}){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(db,{size:14}):t.jsx(Js,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(f=>t.jsx(Eo,{task:f,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p},f.id)),s.map(f=>t.jsx(Eo,{task:f,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:u,onOpenDetailWithTab:d,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:g,workflowStepNameLookup:p},f.id))]})}const zp=a.memo(RN);zp.displayName="WorktreeGroup";function $u(e){return e.toLowerCase().replace(/[-_./]/g,"")}function TN(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 PN(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 IN(e,n){const s=$u(e),i=$u(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&&TN(s,o)||s.length>=4&&PN(s,o,1))return!0;return!1}function $N(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=>IN(o,r))})}function Kn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[b,v]=a.useState(""),[x,y]=a.useState(0),[S,j]=a.useState(null),[A,w]=a.useState(null),_=a.useRef(null),C=a.useRef(null),L=a.useRef(null),E=a.useRef(null),T=a.useRef(null),F=a.useMemo(()=>$N(e,b),[e,b]),K=a.useMemo(()=>F.reduce((te,me)=>((te[me.provider]??=[]).push(me),te),{}),[F]),$=a.useMemo(()=>{const te=[];for(const me of d){const oe=me.indexOf("/");if(oe===-1)continue;const be=me.slice(0,oe),ae=me.slice(oe+1),Ee=F.find($e=>$e.provider===be&&$e.id===ae);Ee&&te.push({model:Ee,fullId:me})}return te},[d,F]),R=a.useMemo(()=>{const te=Object.entries(K),me=new Set(c);return te.sort(([oe],[be])=>{const ae=me.has(oe),Ee=me.has(be);if(ae&&!Ee)return-1;if(!ae&&Ee)return 1;if(ae&&Ee){const $e=c.indexOf(oe),He=c.indexOf(be);if($e!==He)return $e-He}return oe.localeCompare(be)})},[K,c]),I=typeof h=="string"&&h.length>0,H=a.useMemo(()=>{if(!n||I&&n===h)return null;const te=n.indexOf("/");return te===-1?null:n.slice(0,te)},[I,h,n]),J=a.useMemo(()=>{const te=[];return I&&te.push({type:"no-change",value:h,label:g}),te.push({type:"default",value:"",label:"Use default"}),te},[I,g,h]),Z=a.useMemo(()=>{const te=[...J];for(const{model:me,fullId:oe}of $)te.push({type:"favorite",value:oe,label:me.name,provider:me.provider});return R.forEach(([me,oe])=>{te.push({type:"provider",value:`__group_${me}`,label:me,provider:me}),oe.forEach(be=>{te.push({type:"model",value:`${be.provider}/${be.id}`,label:be.name,provider:be.provider})})}),te},[$,R,J]),N=a.useMemo(()=>{if(I&&n===h)return g;if(!n)return"Use default";const te=n.indexOf("/");if(te===-1)return n;const me=n.slice(0,te),oe=n.slice(te+1);return e.find(ae=>ae.provider===me&&ae.id===oe)?.name||n},[I,g,h,n,e]),z=a.useMemo(()=>Z.findIndex(te=>te.value===n),[Z,n]),P=a.useCallback(()=>{const te=window.visualViewport;return te&&te.height>0&&te.width>0?{width:te.width,height:te.height,offsetTop:te.offsetTop,offsetLeft:te.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=a.useCallback(()=>{const{height:te}=P(),me=typeof window.matchMedia=="function",oe=me?window.matchMedia("(max-width: 640px)").matches:!1,be=me?window.matchMedia("(max-width: 768px)").matches:!1;return te<=0?320:oe?Math.min(te*.6,360):be?Math.min(te*.7,420):320},[P]),U=a.useCallback(()=>{const te=C.current;if(!te)return;const me=te.getBoundingClientRect(),{width:oe,height:be,offsetTop:ae,offsetLeft:Ee}=P(),$e=16,He=16,ot=4,Je=k(),et=me.bottom-ae,st=me.top-ae,Oe=me.left-Ee,Ue=be-et,re=st,Ne=Math.max(Ue-He-ot,160),ee=Math.max(re-He-ot,160),Ae=Ue<Je&&re>Ue,Fe=Math.max(Math.min(Ae?ee:Ne,Je),160),fe=Math.min(me.width,oe-$e*2),_e=Math.min(Math.max(Oe,$e),oe-$e-fe)+Ee,ze=Ae?Math.max(He+ae,st-Fe-ot+ae):Math.min(et+ot+ae,be+ae-He-Fe);j({top:ze,left:_e,width:fe,maxHeight:Fe})},[P,k]);a.useEffect(()=>{w(document.body)},[]);const V=a.useRef(!1);a.useEffect(()=>{if(!p){V.current=!1;return}if(V.current||Z.length===0)return;const te=Z.findIndex((me,oe)=>oe>=(z>=0?z:0)&&me.type!=="provider");y(te>=0?te:0),V.current=!0},[p,Z,z]),a.useEffect(()=>{p&&V.current&&(y(0),T.current&&(T.current.scrollTop=0))},[b,p]),a.useEffect(()=>{if(!p)return;U();const te=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(te)},[p,U]),a.useEffect(()=>{if(!p)return;const te=()=>U();window.addEventListener("resize",te),window.addEventListener("scroll",te,!0);const me=window.visualViewport;return me&&(me.addEventListener("resize",te),me.addEventListener("scroll",te)),()=>{window.removeEventListener("resize",te),window.removeEventListener("scroll",te,!0),me&&(me.removeEventListener("resize",te),me.removeEventListener("scroll",te))}},[p,U]),a.useEffect(()=>{if(!p)return;const te=me=>{const oe=me.target,be=_.current?.contains(oe),ae=L.current?.contains(oe);!be&&!ae&&(f(!1),v(""))};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[p]);const pe=a.useCallback(te=>{switch(te.key){case"ArrowDown":if(te.preventDefault(),!p)f(!0);else{let me=x;for(let oe=1;oe<=Z.length;oe++){const be=(x+oe)%Z.length;if(Z[be]?.type!=="provider"){me=be;break}}y(me)}break;case"ArrowUp":if(te.preventDefault(),p){let me=x;for(let oe=1;oe<=Z.length;oe++){const be=(x-oe+Z.length)%Z.length;if(Z[be]?.type!=="provider"){me=be;break}}y(me)}break;case"Enter":if(te.preventDefault(),p){const me=Z[x];me&&me.type!=="provider"&&me.type!=="favorite"&&(s(me.value),f(!1),v(""))}else f(!0);break;case"Escape":te.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,x,Z,s]),ve=a.useCallback(te=>{s(te),f(!1),v("")},[s]),se=a.useCallback(()=>{v(""),E.current?.focus()},[]),he=a.useCallback(()=>{r||f(te=>!te)},[r]);a.useEffect(()=>{if(p&&T.current){const te=T.current.querySelector(`[data-index="${x}"]`);te&&typeof te.scrollIntoView=="function"&&te.scrollIntoView({block:"nearest"})}},[x,p]);const O=b.length>0,ue=p&&S?t.jsxs("div",{ref:L,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:pe,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:te=>v(te.target.value),onClick:te=>te.stopPropagation()}),O&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:se,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[F.length," model",F.length!==1?"s":""]}),t.jsxs("div",{ref:T,className:"model-combobox-list",children:[J.map((te,me)=>t.jsx("div",{"data-index":me,className:`model-combobox-option ${x===me?"model-combobox-option--highlighted":""} ${n===te.value?"model-combobox-option--selected":""}`,onClick:()=>ve(te.value),onMouseEnter:()=>y(me),role:"option","aria-selected":n===te.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:te.label})},`${te.type}-${te.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:te,fullId:me},oe)=>{const be=oe+J.length,ae=x===be,Ee=n===me;return t.jsxs("div",{"data-index":be,className:`model-combobox-option model-combobox-option--favorite ${ae?"model-combobox-option--highlighted":""} ${Ee?"model-combobox-option--selected":""}`,onClick:()=>ve(me),onMouseEnter:()=>y(be),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(Ln,{provider:te.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:te.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:te.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:$e=>{$e.stopPropagation(),m(me)},title:"Remove from favorites","aria-label":`Remove ${te.name} from favorites`,children:"★"})]},me)}),t.jsx("div",{className:"model-combobox-divider"})]}),R.map(([te,me])=>{const oe=Z.findIndex(Ee=>Ee.value===`__group_${te}`),be=c.includes(te),ae=me.filter(Ee=>{const $e=`${Ee.provider}/${Ee.id}`;return!d.includes($e)});return ae.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":oe,children:[t.jsx(Ln,{provider:te,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:te}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${be?"model-combobox-optgroup-favorite--active":""}`,onClick:Ee=>{Ee.stopPropagation(),u(te)},title:be?"Remove from favorites":"Add to favorites","aria-label":be?`Remove ${te} from favorites`:`Add ${te} to favorites`,children:"★"})]}),ae.map(Ee=>{const $e=`${Ee.provider}/${Ee.id}`,He=Z.findIndex(st=>st.value===$e),ot=x===He,Je=n===$e,et=d.includes($e);return t.jsxs("div",{"data-index":He,className:`model-combobox-option ${ot?"model-combobox-option--highlighted":""} ${Je?"model-combobox-option--selected":""}`,onClick:()=>ve($e),onMouseEnter:()=>y(He),role:"option","aria-selected":Je,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 ${et?"model-combobox-option-favorite--active":""}`,onClick:st=>{st.stopPropagation(),m($e)},title:et?"Remove from favorites":"Add to favorites","aria-label":et?`Remove ${Ee.name} from favorites`:`Add ${Ee.name} to favorites`,children:et?"★":"☆"})]},$e)})]},te)}),F.length===0&&O&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:_,className:"model-combobox",onKeyDown:pe,children:t.jsxs("button",{ref:C,type:"button",id:o,className:"model-combobox-trigger",onClick:he,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[H&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Ln,{provider:H,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:N||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),A&&ue?ca.createPortal(ue,A):null]})}function hd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Gn(e,n){return typeof window>"u"?null:window.localStorage.getItem(hd(e,n))}function xs(e,n,s){typeof window>"u"||window.localStorage.setItem(hd(e,s),n)}function yr(e,n){typeof window>"u"||window.localStorage.removeItem(hd(e,n))}const DN=1e4,LN=1e3;function Yo(){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 No();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 No();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<LN||(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()},DN),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await Vj(p);return n(b=>[...b,f]),f},[]),m=a.useCallback(async(p,f)=>{const b=await Wj(p,f);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await Kj(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await Gj(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 Ua="kb-quick-entry-text",zN=["image/png","image/jpeg","image/gif","image/webp"];function ON(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function wl(e,n){return e&&n?`${e}/${n}`:""}function Nl(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 Op({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"&&Gn(Ua,l)||""),[f,b]=a.useState(!1),[v,x]=a.useState(!1),[y,S]=a.useState(!1),j=a.useRef(null),A=a.useRef(null),w=a.useRef(!1),_=a.useRef(l),[C,L]=a.useState([]),E=a.useRef([]),[T,F]=a.useState([]),[K,$]=a.useState(!1),[R,I]=a.useState(""),[H,J]=a.useState(null),[Z,N]=a.useState([]),[z,P]=a.useState(void 0),[k,U]=a.useState(!1),[V,pe]=a.useState(!1),[ve,se]=a.useState(!1),[he,O]=a.useState(!1),[ue,te]=a.useState(null),[me,oe]=a.useState(void 0),[be,ae]=a.useState(void 0),[Ee,$e]=a.useState(void 0),[He,ot]=a.useState(void 0),[Je,et]=a.useState(void 0),[st,Oe]=a.useState(void 0),Ue=a.useRef(null),re=a.useRef(null),Ne=a.useRef(null),ee=a.useRef(null),Ae=a.useRef(null),Fe=a.useRef(null),[fe,_e]=a.useState(null),[ze,Xe]=a.useState(null),[je,ce]=a.useState(null),Re=a.useRef(null),ge=a.useRef(null),[Me,Ge]=a.useState(null),[Pe]=a.useState(()=>typeof document<"u"?document.body:null),[pt,Y]=a.useState(!1),[le,ye]=a.useState(null),[nt,X]=a.useState(i??[]),[Qe,lt]=a.useState([]),[ft,Mt]=a.useState([]),[yt,ht]=a.useState(null),[St,zt]=a.useState(void 0),[It,Rt]=a.useState(!1),[$t,Ot]=a.useState(void 0),{nodes:Vt}=Yo(),[Dt,Ft]=a.useState(!1),[Ct,Nt]=a.useState(!1),Tt=a.useRef(null),Zt=a.useRef(null),[Ut,B]=a.useState(null),xe=u??Qe,Ie=d??ft,M=!e;a.useEffect(()=>{if(i)X(i),Y(!1),ye(null);else{let ie=!1;return Y(!0),ye(null),ps().then(de=>{ie||(X(de.models),u||lt(de.favoriteProviders),d||Mt(de.favoriteModels))}).catch(de=>{ie||ye(ke(de)||"Failed to load models")}).finally(()=>{ie||Y(!1)}),Vo(l).then(de=>{ie||ht(de)}).catch(()=>{}),()=>{ie=!0}}},[i,u,d,l]);const ne=wl(me,be),Le=wl(Ee,He),ut=wl(Je,st),bt=!!(me&&be),Pt=!!(Ee&&He),At=!!(Je&&st),nn=Number(bt)+Number(Pt)+Number(At),zn=St?yt?.modelPresets?.find(ie=>ie.id===St)?.name??"Models":nn>0?`${nn} model${nn===1?"":"s"}`:"Models",hn=a.useCallback((ie,de)=>{if(!ie||!de)return"Using default";const qe=nt.find(mt=>mt.provider===ie&&mt.id===de);return qe?`${qe.provider}/${qe.id}`:`${ie}/${de}`},[nt]);a.useEffect(()=>{p(Gn(Ua,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&xs(Ua,g,l)},[g,l]),a.useEffect(()=>{_.current!==l&&(_.current=l,N([]),P(void 0),J(null),U(!1),_e(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{E.current=C},[C]),a.useEffect(()=>()=>{E.current.forEach(ie=>URL.revokeObjectURL(ie.previewUrl))},[]);const en=a.useCallback(()=>{const ie=j.current;if(!ie)return;ie.style.height="auto";const de=Math.min(ie.scrollHeight,200);ie.style.height=`${de}px`},[]);a.useEffect(()=>{v&&en()},[g,v,en]),a.useEffect(()=>{if(!f&&g===""&&j.current){const ie=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(ie)}},[f,g]),a.useEffect(()=>{K||I("")},[K]),a.useEffect(()=>{if(!Dt)return;const ie=de=>{const qe=de.target,mt=Tt.current?.contains(qe),jt=Zt.current?.contains(qe);!mt&&!jt&&Ft(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[Dt]),a.useEffect(()=>{if(!he)return;const ie=de=>{const qe=de.target,mt=Ue.current?.contains(qe),jt=re.current?.contains(qe),pn=qe instanceof Element&&qe.closest?.(".model-combobox-dropdown--portal")!=null;!mt&&!jt&&!pn&&(O(!1),te(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[he]),a.useEffect(()=>{if(!V)return;const ie=de=>{const qe=de.target;Ae.current?.contains(qe)||Fe.current?.contains(qe)||(pe(!1),Xe(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[V]),a.useEffect(()=>{if(!k)return;const ie=de=>{const qe=de.target;Ne.current?.contains(qe)||ee.current?.contains(qe)||(U(!1),_e(null))};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[k]);const On=a.useCallback(()=>{C.forEach(ie=>URL.revokeObjectURL(ie.previewUrl)),L([]),A.current&&(A.current.value=""),p(""),F([]),J(null),U(!1),_e(null),pe(!1),Xe(null),oe(void 0),ae(void 0),$e(void 0),ot(void 0),et(void 0),Oe(void 0),zt(void 0),Rt(!1),Ot(void 0),$(!1),O(!1),ce(null),te(null),Ft(!1),Nt(!1),x(!1),S(!1),w.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&yr(Ua,l)},[C,l]),we=a.useCallback(ie=>{if(!ie||ie.length===0)return;const de=[];for(let qe=0;qe<ie.length;qe++){const mt=ie[qe];zN.includes(mt.type)&&de.push({file:mt,previewUrl:URL.createObjectURL(mt)})}de.length>0&&L(qe=>[...qe,...de])},[]),it=a.useCallback(ie=>{f||we(ie.clipboardData?.files)},[we,f]),un=a.useCallback(ie=>{L(de=>{const qe=de[ie];return qe&&URL.revokeObjectURL(qe.previewUrl),de.filter((mt,jt)=>jt!==ie)})},[]),Nn=a.useCallback(async()=>{const ie=g.trim();if(!ie||f||!e)return;const de=g;b(!0),p("");try{const qe=await e({description:ie,column:"triage",dependencies:T.length?T:void 0,...H?{assignedAgentId:H}:{},modelPresetId:St,modelProvider:bt?me:void 0,modelId:bt?be:void 0,validatorModelProvider:Pt?Ee:void 0,validatorModelId:Pt?He:void 0,planningModelProvider:At?Je:void 0,planningModelId:At?st:void 0,...It?{executionMode:"fast"}:{},nodeId:$t});if(qe&&C.length>0){const mt=[];for(const jt of C)try{await br(qe.id,jt.file,l)}catch{mt.push(jt.file.name)}mt.length>0&&n(`Failed to upload: ${mt.join(", ")}`,"error")}On()}catch(qe){p(de),n(ke(qe)||"Failed to create task","error")}finally{b(!1)}},[g,f,e,T,H,bt,me,be,Pt,Ee,He,At,Je,st,C,l,n,On,It,$t]),Tn=a.useCallback(ie=>{if(ie.key==="Enter"){if(ie.shiftKey&&v)return;ie.preventDefault(),Nn()}else if(ie.key==="Escape"){if(ie.preventDefault(),ue){te(null);return}if(he){O(!1),ce(null);return}if(K){$(!1);return}if(Dt){Ft(!1);return}if(V){pe(!1),Xe(null);return}if(k){U(!1),_e(null);return}g.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&yr(Ua,l)),x(!1),S(!1),j.current?.blur()}},[Nn,g,v,K,k,V,he,ue,Dt,l,S]),Ce=a.useCallback(()=>{w.current&&(w.current=!1)},[]),Ye=a.useCallback(()=>{c&&x(!0)},[c]),dt=a.useCallback(ie=>{F(de=>de.includes(ie)?de.filter(qe=>qe!==ie):[...de,ie])},[]),vt=a.useCallback(()=>{const ie=window.visualViewport;return ie&&ie.width>0&&ie.height>0?{width:ie.width,height:ie.height,offsetTop:ie.offsetTop,offsetLeft:ie.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Qt=a.useCallback(()=>{const ie=Ue.current;if(!ie)return;const de=ie.getBoundingClientRect(),{width:qe,height:mt,offsetTop:jt,offsetLeft:pn}=vt(),mn=16,an=16,xn=4,Fn=qe<=768,Yn=Math.min(Fn?mt*.6:mt*.5,360),Qn=Math.max(de.width*1.35,320),In=Fn?Math.min(qe-mn*2,360):Qn,Xn=Math.min(In,Math.max(qe-mn*2,240)),Hn=de.top-jt,gs=de.bottom-jt,Mn=de.left-pn,qn=mt-gs,ns=Hn,Ms=Math.max(qn-an-xn,160),ds=Math.max(ns-an-xn,160),An=qn<Yn&&ns>qn,Rn=Math.max(Math.min(An?ds:Ms,Yn),160),js=Math.min(Math.max(Mn,mn),qe-mn-Xn)+pn,Ta=An?Math.max(an+jt,Hn-Rn-xn+jt):Math.min(gs+xn+jt,mt+jt-an-Rn);ce({top:Ta,left:js,width:Xn,maxHeight:Rn})},[vt]),bn=a.useCallback(()=>{const ie=Tt.current?.querySelector(".refine-button");if(!ie)return;const de=ie.getBoundingClientRect(),{width:qe,height:mt,offsetTop:jt,offsetLeft:pn}=vt(),mn=8,an=12,xn=4,Fn=Math.min(200,Math.max(mt-an*2,160)),Yn=Math.min(200,qe-mn*2),Qn=de.top-jt,In=de.bottom-jt,Xn=de.left-pn,Hn=mt-In,gs=Qn,Mn=Hn<Fn&&gs>Hn,qn=Math.min(Math.max(Xn,mn),qe-mn-Yn)+pn,ns=Mn?Math.max(an+jt,Qn-Fn-xn+jt):Math.min(In+xn+jt,mt+jt-an-Fn);B({top:ns,left:qn})},[vt]),Jt=a.useCallback(()=>{const ie=Re.current;if(!ie)return;const de=ie.getBoundingClientRect(),{width:qe,height:mt,offsetTop:jt,offsetLeft:pn}=vt(),mn=16,an=16,xn=4,Fn=qe<=768,Yn=Math.min(Fn?mt*.6:mt*.5,320),Qn=Fn?Math.min(qe-mn*2,360):Math.max(de.width,280),In=Math.min(Qn,Math.max(qe-mn*2,240)),Xn=de.top-jt,Hn=de.bottom-jt,gs=de.left-pn,Mn=mt-Hn,qn=Xn,ns=Math.max(Mn-an-xn,200),Ms=Math.max(qn-an-xn,200),ds=Mn<Yn&&qn>Mn,An=Math.max(Math.min(ds?Ms:ns,Yn),200),Rn=Math.min(Math.max(gs,mn),qe-mn-In)+pn,js=ds?Math.max(an+jt,Xn-An-xn+jt):Math.min(Hn+xn+jt,mt+jt-an-An);Ge({top:js,left:Rn,width:In,maxHeight:An})},[vt]),Xt=a.useCallback(()=>{const ie=Ne.current?.querySelector("button");if(!ie)return;const de=ie.getBoundingClientRect(),{width:qe,height:mt,offsetTop:jt,offsetLeft:pn}=vt(),mn=16,an=16,xn=4,Fn=qe<=768,Yn=Math.min(Fn?mt*.6:mt*.5,320),Qn=Fn?Math.min(qe-mn*2,280):Math.max(de.width,240),In=Math.min(Qn,Math.max(qe-mn*2,200)),Xn=de.top-jt,Hn=de.bottom-jt,gs=de.left-pn,Mn=mt-Hn,qn=Xn,ns=Math.max(Mn-an-xn,160),Ms=Math.max(qn-an-xn,160),ds=Mn<Yn&&qn>Mn,An=Math.max(Math.min(ds?Ms:ns,Yn),160),Rn=Math.min(Math.max(gs,mn),qe-mn-In)+pn,js=ds?Math.max(an+jt,Xn-An-xn+jt):Math.min(Hn+xn+jt,mt+jt-an-An);_e({top:js,left:Rn,width:In,maxHeight:An})},[vt]),_n=a.useCallback(()=>{const ie=Ae.current?.querySelector("button");if(!ie)return;const de=ie.getBoundingClientRect(),{width:qe,height:mt,offsetTop:jt,offsetLeft:pn}=vt(),mn=16,an=16,xn=4,Fn=qe<=768,Yn=Math.min(Fn?mt*.6:mt*.5,320),Qn=Fn?Math.min(qe-mn*2,280):Math.max(de.width,240),In=Math.min(Qn,Math.max(qe-mn*2,200)),Xn=de.top-jt,Hn=de.bottom-jt,gs=de.left-pn,Mn=mt-Hn,qn=Xn,ns=Math.max(Mn-an-xn,160),Ms=Math.max(qn-an-xn,160),ds=Mn<Yn&&qn>Mn,An=Math.max(Math.min(ds?Ms:ns,Yn),160),Rn=Math.min(Math.max(gs,mn),qe-mn-In)+pn,js=ds?Math.max(an+jt,Xn-An-xn+jt):Math.min(Hn+xn+jt,mt+jt-an-An);Xe({top:js,left:Rn,width:In,maxHeight:An})},[vt]);a.useEffect(()=>{if(!he)return;const ie=()=>Qt();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",ie),de.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),de&&(de.removeEventListener("resize",ie),de.removeEventListener("scroll",ie))}},[he,Qt]),a.useEffect(()=>{if(!Dt)return;const ie=()=>bn();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",ie),de.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),de&&(de.removeEventListener("resize",ie),de.removeEventListener("scroll",ie))}},[Dt,bn]),a.useEffect(()=>{if(!K)return;const ie=()=>Jt();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",ie),de.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),de&&(de.removeEventListener("resize",ie),de.removeEventListener("scroll",ie))}},[K,Jt]),a.useEffect(()=>{if(!k)return;const ie=()=>Xt();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",ie),de.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),de&&(de.removeEventListener("resize",ie),de.removeEventListener("scroll",ie))}},[k,Xt]),a.useEffect(()=>{if(!V)return;const ie=()=>_n();window.addEventListener("resize",ie),window.addEventListener("scroll",ie,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",ie),de.addEventListener("scroll",ie)),()=>{window.removeEventListener("resize",ie),window.removeEventListener("scroll",ie,!0),de&&(de.removeEventListener("resize",ie),de.removeEventListener("scroll",ie))}},[V,_n]);const sn=a.useCallback(ie=>{const de=Nl(ie);et(de.provider),Oe(de.modelId)},[]),ls=a.useCallback(ie=>{const de=Nl(ie);oe(de.provider),ae(de.modelId)},[]),cs=a.useCallback(ie=>{const de=Nl(ie);$e(de.provider),ot(de.modelId)},[]),cn=a.useCallback(async ie=>{if(m){m(ie);return}const de=Qe,mt=de.includes(ie)?de.filter(jt=>jt!==ie):[ie,...de];lt(mt);try{await fn({favoriteProviders:mt,favoriteModels:ft})}catch{lt(de)}},[Qe,ft,m]),kt=a.useCallback(async ie=>{if(h){h(ie);return}const de=ft,mt=de.includes(ie)?de.filter(jt=>jt!==ie):[ie,...de];Mt(mt);try{await fn({favoriteProviders:Qe,favoriteModels:mt})}catch{Mt(de)}},[ft,Qe,h]),G=a.useCallback(()=>{const ie=g.trim();if(!ie){n("Enter a description first","error");return}r?.(ie),On()},[g,r,n,On]),De=a.useCallback(()=>{const ie=g.trim();if(!ie){n("Enter a description first","error");return}o?.(ie),On()},[g,o,n,On]),tt=a.useCallback(()=>{Nn()},[Nn]),at=a.useCallback(async ie=>{const de=g.trim();if(!(!de||Ct)){Ft(!1),Nt(!0);try{const qe=await gp(de,ie,l);p(qe),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(qe){const mt=bp(qe);n(mt,"error")}finally{Nt(!1)}}},[g,Ct,n,l]),wt=(ie,de)=>ie.length>de?ie.slice(0,de)+"…":ie,_t=a.useCallback(async()=>{if(i){X(i),ye(null),Y(!1);return}Y(!0),ye(null);try{const ie=await ps();X(ie.models),u||lt(ie.favoriteProviders),d||Mt(ie.favoriteModels)}catch(ie){ye(ke(ie)||"Failed to load models")}finally{Y(!1)}},[i,u,d]),Lt=a.useCallback(async()=>{if(Z.length>0&&z===l){U(!0),Xt();return}se(!0);try{const ie=await Ea(void 0,l);N(ie),P(l),U(!0),Xt()}catch(ie){const de=ke(ie);n(de?`Failed to load agents: ${de}`:"Failed to load agents","error"),U(!1)}finally{se(!1)}},[Z.length,z,l,n,Xt]),Fs=(H?Z.find(ie=>ie.id===H):void 0)?.name??H,li=$t?Vt.find(ie=>ie.id===$t):void 0,_s=y,Us=a.useCallback(()=>{S(ie=>{const de=!ie;return x(de),de})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:j,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ie=>p(ie.target.value),onKeyDown:Tn,onPaste:it,onFocus:Ye,onBlur:Ce,disabled:f||M,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Us,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(mi,{size:14}):t.jsx(Yt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!_s,"aria-hidden":!_s,children:[_s&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:G,onMouseDown:ie=>ie.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(ii,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:De,onMouseDown:ie=>ie.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Uo,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Tt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ct?"refine-button--loading":""}`,onClick:()=>{Ft(ie=>{const de=!ie;return de?bn():B(null),de})},disabled:!g.trim()||Ct,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(rs,{size:12,style:{verticalAlign:"middle"}}),Ct?"Refining...":"Refine"]}),Dt&&Pe&&Ut&&ca.createPortal(t.jsxs("div",{ref:Zt,className:"refine-menu refine-menu--portal",onMouseDown:ie=>ie.preventDefault(),style:{position:"fixed",top:`${Ut.top}px`,left:`${Ut.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>at("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:()=>at("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:()=>at("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:()=>at("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"})]})]}),Pe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Re,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ie=>{const de=!ie;return de?(O(!1),ce(null),te(null),U(!1),_e(null),pe(!1),Xe(null),Jt()):Ge(null),de})},children:[t.jsx(pa,{size:12,style:{verticalAlign:"middle"}}),T.length>0?`${T.length} deps`:"Deps"]})}),K&&Pe&&Me&&(()=>{const ie=R.toLowerCase(),de=(ie?s.filter(qe=>qe.id.toLowerCase().includes(ie)||qe.title&&qe.title.toLowerCase().includes(ie)||qe.description&&qe.description.toLowerCase().includes(ie)):[...s]).sort((qe,mt)=>{const jt=mt.createdAt.localeCompare(qe.createdAt);if(jt!==0)return jt;const pn=parseInt(qe.id.slice(qe.id.lastIndexOf("-")+1),10)||0;return(parseInt(mt.id.slice(mt.id.lastIndexOf("-")+1),10)||0)-pn});return ca.createPortal(t.jsxs("div",{ref:ge,className:"dep-dropdown dep-dropdown--portal",onMouseDown:qe=>qe.preventDefault(),style:{position:"fixed",top:`${Me.top}px`,left:`${Me.left}px`,width:`${Me.width}px`,maxHeight:Me.maxHeight?`${Me.maxHeight}px`:void 0,overflowY:Me.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:R,onChange:qe=>I(qe.target.value),onClick:qe=>qe.stopPropagation()}),de.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):de.map(qe=>t.jsxs("div",{className:`dep-dropdown-item${T.includes(qe.id)?" selected":""}`,onMouseDown:mt=>mt.preventDefault(),onClick:()=>dt(qe.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:qe.id}),t.jsx("span",{className:"dep-dropdown-title",children:wt(qe.title||qe.description||qe.id,60)})]},qe.id))]}),Pe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>A.current?.click(),children:[t.jsx(ip,{size:12,style:{verticalAlign:"middle"}}),C.length>0?`Attach (${C.length})`:"Attach"]}),t.jsxs("button",{ref:Ue,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),U(!1),_e(null),pe(!1),Xe(null),te(null),O(!0),Qt()},children:[t.jsx(vo,{size:12,style:{verticalAlign:"middle"}}),zn]}),t.jsx("div",{className:"node-trigger-wrap",ref:Ae,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{$(!1),U(!1),_e(null),O(!1),ce(null),te(null),pe(ie=>{const de=!ie;return de?_n():Xe(null),de})},children:[t.jsx(fr,{size:12,style:{verticalAlign:"middle"}}),` ${li?.name??"Node"}`,li&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Bi,{status:li.status,showLabel:!0})})]})}),V&&Pe&&ze&&ca.createPortal(t.jsxs("div",{ref:Fe,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ie=>ie.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("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${$t==null?" selected":""}`,onMouseDown:ie=>ie.preventDefault(),onClick:()=>{Ot(void 0),pe(!1),Xe(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Vt.map(ie=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${$t===ie.id?" selected":""}`,onMouseDown:de=>de.preventDefault(),onClick:()=>{Ot(ie.id),pe(!1),Xe(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Bi,{status:ie.status})}),t.jsx("span",{className:"node-picker-item-name",children:ie.name}),t.jsx("span",{className:"node-picker-item-status",children:ON(ie.status)})]},ie.id))]}),Pe),t.jsx("div",{className:"agent-trigger-wrap",ref:Ne,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(U(!1),_e(null)):(pe(!1),Xe(null),Lt())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Sn,{size:12,style:{verticalAlign:"middle"}}),Fs?` ${Fs}`:" Agent"]})}),k&&Pe&&fe&&ca.createPortal(t.jsxs("div",{ref:ee,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ie=>ie.preventDefault(),style:{position:"fixed",top:`${fe.top}px`,left:`${fe.left}px`,width:`${fe.width}px`,maxHeight:fe.maxHeight?`${fe.maxHeight}px`:void 0,overflowY:fe.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ve&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ve&&Z.filter(ie=>ie.state!=="terminated").map(ie=>t.jsxs("div",{className:`dep-dropdown-item${H===ie.id?" selected":""}`,onMouseDown:de=>de.preventDefault(),onClick:()=>{J(ie.id===H?null:ie.id),U(!1),_e(null)},children:[t.jsx(Sn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ie.role}),t.jsx("span",{className:"dep-dropdown-title",children:ie.name})]},ie.id)),!ve&&Z.filter(ie=>ie.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),H&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ie=>ie.preventDefault(),onClick:()=>{J(null),U(!1),_e(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Pe),t.jsx("button",{type:"button",className:`btn btn-sm ${It?"btn-primary":""}`,onClick:()=>Rt(ie=>!ie),onMouseDown:ie=>ie.preventDefault(),"aria-pressed":It,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:tt,onMouseDown:ie=>ie.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(rp,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),C.length>0&&t.jsx("div",{className:"inline-create-previews",children:C.map((ie,de)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ie.previewUrl,alt:ie.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>un(de),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${de}`,children:"×"})]},ie.previewUrl))}),he&&Pe&&je&&ca.createPortal(t.jsx("div",{ref:re,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ie=>ie.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${je.top}px`,left:`${je.left}px`,width:`${je.width}px`,maxHeight:je.maxHeight?`${je.maxHeight}px`:void 0,overflowY:je.maxHeight?"auto":void 0},children:ue===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${At?"model-menu-item--active":""}`,onClick:()=>te("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ii,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:At?hn(Je,st):"Using default"}),t.jsx(kn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${bt?"model-menu-item--active":""}`,onClick:()=>te("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(rs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:bt?hn(me,be):"Using default"}),t.jsx(kn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Pt?"model-menu-item--active":""}`,onClick:()=>te("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(vo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Pt?hn(Ee,He):"Using default"}),t.jsx(kn,{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:()=>te(null),"data-testid":"model-submenu-back",children:[t.jsx(Yt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ue==="plan"&&"Plan Model",ue==="executor"&&"Executor Model",ue==="validator"&&"Reviewer Model"]}),t.jsx(Kn,{models:nt,value:ue==="plan"?ut:ue==="executor"?ne:Le,onChange:ue==="plan"?sn:ue==="executor"?ls:cs,placeholder:"Using default",disabled:pt,id:`model-${ue}-select`,label:`${ue} model`,favoriteProviders:xe,onToggleFavorite:cn,favoriteModels:Ie,onToggleModelFavorite:kt}),le&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:le}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:_t,children:"Retry"})]})]})}),Pe)]}),t.jsx("input",{ref:A,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ie=>{we(ie.target.files),ie.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function FN(e){return ud(e)||e}function UN(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 BN(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=UN(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:FN(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 Du=100,Sl=50,Lu=25;function HN({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,onRetryTask:f,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onArchiveAllDone:y,collapsed:S,onToggleCollapse:j,allTasks:A,availableModels:w,onPlanningMode:_,onSubtaskBreakdown:C,onOpenDetailWithTab:L,favoriteProviders:E,favoriteModels:T,onToggleFavorite:F,onToggleModelFavorite:K,isSearchActive:$,taskStuckTimeoutMs:R,onOpenMission:I,lastFetchTimeMs:H,workflowStepNameLookup:J}){const[Z,N]=a.useState(!1),[z,P]=a.useState(Sl),[k,U]=a.useState(!1),[V,pe]=a.useState(!1),[ve,se]=a.useState(!1),[he,O]=a.useState(!1),ue=a.useRef(null),te=Iw(n.length),{confirm:me}=Ys();a.useEffect(()=>{if(!k)return;function _e(Xe){ue.current?.contains(Xe.target)||U(!1)}function ze(Xe){Xe.key==="Escape"&&U(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",ze),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",ze)}},[k]);const oe=e==="archived",be=oe&&S,ae=!oe&&!$&&e!=="in-progress"&&n.length>Du;a.useEffect(()=>{P(_e=>e==="in-progress"||oe||n.length<=Du?Sl:Math.min(Math.max(_e,Sl),n.length))},[e,oe,n.length]);const Ee=a.useCallback(_e=>{oe||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",N(!0))},[oe]),$e=a.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||N(!1)},[]),He=a.useCallback(async _e=>{_e.preventDefault(),N(!1);const ze=_e.dataTransfer.getData("text/plain");if(!ze)return;const Xe=n.find(je=>je.id===ze);if(!(Xe&&Xe.column===e))try{await r(ze,e)}catch(je){c(ke(je),"error")}},[e,r,c,n]),ot=a.useMemo(()=>e!=="in-progress"?[]:BN(n,n,i),[e,n,i]),Je=a.useMemo(()=>ae?n.slice(0,z):n,[ae,n,z]),et=Math.max(0,n.length-Je.length),st=a.useCallback(()=>{P(_e=>Math.min(_e+Lu,n.length))},[n.length]),Oe=a.useCallback(async()=>{if(U(!1),!(n.length===0||!await me({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){pe(!0);try{const ze=await Promise.allSettled(n.map(ce=>r(ce.id,"triage"))),Xe=ze.filter(ce=>ce.status==="rejected").length,je=ze.length-Xe;Xe===0?c(`Moved ${je} task${je===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${je} of ${ze.length} tasks; ${Xe} failed`,"error")}finally{pe(!1)}}},[n,r,c,me]),Ue=a.useMemo(()=>n.filter(_e=>!_e.paused),[n]),re=Ue.length,Ne=e==="todo"||e==="in-progress"||e==="in-review",ee=V||ve||he,Ae=a.useCallback(async()=>{if(!(!o||(U(!1),re===0)||!await me({title:"Stop All Tasks",message:`Stop all ${re} ${Dn[e].toLowerCase()} task${re===1?"":"s"}?`,danger:!0}))){se(!0);try{const ze=await Promise.allSettled(Ue.map(ce=>o(ce.id))),Xe=ze.filter(ce=>ce.status==="rejected").length,je=ze.length-Xe;Xe===0?c(`Stopped ${je} task${je===1?"":"s"}`,"success"):c(`Stopped ${je} of ${ze.length} tasks; ${Xe} failed`,"error")}finally{se(!1)}}},[o,re,e,Ue,c,me]),Fe=a.useCallback(async()=>{if(U(!1),!(n.length===0||!await me({title:"Move All to Todo",message:`Move all ${n.length} ${Dn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){O(!0);try{const ze=await Promise.allSettled(n.map(ce=>r(ce.id,"todo"))),Xe=ze.filter(ce=>ce.status==="rejected").length,je=ze.length-Xe;Xe===0?c(`Moved ${je} task${je===1?"":"s"} to Todo`,"success"):c(`Moved ${je} of ${ze.length} tasks to Todo; ${Xe} failed`,"error")}finally{O(!1)}}},[n,e,r,c,me]),fe=a.useCallback(async()=>{if(!(!y||n.length===0||!await me({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const ze=await y();c(`Archived ${ze.length} tasks`,"success")}catch(ze){c(ke(ze)||"Failed to archive tasks","error")}},[y,n.length,c,me]);return t.jsxs("div",{className:`column${Z?" drag-over":""}${oe?" column-archived":""}${be?" column-collapsed":""}`,"data-column":e,onDragOver:Ee,onDragLeave:$e,onDrop:He,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Dn[e]}),t.jsx("span",{className:`column-count${te?" 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"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:fe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Lo,{size:16})}),oe&&j&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:j,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(Yt,{size:16}):t.jsx(mi,{size:16})}),Ne&&t.jsxs("div",{className:"column-menu",ref:ue,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(_e=>!_e),"aria-haspopup":"menu","aria-expanded":k,"aria-label":`${Dn[e]} column actions`,title:"Column actions",disabled:ee,children:t.jsx(jb,{size:16})}),k&&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 Oe(),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 Ae(),disabled:re===0||ve||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":re===0?"All tasks are already paused":`Pause ${re} active task${re===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Fe(),disabled:n.length===0||he,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!be&&t.jsx("p",{className:"column-desc",children:Tw[e]}),!be&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Op,{onCreate:u,addToast:c,tasks:A??[],availableModels:w,onPlanningMode:_,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:T,onToggleFavorite:F,onToggleModelFavorite:K}),e==="in-progress"?ot.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):ot.map(_e=>t.jsx(zp,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onOpenDetailWithTab:L,taskStuckTimeoutMs:R,onOpenMission:I,lastFetchTimeMs:H,workflowStepNameLookup:J},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Je.map(_e=>t.jsx(Eo,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onOpenDetailWithTab:L,taskStuckTimeoutMs:R,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:H,workflowStepNameLookup:J},_e.id)),ae&&et>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:st,children:["Load ",Math.min(Lu,et)," more (",et," remaining)"]})]}),t.jsx(Go,{slotId:"board-column-footer",projectId:s})]})]})}const Fp=a.memo(HN);Fp.displayName="Column";function qN(e,n){return[...e].sort((s,i)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=i.status==="merging"||i.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&i.columnMovedAt?i.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!i.columnMovedAt?-1:!s.columnMovedAt&&i.columnMovedAt?1:s.createdAt.localeCompare(i.createdAt)})}function VN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const zu=new Map;function WN(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 KN({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,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,onLoadArchivedTasks:y,searchQuery:S="",availableModels:j,onPlanningMode:A,onSubtaskBreakdown:w,onOpenDetailWithTab:_,favoriteProviders:C,favoriteModels:L,onToggleFavorite:E,onToggleModelFavorite:T,taskStuckTimeoutMs:F,onOpenMission:K,lastFetchTimeMs:$}){const[R,I]=a.useState(!0),H=a.useRef(!1),{fetchBatch:J}=Xw(n),Z=a.useRef(null),[N,z]=a.useState(zu),P=S.trim()!=="",k=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),U=a.useCallback(()=>{I(ve=>{const se=!ve;return!se&&!H.current&&y&&(H.current=!0,y()),se})},[y]),V=a.useMemo(()=>{const ve=Object.fromEntries(Li.map(O=>[O,[]]));for(const O of e)ve[O.column].push(O);const se=k.current,he={};for(const O of Li){const ue=qN(ve[O],O);he[O]=VN(se[O],ue)?se[O]:ue}return k.current=he,he},[e]);a.useEffect(()=>{let ve=!1;return Wo(n).then(se=>{if(ve)return;const he=new Map(se.map(O=>[O.id,O.name]));z(O=>WN(O,he)?O:he)}).catch(()=>{ve||z(se=>se.size===0?se:zu)}),()=>{ve=!0}},[n]);const pe=a.useMemo(()=>e.filter(ve=>ve.prInfo||ve.issueInfo).map(ve=>ve.id),[e]);return a.useEffect(()=>{if(pe.length!==0)return Z.current&&clearTimeout(Z.current),Z.current=setTimeout(()=>{const ve=[];for(let se=0;se<pe.length;se+=50)ve.push(pe.slice(se,se+50));ve.forEach(se=>{J(se)})},500),()=>{Z.current&&clearTimeout(Z.current)}},[pe,J]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Li.map(ve=>t.jsx(Fp,{column:ve,tasks:V[ve],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,allTasks:e,availableModels:j,onOpenDetailWithTab:_,favoriteProviders:C,favoriteModels:L,onToggleFavorite:E,onToggleModelFavorite:T,isSearchActive:P,taskStuckTimeoutMs:F,onOpenMission:K,lastFetchTimeMs:$,workflowStepNameLookup:N,...ve==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:A,onSubtaskBreakdown:w}:{},...ve==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ve==="done"?{onArchiveAllDone:x}:{},...ve==="archived"?{collapsed:R,onToggleCollapse:U}:{}},ve))})})}const Ba={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Ou=new Set(["planning","researching","executing","finalizing","merging"]),Oc=["id","title","status","column","dependencies","progress"];function GN(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function JN(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Fu(e){try{const n=Gn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Oc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Oc)}function Uu(e){try{const n=Gn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Bu(e){try{const n=Gn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Li.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Hu(e){try{const n=Gn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function YN(e){return e.status==="executing"||e.column==="in-progress"}function qu(e){const n=Dp(e);return n.total===0||!YN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function QN({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:y="",lastFetchTimeMs:S}){const[j,A]=a.useState("id"),[w,_]=a.useState("desc"),[C,L]=a.useState(null),[E,T]=a.useState(null),[F,K]=a.useState(null),R=Pr()==="mobile",[I,H]=a.useState(()=>Fu(b)),[J,Z]=a.useState(()=>Uu(b)),[N,z]=a.useState(()=>Bu(b));a.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-list-columns",JSON.stringify([...I]),b)},[b,I]),a.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-hide-done",J.toString(),b)},[J,b]),a.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-list-collapsed",JSON.stringify([...N]),b)},[N,b]);const[P,k]=a.useState(!1),U=a.useRef(null),[V,pe]=a.useState(()=>Hu(b));a.useEffect(()=>{H(Fu(b)),Z(Uu(b)),z(Bu(b)),pe(Hu(b))},[b]),a.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-selected-tasks",JSON.stringify([...V]),b)},[b,V]);const ve=a.useCallback(Y=>{pe(le=>{const ye=new Set(le);return ye.has(Y)?ye.delete(Y):ye.add(Y),ye})},[]),se=a.useCallback(()=>{pe(new Set)},[]),he=a.useCallback(Y=>{H(le=>{const ye=new Set(le);return ye.has(Y)?ye.size>1&&ye.delete(Y):ye.add(Y),ye})},[]);a.useEffect(()=>{if(!P)return;const Y=ye=>{U.current&&!U.current.contains(ye.target)&&k(!1)},le=ye=>{ye.key==="Escape"&&k(!1)};return document.addEventListener("mousedown",Y),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",Y),document.removeEventListener("keydown",le)}},[P]);const O={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},ue=a.useCallback(Y=>{j===Y?_(le=>le==="asc"?"desc":"asc"):(A(Y),_("asc"))},[j]),te=a.useCallback(Y=>{K(le=>le===Y?null:Y)},[]),me=a.useCallback(Y=>{z(le=>{const ye=new Set(le);return ye.has(Y)?ye.delete(Y):ye.add(Y),ye})},[]),oe=a.useCallback(()=>{K(null)},[]),be=a.useMemo(()=>{let Y=y?e.filter(X=>X.id.toLowerCase().includes(y.toLowerCase())||X.title&&X.title.toLowerCase().includes(y.toLowerCase())||X.description.toLowerCase().includes(y.toLowerCase())):[...e];J&&!F&&(Y=Y.filter(X=>X.column!=="done"&&X.column!=="archived"));const ye=[...F?Y.filter(X=>X.column===F):Y].sort((X,Qe)=>{let lt=0;switch(j){case"id":lt=X.id.localeCompare(Qe.id);break;case"title":lt=(X.title||X.description).localeCompare(Qe.title||Qe.description);break;case"status":lt=(X.status||"").localeCompare(Qe.status||"");break;case"column":lt=X.column.localeCompare(Qe.column);break}return w==="asc"?lt:-lt}),nt={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ye.forEach(X=>nt[X.column].push(X)),nt},[e,y,j,w,J,F]),ae=a.useMemo(()=>Object.values(be).reduce((Y,le)=>Y+le.length,0),[be]),Ee=a.useMemo(()=>e.filter(Y=>Y.column==="done"||Y.column==="archived").length,[e]),$e=a.useMemo(()=>J?Ee:0,[J,Ee]),He=a.useCallback(()=>{const Y=Object.values(be).flat().filter(le=>le.column!=="archived").map(le=>le.id);pe(le=>{if(Y.every(nt=>le.has(nt))){const nt=new Set(le);return Y.forEach(X=>nt.delete(X)),nt}else return new Set([...le,...Y])})},[be]),ot=a.useMemo(()=>{const Y=Object.values(be).flat().filter(le=>le.column!=="archived");return Y.length===0?!1:Y.every(le=>V.has(le.id))},[be,V]),Je=a.useMemo(()=>{const Y=Object.values(be).flat().filter(ye=>ye.column!=="archived");if(Y.length===0)return!1;const le=Y.filter(ye=>V.has(ye.id)).length;return le>0&&le<Y.length},[be,V]),[et,st]=a.useState("__no_change__"),[Oe,Ue]=a.useState("__no_change__"),[re,Ne]=a.useState("__no_change__"),[ee,Ae]=a.useState([]),[Fe,fe]=a.useState(!1),_e=a.useMemo(()=>re&&re!=="__no_change__"?ee.find(Y=>Y.id===re):void 0,[ee,re]),[ze,Xe]=a.useState(!1);a.useEffect(()=>{if(V.size===0)return;let Y=!1;return(async()=>{fe(!0);try{const ye=await No();Y||Ae(ye)}catch(ye){console.error("Failed to fetch nodes for bulk edit",ye),Y||Ae([])}finally{Y||fe(!1)}})(),()=>{Y=!0}},[V.size]);const je=a.useCallback(async()=>{if(V.size===0)return;const Y=Array.from(V).filter(ye=>{const nt=e.find(X=>X.id===ye);return nt&&nt.column!=="archived"});if(Y.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const le={taskIds:Y};if(et!=="__no_change__")if(et==="")le.modelProvider=null,le.modelId=null;else{const ye=et.indexOf("/");ye!==-1&&(le.modelProvider=et.slice(0,ye),le.modelId=et.slice(ye+1))}if(Oe!=="__no_change__")if(Oe==="")le.validatorModelProvider=null,le.validatorModelId=null;else{const ye=Oe.indexOf("/");ye!==-1&&(le.validatorModelProvider=Oe.slice(0,ye),le.validatorModelId=Oe.slice(ye+1))}if(re!=="__no_change__"&&(re===""?le.nodeId=null:le.nodeId=re),Object.keys(le).length===1){i("No changes to apply","info");return}Xe(!0);try{const ye=await zv(le.taskIds,le.modelProvider,le.modelId,le.validatorModelProvider,le.validatorModelId,void 0,void 0,le.nodeId,b);f&&f(ye.updated),i(`Updated ${Y.length} task${Y.length===1?"":"s"}`,"success"),se(),st("__no_change__"),Ue("__no_change__"),Ne("__no_change__")}catch(ye){i(ke(ye)||"Failed to update models","error")}finally{Xe(!1)}},[V,e,et,Oe,re,b,i,se,f]),ce=a.useCallback(Y=>{s(Y)},[s]),Re=a.useCallback((Y,le)=>{if(le.paused){Y.preventDefault();return}Y.dataTransfer.setData("text/plain",le.id),Y.dataTransfer.effectAllowed="move",L(le.id)},[]),ge=a.useCallback(()=>{L(null),T(null)},[]),Me=a.useCallback((Y,le)=>{Y.preventDefault(),Y.dataTransfer.dropEffect="move",T(le)},[]),Ge=a.useCallback(()=>{T(null)},[]),Pe=a.useCallback(async(Y,le)=>{Y.preventDefault(),T(null);const ye=Y.dataTransfer.getData("text/plain");if(ye){if(le==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(ye,le)}catch(nt){i(ke(nt),"error")}}},[n,i]),pt=Y=>j!==Y?t.jsx(Yh,{size:14,className:"sort-icon"}):w==="asc"?t.jsx(Di,{size:14,className:"sort-icon active"}):t.jsx(wr,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:U,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>k(Y=>!Y),"aria-expanded":P,"aria-haspopup":"menu",children:[t.jsx(pb,{size:14}),"Columns"]}),P&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Oc.map(Y=>{const le=I.has(Y),ye=le&&I.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ye?" disabled":""}`,role:"menuitem",title:ye?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:le,onChange:()=>he(Y),disabled:ye}),t.jsx("span",{children:O[Y]})]},Y)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>Z(Y=>!Y),"aria-pressed":J,title:J?"Show done tasks":"Hide done tasks",children:[J?t.jsx(ha,{size:14}):t.jsx(Nc,{size:14}),J?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[F?`${ae} of ${e.length} tasks in ${Dn[F]}`:`${ae} of ${e.length} tasks`,$e>0&&!F&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",$e," hidden)"]}),F&&t.jsx("button",{className:"btn btn-sm",onClick:oe,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),V.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[V.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:se,children:"Clear"})]}),V.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 & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Kn,{models:c,value:et,onChange:st,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(Kn,{models:c,value:Oe,onChange:Ue,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:re,onChange:Y=>Ne(Y.target.value),"aria-label":"Node Override",disabled:Fe,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),ee.map(Y=>t.jsx("option",{value:Y.id,children:`${JN(Y.status)} ${Y.name||Y.id} (${GN(Y.status)})`},Y.id))]}),_e?t.jsx(Bi,{status:_e.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:je,disabled:ze||et==="__no_change__"&&Oe==="__no_change__"&&re==="__no_change__",children:ze?"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:Li.map(Y=>{const le=e.filter(Qe=>Qe.column===Y).length,ye=Y==="done"||Y==="archived",nt=J&&ye?0:le,X=J&&ye&&le>0;return t.jsxs("div",{className:`list-drop-zone${E===Y?" drag-over":""}${F===Y?" active":""}`,onClick:()=>te(Y),onDragOver:Qe=>Me(Qe,Y),onDragLeave:Ge,onDrop:Qe=>Pe(Qe,Y),"data-column":Y,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Ba[Y]}}),t.jsx("span",{className:"drop-zone-label",children:Dn[Y]}),t.jsx("span",{className:"drop-zone-count",children:X?`${nt} of ${le}`:le})]},Y)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Op,{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})}),ae===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):R?t.jsx("div",{className:"list-cards",children:Li.map(Y=>{if(F&&Y!==F||J&&(Y==="done"||Y==="archived")&&!F)return null;const le=be[Y],ye=le.length===0;if(y&&ye)return null;const nt=N.has(Y);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${nt?" list-section-header--collapsed":""}`,onClick:()=>me(Y),"aria-expanded":!nt,role:"button",tabIndex:0,onKeyDown:X=>{(X.key==="Enter"||X.key===" ")&&(X.preventDefault(),me(Y))},children:[t.jsx(kn,{size:14,className:`list-section-chevron${nt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Y}`}),t.jsx("span",{className:"list-section-title",children:Dn[Y]}),t.jsx("span",{className:"list-section-count",children:le.length})]}),!nt&&t.jsx(t.Fragment,{children:ye?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):le.map(X=>{const Qe=X.status==="failed",lt=X.paused===!0,ft=Co(X,x,S),Mt=!r&&!Qe&&!lt&&!ft&&(X.column==="in-progress"||Ou.has(X.status)),yt=typeof X.status=="string"&&X.status.trim().length>0,ht=!!(X.dependencies&&X.dependencies.length>0),St=qu(X),zt=St.hasProgress,It=V.size>0;return t.jsxs("div",{className:`list-card${Mt?" agent-active":""}${It?" list-card--selectable":""}`,onClick:()=>ce(X),"data-id":X.id,children:[It&&t.jsx("label",{className:"list-card-checkbox",onClick:Rt=>Rt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:V.has(X.id),onChange:Rt=>{Rt.stopPropagation(),ve(X.id)},onClick:Rt=>Rt.stopPropagation(),disabled:X.column==="archived","aria-label":`Select ${X.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:X.id}),X.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),ft?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):yt?t.jsx("span",{className:`list-status-badge list-status-badge--${X.column}${Qe?" failed":""}${Mt?" pulsing":""}`,children:X.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:X.title||X.description})}),(ht||zt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[ht&&t.jsxs("span",{className:"list-dep-badge",title:X.dependencies.join(", "),children:[t.jsx(pa,{size:12})," ",X.dependencies.length]}),zt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${St.percent}%`,backgroundColor:Ba[X.column]}})}),t.jsx("span",{className:"list-progress-label",children:St.label})]})]})]},X.id)})})]},Y)})}):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:ot,ref:Y=>{Y&&(Y.indeterminate=Je)},onChange:He,"aria-label":"Select all visible tasks"})}),I.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ue("id"),children:["ID ",pt("id")]}),I.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ue("title"),children:["Title ",pt("title")]}),I.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ue("status"),children:["Status ",pt("status")]}),I.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ue("column"),children:["Column ",pt("column")]}),I.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),I.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Li.map(Y=>{if(F&&Y!==F||J&&(Y==="done"||Y==="archived")&&!F)return null;const le=be[Y],ye=le.length===0;if(y&&ye)return null;const nt=N.has(Y);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${nt?" list-section-header--collapsed":""}`,onClick:()=>me(Y),"aria-expanded":!nt,children:t.jsxs("th",{colSpan:I.size+1,className:"list-section-cell",children:[t.jsx(kn,{size:14,className:`list-section-chevron${nt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Y}`}),t.jsx("span",{className:"list-section-title",children:Dn[Y]}),t.jsx("span",{className:"list-section-count",children:le.length})]})}),!nt&&t.jsx(t.Fragment,{children:ye?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:I.size+1,className:"list-empty-cell",children:"No tasks"})}):le.map(X=>{const Qe=X.status==="failed",lt=X.paused===!0,ft=Co(X,x,S),Mt=!r&&!Qe&&!lt&&!ft&&(X.column==="in-progress"||Ou.has(X.status)),yt=C===X.id;return t.jsxs("tr",{className:`list-row${Qe?" failed":""}${lt?" paused":""}${ft?" stuck":""}${Mt?" agent-active":""}${yt?" dragging":""}`,onClick:()=>ce(X),draggable:!lt,onDragStart:ht=>Re(ht,X),onDragEnd:ge,"data-id":X.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:V.has(X.id),onChange:ht=>{ht.stopPropagation(),ve(X.id)},onClick:ht=>ht.stopPropagation(),disabled:X.column==="archived","aria-label":`Select ${X.id}`})}),I.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:X.id}),I.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[X.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:X.title||X.description})]})}),I.has("status")&&t.jsx("td",{className:"list-cell",children:ft?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):X.status?t.jsx("span",{className:`list-status-badge list-status-badge--${X.column}${Qe?" failed":""}${Mt?" pulsing":""}`,children:X.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),I.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Ba[X.column]}20`,color:Ba[X.column]},children:Dn[X.column]})}),I.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:X.dependencies&&X.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:X.dependencies.join(", "),children:[t.jsx(pa,{size:12})," ",X.dependencies.length]}):"-"}),I.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const ht=qu(X);return ht.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:`${ht.percent}%`,backgroundColor:Ba[X.column]}})}),t.jsx("span",{className:"list-progress-label",children:ht.label})]}):"-"})()})]},X.id)})})]},Y)})})]})]})]})}const XN={active:{label:"Active",color:"var(--success)",icon:Cn},paused:{label:"Paused",color:"var(--warning)",icon:Ks},errored:{label:"Error",color:"var(--color-error)",icon:hs},initializing:{label:"Initializing",color:"var(--info)",icon:rt}};function ZN(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 e1(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 t1(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 n1({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=XN[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(j=>{j.stopPropagation(),i(e)},[i,e]),b=a.useCallback(j=>{j.stopPropagation(),r(e)},[r,e]),v=a.useCallback(j=>{if(j.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",y=e.status==="errored",S=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Wn,{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:e1(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:S?"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:ZN(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(Cn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||S,title:S?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Ks,{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(Nr,{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(on,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const s1=a.memo(n1,t1);function i1(){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(Wn,{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(zs,{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(wn,{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(hs,{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 a1=1e4,Vu=5;function r1(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+=Vu){const b=e.slice(f,f+Vu),v=await Promise.allSettled(b.map(async x=>{try{return await ou(x)}catch{return null}}));if(b.forEach((x,y)=>{const S=v[y];p[x]=S.status==="fulfilled"?S.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 ou(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()},a1),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function o1({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 K=localStorage.getItem("kb-dashboard-recent-projects");if(K)try{const $=JSON.parse(K);x($)}catch{}},[]);const[v,x]=a.useState([]),y=a.useMemo(()=>e.map(K=>K.id),[e]),{healthMap:S,loading:j}=r1(y),A=a.useMemo(()=>e.map(K=>({project:K,health:S[K.id]||null})),[e,S]),w=a.useMemo(()=>{let K=[...A];return u!=="all"&&(K=K.filter(({project:$})=>$.status===u)),m!==null&&(K=K.filter(({project:$})=>$.nodeId===m)),K},[A,u,m]),_=a.useMemo(()=>{const K=[...w];return K.sort(($,R)=>{let I=0;switch(g){case"name":I=$.project.name.localeCompare(R.project.name);break;case"activity":{const H=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,J=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt;I=new Date(J).getTime()-new Date(H).getTime();break}case"status":{const H={errored:0,initializing:1,paused:2,active:3};I=H[$.project.status]-H[R.project.status];break}}return f==="asc"?I:-I}),K},[w,g,f]),C=a.useMemo(()=>{const K=e.length,$=e.filter(z=>z.status==="active").length,R=e.filter(z=>z.status==="errored").length,I=new Set;e.forEach(z=>{z.nodeId&&I.add(z.nodeId)});const H=I.size||(K>0?1:0);let J=0,Z=0,N=0;return Object.values(S).forEach(z=>{z&&(J+=z.activeTaskCount,Z+=z.totalTasksCompleted,N+=z.inFlightAgentCount)}),{totalProjects:K,activeProjects:$,erroredProjects:R,totalNodes:H,totalActiveTasks:J,totalCompletedTasks:Z,totalInFlightAgents:N}},[e,S]),L=a.useMemo(()=>({all:e.length,active:e.filter(K=>K.status==="active").length,paused:e.filter(K=>K.status==="paused").length,errored:e.filter(K=>K.status==="errored").length}),[e]),E=a.useMemo(()=>{const K=new Map;return e.forEach($=>{const R=$.nodeId,I=K.get(R);if(I)I.count++;else{const J=c.find(Z=>Z.id===R)?.name??$._sourceNodeName??"Local";K.set(R,{name:J,count:1})}}),Array.from(K.entries()).map(([$,{name:R,count:I}])=>({nodeId:$??null,name:R,count:I}))},[e,c]),T=a.useCallback(K=>{const $=[K.id,...v.filter(R=>R!==K.id)].slice(0,3);x($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(K)},[s,v]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(i1,{}):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(ir,{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(ln,{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(Ui,{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(Wn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(zs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.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(wn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),C.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(hs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:C.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),C.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:C.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(ln,{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:L.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:L.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:L.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${L.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:L.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(fr,{size:14}),t.jsxs("select",{value:m??"",onChange:K=>{h(K.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:K,name:$,count:R})=>t.jsxs("option",{value:K??"",children:[$," (",R,")"]},K??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(yo,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:K=>{const[$,R]=K.target.value.split("-");p($),b(R)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(Yh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:_.map(({project:K,health:$})=>{const R=c.find(H=>H.id===K.nodeId),I=R?void 0:K._sourceNodeName;return t.jsx(s1,{project:K,health:$,node:R,nodeNameFallback:I,onSelect:T,onPause:r,onResume:o,onRemove:l},K.id)})}),_.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(yo,{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 l1=45e3,c1=3e3,d1=2e3,u1=1500,Wu="fusion:sse-client-id";let na=null;const ki=new Map;function Ku(){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 Up(){if(!(typeof window>"u")){if(na)return na;try{const e=window.sessionStorage.getItem(Wu);if(e)return na=e,e;const n=Ku();return window.sessionStorage.setItem(Wu,n),na=n,n}catch{return na=Ku(),na}}}function Bp(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Hp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function m1(e){const n=Up();if(!n)return e;const s=Bp(e);return!s||!Hp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pd(e,n){const s=Up();if(!s)return;const i=Bp(e);if(!i||!Hp(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),ai(`${r.pathname}${r.search}${r.hash}`)}function h1(e){if(typeof window>"u")return;const n=pd(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 Qo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Gu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=pd(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),u1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function p1(e){Qo(e),pd(e.url,"keepalive")&&(Gu(e),e.keepaliveTimer=window.setInterval(()=>{Gu(e)},d1))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ki.values()))if(!s.closed){if(Qo(s),h1(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(ki.values()))i.subscribers.size!==0&&(i.closed=!1,fd(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function ar(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{qp(e)},l1)}function qp(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Qo(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ki.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=ki.get(e.url);s&&s===e&&e.subscribers.size>0&&fd(e)},c1)}}function fd(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ai(m1(e.url)));e.es=n,p1(e),n.addEventListener("open",()=>{ar(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);qp(e)}),n.addEventListener("message",()=>ar(e)),n.addEventListener("heartbeat",()=>ar(e)),Vp(e),ar(e)}function Vp(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=>{ar(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 f1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Qo(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ki.delete(e.url)}function Qs(e,n={}){let s=ki.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ki.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let u=i.events.get(l);u||(u=new Set,i.events.set(l,u)),u.add(c)}s.subscribers.add(i);const r=!!s.es&&s.hasOpenedOnce;fd(s),Vp(s),r&&queueMicrotask(()=>{s.subscribers.has(i)&&i.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=ki.get(e);l&&(l.subscribers.delete(i),l.subscribers.size===0&&f1(l))}}const gd="kb-planning-last-description",bd="kb-subtask-last-description",xd="kb-mission-last-goal";function g1(e,n){xs(gd,e,n)}function b1(e){return Gn(gd,e)||""}function sa(e){yr(gd,e)}function x1(e,n){xs(bd,e,n)}function v1(e){return Gn(bd,e)||""}function Cl(e){yr(bd,e)}function y1(e,n){xs(xd,e,n)}function j1(e){return Gn(xd,e)||""}function bi(e){yr(xd,e)}function k1(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 w1(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 N1(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 Os({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=N1(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?k1(o):void 0,h=o.question&&m!==void 0?w1(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 Ju="fusion-tab-id";function S1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ki(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Ju);if(e)return e;const n=S1();return window.sessionStorage.setItem(Ju,n),n}function Xo(e){const n=a.useMemo(()=>Ki(),[]),[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(Yk(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=Qk(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=ai(`/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(Xk(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const C1="fusion:ai-session-sync",Yu="fusion:ai-session-sync",E1=3e4,_1=6e4;function Zs(){return Date.now()}function M1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Qu(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 A1{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=M1(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:Zs()})}broadcastUpdate(n){const s=n.timestamp??Zs();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",i=n.timestamp??Zs();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},i),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:i})}broadcastLock(n,s){const i=Zs();this.applyTabOwnership(n,s,i),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:i})}broadcastUnlock(n,s){const i=Zs();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Zs();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(C1),this.channel.onmessage=s=>{const i=Qu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Yu||!s.newValue))try{const i=JSON.parse(s.newValue),r=Qu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Zs();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},E1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Zs();this.publish({type:"tab:inactive",tabId:i,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const i={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Yu,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:Zs()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,i=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const 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=Zs(),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>_1;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 ei=new A1;function Ma(){const e=a.useSyncExternalStore(c=>ei.subscribe(c),()=>ei.getSnapshot(),()=>ei.getSnapshot());a.useEffect(()=>{ei.requestSync()},[]);const n=a.useCallback(c=>{ei.broadcastUpdate(c)},[]),s=a.useCallback(c=>{ei.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{ei.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{ei.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{ei.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{ei.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function R1(e,n){return e&&n?`${e}/${n}`:""}function T1(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 P1=["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 I1({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,b]=a.useState([]),[v,x]=a.useState(null),[y,S]=a.useState(!1),j=a.useRef(!1),[A,w]=a.useState(""),[_,C]=a.useState(!0),[L,E]=a.useState(!1),[T,F]=a.useState(!1),[K,$]=a.useState(!1),R=a.useRef(null),I=a.useRef(null),H=a.useRef(null),J=a.useRef(null),[Z,N]=a.useState(o??null),z=a.useMemo(()=>Ki(),[]),{isLockedByOther:P,takeControl:k,isLoading:U}=Xo(e?Z:null),{activeTabMap:V,broadcastUpdate:pe,broadcastCompleted:ve,broadcastLock:se,broadcastUnlock:he,broadcastHeartbeat:O}=Ma(),{confirm:ue}=Ys(),[te,me]=a.useState(void 0),[oe,be]=a.useState(void 0),[ae,Ee]=a.useState([]),[$e,He]=a.useState(!0),[ot,Je]=a.useState(null),[et,st]=a.useState([]),[Oe,Ue]=a.useState([]),re=R1(te,oe);a.useEffect(()=>{(async()=>{try{He(!0);const le=await ps();Ee(le.models),st(le.favoriteProviders),Ue(le.favoriteModels)}catch(le){Je(ke(le)||"Failed to load models")}finally{He(!1)}})()},[]);const Ne=a.useCallback(Y=>{st(le=>{const ye=le,X=ye.includes(Y)?ye.filter(Qe=>Qe!==Y):[Y,...ye];return fn({favoriteProviders:X,favoriteModels:Oe}).catch(()=>{st(ye)}),X})},[Oe]),ee=a.useCallback(Y=>{Ue(le=>{const ye=le,X=ye.includes(Y)?ye.filter(Qe=>Qe!==Y):[Y,...ye];return fn({favoriteProviders:et,favoriteModels:X}).catch(()=>{Ue(ye)}),X})},[et]),Ae=a.useCallback((Y,le)=>{if(!Y||!le)return"Using default";const ye=ae.find(nt=>nt.provider===Y&&nt.id===le);return ye?`${ye.provider}/${ye.id}`:`${Y}/${le}`},[ae]),Fe=a.useCallback(Y=>{I.current?.close();const le=zk(Y,i,{onThinking:ye=>{w(nt=>nt+ye),pe({sessionId:Y,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:ye=>{E(!1),F(!1),bi(i),d({type:"question",sessionId:Y,question:ye}),w(""),S(!0),pe({sessionId:Y,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:ye=>{E(!1),F(!1),bi(i),d({type:"summary",sessionId:Y,summary:ye}),x(ye),w(""),S(!0),pe({sessionId:Y,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:ye=>{const nt=ye||"Session failed while contacting the AI.";E(!1),F(!1),h(null),d({type:"error",sessionId:Y,errorMessage:nt}),w(""),S(!0),H.current=Y,pe({sessionId:Y,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),ve({sessionId:Y,status:"error"})},onComplete:()=>{E(!1),F(!1),H.current=null,ve({sessionId:Y,status:"complete"})},onConnectionStateChange:ye=>{E(ye==="reconnecting")}});I.current=le},[ve,pe,l,i,z]),fe=a.useCallback(async Y=>{const le=Y??l;if(le.trim()){h(null),w(""),p([]),b([]),E(!1),d({type:"loading"});try{const{sessionId:ye}=await Ik(le.trim(),i,te&&oe?{modelProvider:te,modelId:oe}:void 0);H.current=ye,N(ye),bi(i),Fe(ye),p([])}catch(ye){E(!1),h(ke(ye)||"Failed to start interview session"),d({type:"initial"}),H.current=null,N(null)}}},[Fe,l,te,oe,i]);a.useEffect(()=>{e&&u.type==="initial"&&R.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!j.current&&u.type==="initial"){c(r);const Y=setTimeout(()=>{j.current=!0,fe(r)},0);return()=>clearTimeout(Y)}else if(e&&!r&&!j.current&&u.type==="initial"){const Y=j1(i);Y&&c(Y)}},[e,r,u.type,fe]),a.useEffect(()=>{e||(j.current=!1,E(!1),F(!1),N(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Y=!1;return ui(o).then(le=>{if(Y||!le)return;const ye=xa(le.conversationHistory);if(b(ye),N(le.id),p(ye.map(nt=>nt.response).filter(nt=>!!(nt&&typeof nt=="object"&&!Array.isArray(nt)))),le.status==="awaiting_input"&&le.currentQuestion)try{bi(i);const nt=JSON.parse(le.currentQuestion);H.current=le.id,S(!0),d({type:"question",sessionId:le.id,question:nt})}catch{h("Failed to restore session question.")}else if(le.status==="complete"&&le.result)try{bi(i);const nt=JSON.parse(le.result);H.current=le.id,S(!0),x(nt),d({type:"summary",sessionId:le.id,summary:nt})}catch{h("Failed to restore session result.")}else le.status==="generating"?(H.current=le.id,S(!0),le.thinkingOutput&&w(le.thinkingOutput),d({type:"loading"}),Fe(le.id)):le.status==="error"&&(H.current=le.id,S(!0),h(null),d({type:"error",sessionId:le.id,errorMessage:le.error??"The session encountered an error."}))}).catch(()=>{Y||h("Failed to resume session.")}),()=>{Y=!0}},[Fe,e,o,u.type,i]),a.useEffect(()=>{if(!e){J.current&&(he(J.current,z),J.current=null);return}if(Z&&J.current!==Z){J.current&&he(J.current,z),se(Z,z),J.current=Z;return}!Z&&J.current&&(he(J.current,z),J.current=null)},[se,he,e,Z,z]),a.useEffect(()=>{if(!e||!Z||J.current!==Z)return;O(z);const Y=setInterval(()=>{O(z)},3e4);return()=>{clearInterval(Y)}},[O,e,Z,z]),a.useEffect(()=>()=>{I.current?.close(),I.current=null,J.current&&(he(J.current,z),J.current=null)},[he,z]),a.useEffect(()=>{if(!e)return;const Y=le=>{(u.type==="question"||u.type==="summary")&&(le.preventDefault(),le.returnValue=""),I.current?.close()};return window.addEventListener("beforeunload",Y),()=>window.removeEventListener("beforeunload",Y)},[e,u]);const _e=a.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),ze=a.useCallback(async()=>{if(l&&y1(l,i),!(y&&!await ue({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(I.current?.close(),I.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await wp(u.sessionId,i,z)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),w(""),E(!1),F(!1),S(!1),$(!1),me(void 0),be(void 0),H.current=null,N(null),n()}},[l,y,u,n,i,z,ue]);a.useEffect(()=>{if(!e)return;const Y=le=>{le.key==="Escape"&&ze()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,ze]);const Xe=a.useCallback(async Y=>{if(u.type!=="question")return;const{sessionId:le}=u;h(null),p(ye=>[...ye,Y]),b(ye=>[...ye,{question:u.question,response:Y}]),d({type:"loading"}),w("");try{Fe(le),await $k(le,Y,i,z),S(!0)}catch(ye){I.current?.close(),I.current=null,h(ke(ye)||"Failed to submit response"),d({type:"question",sessionId:le,question:u.question})}},[u,i,z,Fe]),je=a.useCallback(async()=>{if(u.type!=="error")return;const Y=u.sessionId;h(null),F(!0),w(""),d({type:"loading"}),Fe(Y);try{H.current=Y,N(Y),await Dk(Y,i,z)}catch(le){let ye=le;if((ke(le)||"").includes("not in an error state"))try{const X=await ui(Y);if(!X)throw new Error("Failed to refresh interview session.");const Qe=xa(X.conversationHistory);if(b(Qe),p(Qe.map(lt=>lt.response).filter(lt=>!!(lt&&typeof lt=="object"&&!Array.isArray(lt)))),H.current=X.id,N(X.id),S(!0),X.status==="generating")w(X.thinkingOutput??""),d({type:"loading"}),I.current?.isConnected()||Fe(X.id);else if(X.status==="awaiting_input"){if(!X.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");bi(i);const lt=JSON.parse(X.currentQuestion);d({type:"question",sessionId:X.id,question:lt}),I.current?.isConnected()||Fe(X.id)}else if(X.status==="complete"){if(!X.result)throw new Error("Interview session is complete but has no result.");bi(i);const lt=JSON.parse(X.result);x(lt),d({type:"summary",sessionId:X.id,summary:lt})}else X.status==="error"&&d({type:"error",sessionId:X.id,errorMessage:X.error??"Retry failed. Please try again."});E(!1);return}catch(X){ye=X}I.current?.close(),I.current=null,d({type:"error",sessionId:Y,errorMessage:ke(ye)||"Retry failed. Please try again."}),E(!1)}finally{F(!1)}},[Fe,i,z,u]),ce=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const Y=await Lk(u.sessionId,v||void 0,i);s(Y),bi(i),I.current?.close(),I.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),w(""),E(!1),F(!1),S(!1),$(!1),H.current=null,N(null),n()}catch(Y){h(ke(Y)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),Re=()=>u.type==="question"?Math.min(g.length+1,6):6,ge=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Me=Z?V.get(Z):null,Ge=Me&&Me.tabId!==z,Pe=!!(Ge&&!Me.stale),pt=P&&(!Ge||Me.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Y=>Y.target===Y.currentTarget&&ze(),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(vs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ge&&t.jsx("button",{className:"modal-send-to-background",onClick:_e,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ze,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),L&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Pe&&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(rs,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:R,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:Y=>c(Y.target.value),onKeyDown:Y=>{Y.key==="Enter"&&!Y.shiftKey&&l.trim()&&(Y.preventDefault(),fe())}})]}),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:P1.map((Y,le)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Y),children:Y.length>45?Y.slice(0,45)+"...":Y},le))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",$e&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Kn,{id:"mission-interview-modal-model",label:"Planning Model",value:re,onChange:Y=>{const{provider:le,modelId:ye}=T1(Y);me(le),be(ye)},models:ae,disabled:$e,favoriteProviders:et,onToggleFavorite:Ne,favoriteModels:Oe,onToggleModelFavorite:ee}),ot&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ot," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{He(!0);const Y=await ps();Ee(Y.models),st(Y.favoriteProviders),Ue(Y.favoriteModels),Je(null)}catch(Y){Je(ke(Y)||"Failed to load models")}finally{He(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${te&&oe?"model-badge-custom":"model-badge-default"}`,children:Ae(te,oe)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>fe(),disabled:!l.trim(),children:[t.jsx(vs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:A?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>C(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&A&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:A})})]})]}),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(Os,{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 je(),disabled:T,children:[T?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Pn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:T?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:ze,disabled:T,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx($1,{question:u.question,progress:Re(),historyEntries:f,onSubmit:Xe}),u.type==="summary"&&v&&t.jsx(D1,{summary:v,historyEntries:f,onSummaryChange:x,onApprove:ce,onStartOver:()=>{d({type:"initial"}),S(!1),x(null),p([]),b([]),N(null),I.current?.close(),I.current=null},isCreating:K}),P&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Bo,{size:16}),t.jsx("span",{children:pt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),pt&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function $1({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(Os,{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(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Kt,{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(Nr,{size:16,className:"icon-ml-4"})]})})]})}function D1({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((j,A)=>A))),[u,d]=a.useState(()=>{const j=new Set;return e.milestones.forEach((A,w)=>{A.slices.forEach((_,C)=>j.add(`${w}-${C}`))}),j}),m=j=>{c(A=>{const w=new Set(A);return w.has(j)?w.delete(j):w.add(j),w})},h=j=>{d(A=>{const w=new Set(A);return w.has(j)?w.delete(j):w.add(j),w})},g=(j,A)=>{const w=[...e.milestones];w[j]={...w[j],...A},s({...e,milestones:w})},p=(j,A,w)=>{const _=[...e.milestones],C=[..._[j].slices];C[A]={...C[A],...w},_[j]={..._[j],slices:C},s({...e,milestones:_})},f=(j,A,w,_)=>{const C=[...e.milestones],L=[...C[j].slices],E=[...L[A].features];E[w]={...E[w],..._},L[A]={...L[A],features:E},C[j]={...C[j],slices:L},s({...e,milestones:C})},b=j=>{const A=e.milestones.filter((w,_)=>_!==j);s({...e,milestones:A})},v=(j,A)=>{const w=[...e.milestones];w[j]={...w[j],slices:w[j].slices.filter((_,C)=>C!==A)},s({...e,milestones:w})},x=(j,A,w)=>{const _=[...e.milestones],C=[..._[j].slices];C[A]={...C[A],features:C[A].features.filter((L,E)=>E!==w)},_[j]={..._[j],slices:C},s({...e,milestones:_})},y=(j,A)=>{const w=[...e.milestones],_=[...w[j].slices];_[A]={..._[A],features:[..._[A].features,{title:"New feature",description:""}]},w[j]={...w[j],slices:_},s({...e,milestones:w})},S=e.milestones.reduce((j,A)=>j+A.slices.reduce((w,_)=>w+_.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(Os,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," 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:j=>s({...e,missionTitle:j.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:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,A)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(A),children:[l.has(A)?t.jsx(Yt,{size:16,className:"icon-text-secondary"}):t.jsx(kn,{size:16,className:"icon-text-secondary"}),t.jsx(Fi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:w=>g(A,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),b(A)},title:"Remove milestone",children:t.jsx(on,{size:14,className:"icon-text-secondary"})})]}),l.has(A)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:w=>g(A,{description:w.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:j.verification||"",onChange:w=>g(A,{verification:w.target.value})})]}),j.slices.map((w,_)=>{const C=`${A}-${_}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(C),children:[u.has(C)?t.jsx(Yt,{size:14,className:"icon-text-secondary"}):t.jsx(kn,{size:14,className:"icon-text-secondary"}),t.jsx(Mc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:L=>p(A,_,{title:L.target.value}),onClick:L=>L.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:L=>{L.stopPropagation(),v(A,_)},title:"Remove slice",children:t.jsx(on,{size:12,className:"icon-text-secondary"})})]}),u.has(C)&&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:w.verification||"",onChange:L=>p(A,_,{verification:L.target.value})})]}),w.features.map((L,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(jc,{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:L.title,onChange:T=>f(A,_,E,{title:T.target.value})}),L.description&&t.jsx("p",{className:"roadmap-feature-text",children:L.description}),L.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",L.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(A,_,E),title:"Remove feature",children:t.jsx(on,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(A,_),children:[t.jsx(ln,{size:12}),"Add Feature"]})]})]},_)})]})]},A))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ca,{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(rt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function L1({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[b,v]=a.useState([]),[x,y]=a.useState(null),[S,j]=a.useState(""),[A,w]=a.useState(!0),[_,C]=a.useState(!1),[L,E]=a.useState(!1),T=a.useRef(null),F=a.useRef(null),K=a.useRef(null),$=a.useRef(null),[R,I]=a.useState(null),H=a.useMemo(()=>Ki(),[]);Xo(e?R:null);const{activeTabMap:J,broadcastUpdate:Z,broadcastCompleted:N,broadcastLock:z,broadcastUnlock:P,broadcastHeartbeat:k}=Ma(),U=i==="milestone"?Ok:qk,V=i==="milestone"?Fk:Vk,pe=i==="milestone"?Uk:Wk,ve=i==="milestone"?Bk:Kk,se=i==="milestone"?Hk:Gk,he=i==="milestone"?"Milestone":"Slice",O=i==="milestone"?"milestone_interview":"slice_interview",ue=a.useCallback(Oe=>{F.current?.close();const Ue=pe(Oe,c,{onThinking:re=>{j(Ne=>Ne+re),Z({sessionId:Oe,status:"generating",needsInput:!1,owningTabId:H,type:O,title:o,projectId:c??null})},onQuestion:re=>{C(!1),te(),m({type:"question",sessionId:Oe,question:re}),j(""),Z({sessionId:Oe,status:"awaiting_input",needsInput:!0,owningTabId:H,type:O,title:o,projectId:c??null})},onSummary:re=>{C(!1),te(),m({type:"summary",sessionId:Oe,summary:re}),y(re),j(""),Z({sessionId:Oe,status:"complete",needsInput:!1,owningTabId:H,type:O,title:o,projectId:c??null})},onError:re=>{const Ne=re||"Session failed while contacting the AI.";C(!1),g(null),m({type:"error",sessionId:Oe,errorMessage:Ne}),j(""),K.current=Oe,Z({sessionId:Oe,status:"error",needsInput:!1,owningTabId:H,type:O,title:o,projectId:c??null}),N({sessionId:Oe,status:"error"})},onComplete:()=>{C(!1),K.current=null,N({sessionId:Oe,status:"complete"})},onConnectionStateChange:re=>{C(re==="reconnecting")}});F.current=Ue},[N,Z,pe,O,c,H,o]),te=()=>{y(null),f([]),v([]),j("")},me=a.useCallback(async()=>{g(null),te(),C(!1),m({type:"loading"});try{const{sessionId:Oe}=await U(r,c);K.current=Oe,I(Oe),ue(Oe)}catch(Oe){C(!1),g(ke(Oe)||`Failed to start ${he.toLowerCase()} interview`),m({type:"initial"}),K.current=null,I(null)}},[ue,c,U,r,he]),oe=a.useCallback(async()=>{g(null),E(!0);try{await se(r,c),s(),m({type:"applied"})}catch(Oe){g(ke(Oe)||`Failed to skip ${he.toLowerCase()} interview`),E(!1)}},[s,c,se,r,he]);a.useEffect(()=>{e&&d.type==="initial"&&T.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Oe=!1;return ui(u).then(Ue=>{if(Oe||!Ue)return;const re=xa(Ue.conversationHistory);if(v(re),I(Ue.id),f(re.map(Ne=>Ne.response).filter(Ne=>!!(Ne&&typeof Ne=="object"&&!Array.isArray(Ne)))),Ue.status==="awaiting_input"&&Ue.currentQuestion)try{const Ne=JSON.parse(Ue.currentQuestion);K.current=Ue.id,m({type:"question",sessionId:Ue.id,question:Ne})}catch{g("Failed to restore session question.")}else if(Ue.status==="complete"&&Ue.result)try{const Ne=JSON.parse(Ue.result);K.current=Ue.id,y(Ne),m({type:"summary",sessionId:Ue.id,summary:Ne})}catch{g("Failed to restore session result.")}else Ue.status==="generating"?(K.current=Ue.id,Ue.thinkingOutput&&j(Ue.thinkingOutput),m({type:"loading"}),ue(Ue.id)):Ue.status==="error"&&(K.current=Ue.id,g(null),m({type:"error",sessionId:Ue.id,errorMessage:Ue.error??"The session encountered an error."}))}).catch(()=>{Oe||g("Failed to resume session.")}),()=>{Oe=!0}},[ue,e,u,d.type]),a.useEffect(()=>{e||(C(!1),I(null))},[e]),a.useEffect(()=>{if(!(!e||!R)){if($.current!==R){$.current&&P($.current,H),z(R,H),$.current=R;return}!R&&$.current&&(P($.current,H),$.current=null)}},[z,P,e,R,H]),a.useEffect(()=>{if(!e||!R||$.current!==R)return;k(H);const Oe=setInterval(()=>{k(H)},3e4);return()=>{clearInterval(Oe)}},[k,e,R,H]),a.useEffect(()=>()=>{F.current?.close(),F.current=null,$.current&&(P($.current,H),$.current=null)},[P,H]);const be=a.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),ae=a.useCallback(async()=>{F.current?.close(),F.current=null,te(),m({type:"initial"}),g(null),K.current=null,I(null),n()},[n]),Ee=a.useCallback(async Oe=>{if(d.type!=="question")return;const{sessionId:Ue}=d;g(null),f(re=>[...re,Oe]),v(re=>[...re,{question:d.question,response:Oe}]),m({type:"loading"}),j("");try{ue(Ue),await V(Ue,Oe,c,H)}catch(re){F.current?.close(),F.current=null,g(ke(re)||"Failed to submit response"),m({type:"question",sessionId:Ue,question:d.question})}},[ue,c,V,H,d]),$e=a.useCallback(async()=>{if(d.type==="summary"){g(null),E(!0);try{await ve(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(Oe){g(ke(Oe)||"Failed to apply interview results"),E(!1)}}},[ve,x,s,c,d]),He=()=>d.type==="question"?Math.min(p.length+1,6):6,ot=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Je=R?J.get(R):null,st=!!(Je&&Je.tabId!==H&&!Je.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Oe=>Oe.target===Oe.currentTarget&&ae(),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(rs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",he,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[ot&&t.jsx("button",{className:"modal-send-to-background",onClick:be,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ae,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),st&&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(rs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",he," 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 me(),children:[t.jsx(rs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void oe(),disabled:L,children:[L?t.jsx(rt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ae,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:S?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),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(Os,{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:ae,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(z1,{question:d.question,progress:He(),historyEntries:b,onSubmit:Ee}),d.type==="summary"&&x&&t.jsx(O1,{summary:x,historyEntries:b,onSummaryChange:y,onApply:$e,onCancel:ae,isApplying:L}),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(wn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[he," 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 z1({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(Os,{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(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Kt,{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(Nr,{size:16,className:"icon-ml-4"})]})})]})}function O1({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(Os,{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(Yt,{size:16}):t.jsx(kn,{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(rt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const Ha={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)"}},Xu={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)"}},Zu={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)"}},Yr={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)"}},Qr={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)"}},Xr={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)"}},em={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)"}},F1=3;function U1(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function tm({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 nm(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const El={title:"",description:"",status:"planning",autopilotEnabled:!1},_l={title:"",description:"",status:"planning",dependencies:[]},Ml={title:"",description:"",status:"pending"},Al={title:"",description:"",acceptanceCriteria:"",status:"defined"},B1=3600*1e3;function _o(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 H1(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=B1,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 q1(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 V1(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 Rl(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 Wp=["feature_triaged","feature_completed"],Kp=["slice_activated","slice_completed","milestone_completed"],Gp=["mission_started","mission_paused","mission_resumed","mission_completed"],Jp=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function sm(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Gp.includes(e);case"tasks":return Wp.includes(e);case"slices":return Kp.includes(e);case"autopilot":return Jp.includes(e);default:return!0}}function W1(e){return e==="error"||e==="warning"?"mission-event__type--error":Gp.includes(e)?"mission-event__type--state":Wp.includes(e)?"mission-event__type--task":Kp.includes(e)?"mission-event__type--slice":Jp.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function K1(e){return e.replace(/_/g," ")}function G1(e,n){return n?e==="watching"?`Watching since ${_o(n)}`:`Last activation ${_o(n)}`:null}function J1({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,b]=a.useState(null),[v,x]=a.useState(!0),[y,S]=a.useState(!1),[j,A]=a.useState(!1),[w,_]=a.useState(null),[C,L]=a.useState(El),[E,T]=a.useState(!1),[F,K]=a.useState(new Set),[$,R]=a.useState(new Set),[I,H]=a.useState(null),[J,Z]=a.useState(_l),[N,z]=a.useState(!1),[P,k]=a.useState(null),[U,V]=a.useState(Ml),[pe,ve]=a.useState(!1),[se,he]=a.useState(null),[O,ue]=a.useState(null),[te,me]=a.useState(Al),[oe,be]=a.useState(!1),[ae,Ee]=a.useState(null),[$e,He]=a.useState(null),[ot,Je]=a.useState(""),[et,st]=a.useState(!1),[Oe,Ue]=a.useState([]),[re,Ne]=a.useState(void 0),ee=re??c,[Ae,Fe]=a.useState(null),[fe,_e]=a.useState(null),[ze,Xe]=a.useState(null);a.useEffect(()=>{h&&ee&&st(!0)},[h,ee]),a.useEffect(()=>{if(!h||ee)return;let q=!1;return ld(r).then(Se=>{if(q)return;const Te=Se.filter(gt=>gt.type==="mission_interview"&&(gt.status==="awaiting_input"||gt.status==="error"));Ue(Te)}).catch(Se=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Se)}),()=>{q=!0}},[h,r,ee]),a.useEffect(()=>{if(!h||!d)return;let q=!1;return ui(d).then(Se=>{if(!(q||!Se))try{const Te=JSON.parse(Se.inputPayload||"{}");Te.targetId&&Te.targetType&&Fe({type:Te.targetType,id:Te.targetId,title:Te.targetTitle||Se.title,resumeSessionId:d})}catch{Fe({type:"milestone",id:"",title:Se.title,resumeSessionId:d})}}).catch(Se=>{q||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Se),m?.())}),()=>{q=!0}},[h,d,m]);const[je,ce]=a.useState(null),[Re,ge]=a.useState(new Map),[Me,Ge]=a.useState(null),[Pe,pt]=a.useState({title:"",assertion:"",status:"pending"}),[Y,le]=a.useState(!1),[ye,nt]=a.useState(null),[X,Qe]=a.useState(new Map),[lt,ft]=a.useState(new Set),[Mt,yt]=a.useState(new Set),[ht,St]=a.useState(null),[zt,It]=a.useState(new Map),[Rt,$t]=a.useState(null),[Ot,Vt]=a.useState(null),[Dt,Ft]=a.useState(!0),[Ct,Nt]=a.useState(new Set),[Tt,Zt]=a.useState(new Map),[Ut,B]=a.useState(null),[xe,Ie]=a.useState(new Map),[M,ne]=a.useState(null),[Le,ut]=a.useState(new Map),[bt,Pt]=a.useState(new Map),[At,nn]=a.useState("structure"),[zn,hn]=a.useState([]),en=a.useRef([]),On=a.useRef([]),we=a.useRef(null),it=a.useRef(null),un=a.useRef("structure"),Nn=a.useRef("all"),[Tn,Ce]=a.useState(!1),[Ye,dt]=a.useState(0),[vt,Qt]=a.useState("all"),[bn,Jt]=a.useState(new Set),Xt=a.useRef(null),_n=a.useRef(null);On.current=g,we.current=f,it.current=Rt,un.current=At,Nn.current=vt;const sn=a.useCallback((q="auto")=>{const Se=_n.current;if(Se&&typeof Se.scrollIntoView=="function"){Se.scrollIntoView({block:"end",behavior:q});return}const Te=Xt.current;Te&&(Te.scrollTop=Te.scrollHeight)},[]),ls=a.useCallback(()=>{const q=Xt.current;return q?q.scrollHeight-q.scrollTop-q.clientHeight<=100:!0},[]),cs=a.useCallback(async q=>{if(q.length===0){Pt(new Map);return}const Se=await ok(r);Pt(Te=>{const gt=new Map(Te);for(const[vn,Ht]of Object.entries(Se))q1(Ht)&&gt.set(vn,Ht);return gt})},[r]),cn=a.useCallback(async()=>{try{x(!0);const q=await nk(r);p(q),cs(q)}catch(q){i(ke(q)||"Failed to load missions","error")}finally{x(!1)}},[i,r,cs]),kt=a.useCallback(async q=>{try{S(!0);const Se=await kp(q,r);if(b(Se),Se.milestones.length>0){const Te=Se.milestones[0].id;$t(Te),Ft(!0),K(new Set([Te])),fl(Te,r).then(gt=>{ge(vn=>{const Ht=new Map(vn);return Ht.set(Te,gt),Ht})}).catch(()=>{}),gl(Te,r).then(gt=>{It(vn=>{const Ht=new Map(vn);return Ht.set(Te,gt),Ht})}).catch(()=>{}),Se.milestones[0].slices.length>0&&R(new Set([Se.milestones[0].slices[0].id]))}else $t(null),Vt(null)}catch(Se){i(ke(Se)||"Failed to load mission details","error")}finally{S(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Rt){Vt(null);return}let q=!1;return Vt(null),cu(Rt,r).then(Se=>{if(!q){if(!Rl(Se)){Vt(null);return}Vt(Se),It(Te=>{const gt=new Map(Te);return gt.set(Rt,Se.rollup),gt})}}).catch(()=>{q||Vt(null)}),()=>{q=!0}},[h,Rt,r]),a.useEffect(()=>{Ft(!0)},[Rt]);const G=a.useCallback(q=>{!q||q!==it.current||cu(q,r).then(Se=>{it.current!==q||!Rl(Se)||(Vt(Se),It(Te=>{const gt=new Map(Te);return gt.set(q,Se.rollup),gt}))}).catch(()=>{})},[r]),De=a.useCallback(async(q,Se)=>{const Te=Se?.append??!1,gt=Te?en.current.length:0;Te||(Ce(!0),Jt(new Set));try{const vn=await rk(q,{limit:50,offset:gt,eventType:void 0},r),Ht=vn.events.filter(rn=>sm(rn.eventType,vt));hn(rn=>{if(!Te)return Ht;const We=new Set(rn.map(xt=>xt.id)),Ke=[...rn];for(const xt of Ht)We.has(xt.id)||Ke.push(xt);return Ke}),dt(vn.total),Te||requestAnimationFrame(()=>{sn("auto")})}catch(vn){i(ke(vn)||"Failed to load mission activity","error")}finally{Te||Ce(!1)}},[i,vt,r,sn]);a.useEffect(()=>{en.current=zn},[zn]),a.useEffect(()=>{h&&(cn(),b(null),$t(null),Vt(null),hn([]),dt(0),nn("structure"),Qt("all"),Jt(new Set))},[h,cn]);const tt=a.useRef(null);a.useEffect(()=>{h&&u&&tt.current!==u&&g.length>0&&(tt.current=u,kt(u))},[h,u,g,kt]),a.useEffect(()=>{h||(tt.current=null)},[h]),a.useEffect(()=>{!h||!f||At!=="activity"||De(f.id)},[At,h,De,f,vt]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const q=new URLSearchParams;r&&q.set("projectId",r);const Se=`/api/events${q.size>0?`?${q.toString()}`:""}`,Te=()=>{cs(On.current)},gt=es=>{Te();const En=es;if(En.data)try{const Wt=JSON.parse(En.data);Wt?.id&&p(Ai=>Ai.map(Ps=>Ps.id===Wt.id?{...Ps,...Wt}:Ps))}catch{}we.current&&kt(we.current.id)},vn=es=>{Te(),we.current&&kt(we.current.id)},Ht=()=>{Te(),we.current&&kt(we.current.id)},rn=es=>{Te(),we.current&&kt(we.current.id)},We=es=>{const En=es;if(En.data)try{const Wt=JSON.parse(En.data);Wt&&Wt.featureId&&(Hs(Wt.featureId),Un(Wt.featureId),Wt.milestoneId&&G(Wt.milestoneId))}catch{}},Ke=es=>{const En=es;if(En.data)try{const Wt=JSON.parse(En.data);Wt&&Wt.featureId&&(Hs(Wt.featureId),Un(Wt.featureId),Wt.milestoneId&&G(Wt.milestoneId),we.current&&kt(we.current.id))}catch{}},xt=es=>{const En=es;if(En.data)try{const Wt=JSON.parse(En.data);Wt&&Wt.milestoneId&&(Rn(Wt.milestoneId),G(Wt.milestoneId))}catch{}},yn=es=>{const En=es;if(En.data)try{const Wt=JSON.parse(En.data);Wt&&Wt.milestoneId&&(An(Wt.milestoneId),Rn(Wt.milestoneId),G(Wt.milestoneId))}catch{}};return Qs(Se,{events:{"mission:updated":gt,"slice:updated":vn,"feature:updated":Ht,"milestone:updated":rn,"mission:event":es=>{Te();const En=we.current;if(!En||un.current!=="activity")return;const Wt=ls(),Ai=es;if(Ai.data)try{const Ps=JSON.parse(Ai.data);if(!V1(Ps)||Ps.missionId!==En.id||!sm(Ps.eventType,Nn.current))return;hn(ci=>{const dl=ci.filter(ul=>ul.id!==Ps.id);return[Ps,...dl].slice(0,100)}),dt(ci=>ci+1),Wt&&requestAnimationFrame(()=>{const ci=Xt.current;ci&&(ci.scrollTop=0)})}catch{}},"validator-run:started":We,"validator-run:completed":Ke,"milestone:validation:updated":xt,"assertion:created":yn,"assertion:updated":yn,"assertion:deleted":yn,"assertion:linked":yn,"assertion:unlinked":yn,"fix-feature:created":es=>{const En=es;if(En.data)try{const Wt=JSON.parse(En.data);if(Wt&&Wt.sourceFeatureId){Hs(Wt.sourceFeatureId);const Ai=Wt?.feature?.sliceId,Ps=we.current;if(Ai&&Ps){const ci=Ps.milestones.find(dl=>dl.slices.some(ul=>ul.id===Ai));ci&&G(ci.id)}we.current&&kt(we.current.id)}}catch{}}}})},[h,ls,kt,cs,r,G]);const at=a.useCallback(()=>{A(!0),_(null),L(El)},[]),wt=a.useCallback(q=>{_(q.id),A(!1),L({title:q.title,description:q.description||"",status:q.status,autopilotEnabled:q.autopilotEnabled??!1})},[]),_t=a.useCallback(()=>{_(null),A(!1),L(El)},[]),Lt=a.useCallback(async()=>{if(!C.title.trim()){i("Mission title is required","error");return}try{if(T(!0),j)await sk({title:C.title.trim(),description:C.description.trim()||void 0,autopilotEnabled:C.autopilotEnabled},r),i("Mission created","success");else if(w){const q={title:C.title.trim(),description:C.description.trim()||void 0,status:C.status,autopilotEnabled:C.autopilotEnabled};C.autopilotEnabled&&(q.autoAdvance=!0),await ik(w,q,r),i("Mission updated","success"),f?.id===w&&await kt(w)}await cn(),_t()}catch(q){i(ke(q)||"Failed to save mission","error")}finally{T(!1)}},[C,j,w,i,cn,kt,f,_t,r]),Jn=a.useCallback(async q=>{try{await ak(q,r),i("Mission deleted","success"),f?.id===q&&b(null),await cn(),ce(null)}catch(Se){i(ke(Se)||"Failed to delete mission","error")}},[i,cn,f,r]),Fs=a.useCallback(()=>{z(!0),H(null),Z(_l)},[]),li=a.useCallback(q=>{H(q.id),z(!1),Z({title:q.title,description:q.description||"",status:q.status,dependencies:q.dependencies})},[]),_s=a.useCallback(()=>{H(null),z(!1),Z(_l)},[]),Us=a.useCallback(async()=>{if(!J.title.trim()){i("Milestone title is required","error");return}try{T(!0),N&&f?(await lk(f.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),i("Milestone created","success")):I&&(await ck(I,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status,dependencies:J.dependencies},r),i("Milestone updated","success")),await kt(f.id),_s()}catch(q){i(ke(q)||"Failed to save milestone","error")}finally{T(!1)}},[J,N,I,f,i,kt,_s,C.title,r]),ie=a.useCallback(async q=>{try{await dk(q,r),i("Milestone deleted","success"),await kt(f.id),ce(null)}catch(Se){i(ke(Se)||"Failed to delete milestone","error")}},[i,kt,f,r]),de=a.useCallback(q=>{$t(q),Ft(!0),K(Se=>{const Te=new Set(Se);return!Te.has(q)?(Te.add(q),fl(q,r).then(vn=>{ge(Ht=>{const rn=new Map(Ht);return rn.set(q,vn),rn})}).catch(()=>{}),gl(q,r).then(vn=>{It(Ht=>{const rn=new Map(Ht);return rn.set(q,vn),rn})}).catch(()=>{})):Te.delete(q),Te})},[r]),qe=a.useCallback(q=>{he(q),ve(!0),k(null),V(Ml)},[]),mt=a.useCallback(q=>{k(q.id),ve(!1),V({title:q.title,description:q.description||"",status:q.status})},[]),jt=a.useCallback(()=>{k(null),ve(!1),he(null),V(Ml)},[]),pn=a.useCallback(async()=>{if(!U.title.trim()){i("Slice title is required","error");return}try{T(!0),pe&&se?(await uk(se,{title:U.title.trim(),description:U.description.trim()||void 0},r),i("Slice created","success")):P&&(await mk(P,{title:U.title.trim(),description:U.description.trim()||void 0,status:U.status},r),i("Slice updated","success")),await kt(f.id),jt()}catch(q){i(ke(q)||"Failed to save slice","error")}finally{T(!1)}},[U,pe,P,se,f,i,kt,jt,r]),mn=a.useCallback(async q=>{try{await hk(q,r),i("Slice deleted","success"),await kt(f.id),ce(null)}catch(Se){i(ke(Se)||"Failed to delete slice","error")}},[i,kt,f,r]),an=a.useCallback(async q=>{try{await pk(q,r),i("Slice activated","success"),await kt(f.id)}catch(Se){i(ke(Se)||"Failed to activate slice","error")}},[i,kt,f,r]),xn=a.useCallback(q=>{R(Se=>{const Te=new Set(Se);return Te.has(q)?Te.delete(q):Te.add(q),Te})},[]),Fn=a.useCallback(q=>{Ee(q),be(!0),ue(null),me(Al)},[]),Yn=a.useCallback(q=>{ue(q.id),be(!1),me({title:q.title,description:q.description||"",acceptanceCriteria:q.acceptanceCriteria||"",status:q.status})},[]),Qn=a.useCallback(()=>{ue(null),be(!1),Ee(null),me(Al)},[]),In=a.useCallback(async()=>{if(!te.title.trim()){i("Feature title is required","error");return}try{T(!0),oe&&ae?(await fk(ae,{title:te.title.trim(),description:te.description.trim()||void 0,acceptanceCriteria:te.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):O&&(await gk(O,{title:te.title.trim(),description:te.description.trim()||void 0,acceptanceCriteria:te.acceptanceCriteria.trim()||void 0,status:te.status},r),i("Feature updated","success")),await kt(f.id),Qn()}catch(q){i(ke(q)||"Failed to save feature","error")}finally{T(!1)}},[te,oe,O,ae,f,i,kt,Qn,r]),Xn=a.useCallback(async q=>{try{await bk(q,r),i("Feature deleted","success"),await kt(f.id),ce(null)}catch(Se){i(ke(Se)||"Failed to delete feature","error")}},[i,kt,f,r]),Hn=a.useCallback(async()=>{if(!$e||!ot.trim()){i("Task ID is required","error");return}try{await xk($e,ot.trim(),r),i("Feature linked to task","success"),await kt(f.id),He(null),Je("")}catch(q){i(ke(q)||"Failed to link feature to task","error")}},[$e,ot,i,kt,f,r]),gs=a.useCallback(async q=>{try{await vk(q,r),i("Feature unlinked from task","success"),await kt(f.id)}catch(Se){i(ke(Se)||"Failed to unlink feature","error")}},[i,kt,f,r]),Mn=a.useCallback(async q=>{try{T(!0),await yk(q,void 0,void 0,r),i("Feature triaged — task created","success"),await kt(f.id)}catch(Se){i(ke(Se)||"Failed to triage feature","error")}finally{T(!1)}},[i,kt,f,r]),qn=a.useCallback(async q=>{Xe(q);try{const Se=await Jk(q,r);_e({featureId:q,enrichedDescription:Se.description})}catch{await Mn(q)}finally{Xe(null)}},[Mn,r]),ns=a.useCallback(async()=>{fe&&(_e(null),await Mn(fe.featureId))},[Mn,fe]),Ms=a.useCallback(()=>{_e(null)},[]),ds=a.useCallback(async q=>{try{T(!0);const Se=await jk(q,r);i(`Triaged ${Se.count} feature${Se.count!==1?"s":""}`,"success"),await kt(f.id)}catch(Se){i(ke(Se)||"Failed to triage slice features","error")}finally{T(!1)}},[i,kt,f,r]),An=a.useCallback(async q=>{try{const Se=await fl(q,r);ge(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch{}},[r]),Rn=a.useCallback(async q=>{try{const Se=await gl(q,r);It(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch{}},[r]),js=a.useCallback(async q=>{if(!Pe.title.trim()||!Pe.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await kk(q,{title:Pe.title.trim(),assertion:Pe.assertion.trim(),status:Pe.status},r),i("Assertion created","success"),await An(q),await Rn(q),le(!1),pt({title:"",assertion:"",status:"pending"})}catch(Se){i(ke(Se)||"Failed to create assertion","error")}finally{T(!1)}},[Pe,i,An,Rn,r]),Ta=a.useCallback(q=>{Ge(q.id),pt({title:q.title,assertion:q.assertion,status:q.status})},[]),Ji=a.useCallback(()=>{Ge(null),le(!1),pt({title:"",assertion:"",status:"pending"})},[]),Lr=a.useCallback(async(q,Se)=>{if(!Pe.title.trim()||!Pe.assertion.trim()){i("Title and assertion text are required","error");return}try{T(!0),await wk(q,{title:Pe.title.trim(),assertion:Pe.assertion.trim(),status:Pe.status},r),i("Assertion updated","success"),await An(Se),await Rn(Se),Ji()}catch(Te){i(ke(Te)||"Failed to update assertion","error")}finally{T(!1)}},[Pe,i,An,Rn,Ji,r]),Bs=a.useCallback(async q=>{try{const Se=await Ck(q,r);Qe(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch{}},[r]),Pa=a.useCallback(async q=>{const Se=ye!==q;nt(Te=>Te===q?null:q),Se&&await Bs(q)},[ye,Bs]),zr=a.useCallback(q=>{nt(q),Bs(q),requestAnimationFrame(()=>{const Se=document.querySelector(`[data-mission-assertion-id="${q}"]`);Se instanceof HTMLElement&&typeof Se.scrollIntoView=="function"&&Se.scrollIntoView({behavior:"smooth",block:"center"})})},[Bs]),il=a.useCallback(async(q,Se)=>{try{ft(Te=>new Set(Te).add(Se)),await Nk(q,Se,r),i("Feature linked to assertion","success"),await Bs(Se),St(null)}catch(Te){i(ke(Te)||"Failed to link feature","error")}finally{ft(Te=>{const gt=new Set(Te);return gt.delete(Se),gt})}},[i,Bs,r]),Or=a.useCallback(async(q,Se)=>{const Te=`${q}-${Se}`;try{yt(gt=>new Set(gt).add(Te)),await Sk(q,Se,r),i("Feature unlinked from assertion","success"),await Bs(Se)}catch(gt){i(ke(gt)||"Failed to unlink feature","error")}finally{yt(gt=>{const vn=new Set(gt);return vn.delete(Te),vn})}},[i,Bs,r]),Zn=a.useCallback(async q=>{try{Nt(Te=>new Set(Te).add(q)),await Ek(q,r),i("Validation triggered","success");const Se=await du(q,r);Zt(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch(Se){i(ke(Se)||"Failed to trigger validation","error")}finally{Nt(Se=>{const Te=new Set(Se);return Te.delete(q),Te})}},[i,r]),Hs=a.useCallback(async q=>{try{const Se=await du(q,r);Zt(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch{}},[r]),Un=a.useCallback(async q=>{try{const Se=await _k(q,{limit:10},r);Ie(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch{}},[r]),Ei=a.useCallback(q=>{const Se=we.current;if(Se){for(const Te of Se.milestones)for(const gt of Te.slices)if(gt.features.find(Ht=>Ht.id===q)){K(Ht=>{const rn=new Set(Ht);return rn.add(Te.id),rn}),R(Ht=>{const rn=new Set(Ht);return rn.add(gt.id),rn}),B(q),$t(Te.id),Hs(q),Un(q),requestAnimationFrame(()=>{const Ht=document.querySelector(`[data-mission-feature-id="${q}"]`);Ht instanceof HTMLElement&&typeof Ht.scrollIntoView=="function"&&Ht.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Hs,Un]),Ia=a.useCallback(async q=>{try{const Se=await Mk(q,r);ut(Te=>{const gt=new Map(Te);return gt.set(q,Se),gt})}catch{}},[r]),Fr=a.useCallback(async q=>{Ut===q?B(null):(B(q),await Hs(q),await Un(q))},[Ut,Hs,Un]),Yi=a.useCallback(async q=>{M===q?ne(null):(ne(q),await Ia(q))},[M,Ia]),Ur=a.useCallback(async q=>{try{await Ak(q,r),i("Mission resumed","success"),await kt(q),cn()}catch(Se){i(ke(Se)||"Failed to resume mission","error")}},[i,kt,cn,r]),$a=a.useCallback(async q=>{try{const Te=(await Rk(q,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Te} task${Te!==1?"s":""} paused)`,"success"),await kt(q),cn()}catch(Se){i(ke(Se)||"Failed to stop mission","error")}},[i,kt,cn,r]),Q=a.useCallback(async q=>{try{await Tk(q,r),i("Mission started — first slice activated","success"),await kt(q),cn()}catch(Se){i(ke(Se)||"Failed to start mission","error")}},[i,kt,cn,r]),Ve=a.useCallback(async(q,Se)=>{try{await Pk(q,{enabled:Se},r),i(Se?"Autopilot enabled":"Autopilot disabled","success"),await kt(q),cn()}catch(Te){i(ke(Te)||"Failed to update autopilot","error")}},[i,kt,cn,r]),ct=a.useCallback(q=>{nn("structure"),$t(null),Vt(null),hn([]),dt(0),Qt("all"),Jt(new Set),kt(q.id)},[kt]),Bt=a.useCallback(()=>{b(null),$t(null),Vt(null),nn("structure"),hn([]),dt(0),Qt("all"),Jt(new Set),cn()},[cn]),As=zn.length<Ye,ss=f?.autopilotState??"inactive",Br=ss==="watching"||ss==="activating",Da=G1(ss,f?.lastAutopilotActivityAt),Qi=a.useMemo(()=>!Ot||!Rt||!Rl(Ot)?null:Ot.rollup.milestoneId===Rt?Ot:null,[Rt,Ot]),al=a.useMemo(()=>{const q=new Map;for(const Se of Qi?.validationTelemetry.validationRounds??[]){const Te=q.get(Se.featureId);(!Te||Se.startedAt>Te.startedAt)&&q.set(Se.featureId,Se)}return q},[Qi]),rl=a.useCallback(()=>{!f||Tn||!As||De(f.id,{append:!0})},[Tn,As,De,f]),ol=a.useCallback(q=>{Jt(Se=>{const Te=new Set(Se);return Te.has(q)?Te.delete(q):Te.add(q),Te})},[]),La=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),Lt())},[Lt]),Xi=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),Us())},[Us]),Zi=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),pn())},[pn]),_i=a.useCallback(q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),In())},[In]),za=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const q=Se=>{Se.key==="Escape"&&s()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[h,s]),!h)return null;const ll=t.jsxs("div",{ref:za,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:Bt,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(zo,{size:18})}):null,t.jsx(vs,{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(Kt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(rt,{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:[Br&&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:(Ha[f.status]||Ha.planning).bg,color:(Ha[f.status]||Ha.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:q=>Ve(f.id,q.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:(Qr[ss]||Qr.inactive).bg,color:(Qr[ss]||Qr.inactive).text},"data-testid":"autopilot-state-badge",children:[Br&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),ss]})]}),Da&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Da})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>$a(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(ws,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ur(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Cn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Q(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>wt(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(on,{size:14})})]})]}),w===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:q=>L({...C,title:q.target.value}),onKeyDown:La,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:q=>L({...C,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:q=>L({...C,status:q.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:C.autopilotEnabled,onChange:q=>L({...C,autopilotEnabled:q.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:Lt,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_t,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${At==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>nn("structure"),role:"tab","aria-selected":At==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${At==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>nn("activity"),role:"tab","aria-selected":At==="activity","data-testid":"mission-tab-activity",children:["Activity (",Ye,")"]})]}),At==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(q=>{const Se=Qi?.rollup.milestoneId===q.id?Qi:null,Te=Se?.rollup??zt.get(q.id),gt=Se?.validationTelemetry.validationRounds??[],vn=Se?.fixFeatures??[],Ht=em[Te?.state??"not_started"]??em.not_started,rn=Te&&(Te.state==="blocked"||Te.state==="failed")?Se?.validationTelemetry.validationRounds.find(We=>We.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>de(q.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:F.has(q.id)?t.jsx(Yt,{size:16}):t.jsx(kn,{size:16})}),t.jsx(Fi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:q.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Xu[q.status].bg,color:Xu[q.status].text},children:q.status}),t.jsxs("span",{className:"mission-milestone__count",children:[q.slices.length," slices"]}),t.jsx(tm,{state:U1(q.interviewState)}),Te&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ht.bg,color:Ht.text},title:"Validation state",children:nm(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)"}})})]}),q.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fe({type:"milestone",id:q.id,title:q.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Oi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:We=>We.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(q.id),title:"Add slice",children:t.jsx(ln,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>li(q),title:"Edit milestone",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"milestone",id:q.id}),title:"Delete milestone",children:t.jsx(on,{size:14})})]})]}),F.has(q.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(N||I===q.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:We=>Z({...J,title:We.target.value}),onKeyDown:Xi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:We=>Z({...J,description:We.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Us,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),I?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_s,children:"Cancel"})]})]}),Se&&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:[Se.validationTelemetry.totalRuns," rounds",Se.validationTelemetry.lastValidatorStatus?` · Last ${Se.validationTelemetry.lastValidatorStatus}`:""]})]}),rn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",rn]}),gt.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:()=>Ft(We=>!We),title:Dt?"Hide validation rounds":"Show validation rounds",children:[Dt?t.jsx(Yt,{size:12}):t.jsx(kn,{size:12}),"Validation rounds (",gt.length,")"]}),Dt&&t.jsx("div",{className:"mission-validation-rounds__list",children:gt.map(We=>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--${We.validatorStatus}`,children:We.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:We.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",We.implementationAttempt," · reviewer #",We.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),We.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:We.failedAssertionIds.map(Ke=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>zr(Ke),title:`Jump to assertion ${Ke}`,children:Ke},`${We.roundId}-${Ke}`))}):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:"}),We.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:We.generatedFixFeatureIds.map(Ke=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ei(Ke),title:`Jump to fix feature ${Ke}`,children:Ke},`${We.roundId}-${Ke}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),We.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:We.blockedReason})]},We.roundId))})]}),vn.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:vn.map(We=>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:()=>Ei(We.id),title:`Jump to feature ${We.id}`,children:We.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yr[We.status].bg,color:Yr[We.status].text},children:We.status}),We.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${We.loopState}`,children:We.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:()=>Ei(We.sourceFeatureId),title:`Jump to source feature ${We.sourceFeatureId}`,children:We.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:We.runId})]}),We.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:We.failedAssertionIds.map(Ke=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>zr(Ke),title:`Jump to assertion ${Ke}`,children:Ke},`${We.id}-${Ke}`))})]})]},We.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[q.slices.map(We=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>xn(We.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(We.id)?t.jsx(Yt,{size:16}):t.jsx(kn,{size:16})}),t.jsx(Mc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:We.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Zu[We.status].bg,color:Zu[We.status].text},children:We.status}),t.jsxs("span",{className:"mission-slice__count",children:[We.features?.length||0," features"]}),t.jsx(tm,{state:We.planState??"not_started"}),We.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fe({type:"slice",id:We.id,title:We.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Oi,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Ke=>Ke.stopPropagation(),children:[We.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>an(We.id),title:"Activate slice",children:t.jsx(Cn,{size:14})}),We.status==="active"&&We.features?.some(Ke=>Ke.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ds(We.id),title:"Triage all features",disabled:E,children:E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Vn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fn(We.id),title:"Add feature",children:t.jsx(ln,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>mt(We),title:"Edit slice",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"slice",id:We.id}),title:"Delete slice",children:t.jsx(on,{size:14})})]})]}),$.has(We.id)&&t.jsxs("div",{className:"mission-slice__body",children:[pe&&se===q.id&&!P&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:Ke=>V({...U,title:Ke.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:Ke=>V({...U,description:Ke.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:pn,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:jt,children:"Cancel"})]})]}),P===We.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:Ke=>V({...U,title:Ke.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:Ke=>V({...U,description:Ke.target.value}),rows:2}),t.jsxs("select",{value:U.status,onChange:Ke=>V({...U,status:Ke.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:pn,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:jt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[We.features?.map(Ke=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":Ke.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Fr(Ke.id),title:Ut===Ke.id?"Collapse details":"Expand to show run history",children:Ut===Ke.id?t.jsx(Yt,{size:14}):t.jsx(kn,{size:14})}),t.jsx(jc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:Ke.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Yr[Ke.status].bg,color:Yr[Ke.status].text},children:Ke.status}),Ke.loopState&&Ke.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${Ke.loopState}`,title:`Loop state: ${Ke.loopState}`,children:[Ke.loopState==="implementing"&&"⏳",Ke.loopState==="validating"&&"🔄",Ke.loopState==="needs_fix"&&"🔧",Ke.loopState==="passed"&&"✅",Ke.loopState==="blocked"&&"🚫"]}),Ke.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ei(Ke.generatedFromFeatureId),title:`Generated from feature: ${Ke.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ke.loopState==="validating"||Ke.loopState==="needs_fix")&&(()=>{const xt=Tt.get(Ke.id),yn=al.get(Ke.id),Ts=xt?.implementationAttemptCount??yn?.implementationAttempt??Ke.implementationAttemptCount??0,Mi=xt?.retryBudgetRemaining??Math.max(0,F1-Ts);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Ts," · ",Mi," ",Mi===1?"retry":"retries"," left"]})})(),Ke.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Zn(Ke.id),title:"Validate feature",disabled:Ct.has(Ke.id),children:Ct.has(Ke.id)?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(rs,{size:14})}),Ke.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(Ke.taskId),title:"Click to view task",children:Ke.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[Ke.status==="defined"&&!Ke.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>qn(Ke.id),title:"Triage — create task",disabled:E||ze===Ke.id,children:ze===Ke.id?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Vn,{size:14})}),Ke.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>gs(Ke.id),title:"Unlink task",children:t.jsx(Ud,{size:14})}):Ke.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>He(Ke.id),title:"Link to task",children:t.jsx(pa,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Yn(Ke),title:"Edit feature",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"feature",id:Ke.id}),title:"Delete feature",children:t.jsx(on,{size:14})})]})]}),Ke.description&&t.jsx("p",{className:"mission-feature__description",children:Ke.description}),Ke.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",Ke.acceptanceCriteria]}),fe?.featureId===Ke.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:fe.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:ns,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ms,disabled:E,children:"Cancel"})]})]}),O===Ke.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:te.title,onChange:xt=>me({...te,title:xt.target.value}),onKeyDown:_i,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:te.description,onChange:xt=>me({...te,description:xt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:te.acceptanceCriteria,onChange:xt=>me({...te,acceptanceCriteria:xt.target.value}),rows:2}),t.jsxs("select",{value:te.status,onChange:xt=>me({...te,status:xt.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:In,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),Ut===Ke.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"})}),(xe.get(Ke.id)??[]).map(xt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Yi(xt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${xt.status}`,title:xt.status,children:xt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(xt.startedAt).toLocaleString()}),xt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(xt.completedAt).getTime()-new Date(xt.startedAt).getTime())/1e3),"s"]}),xt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:xt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:M===xt.id?"Hide details":"Show details",children:M===xt.id?t.jsx(Yt,{size:12}):t.jsx(kn,{size:12})})]}),M===xt.id&&Le.get(xt.id)&&t.jsxs("div",{className:"mission-run__details",children:[xt.summary&&t.jsx("p",{className:"mission-run__summary",children:xt.summary}),xt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",xt.blockedReason]}),Le.get(xt.id)?.failures&&Le.get(xt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Le.get(xt.id).failures.map(yn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:yn.message}),yn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",yn.expected]}),yn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",yn.actual]})]},yn.id))]}),(!Le.get(xt.id)?.failures||Le.get(xt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},xt.id)),(!xe.get(Ke.id)||xe.get(Ke.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ke.id)),oe&&ae===We.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:te.title,onChange:Ke=>me({...te,title:Ke.target.value}),onKeyDown:_i,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:te.description,onChange:Ke=>me({...te,description:Ke.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:te.acceptanceCriteria,onChange:Ke=>me({...te,acceptanceCriteria:Ke.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:In,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Qn,children:"Cancel"})]})]}),!oe&&(!We.features||We.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(jc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},We.id)),q.slices.length===0&&!pe&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Mc,{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:Ht.bg,color:Ht.text},children:nm(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:()=>{le(!0),Ge(null),pt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(ln,{size:14})})]}),Y&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Pe.title,onChange:We=>pt({...Pe,title:We.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Pe.assertion,onChange:We=>pt({...Pe,assertion:We.target.value}),rows:2}),t.jsxs("select",{value:Pe.status,onChange:We=>pt({...Pe,status:We.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:()=>js(q.id),disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ji,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Re.get(q.id))?Re.get(q.id):[]).map(We=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":We.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Me===We.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Pe.title,onChange:Ke=>pt({...Pe,title:Ke.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Pe.assertion,onChange:Ke=>pt({...Pe,assertion:Ke.target.value}),rows:2}),t.jsxs("select",{value:Pe.status,onChange:Ke=>pt({...Pe,status:Ke.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:()=>Lr(We.id,q.id),disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ji,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Xr[We.status]??Xr.pending).bg,color:(Xr[We.status]??Xr.pending).text},children:We.status}),t.jsx("span",{className:"mission-assertion__title",children:We.title}),(()=>{const xt=X.get(We.id)?.length??0;return xt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${xt} linked feature${xt!==1?"s":""}`,children:["(",xt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Pa(We.id),title:"Toggle details",children:ye===We.id?t.jsx(Yt,{size:14}):t.jsx(kn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ta(We),title:"Edit assertion",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"assertion",id:We.id}),title:"Delete assertion",children:t.jsx(on,{size:14})})]})}),ye===We.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:We.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()=>{ye!==We.id&&await Pa(We.id),St(ht===We.id?null:We.id)},title:"Link a feature",children:[t.jsx(pa,{size:12}),"Link Feature"]})]}),ht===We.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ke=new Set((X.get(We.id)??[]).map(yn=>yn.id)),xt=[];return f?.milestones.forEach(yn=>yn.slices.forEach(Ts=>xt.push(...Ts.features.filter(Mi=>!Ke.has(Mi.id))))),xt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):xt.map(yn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>il(yn.id,We.id),disabled:lt.has(We.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:yn.title}),lt.has(We.id)&&t.jsx(rt,{size:12,className:"spinner"})]},yn.id))})()})}),(()=>{const Ke=X.get(We.id)??[];return Ke.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ke.map(xt=>{const yn=`${xt.id}-${We.id}`,Ts=Mt.has(yn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:xt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Or(xt.id,We.id),disabled:Ts,title:"Unlink feature",children:Ts?t.jsx(rt,{size:12,className:"spinner"}):t.jsx(Ud,{size:12})})]},xt.id)})})()]})]})]},We.id)),(!Re.get(q.id)||Re.get(q.id)?.length===0)&&!Y&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},q.id)}),f&&!N&&I===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Fs,children:[t.jsx(ln,{size:16}),"Add Milestone"]}),N&&I===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:q=>Z({...J,title:q.target.value}),onKeyDown:Xi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:q=>Z({...J,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Us,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_s,children:"Cancel"})]})]}),f.milestones.length===0&&!N&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Fi,{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:vt,onChange:q=>Qt(q.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:[zn.length," of ",Ye]})]}),!Tn&&As&&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:rl,"data-testid":"mission-activity-load-more",children:"Load more"})}),Tn?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(rt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):zn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(zs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Xt,className:"mission-events","data-testid":"mission-activity-events",children:[zn.map(q=>{const Se=!!(q.metadata&&Object.keys(q.metadata).length>0),Te=bn.has(q.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${W1(q.eventType)}`,children:K1(q.eventType)}),t.jsx("span",{className:"mission-event__time",children:_o(q.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:q.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(q.timestamp).toLocaleString()}),Se&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>ol(q.id),"data-testid":`mission-event-metadata-${q.id}`,children:[Te?"Hide":"Show"," metadata"]}),Te&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(q.metadata,null,2)})]})]},q.id)}),t.jsx("div",{ref:_n})]})]})]}):t.jsxs("div",{className:"mission-list",children:[j&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:q=>L({...C,title:q.target.value}),onKeyDown:La,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:q=>L({...C,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Lt,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_t,children:"Cancel"})]})]}),g.map(q=>{const Se=q,Te=f,gt=Te&&Te.id===Se.id,vn=Ha[Se.status]||{bg:"",text:""},Ht=Se.summary,rn=bt.get(Se.id),We=H1(rn),Ke=!!(Ht&&(Ht.totalMilestones>0||Ht.totalFeatures>0)),xt=rn?.totalTasks??0,yn=rn?.tasksCompleted??0,Ts=rn?.tasksFailed??0,Mi=rn?.estimatedCompletionPercent??Ht?.progressPercent??0,es=Ke||xt>0||Ts>0||!!rn?.lastActivityAt,En=Se.status==="active"&&(rn?.currentMilestoneId||rn?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${gt?"mission-list__item--selected":""}`,onClick:()=>ct(q),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(vs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Se.title}),q.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--${We}`,"data-testid":`mission-health-badge-${Se.id}`,"aria-label":`Mission health: ${We}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:vn.bg,color:vn.text},children:Se.status})]}),Se.description&&t.jsx("p",{className:"mission-list__item-description",children:Se.description}),En&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",En]}),es&&t.jsxs("div",{className:"mission-list__item-summary",children:[Ke&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Ht.completedMilestones,"/",Ht.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Ht.completedFeatures,"/",Ht.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Se.id}`,children:[yn,"/",xt," tasks"]}),Ts>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Wt=>{Wt.stopPropagation(),ct(q)},"data-testid":`mission-failed-${Se.id}`,title:"View mission failures",children:[Ts," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Se.id}`,children:["Activity ",_o(rn?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${We}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Mi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Wt=>Wt.stopPropagation(),children:[Se.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>$a(Se.id),title:"Stop mission",children:t.jsx(ws,{size:14})}),Se.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ur(Se.id),title:"Resume mission",children:t.jsx(Cn,{size:14})}),Se.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Q(Se.id),title:"Start mission",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>wt(q),title:"Edit mission",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>ce({type:"mission",id:Se.id}),title:"Delete mission",children:t.jsx(on,{size:14})})]})]},Se.id)}),w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:C.title,onChange:q=>L({...C,title:q.target.value}),onKeyDown:La,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:C.description,onChange:q=>L({...C,description:q.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:C.status,onChange:q=>L({...C,status:q.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:C.autopilotEnabled,onChange:q=>L({...C,autopilotEnabled:q.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:Lt,disabled:E,children:[E?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:_t,children:"Cancel"})]})]}),g.length===0&&!j&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(vs,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!j&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Oe.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(hs,{size:16}),t.jsx("span",{children:Oe.length===1?`Resume "${Oe[0].title}"?`:`${Oe.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Oe.map(q=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{Ne(q.id),st(!0),Ue([])},children:[q.status==="error"?t.jsx(Pn,{size:14}):t.jsx(rs,{size:14}),q.status==="error"?"Retry":"Resume"]},q.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>st(!0),children:[t.jsx(rs,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:at,children:[t.jsx(ln,{size:16}),"New Mission"]})]})]})]})}),je&&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 ",je.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()=>{je.type==="mission"?await Jn(je.id):je.type==="milestone"?await ie(je.id):je.type==="slice"?await mn(je.id):je.type==="feature"&&await Xn(je.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>ce(null),children:"Cancel"})]})]})}),$e&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:ot,onChange:q=>Je(q.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(q=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Je(q.id),children:[q.id,": ",q.title||"Untitled"]},q.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:Hn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{He(null),Je("")},children:"Cancel"})]})]})})]}),cl=t.jsx(I1,{isOpen:et,onClose:()=>st(!1),onMissionCreated:()=>{cn(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:ee}),Rs=Ae?t.jsx(L1,{isOpen:!0,onClose:()=>Fe(null),onApplied:()=>{Fe(null),f&&kt(f.id)},targetType:Ae.type,targetId:Ae.id,targetTitle:Ae.title,missionContext:f?.title,projectId:r,resumeSessionId:Ae.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[ll,cl,Rs]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:q=>q.target===q.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:ll}),cl,Rs]})}const Zr=2e3;function im({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,b]=a.useState(!1),[v,x]=a.useState(null),y=u.trim()!==""&&g.trim().length>0&&g.length<=Zr,S=a.useCallback(async()=>{if(!(!y||f)){b(!0),x(null);try{const A=m==="agent"?"user-to-agent":"system";await nw({toId:u.trim(),toType:m,content:g.trim(),type:A,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(A){const w=ke(A)||"Failed to send message";x(w),l?.(w,"error")}finally{b(!1)}}},[y,f,u,m,g,n,i,r,l]),j=a.useCallback(A=>{d(A),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(Kt,{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:A=>j(A.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(A=>t.jsx("option",{value:A.id,children:A.name||A.id},A.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(Sn,{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:A=>p(A.target.value),maxLength:Zr,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>Zr?"over-limit":"",children:[g.length,"/",Zr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(hs,{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:S,disabled:!y||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx($i,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function ia(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 Y1(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 Q1(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 am(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function X1(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 Z1({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,y]=a.useState(!1),[S,j]=a.useState(null),[A,w]=a.useState(null),[_,C]=a.useState(null),[L,E]=a.useState("inbox"),[T,F]=a.useState(null),[K,$]=a.useState([]),R=a.useMemo(()=>new Map(K.map(ae=>[ae.id,ae.name??""])),[K]),I=a.useCallback((ae,Ee)=>Y1(ae,Ee,R),[R]),J=Pr()==="mobile",Z=!J,N=a.useCallback(async()=>{g(!0);try{const ae=await ew({limit:50},e);l(ae),m(ae.unreadCount),s?.(ae.unreadCount)}catch{}finally{g(!1)}},[e,s]),z=a.useCallback(async()=>{g(!0);try{const ae=await tw({limit:50},e);u(ae)}catch{}finally{g(!1)}},[e]),P=a.useCallback(async ae=>{g(!0);try{const Ee=await ow(ae,e);F(Ee)}catch{}finally{g(!1)}},[e]),k=a.useCallback(async()=>{try{const ae=await Ea(void 0,e);$(ae)}catch{}},[e]),U=a.useCallback(async()=>{try{const ae=await Sp(e);m(ae.unreadCount),s?.(ae.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?N():i==="outbox"?z():i==="agents"&&k()},[i,N,z,k]),a.useEffect(()=>{_&&P(_)},[_,P]),a.useEffect(()=>{U()},[U]),a.useEffect(()=>{k()},[k]),a.useEffect(()=>{if(typeof EventSource>"u")return;const ae=e?`?projectId=${encodeURIComponent(e)}`:"",Ee=()=>{U(),i==="inbox"?N():i==="outbox"&&z(),_&&P(_)};return Qs(`/api/events${ae}`,{events:{"message:sent":Ee,"message:received":Ee,"message:read":Ee,"message:deleted":Ee}})},[e,i,_,U,N,z,P]);const V=a.useCallback(async ae=>{if(f(ae),!ae.read)try{const Ee=await sw(ae.id,e);Ee&&l(He=>He&&{...He,messages:He.messages.map(ot=>ot.id===Ee.id?Ee:ot),unreadCount:Math.max(0,He.unreadCount-1)});const $e=Math.max(0,d-1);m($e),s?.($e)}catch{}try{const Ee=await rw(ae.fromId,ae.fromType,e);v(Ee)}catch{v([ae])}},[e,d,s]),pe=a.useCallback(()=>{f(null),v([])},[]),ve=a.useCallback(async()=>{try{const ae=await iw(e);m(0),s?.(0),l(Ee=>Ee&&{...Ee,messages:Ee.messages.map($e=>({...$e,read:!0})),unreadCount:0}),n?.(`Marked ${ae.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),se=a.useCallback(async ae=>{try{await aw(ae,e),f(null),v([]),i==="inbox"?N():i==="outbox"?z():_&&P(_),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,_,N,z,P,n]),he=a.useCallback(ae=>{j({id:ae.fromId,type:ae.fromType}),w({messageId:ae.id,preview:am(ae.content,120)}),y(!0)},[]),O=a.useCallback(()=>{y(!1),j(null),w(null),n?.("Message sent","success"),i==="outbox"?z():i==="agents"&&_&&P(_),U()},[i,z,_,P,n,U]),ue=a.useCallback(()=>{j(i==="agents"&&_?{id:_,type:"agent"}:null),w(null),y(!0)},[i,_]),te=a.useCallback(()=>{y(!1),j(null),w(null)},[]),me=()=>!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:[J&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:pe,"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:Q1(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:ia(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>he(p),"data-testid":"mailbox-reply",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>se(p.id),"data-testid":"mailbox-delete",children:[t.jsx(on,{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(Sn,{size:14}):t.jsx(ea,{size:14}),I(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(Sn,{size:14}):t.jsx(ea,{size:14}),I(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(ae=>{const Ee=ae.metadata?.replyTo?.messageId,$e=Ee?b.find(He=>He.id===Ee):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ae.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:I(ae.fromId,ae.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:ia(ae.createdAt)})]}),Ee&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ae.id}`,children:["↪ Replying to ",$e?am($e.content,60):`message ${Ee}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ae.content})]},ae.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})]})]}),oe=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Tl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ir,{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:X1(o.messages).map(ae=>t.jsxs("div",{className:`mailbox-conversation-group ${ae.unreadCount>0?"unread":""}`,onClick:()=>V(ae.latestMessage),"data-testid":`mailbox-conversation-${ae.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.fromType==="agent"?t.jsx(Sn,{size:16}):t.jsx(ea,{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:I(ae.fromId,ae.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.latestMessage.content.slice(0,80),ae.latestMessage.content.length>80?"…":""]})]}),ae.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ae.key}`,children:ae.unreadCount>9?"9+":ae.unreadCount})]},ae.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Tl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx($i,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ae=>t.jsxs("div",{className:"mailbox-item",onClick:()=>V(ae),"data-testid":`mailbox-item-${ae.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.toType==="agent"?t.jsx(Sn,{size:16}):t.jsx(ea,{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: ",I(ae.toId,ae.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.content.slice(0,80),ae.content.length>80?"…":""]})]})]},ae.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:K.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Sn,{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:_??"",onChange:ae=>{C(ae.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),K.map(ae=>t.jsx("option",{value:ae.id,children:ae.name||ae.id},ae.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:ue,"data-testid":"mailbox-compose-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Compose"})]})]}),_&&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 ${L==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ir,{size:12}),t.jsx("span",{children:"Inbox"}),T&&T.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:T.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${L==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx($i,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!_&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Sn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),_&&h&&!T&&t.jsx(Tl,{}),_&&T&&L==="inbox"&&T.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ir,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),_&&T&&L==="outbox"&&T.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx($i,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),_&&T&&L==="inbox"&&T.inbox.map(ae=>t.jsxs("div",{className:`mailbox-item ${ae.read?"":"unread"}`,onClick:()=>V(ae),"data-testid":`mailbox-item-${ae.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.fromType==="agent"?t.jsx(Sn,{size:16}):t.jsx(ea,{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:I(ae.fromId,ae.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.content.slice(0,80),ae.content.length>80?"…":""]})]})]},ae.id)),_&&T&&L==="outbox"&&T.outbox.map(ae=>t.jsxs("div",{className:"mailbox-item",onClick:()=>V(ae),"data-testid":`mailbox-item-${ae.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ae.toType==="agent"?t.jsx(Sn,{size:16}):t.jsx(ea,{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: ",I(ae.toId,ae.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ia(ae.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ae.content.slice(0,80),ae.content.length>80?"…":""]})]})]},ae.id))]})]})})]}),be=()=>x?t.jsx(im,{recipient:S,replyContext:A,agents:K,projectId:e,onSend:O,onCancel:te,addToast:n}):p?me():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(fa,{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(fa,{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:ue,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:ve,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Yg,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?N():i==="outbox"?z():_&&P(_)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Pn,{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(ir,{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($i,{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(Sn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:Z?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:oe()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:be()})]}):t.jsxs(t.Fragment,{children:[me(),x&&t.jsx(im,{recipient:S,replyContext:A,agents:K,projectId:e,onSend:O,onCancel:te,addToast:n}),!p&&!x&&oe()]})})]})}function Tl(){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 ri(e,n,s){a.useEffect(()=>{if(!n)return;const i=e.current;if(!i)return;try{const u=localStorage.getItem(s);if(u){const{width:d,height:m}=JSON.parse(u);typeof d=="number"&&d>0&&(i.style.width=`${d}px`),typeof m=="number"&&m>0&&(i.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=i.offsetWidth,o=i.offsetHeight,l=null;const c=new ResizeObserver(()=>{const u=i.offsetWidth,d=i.offsetHeight;u===r&&d===o||(r=u,o=d,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:d}))}catch{}},200))});return c.observe(i),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function Si(e){const n=a.useRef(!1),s=a.useCallback(r=>{n.current=r.target===r.currentTarget},[]),i=a.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:i}}function e0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const t0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,n0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,s0={};function rm(e,n){return(s0.jsx?n0:t0).test(e)}const i0=/[ \t\n\f\r]/g;function a0(e){return typeof e=="object"?e.type==="text"?om(e.value):!1:om(e)}function om(e){return e.replace(i0,"")===""}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 Yp(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 Fc(e){return e.toLowerCase()}class ys{constructor(n,s){this.attribute=s,this.property=n}}ys.prototype.attribute="";ys.prototype.booleanish=!1;ys.prototype.boolean=!1;ys.prototype.commaOrSpaceSeparated=!1;ys.prototype.commaSeparated=!1;ys.prototype.defined=!1;ys.prototype.mustUseProperty=!1;ys.prototype.number=!1;ys.prototype.overloadedBoolean=!1;ys.prototype.property="";ys.prototype.spaceSeparated=!1;ys.prototype.space=void 0;let r0=0;const qt=Gi(),$n=Gi(),Uc=Gi(),Ze=Gi(),jn=Gi(),ma=Gi(),ks=Gi();function Gi(){return 2**++r0}const Bc=Object.freeze(Object.defineProperty({__proto__:null,boolean:qt,booleanish:$n,commaOrSpaceSeparated:ks,commaSeparated:ma,number:Ze,overloadedBoolean:Uc,spaceSeparated:jn},Symbol.toStringTag,{value:"Module"})),Pl=Object.keys(Bc);class vd extends ys{constructor(n,s,i,r){let o=-1;if(super(n,s),lm(this,"space",r),typeof i=="number")for(;++o<Pl.length;){const l=Pl[o];lm(this,Pl[o],(i&Bc[l])===Bc[l])}}}vd.prototype.defined=!0;function lm(e,n,s){s&&(e[n]=s)}function Aa(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new vd(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Fc(i)]=i,s[Fc(o.attribute)]=i}return new Ir(n,s,e.space)}const Qp=Aa({properties:{ariaActiveDescendant:null,ariaAtomic:$n,ariaAutoComplete:null,ariaBusy:$n,ariaChecked:$n,ariaColCount:Ze,ariaColIndex:Ze,ariaColSpan:Ze,ariaControls:jn,ariaCurrent:null,ariaDescribedBy:jn,ariaDetails:null,ariaDisabled:$n,ariaDropEffect:jn,ariaErrorMessage:null,ariaExpanded:$n,ariaFlowTo:jn,ariaGrabbed:$n,ariaHasPopup:null,ariaHidden:$n,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:jn,ariaLevel:Ze,ariaLive:null,ariaModal:$n,ariaMultiLine:$n,ariaMultiSelectable:$n,ariaOrientation:null,ariaOwns:jn,ariaPlaceholder:null,ariaPosInSet:Ze,ariaPressed:$n,ariaReadOnly:$n,ariaRelevant:null,ariaRequired:$n,ariaRoleDescription:jn,ariaRowCount:Ze,ariaRowIndex:Ze,ariaRowSpan:Ze,ariaSelected:$n,ariaSetSize:Ze,ariaSort:null,ariaValueMax:Ze,ariaValueMin:Ze,ariaValueNow:Ze,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Xp(e,n){return n in e?e[n]:n}function Zp(e,n){return Xp(e,n.toLowerCase())}const o0=Aa({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:ma,acceptCharset:jn,accessKey:jn,action:null,allow:null,allowFullScreen:qt,allowPaymentRequest:qt,allowUserMedia:qt,alt:null,as:null,async:qt,autoCapitalize:null,autoComplete:jn,autoFocus:qt,autoPlay:qt,blocking:jn,capture:null,charSet:null,checked:qt,cite:null,className:jn,cols:Ze,colSpan:null,content:null,contentEditable:$n,controls:qt,controlsList:jn,coords:Ze|ma,crossOrigin:null,data:null,dateTime:null,decoding:null,default:qt,defer:qt,dir:null,dirName:null,disabled:qt,download:Uc,draggable:$n,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:qt,formTarget:null,headers:jn,height:Ze,hidden:Uc,high:Ze,href:null,hrefLang:null,htmlFor:jn,httpEquiv:jn,id:null,imageSizes:null,imageSrcSet:null,inert:qt,inputMode:null,integrity:null,is:null,isMap:qt,itemId:null,itemProp:jn,itemRef:jn,itemScope:qt,itemType:jn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:qt,low:Ze,manifest:null,max:null,maxLength:Ze,media:null,method:null,min:null,minLength:Ze,multiple:qt,muted:qt,name:null,nonce:null,noModule:qt,noValidate:qt,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:qt,optimum:Ze,pattern:null,ping:jn,placeholder:null,playsInline:qt,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:qt,referrerPolicy:null,rel:jn,required:qt,reversed:qt,rows:Ze,rowSpan:Ze,sandbox:jn,scope:null,scoped:qt,seamless:qt,selected:qt,shadowRootClonable:qt,shadowRootDelegatesFocus:qt,shadowRootMode:null,shape:null,size:Ze,sizes:null,slot:null,span:Ze,spellCheck:$n,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Ze,step:null,style:null,tabIndex:Ze,target:null,title:null,translate:null,type:null,typeMustMatch:qt,useMap:null,value:$n,width:Ze,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:jn,axis:null,background:null,bgColor:null,border:Ze,borderColor:null,bottomMargin:Ze,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:qt,declare:qt,event:null,face:null,frame:null,frameBorder:null,hSpace:Ze,leftMargin:Ze,link:null,longDesc:null,lowSrc:null,marginHeight:Ze,marginWidth:Ze,noResize:qt,noHref:qt,noShade:qt,noWrap:qt,object:null,profile:null,prompt:null,rev:null,rightMargin:Ze,rules:null,scheme:null,scrolling:$n,standby:null,summary:null,text:null,topMargin:Ze,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Ze,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:qt,disableRemotePlayback:qt,prefix:null,property:null,results:Ze,security:null,unselectable:null},space:"html",transform:Zp}),l0=Aa({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:ks,accentHeight:Ze,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Ze,amplitude:Ze,arabicForm:null,ascent:Ze,attributeName:null,attributeType:null,azimuth:Ze,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Ze,by:null,calcMode:null,capHeight:Ze,className:jn,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:Ze,diffuseConstant:Ze,direction:null,display:null,dur:null,divisor:Ze,dominantBaseline:null,download:qt,dx:null,dy:null,edgeMode:null,editable:null,elevation:Ze,enableBackground:null,end:null,event:null,exponent:Ze,externalResourcesRequired:null,fill:null,fillOpacity:Ze,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:ma,g2:ma,glyphName:ma,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Ze,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Ze,horizOriginX:Ze,horizOriginY:Ze,id:null,ideographic:Ze,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Ze,k:Ze,k1:Ze,k2:Ze,k3:Ze,k4:Ze,kernelMatrix:ks,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Ze,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:Ze,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:Ze,overlineThickness:Ze,paintOrder:null,panose1:null,path:null,pathLength:Ze,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:jn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Ze,pointsAtY:Ze,pointsAtZ:Ze,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ks,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ks,rev:ks,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ks,requiredFeatures:ks,requiredFonts:ks,requiredFormats:ks,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:Ze,specularExponent:Ze,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Ze,strikethroughThickness:Ze,string:null,stroke:null,strokeDashArray:ks,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Ze,strokeOpacity:Ze,strokeWidth:null,style:null,surfaceScale:Ze,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ks,tabIndex:Ze,tableValues:null,target:null,targetX:Ze,targetY:Ze,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ks,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Ze,underlineThickness:Ze,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Ze,values:null,vAlphabetic:Ze,vMathematical:Ze,vectorEffect:null,vHanging:Ze,vIdeographic:Ze,version:null,vertAdvY:Ze,vertOriginX:Ze,vertOriginY:Ze,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Ze,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Xp}),ef=Aa({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()}}),tf=Aa({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Zp}),nf=Aa({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),c0={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"},d0=/[A-Z]/g,cm=/-[a-z]/g,u0=/^data[-\w.:]+$/i;function m0(e,n){const s=Fc(n);let i=n,r=ys;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&u0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(cm,p0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!cm.test(o)){let l=o.replace(d0,h0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=vd}return new r(i,n)}function h0(e){return"-"+e.toLowerCase()}function p0(e){return e.charAt(1).toUpperCase()}const f0=Yp([Qp,o0,ef,tf,nf],"html"),yd=Yp([Qp,l0,ef,tf,nf],"svg");function g0(e){return e.join(" ").trim()}var aa={},Il,dm;function b0(){if(dm)return Il;dm=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=`
619
- `,d="/",m="*",h="",g="comment",p="declaration";function f(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,S=1;function j($){var R=$.match(n);R&&(y+=R.length);var I=$.lastIndexOf(u);S=~I?$.length-I:S+$.length}function A(){var $={line:y,column:S};return function(R){return R.position=new w($),L(),R}}function w($){this.start=$,this.end={line:y,column:S},this.source=x.source}w.prototype.content=v;function _($){var R=new Error(x.source+":"+y+":"+S+": "+$);if(R.reason=$,R.filename=x.source,R.line=y,R.column=S,R.source=v,!x.silent)throw R}function C($){var R=$.exec(v);if(R){var I=R[0];return j(I),v=v.slice(I.length),R}}function L(){C(s)}function E($){var R;for($=$||[];R=T();)R!==!1&&$.push(R);return $}function T(){var $=A();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var R=2;h!=v.charAt(R)&&(m!=v.charAt(R)||d!=v.charAt(R+1));)++R;if(R+=2,h===v.charAt(R-1))return _("End of comment missing");var I=v.slice(2,R-2);return S+=2,j(I),v=v.slice(R),S+=2,$({type:g,comment:I})}}function F(){var $=A(),R=C(i);if(R){if(T(),!C(r))return _("property missing ':'");var I=C(o),H=$({type:p,property:b(R[0].replace(e,h)),value:I?b(I[0].replace(e,h)):h});return C(l),H}}function K(){var $=[];E($);for(var R;R=F();)R!==!1&&($.push(R),E($));return $}return L(),K()}function b(v){return v?v.replace(c,h):h}return Il=f,Il}var um;function x0(){if(um)return aa;um=1;var e=aa&&aa.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(aa,"__esModule",{value:!0}),aa.default=s;const n=e(b0());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 aa}var qa={},mm;function v0(){if(mm)return qa;mm=1,Object.defineProperty(qa,"__esModule",{value:!0}),qa.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 qa.camelCase=u,qa}var Va,hm;function y0(){if(hm)return Va;hm=1;var e=Va&&Va.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(x0()),s=v0();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 j0=y0();const k0=Gh(j0),sf=af("end"),jd=af("start");function af(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 w0(e){const n=jd(e),s=sf(e);if(n&&s)return{start:n,end:s}}function dr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?pm(e.position):"start"in e||"end"in e?pm(e):"line"in e||"column"in e?Hc(e):""}function Hc(e){return fm(e&&e.line)+":"+fm(e&&e.column)}function pm(e){return Hc(e&&e.start)+"-"+Hc(e&&e.end)}function fm(e){return e&&typeof e=="number"?e:1}class os 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=dr(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}}os.prototype.file="";os.prototype.name="";os.prototype.reason="";os.prototype.message="";os.prototype.stack="";os.prototype.column=void 0;os.prototype.line=void 0;os.prototype.ancestors=void 0;os.prototype.cause=void 0;os.prototype.fatal=void 0;os.prototype.place=void 0;os.prototype.ruleId=void 0;os.prototype.source=void 0;const kd={}.hasOwnProperty,N0=new Map,S0=/[A-Z]/g,C0=new Set(["table","tbody","thead","tfoot","tr"]),E0=new Set(["td","th"]),rf="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function _0(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=D0(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=$0(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"?yd:f0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=of(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function of(e,n,s){if(n.type==="element")return M0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return A0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return T0(e,n,s);if(n.type==="mdxjsEsm")return R0(e,n);if(n.type==="root")return P0(e,n,s);if(n.type==="text")return I0(e,n)}function M0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=yd,e.schema=r),e.ancestors.push(n);const o=cf(e,n.tagName,!1),l=L0(e,n);let c=Nd(e,n);return C0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!a0(u):!0})),lf(e,l,o,n),wd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function A0(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)}jr(e,n.position)}function R0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);jr(e,n.position)}function T0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=yd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:cf(e,n.name,!0),l=z0(e,n),c=Nd(e,n);return lf(e,l,o,n),wd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function P0(e,n,s){const i={};return wd(i,Nd(e,n)),e.create(n,e.Fragment,i,s)}function I0(e,n){return n.value}function lf(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function wd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function $0(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 D0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=jd(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 L0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&kd.call(n.properties,r)){const o=O0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&E0.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 z0(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 jr(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 jr(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Nd(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:N0;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=of(e,o,l);c!==void 0&&s.push(c)}return s}function O0(e,n,s){const i=m0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?e0(s):g0(s)),i.property==="style"){let r=typeof s=="object"?s:F0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=U0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?c0[i.property]||i.property:i.attribute,s]}}function F0(e,n){try{return k0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new os("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=rf+"#cannot-parse-style-attribute",r}}function cf(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=rm(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=rm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return kd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);jr(e)}function jr(e,n){const s=new os("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=rf+"#cannot-handle-mdx-estrees-without-createevaluater",s}function U0(e){const n={};let s;for(s in e)kd.call(e,s)&&(n[B0(s)]=e[s]);return n}function B0(e){let n=e.replace(S0,H0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function H0(e){return"-"+e.toLowerCase()}const $l={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"]},q0={};function Sd(e,n){const s=q0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return df(e,i,r)}function df(e,n,s){if(V0(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 gm(e.children,n,s)}return Array.isArray(e)?gm(e,n,s):""}function gm(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=df(e[r],n,s);return i.join("")}function V0(e){return!!(e&&typeof e=="object")}const bm=document.createElement("i");function Cd(e){const n="&"+e+";";bm.innerHTML=n;const s=bm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Cs(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 Ds(e,n){return e.length>0?(Cs(e,e.length,0,n),e):n}const xm={}.hasOwnProperty;function uf(e){const n={};let s=-1;for(;++s<e.length;)W0(n,e[s]);return n}function W0(e,n){let s;for(s in n){const r=(xm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){xm.call(r,l)||(r[l]=[]);const c=o[l];K0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function K0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);Cs(e,0,0,i)}function mf(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 Gs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const ms=Ci(/[A-Za-z]/),as=Ci(/[\dA-Za-z]/),G0=Ci(/[#-'*+\--9=?A-Z^-~]/);function Mo(e){return e!==null&&(e<32||e===127)}const qc=Ci(/\d/),J0=Ci(/[\dA-Fa-f]/),Y0=Ci(/[!-/:-@[-`{-~]/);function Et(e){return e!==null&&e<-2}function gn(e){return e!==null&&(e<0||e===32)}function Gt(e){return e===-2||e===-1||e===32}const Zo=Ci(/\p{P}|\p{S}/u),qi=Ci(/\s/);function Ci(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Ra(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&as(e.charCodeAt(s+1))&&as(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 tn(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Gt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Gt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const Q0={tokenize:X0};function X0(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"),tn(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 Et(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const Z0={tokenize:eS},vm={tokenize:tS};function eS(e){const n=this,s=[];let i=0,r,o,l;return c;function c(S){if(i<s.length){const j=s[i];return n.containerState=j[1],e.attempt(j[0].continuation,u,d)(S)}return d(S)}function u(S){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const j=n.events.length;let A=j,w;for(;A--;)if(n.events[A][0]==="exit"&&n.events[A][1].type==="chunkFlow"){w=n.events[A][1].end;break}x(i);let _=j;for(;_<n.events.length;)n.events[_][1].end={...w},_++;return Cs(n.events,A+1,0,n.events.slice(j)),n.events.length=_,d(S)}return c(S)}function d(S){if(i===s.length){if(!r)return g(S);if(r.currentConstruct&&r.currentConstruct.concrete)return f(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(vm,m,h)(S)}function m(S){return r&&y(),x(i),g(S)}function h(S){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(S)}function g(S){return n.containerState={},e.attempt(vm,p,f)(S)}function p(S){return i++,s.push([n.currentConstruct,n.containerState]),g(S)}function f(S){if(S===null){r&&y(),x(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(S)}function b(S){if(S===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(S);return}return Et(S)?(e.consume(S),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(S),b)}function v(S,j){const A=n.sliceStream(S);if(j&&A.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(A),n.parser.lazy[S.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const _=n.events.length;let C=_,L,E;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){if(L){E=n.events[C][1].end;break}L=!0}for(x(i),w=_;w<n.events.length;)n.events[w][1].end={...E},w++;Cs(n.events,C+1,0,n.events.slice(_)),n.events.length=w}}function x(S){let j=s.length;for(;j-- >S;){const A=s[j];n.containerState=A[1],A[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function tS(e,n,s){return tn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function va(e){if(e===null||gn(e)||qi(e))return 1;if(Zo(e))return 2}function el(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 Vc={name:"attention",resolveAll:nS,tokenize:sS};function nS(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};ym(h,-u),ym(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=Ds(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=Ds(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=Ds(d,el(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=Ds(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=Ds(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Cs(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 sS(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=va(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=va(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 ym(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const iS={name:"autolink",tokenize:aS};function aS(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 ms(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||as(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||as(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||Mo(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):G0(p)?(e.consume(p),d):s(p)}function m(p){return as(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||as(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const $r={partial:!0,tokenize:rS};function rS(e,n,s){return i;function i(o){return Gt(o)?tn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Et(o)?n(o):s(o)}}const hf={continuation:{tokenize:lS},exit:cS,name:"blockQuote",tokenize:oS};function oS(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 Gt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function lS(e,n,s){const i=this;return r;function r(l){return Gt(l)?tn(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(hf,n,s)(l)}}function cS(e){e.exit("blockQuote")}const pf={name:"characterEscape",tokenize:dS};function dS(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 Y0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const ff={name:"characterReference",tokenize:uS};function uS(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=as,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=J0,m):(e.enter("characterReferenceValue"),o=7,l=qc,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===as&&!Cd(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 jm={partial:!0,tokenize:hS},km={concrete:!0,name:"codeFenced",tokenize:mS};function mS(e,n,s){const i=this,r={partial:!0,tokenize:A};let o=0,l=0,c;return u;function u(w){return d(w)}function d(w){const _=i.events[i.events.length-1];return o=_&&_[1].type==="linePrefix"?_[2].sliceSerialize(_[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),Gt(w)?tn(e,h,"whitespace")(w):h(w))}function h(w){return w===null||Et(w)?(e.exit("codeFencedFence"),i.interrupt?n(w):e.check(jm,b,j)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||Et(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):Gt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),tn(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),g)}function p(w){return w===null||Et(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||Et(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),f)}function b(w){return e.attempt(r,j,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),x}function x(w){return o>0&&Gt(w)?tn(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||Et(w)?e.check(jm,b,j)(w):(e.enter("codeFlowValue"),S(w))}function S(w){return w===null||Et(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),S)}function j(w){return e.exit("codeFenced"),n(w)}function A(w,_,C){let L=0;return E;function E(R){return w.enter("lineEnding"),w.consume(R),w.exit("lineEnding"),T}function T(R){return w.enter("codeFencedFence"),Gt(R)?tn(w,F,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(R):F(R)}function F(R){return R===c?(w.enter("codeFencedFenceSequence"),K(R)):C(R)}function K(R){return R===c?(L++,w.consume(R),K):L>=l?(w.exit("codeFencedFenceSequence"),Gt(R)?tn(w,$,"whitespace")(R):$(R)):C(R)}function $(R){return R===null||Et(R)?(w.exit("codeFencedFence"),_(R)):C(R)}}}function hS(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 Dl={name:"codeIndented",tokenize:fS},pS={partial:!0,tokenize:gS};function fS(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),tn(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):Et(d)?e.attempt(pS,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||Et(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function gS(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):Et(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):tn(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):Et(l)?r(l):s(l)}}const bS={name:"codeText",previous:vS,resolve:xS,tokenize:yS};function xS(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 vS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function yS(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)):Et(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||Et(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 jS{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&&Wa(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),Wa(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Wa(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const s=this.left.splice(n,Number.POSITIVE_INFINITY);Wa(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Wa(this.left,s.reverse())}}}function Wa(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 gf(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new jS(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,kS(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 Cs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function kS(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(b=g+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const x=c.slice(v[g],v[g+1]),y=o.pop();u.push([y,y+x.length-1]),e.splice(y,2,x)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const wS={resolve:SS,tokenize:CS},NS={partial:!0,tokenize:ES};function SS(e){return gf(e),e}function CS(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):Et(c)?e.check(NS,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 ES(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),tn(e,o,"linePrefix")}function o(l){if(l===null||Et(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 bf(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||Mo(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||Et(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||gn(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||Mo(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 xf(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):Et(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||Et(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Gt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function vf(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):Et(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),tn(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||Et(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 ur(e,n){let s;return i;function i(r){return Et(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Gt(r)?tn(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const _S={name:"definition",tokenize:AS},MS={partial:!0,tokenize:RS};function AS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return xf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Gs(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 gn(p)?ur(e,d)(p):d(p)}function d(p){return bf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(MS,h,h)(p)}function h(p){return Gt(p)?tn(e,g,"whitespace")(p):g(p)}function g(p){return p===null||Et(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function RS(e,n,s){return i;function i(c){return gn(c)?ur(e,r)(c):s(c)}function r(c){return vf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Gt(c)?tn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Et(c)?n(c):s(c)}}const TS={name:"hardBreakEscape",tokenize:PS};function PS(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Et(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const IS={name:"headingAtx",resolve:$S,tokenize:DS};function $S(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"},Cs(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function DS(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||gn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||Et(m)?(e.exit("atxHeading"),n(m)):Gt(m)?tn(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||gn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const LS=["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"],wm=["pre","script","style","textarea"],zS={concrete:!0,name:"htmlFlow",resolveTo:US,tokenize:BS},OS={partial:!0,tokenize:qS},FS={partial:!0,tokenize:HS};function US(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 BS(e,n,s){const i=this;let r,o,l,c,u;return d;function d(k){return m(k)}function m(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),h}function h(k){return k===33?(e.consume(k),g):k===47?(e.consume(k),o=!0,b):k===63?(e.consume(k),r=3,i.interrupt?n:N):ms(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function g(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,f):ms(k)?(e.consume(k),r=4,i.interrupt?n:N):s(k)}function p(k){return k===45?(e.consume(k),i.interrupt?n:N):s(k)}function f(k){const U="CDATA[";return k===U.charCodeAt(c++)?(e.consume(k),c===U.length?i.interrupt?n:F:f):s(k)}function b(k){return ms(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function v(k){if(k===null||k===47||k===62||gn(k)){const U=k===47,V=l.toLowerCase();return!U&&!o&&wm.includes(V)?(r=1,i.interrupt?n(k):F(k)):LS.includes(l.toLowerCase())?(r=6,U?(e.consume(k),x):i.interrupt?n(k):F(k)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(k):o?y(k):S(k))}return k===45||as(k)?(e.consume(k),l+=String.fromCharCode(k),v):s(k)}function x(k){return k===62?(e.consume(k),i.interrupt?n:F):s(k)}function y(k){return Gt(k)?(e.consume(k),y):E(k)}function S(k){return k===47?(e.consume(k),E):k===58||k===95||ms(k)?(e.consume(k),j):Gt(k)?(e.consume(k),S):E(k)}function j(k){return k===45||k===46||k===58||k===95||as(k)?(e.consume(k),j):A(k)}function A(k){return k===61?(e.consume(k),w):Gt(k)?(e.consume(k),A):S(k)}function w(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),u=k,_):Gt(k)?(e.consume(k),w):C(k)}function _(k){return k===u?(e.consume(k),u=null,L):k===null||Et(k)?s(k):(e.consume(k),_)}function C(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||gn(k)?A(k):(e.consume(k),C)}function L(k){return k===47||k===62||Gt(k)?S(k):s(k)}function E(k){return k===62?(e.consume(k),T):s(k)}function T(k){return k===null||Et(k)?F(k):Gt(k)?(e.consume(k),T):s(k)}function F(k){return k===45&&r===2?(e.consume(k),I):k===60&&r===1?(e.consume(k),H):k===62&&r===4?(e.consume(k),z):k===63&&r===3?(e.consume(k),N):k===93&&r===5?(e.consume(k),Z):Et(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(OS,P,K)(k)):k===null||Et(k)?(e.exit("htmlFlowData"),K(k)):(e.consume(k),F)}function K(k){return e.check(FS,$,P)(k)}function $(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),R}function R(k){return k===null||Et(k)?K(k):(e.enter("htmlFlowData"),F(k))}function I(k){return k===45?(e.consume(k),N):F(k)}function H(k){return k===47?(e.consume(k),l="",J):F(k)}function J(k){if(k===62){const U=l.toLowerCase();return wm.includes(U)?(e.consume(k),z):F(k)}return ms(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),J):F(k)}function Z(k){return k===93?(e.consume(k),N):F(k)}function N(k){return k===62?(e.consume(k),z):k===45&&r===2?(e.consume(k),N):F(k)}function z(k){return k===null||Et(k)?(e.exit("htmlFlowData"),P(k)):(e.consume(k),z)}function P(k){return e.exit("htmlFlow"),n(k)}}function HS(e,n,s){const i=this;return r;function r(l){return Et(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 qS(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt($r,n,s)}}const VS={name:"htmlText",tokenize:WS};function WS(e,n,s){const i=this;let r,o,l;return c;function c(N){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(N),u}function u(N){return N===33?(e.consume(N),d):N===47?(e.consume(N),A):N===63?(e.consume(N),S):ms(N)?(e.consume(N),C):s(N)}function d(N){return N===45?(e.consume(N),m):N===91?(e.consume(N),o=0,f):ms(N)?(e.consume(N),y):s(N)}function m(N){return N===45?(e.consume(N),p):s(N)}function h(N){return N===null?s(N):N===45?(e.consume(N),g):Et(N)?(l=h,H(N)):(e.consume(N),h)}function g(N){return N===45?(e.consume(N),p):h(N)}function p(N){return N===62?I(N):N===45?g(N):h(N)}function f(N){const z="CDATA[";return N===z.charCodeAt(o++)?(e.consume(N),o===z.length?b:f):s(N)}function b(N){return N===null?s(N):N===93?(e.consume(N),v):Et(N)?(l=b,H(N)):(e.consume(N),b)}function v(N){return N===93?(e.consume(N),x):b(N)}function x(N){return N===62?I(N):N===93?(e.consume(N),x):b(N)}function y(N){return N===null||N===62?I(N):Et(N)?(l=y,H(N)):(e.consume(N),y)}function S(N){return N===null?s(N):N===63?(e.consume(N),j):Et(N)?(l=S,H(N)):(e.consume(N),S)}function j(N){return N===62?I(N):S(N)}function A(N){return ms(N)?(e.consume(N),w):s(N)}function w(N){return N===45||as(N)?(e.consume(N),w):_(N)}function _(N){return Et(N)?(l=_,H(N)):Gt(N)?(e.consume(N),_):I(N)}function C(N){return N===45||as(N)?(e.consume(N),C):N===47||N===62||gn(N)?L(N):s(N)}function L(N){return N===47?(e.consume(N),I):N===58||N===95||ms(N)?(e.consume(N),E):Et(N)?(l=L,H(N)):Gt(N)?(e.consume(N),L):I(N)}function E(N){return N===45||N===46||N===58||N===95||as(N)?(e.consume(N),E):T(N)}function T(N){return N===61?(e.consume(N),F):Et(N)?(l=T,H(N)):Gt(N)?(e.consume(N),T):L(N)}function F(N){return N===null||N===60||N===61||N===62||N===96?s(N):N===34||N===39?(e.consume(N),r=N,K):Et(N)?(l=F,H(N)):Gt(N)?(e.consume(N),F):(e.consume(N),$)}function K(N){return N===r?(e.consume(N),r=void 0,R):N===null?s(N):Et(N)?(l=K,H(N)):(e.consume(N),K)}function $(N){return N===null||N===34||N===39||N===60||N===61||N===96?s(N):N===47||N===62||gn(N)?L(N):(e.consume(N),$)}function R(N){return N===47||N===62||gn(N)?L(N):s(N)}function I(N){return N===62?(e.consume(N),e.exit("htmlTextData"),e.exit("htmlText"),n):s(N)}function H(N){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),J}function J(N){return Gt(N)?tn(e,Z,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(N):Z(N)}function Z(N){return e.enter("htmlTextData"),l(N)}}const Ed={name:"labelEnd",resolveAll:YS,resolveTo:QS,tokenize:XS},KS={tokenize:ZS},GS={tokenize:eC},JS={tokenize:tC};function YS(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&&Cs(e,0,e.length,s),e}function QS(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=Ds(c,e.slice(o+1,o+i+3)),c=Ds(c,[["enter",m,n]]),c=Ds(c,el(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=Ds(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=Ds(c,e.slice(l+1)),c=Ds(c,[["exit",u,n]]),Cs(e,o,e.length,c),e}function XS(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(Gs(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(KS,m,l?m:h)(g):g===91?e.attempt(GS,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(JS,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function ZS(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 gn(h)?ur(e,o)(h):o(h)}function o(h){return h===41?m(h):bf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return gn(h)?ur(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?vf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return gn(h)?ur(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 eC(e,n,s){const i=this;return r;function r(c){return xf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Gs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function tC(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 nC={name:"labelStartImage",resolveAll:Ed.resolveAll,tokenize:sC};function sC(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 iC={name:"labelStartLink",resolveAll:Ed.resolveAll,tokenize:aC};function aC(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 Ll={name:"lineEnding",tokenize:rC};function rC(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),tn(e,n,"linePrefix")}}const go={name:"thematicBreak",tokenize:oC};function oC(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||Et(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Gt(d)?tn(e,c,"whitespace")(d):c(d))}}const bs={continuation:{tokenize:uC},exit:hC,name:"list",tokenize:dC},lC={partial:!0,tokenize:pC},cC={partial:!0,tokenize:mC};function dC(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:qc(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(go,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 qc(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($r,i.interrupt?s:m,e.attempt(lC,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Gt(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 uC(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check($r,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,tn(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Gt(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(cC,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,tn(e,e.attempt(bs,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function mC(e,n,s){const i=this;return tn(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 hC(e){e.exit(this.containerState.type)}function pC(e,n,s){const i=this;return tn(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!Gt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Nm={name:"setextUnderline",resolveTo:fC,tokenize:gC};function fC(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 gC(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"),Gt(d)?tn(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||Et(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const bC={tokenize:xC};function xC(e){const n=this,s=e.attempt($r,i,e.attempt(this.parser.constructs.flowInitial,r,tn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(wS,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 vC={resolveAll:jf()},yC=yf("string"),jC=yf("text");function yf(e){return{resolveAll:jf(e==="text"?kC: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 jf(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 kC(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 wC={42:bs,43:bs,45:bs,48:bs,49:bs,50:bs,51:bs,52:bs,53:bs,54:bs,55:bs,56:bs,57:bs,62:hf},NC={91:_S},SC={[-2]:Dl,[-1]:Dl,32:Dl},CC={35:IS,42:go,45:[Nm,go],60:zS,61:Nm,95:go,96:km,126:km},EC={38:ff,92:pf},_C={[-5]:Ll,[-4]:Ll,[-3]:Ll,33:nC,38:ff,42:Vc,60:[iS,VS],91:iC,92:[TS,pf],93:Ed,95:Vc,96:bS},MC={null:[Vc,vC]},AC={null:[42,95]},RC={null:[]},TC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:AC,contentInitial:NC,disable:RC,document:wC,flow:CC,flowInitial:SC,insideSpan:MC,string:EC,text:_C},Symbol.toStringTag,{value:"Module"}));function PC(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:_(A),check:_(w),consume:y,enter:S,exit:j,interrupt:_(w,{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(T){return l=Ds(l,T),v(),l[l.length-1]!==null?[]:(C(n,0),d.events=el(o,d.events,d),d.events)}function g(T,F){return $C(p(T),F)}function p(T){return IC(l,T)}function f(){const{_bufferIndex:T,_index:F,line:K,column:$,offset:R}=i;return{_bufferIndex:T,_index:F,line:K,column:$,offset:R}}function b(T){r[T.line]=T.column,E()}function v(){let T;for(;i._index<l.length;){const F=l[i._index];if(typeof F=="string")for(T=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===T&&i._bufferIndex<F.length;)x(F.charCodeAt(i._bufferIndex));else x(F)}}function x(T){m=m(T)}function y(T){Et(T)?(i.line++,i.column=1,i.offset+=T===-3?2:1,E()):T!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=T}function S(T,F){const K=F||{};return K.type=T,K.start=f(),d.events.push(["enter",K,d]),c.push(K),K}function j(T){const F=c.pop();return F.end=f(),d.events.push(["exit",F,d]),F}function A(T,F){C(T,F.from)}function w(T,F){F.restore()}function _(T,F){return K;function K($,R,I){let H,J,Z,N;return Array.isArray($)?P($):"tokenize"in $?P([$]):z($);function z(pe){return ve;function ve(se){const he=se!==null&&pe[se],O=se!==null&&pe.null,ue=[...Array.isArray(he)?he:he?[he]:[],...Array.isArray(O)?O:O?[O]:[]];return P(ue)(se)}}function P(pe){return H=pe,J=0,pe.length===0?I:k(pe[J])}function k(pe){return ve;function ve(se){return N=L(),Z=pe,pe.partial||(d.currentConstruct=pe),pe.name&&d.parser.constructs.disable.null.includes(pe.name)?V():pe.tokenize.call(F?Object.assign(Object.create(d),F):d,u,U,V)(se)}}function U(pe){return T(Z,N),R}function V(pe){return N.restore(),++J<H.length?k(H[J]):I}}}function C(T,F){T.resolveAll&&!o.includes(T)&&o.push(T),T.resolve&&Cs(d.events,F,d.events.length-F,T.resolve(d.events.slice(F),d)),T.resolveTo&&(d.events=T.resolveTo(d.events,d))}function L(){const T=f(),F=d.previous,K=d.currentConstruct,$=d.events.length,R=Array.from(c);return{from:$,restore:I};function I(){i=T,d.previous=F,d.currentConstruct=K,d.events.length=$,c=R,E()}}function E(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function IC(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 $C(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=`
620
- `;break}case-3:{l=`\r
621
- `;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 DC(e){const i={constructs:uf([TC,...(e||{}).extensions||[]]),content:r(Q0),defined:[],document:r(Z0),flow:r(bC),lazy:{},string:r(yC),text:r(jC)};return i;function r(o){return l;function l(c){return PC(i,o,c)}}}function LC(e){for(;!gf(e););return e}const Sm=/[\0\t\n\r]/g;function zC(){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(Sm.lastIndex=h,d=Sm.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 OC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function FC(e){return e.replace(OC,UC)}function UC(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return mf(s.slice(o?2:1),o?16:10)}return Cd(s)||e}const kf={}.hasOwnProperty;function BC(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),HC(s)(LC(DC(s).document().write(zC()(e,n,!0))))}function HC(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(He),autolinkProtocol:L,autolinkEmail:L,atxHeading:o(be),blockQuote:o(O),characterEscape:L,characterReference:L,codeFenced:o(ue),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ue,l),codeText:o(te,l),codeTextData:L,data:L,codeFlowValue:L,definition:o(me),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(oe),hardBreakEscape:o(ae),hardBreakTrailing:o(ae),htmlFlow:o(Ee,l),htmlFlowData:L,htmlText:o(Ee,l),htmlTextData:L,image:o($e),label:l,link:o(He),listItem:o(Je),listItemValue:g,listOrdered:o(ot,h),listUnordered:o(ot),paragraph:o(et),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(be),strong:o(st),thematicBreak:o(Ue)},exit:{atxHeading:u(),atxHeadingSequence:A,autolink:u(),autolinkEmail:he,autolinkProtocol:se,blockQuote:u(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:V,characterReferenceMarkerNumeric:V,characterReferenceValue:pe,characterReference:ve,codeFenced:u(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:E,codeIndented:u(x),codeText:u(R),codeTextData:E,data:E,definition:u(),definitionDestinationString:j,definitionLabelString:y,definitionTitleString:S,emphasis:u(),hardBreakEscape:u(F),hardBreakTrailing:u(F),htmlFlow:u(K),htmlFlowData:E,htmlText:u($),htmlTextData:E,image:u(H),label:Z,labelText:J,lineEnding:T,link:u(I),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:U,resourceDestinationString:N,resourceTitleString:z,resource:P,setextHeading:u(C),setextHeadingLineSequence:_,setextHeadingText:w,strong:u(),thematicBreak:u()}};wf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(re){let Ne={type:"root",children:[]};const ee={stack:[Ne],tokenStack:[],config:n,enter:c,exit:d,buffer:l,resume:m,data:s},Ae=[];let Fe=-1;for(;++Fe<re.length;)if(re[Fe][1].type==="listOrdered"||re[Fe][1].type==="listUnordered")if(re[Fe][0]==="enter")Ae.push(Fe);else{const fe=Ae.pop();Fe=r(re,fe,Fe)}for(Fe=-1;++Fe<re.length;){const fe=n[re[Fe][0]];kf.call(fe,re[Fe][1].type)&&fe[re[Fe][1].type].call(Object.assign({sliceSerialize:re[Fe][2].sliceSerialize},ee),re[Fe][1])}if(ee.tokenStack.length>0){const fe=ee.tokenStack[ee.tokenStack.length-1];(fe[1]||Cm).call(ee,void 0,fe[0])}for(Ne.position={start:xi(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:xi(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Fe=-1;++Fe<n.transforms.length;)Ne=n.transforms[Fe](Ne)||Ne;return Ne}function r(re,Ne,ee){let Ae=Ne-1,Fe=-1,fe=!1,_e,ze,Xe,je;for(;++Ae<=ee;){const ce=re[Ae];switch(ce[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{ce[0]==="enter"?Fe++:Fe--,je=void 0;break}case"lineEndingBlank":{ce[0]==="enter"&&(_e&&!je&&!Fe&&!Xe&&(Xe=Ae),je=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:je=void 0}if(!Fe&&ce[0]==="enter"&&ce[1].type==="listItemPrefix"||Fe===-1&&ce[0]==="exit"&&(ce[1].type==="listUnordered"||ce[1].type==="listOrdered")){if(_e){let Re=Ae;for(ze=void 0;Re--;){const ge=re[Re];if(ge[1].type==="lineEnding"||ge[1].type==="lineEndingBlank"){if(ge[0]==="exit")continue;ze&&(re[ze][1].type="lineEndingBlank",fe=!0),ge[1].type="lineEnding",ze=Re}else if(!(ge[1].type==="linePrefix"||ge[1].type==="blockQuotePrefix"||ge[1].type==="blockQuotePrefixWhitespace"||ge[1].type==="blockQuoteMarker"||ge[1].type==="listItemIndent"))break}Xe&&(!ze||Xe<ze)&&(_e._spread=!0),_e.end=Object.assign({},ze?re[ze][1].start:ce[1].end),re.splice(ze||Ae,0,["exit",_e,ce[2]]),Ae++,ee++}if(ce[1].type==="listItemPrefix"){const Re={type:"listItem",_spread:!1,start:Object.assign({},ce[1].start),end:void 0};_e=Re,re.splice(Ae,0,["enter",Re,ce[2]]),Ae++,ee++,Xe=void 0,je=!0}}}return re[Ne][1]._spread=fe,ee}function o(re,Ne){return ee;function ee(Ae){c.call(this,re(Ae),Ae),Ne&&Ne.call(this,Ae)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(re,Ne,ee){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([Ne,ee||void 0]),re.position={start:xi(Ne.start),end:void 0}}function u(re){return Ne;function Ne(ee){re&&re.call(this,ee),d.call(this,ee)}}function d(re,Ne){const ee=this.stack.pop(),Ae=this.tokenStack.pop();if(Ae)Ae[0].type!==re.type&&(Ne?Ne.call(this,re,Ae[0]):(Ae[1]||Cm).call(this,re,Ae[0]));else throw new Error("Cannot close `"+re.type+"` ("+dr({start:re.start,end:re.end})+"): it’s not open");ee.position.end=xi(re.end)}function m(){return Sd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(re){if(this.data.expectingFirstListItemValue){const Ne=this.stack[this.stack.length-2];Ne.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.lang=re}function f(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.meta=re}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=re.replace(/(\r?\n|\r)$/g,"")}function y(re){const Ne=this.resume(),ee=this.stack[this.stack.length-1];ee.label=Ne,ee.identifier=Gs(this.sliceSerialize(re)).toLowerCase()}function S(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.title=re}function j(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.url=re}function A(re){const Ne=this.stack[this.stack.length-1];if(!Ne.depth){const ee=this.sliceSerialize(re).length;Ne.depth=ee}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function _(re){const Ne=this.stack[this.stack.length-1];Ne.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function C(){this.data.setextHeadingSlurpLineEnding=void 0}function L(re){const ee=this.stack[this.stack.length-1].children;let Ae=ee[ee.length-1];(!Ae||Ae.type!=="text")&&(Ae=Oe(),Ae.position={start:xi(re.start),end:void 0},ee.push(Ae)),this.stack.push(Ae)}function E(re){const Ne=this.stack.pop();Ne.value+=this.sliceSerialize(re),Ne.position.end=xi(re.end)}function T(re){const Ne=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ee=Ne.children[Ne.children.length-1];ee.position.end=xi(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Ne.type)&&(L.call(this,re),E.call(this,re))}function F(){this.data.atHardBreak=!0}function K(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=re}function $(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=re}function R(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.value=re}function I(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const Ne=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=Ne,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function H(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const Ne=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=Ne,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function J(re){const Ne=this.sliceSerialize(re),ee=this.stack[this.stack.length-2];ee.label=FC(Ne),ee.identifier=Gs(Ne).toLowerCase()}function Z(){const re=this.stack[this.stack.length-1],Ne=this.resume(),ee=this.stack[this.stack.length-1];if(this.data.inReference=!0,ee.type==="link"){const Ae=re.children;ee.children=Ae}else ee.alt=Ne}function N(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.url=re}function z(){const re=this.resume(),Ne=this.stack[this.stack.length-1];Ne.title=re}function P(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function U(re){const Ne=this.resume(),ee=this.stack[this.stack.length-1];ee.label=Ne,ee.identifier=Gs(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function V(re){this.data.characterReferenceType=re.type}function pe(re){const Ne=this.sliceSerialize(re),ee=this.data.characterReferenceType;let Ae;ee?(Ae=mf(Ne,ee==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ae=Cd(Ne);const Fe=this.stack[this.stack.length-1];Fe.value+=Ae}function ve(re){const Ne=this.stack.pop();Ne.position.end=xi(re.end)}function se(re){E.call(this,re);const Ne=this.stack[this.stack.length-1];Ne.url=this.sliceSerialize(re)}function he(re){E.call(this,re);const Ne=this.stack[this.stack.length-1];Ne.url="mailto:"+this.sliceSerialize(re)}function O(){return{type:"blockquote",children:[]}}function ue(){return{type:"code",lang:null,meta:null,value:""}}function te(){return{type:"inlineCode",value:""}}function me(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function oe(){return{type:"emphasis",children:[]}}function be(){return{type:"heading",depth:0,children:[]}}function ae(){return{type:"break"}}function Ee(){return{type:"html",value:""}}function $e(){return{type:"image",title:null,url:"",alt:null}}function He(){return{type:"link",title:null,url:"",children:[]}}function ot(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function Je(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function et(){return{type:"paragraph",children:[]}}function st(){return{type:"strong",children:[]}}function Oe(){return{type:"text",value:""}}function Ue(){return{type:"thematicBreak"}}}function xi(e){return{line:e.line,column:e.column,offset:e.offset}}function wf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?wf(e,i):qC(e,i)}}function qC(e,n){let s;for(s in n)if(kf.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 Cm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+dr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+dr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+dr({start:n.start,end:n.end})+") is still open")}function VC(e){const n=this;n.parser=s;function s(i){return BC(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function WC(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 KC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
622
- `}]}function GC(e,n){const s=n.value?n.value+`
623
- `:"",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 JC(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function YC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function QC(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Ra(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 XC(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 ZC(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Nf(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 e2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Nf(e,n);const r={src:Ra(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 t2(e,n){const s={src:Ra(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 n2(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 s2(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return Nf(e,n);const r={href:Ra(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 i2(e,n){const s={href:Ra(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 a2(e,n,s){const i=e.all(n),r=s?r2(s):Sf(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:`
624
- `}),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:`
625
- `});const d={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,d),e.applyData(n,d)}function r2(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=Sf(s[i])}return n}function Sf(e){const n=e.spread;return n??e.children.length>1}function o2(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 l2(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function c2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function d2(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function u2(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=jd(n.children[1]),u=sf(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 m2(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 h2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Em=9,_m=32;function p2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Mm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Mm(n.slice(r),r>0,!1)),o.join("")}function Mm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===Em||o===_m;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===Em||o===_m;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function f2(e,n){const s={type:"text",value:p2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function g2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const b2={blockquote:WC,break:KC,code:GC,delete:JC,emphasis:YC,footnoteReference:QC,heading:XC,html:ZC,imageReference:e2,image:t2,inlineCode:n2,linkReference:s2,link:i2,listItem:a2,list:o2,paragraph:l2,root:c2,strong:d2,table:u2,tableCell:h2,tableRow:m2,text:f2,thematicBreak:g2,toml:eo,yaml:eo,definition:eo,footnoteDefinition:eo};function eo(){}const Cf=-1,tl=0,mr=1,Ao=2,_d=3,Md=4,Ad=5,Rd=6,Ef=7,_f=8,Am=typeof self=="object"?self:globalThis,x2=(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 tl:case Cf:return s(l,r);case mr:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Ao:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case _d:return s(new Date(l),r);case Md:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Ad:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Rd:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case Ef:{const{name:c,message:u}=l;return s(new Am[c](u),r)}case _f: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 Am[o](l),r)};return i},Rm=e=>x2(new Map,e)(0),ra="",{toString:v2}={},{keys:y2}=Object,Ka=e=>{const n=typeof e;if(n!=="object"||!e)return[tl,n];const s=v2.call(e).slice(8,-1);switch(s){case"Array":return[mr,ra];case"Object":return[Ao,ra];case"Date":return[_d,ra];case"RegExp":return[Md,ra];case"Map":return[Ad,ra];case"Set":return[Rd,ra];case"DataView":return[mr,s]}return s.includes("Array")?[mr,s]:s.includes("Error")?[Ef,s]:[Ao,s]},to=([e,n])=>e===tl&&(n==="function"||n==="symbol"),j2=(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 tl:{let m=l;switch(u){case"bigint":c=_f,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([Cf],l)}return r([c,m],l)}case mr:{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 Ao:{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 y2(l))(e||!to(Ka(l[g])))&&m.push([o(g),o(l[g])]);return h}case _d:return r([c,l.toISOString()],l);case Md:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Ad:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(to(Ka(g))||to(Ka(p))))&&m.push([o(g),o(p)]);return h}case Rd:{const m=[],h=r([c,m],l);for(const g of l)(e||!to(Ka(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Tm=(e,{json:n,lossy:s}={})=>{const i=[];return j2(!(n||s),!!n,new Map,i)(e),i},Ro=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Rm(Tm(e,n)):structuredClone(e):(e,n)=>Rm(Tm(e,n));function k2(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 w2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function N2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||k2,i=e.options.footnoteBackLabel||w2,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=Ra(h.toLowerCase());let p=0;const f=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){f.length>0&&f.push({type:"text",value:" "});let y=typeof s=="string"?s:s(u,p);typeof y=="string"&&(y={type:"text",value:y}),f.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+g+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof i=="string"?i:i(u,p),className:["data-footnote-backref"]},children:Array.isArray(y)?y:[y]})}const v=m[m.length-1];if(v&&v.type==="element"&&v.tagName==="p"){const y=v.children[v.children.length-1];y&&y.type==="text"?y.value+=" ":v.children.push({type:"text",value:" "}),v.children.push(...f)}else m.push(...f);const x={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:e.wrap(m,!0)};e.patch(d,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Ro(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
626
- `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
627
- `}]}}const nl=(function(e){if(e==null)return _2;if(typeof e=="function")return sl(e);if(typeof e=="object")return Array.isArray(e)?S2(e):C2(e);if(typeof e=="string")return E2(e);throw new Error("Expected function, string, or object as test")});function S2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=nl(e[s]);return sl(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function C2(e){const n=e;return sl(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function E2(e){return sl(n);function n(s){return s&&s.type===e}}function sl(e){return n;function n(s,i,r){return!!(M2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function _2(){return!0}function M2(e){return e!==null&&typeof e=="object"&&"type"in e}const Mf=[],A2=!0,Wc=!1,R2="skip";function Af(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=nl(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=Mf,f,b,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=T2(s(u,m)),p[0]===Wc))return p;if("children"in u&&u.children){const x=u;if(x.children&&p[0]!==R2)for(b=(i?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(f=c(y,b,v)(),f[0]===Wc)return f;b=typeof f[1]=="number"?f[1]:b+l}}return p}}}function T2(e){return Array.isArray(e)?e:typeof e=="number"?[A2,e]:e==null?Mf:[e]}function Td(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),Af(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 Kc={}.hasOwnProperty,P2={};function I2(e,n){const s=n||P2,i=new Map,r=new Map,o=new Map,l={...b2,...s.handlers},c={all:d,applyData:D2,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:$2,wrap:z2};return Td(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(Kc.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=Ro(v);return x.children=c.all(m),x}return Ro(m)}return(c.options.unknownHandler||L2)(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=Pm(f.value)),!Array.isArray(f)&&f.type==="element")){const b=f.children[0];b&&b.type==="text"&&(b.value=Pm(b.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function $2(e,n){e.position&&(n.position=w0(e))}function D2(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,Ro(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function L2(e,n){const s=n.data||{},i="value"in n&&!(Kc.call(s,"hProperties")||Kc.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 z2(e,n){const s=[];let i=-1;for(n&&s.push({type:"text",value:`
628
- `});++i<e.length;)i&&s.push({type:"text",value:`
629
- `}),s.push(e[i]);return n&&e.length>0&&s.push({type:"text",value:`
630
- `}),s}function Pm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Im(e,n){const s=I2(e,n),i=s.one(e,void 0),r=N2(s),o=Array.isArray(i)?{type:"root",children:i}:i||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
631
- `},r),o}function O2(e,n){return e&&"run"in e?async function(s,i){const r=Im(s,{file:i,...n});await e.run(r,i)}:function(s,i){return Im(s,{file:i,...e||n})}}function $m(e){if(e)throw e}var zl,Dm;function F2(){if(Dm)return zl;Dm=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 zl=function u(){var d,m,h,g,p,f,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(d=arguments[v],d!=null)for(m in d)h=c(b,m),g=c(d,m),b!==g&&(y&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(b,{name:m,newValue:u(y,f,g)})):typeof g<"u"&&l(b,{name:m,newValue:g}));return b},zl}var U2=F2();const Ol=Gh(U2);function Gc(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 B2(){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?H2(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 H2(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 ti={basename:q2,dirname:V2,extname:W2,join:K2,sep:"/"};function q2(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Dr(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 V2(e){if(Dr(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 W2(e){Dr(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 K2(...e){let n=-1,s;for(;++n<e.length;)Dr(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":G2(s)}function G2(e){Dr(e);const n=e.codePointAt(0)===47;let s=J2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function J2(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 Dr(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const Y2={cwd:Q2};function Q2(){return"/"}function Jc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function X2(e){if(typeof e=="string")e=new URL(e);else if(!Jc(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 Z2(e)}function Z2(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 Fl=["history","path","basename","stem","extname","dirname"];class Rf{constructor(n){let s;n?Jc(n)?s={path:n}:typeof n=="string"||eE(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":Y2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Fl.length;){const o=Fl[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)Fl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?ti.basename(this.path):void 0}set basename(n){Bl(n,"basename"),Ul(n,"basename"),this.path=ti.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?ti.dirname(this.path):void 0}set dirname(n){Lm(this.basename,"dirname"),this.path=ti.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?ti.extname(this.path):void 0}set extname(n){if(Ul(n,"extname"),Lm(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=ti.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Jc(n)&&(n=X2(n)),Bl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?ti.basename(this.path,this.extname):void 0}set stem(n){Bl(n,"stem"),Ul(n,"stem"),this.path=ti.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 os(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 Ul(e,n){if(e&&e.includes(ti.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+ti.sep+"`")}function Bl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Lm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function eE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const tE=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),nE={}.hasOwnProperty;class Pd extends tE{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=B2()}copy(){const n=new Pd;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data(Ol(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Vl("data",this.frozen),this.namespace[n]=s,this):nE.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Vl("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=no(n),i=this.parser||this.Parser;return Hl("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Hl("process",this.parser||this.Parser),ql("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=no(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);aE(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(),Hl("processSync",this.parser||this.Parser),ql("processSync",this.compiler||this.Compiler),this.process(n,r),Om("processSync","process",s),i;function r(o,l){s=!0,$m(o),i=l}}run(n,s,i){zm(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=no(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),Om("runSync","run",i),r;function o(l,c){$m(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=no(s),r=this.compiler||this.Compiler;return ql("stringify",r),zm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Vl("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=Ol(!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];Gc(b)&&Gc(p)&&(p=Ol(!0,b,p)),i[g]=[d,p,...f]}}}}const sE=new Pd().freeze();function Hl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ql(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Vl(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 zm(e){if(!Gc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Om(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function no(e){return iE(e)?e:new Rf(e)}function iE(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function aE(e){return typeof e=="string"||rE(e)}function rE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const oE="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Fm=[],Um={allowDangerousHtml:!0},lE=/^(https?|ircs?|mailto|xmpp)$/i,cE=[{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 pi(e){const n=dE(e),s=uE(e);return mE(n.runSync(n.parse(s),s),e)}function dE(e){const n=e.rehypePlugins||Fm,s=e.remarkPlugins||Fm,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Um}:Um;return sE().use(VC).use(s).use(O2,i).use(n)}function uE(e){const n=e.children||"",s=new Rf;return typeof n=="string"&&(s.value=n),s}function mE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||hE;for(const m of cE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+oE+m.id,void 0);return Td(e,d),_0(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 $l)if(Object.hasOwn($l,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],b=$l[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 hE(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||lE.test(e.slice(0,n))?e:""}function Bm(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 pE(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function fE(e,n,s){const r=nl((s||{}).ignore||[]),o=gE(n);let l=-1;for(;++l<o.length;)Af(e,"text",c);function c(d,m){let h=-1,g;for(;++h<m.length;){const p=m[h],f=g?g.children:void 0;if(r(p,f?f.indexOf(p):void 0,g))return;g=p}if(g)return u(d,m)}function u(d,m){const h=m[m.length-1],g=o[l][0],p=o[l][1];let f=0;const v=h.children.indexOf(d);let x=!1,y=[];g.lastIndex=0;let S=g.exec(d.value);for(;S;){const j=S.index,A={index:S.index,input:S.input,stack:[...m,d]};let w=p(...S,A);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=j+1:(f!==j&&y.push({type:"text",value:d.value.slice(f,j)}),Array.isArray(w)?y.push(...w):w&&y.push(w),f=j+S[0].length,x=!0),!g.global)break;S=g.exec(d.value)}return x?(f<d.value.length&&y.push({type:"text",value:d.value.slice(f)}),h.children.splice(v,1,...y)):y=[d],v+y.length}}function gE(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([bE(r[0]),xE(r[1])])}return n}function bE(e){return typeof e=="string"?new RegExp(pE(e),"g"):e}function xE(e){return typeof e=="function"?e:function(){return e}}const Wl="phrasing",Kl=["autolink","link","image","label"];function vE(){return{transforms:[CE],enter:{literalAutolink:jE,literalAutolinkEmail:Gl,literalAutolinkHttp:Gl,literalAutolinkWww:Gl},exit:{literalAutolink:SE,literalAutolinkEmail:NE,literalAutolinkHttp:kE,literalAutolinkWww:wE}}}function yE(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Wl,notInConstruct:Kl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Wl,notInConstruct:Kl},{character:":",before:"[ps]",after:"\\/",inConstruct:Wl,notInConstruct:Kl}]}}function jE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Gl(e){this.config.enter.autolinkProtocol.call(this,e)}function kE(e){this.config.exit.autolinkProtocol.call(this,e)}function wE(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 NE(e){this.config.exit.autolinkEmail.call(this,e)}function SE(e){this.exit(e)}function CE(e){fE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,EE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,_E]],{ignore:["link","linkReference"]})}function EE(e,n,s,i,r){let o="";if(!Tf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!ME(s)))return!1;const l=AE(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 _E(e,n,s,i){return!Tf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function ME(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 AE(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=Bm(e,"(");let o=Bm(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 Tf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||qi(s)||Zo(s))&&(!n||s!==47)}Pf.peek=OE;function RE(){this.buffer()}function TE(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function PE(){this.buffer()}function IE(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function $E(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Gs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function DE(e){this.exit(e)}function LE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Gs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function zE(e){this.exit(e)}function OE(){return"["}function Pf(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 FE(){return{enter:{gfmFootnoteCallString:RE,gfmFootnoteCall:TE,gfmFootnoteDefinitionLabelString:PE,gfmFootnoteDefinition:IE},exit:{gfmFootnoteCallString:$E,gfmFootnoteCall:DE,gfmFootnoteDefinitionLabelString:LE,gfmFootnoteDefinition:zE}}}function UE(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Pf},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?`
632
- `:" ")+o.indentLines(o.containerFlow(i,c.current()),n?If:BE))),d(),u}}function BE(e,n,s){return n===0?e:If(e,n,s)}function If(e,n,s){return(s?"":" ")+e}const HE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];$f.peek=GE;function qE(){return{canContainEols:["delete"],enter:{strikethrough:WE},exit:{strikethrough:KE}}}function VE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:HE}],handlers:{delete:$f}}}function WE(e){this.enter({type:"delete",children:[]},e)}function KE(e){this.exit(e)}function $f(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 GE(){return"~"}function JE(e){return e.length}function YE(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||JE,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>d&&(d=e[m].length);++x<e[m].length;){const y=QE(e[m][x]);if(s.alignDelimiters!==!1){const S=r(y);v[x]=S,(u[x]===void 0||S>u[x])&&(u[x]=S)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=Hm(i[h]);else{const b=Hm(i);for(;++h<d;)o[h]=b}h=-1;const g=[],p=[];for(;++h<d;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-x.length);const S=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>u[h]&&(u[h]=y),p[h]=y),g[h]=S}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<d;){const y=b[h]||"";let S="",j="";if(s.alignDelimiters!==!1){const A=u[h]-(v[h]||0),w=o[h];w===114?S=" ".repeat(A):w===99?A%2?(S=" ".repeat(A/2+.5),j=" ".repeat(A/2-.5)):(S=" ".repeat(A/2),j=S):j=" ".repeat(A)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(S),x.push(y),s.alignDelimiters!==!1&&x.push(j),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(`
633
- `)}function QE(e){return e==null?"":String(e)}function Hm(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 XE(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()),ZE);return r(),l}function ZE(e,n,s){return">"+(s?"":" ")+e}function e_(e,n){return qm(e,n.inConstruct,!0)&&!qm(e,n.notInConstruct,!1)}function qm(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 Vm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
634
- `&&e_(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
635
- `}function t_(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 n_(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 s_(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 i_(e,n,s,i){const r=s_(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(n_(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,a_);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(t_(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:`
636
- `,encode:["`"],...c.current()})),h()}return m+=c.move(`
637
- `),o&&(m+=c.move(o+`
638
- `)),m+=c.move(u),d(),m}function a_(e,n,s){return(s?"":" ")+e}function Id(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 r_(e,n,s,i){const r=Id(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?" ":`
639
- `,...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 o_(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 kr(e){return"&#x"+e.toString(16).toUpperCase()+";"}function To(e,n,s){const i=va(e),r=va(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}}Df.peek=l_;function Df(e,n,s,i){const r=o_(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=To(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=kr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=To(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+kr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function l_(e,n,s){return s.options.emphasis||"*"}function c_(e,n){let s=!1;return Td(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Wc}),!!((!e.depth||e.depth<3)&&Sd(e)&&(n.options.setext||s))}function d_(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(c_(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),g=s.containerPhrasing(e,{...o.current(),before:`
640
- `,after:`
641
- `});return h(),m(),g+`
642
- `+(r===1?"=":"-").repeat(g.length-(Math.max(g.lastIndexOf("\r"),g.lastIndexOf(`
643
- `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
644
- `,...o.current()});return/^[\t ]/.test(d)&&(d=kr(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Lf.peek=u_;function Lf(e){return e.value||""}function u_(){return"<"}zf.peek=m_;function zf(e,n,s,i){const r=Id(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 m_(){return"!"}Of.peek=h_;function Of(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 h_(){return"!"}Ff.peek=p_;function Ff(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 p_(){return"`"}function Uf(e,n){const s=Sd(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))}Bf.peek=f_;function Bf(e,n,s,i){const r=Id(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if(Uf(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 f_(e,n,s){return Uf(e,s)?"<":"["}Hf.peek=g_;function Hf(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 g_(){return"["}function $d(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 b_(e){const n=$d(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 x_(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 qf(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 v_(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?x_(s):$d(s);const c=e.ordered?l==="."?")":".":b_(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),qf(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 y_(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 j_(e,n,s,i){const r=y_(s);let o=s.bulletCurrent||$d(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 k_(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const w_=nl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function N_(e,n,s,i){return(e.children.some(function(l){return w_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function S_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Vf.peek=C_;function Vf(e,n,s,i){const r=S_(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=To(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=kr(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=To(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+kr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function C_(e,n,s){return s.options.strong||"*"}function E_(e,n,s,i){return s.safe(e.value,i)}function __(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 M_(e,n,s){const i=(qf(s)+(s.options.ruleSpaces?" ":"")).repeat(__(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Wf={blockquote:XE,break:Vm,code:i_,definition:r_,emphasis:Df,hardBreak:Vm,heading:d_,html:Lf,image:zf,imageReference:Of,inlineCode:Ff,link:Bf,linkReference:Hf,list:v_,listItem:j_,paragraph:k_,root:N_,strong:Vf,text:E_,thematicBreak:M_};function A_(){return{enter:{table:R_,tableData:Wm,tableHeader:Wm,tableRow:P_},exit:{codeText:I_,table:T_,tableData:Jl,tableHeader:Jl,tableRow:Jl}}}function R_(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 T_(e){this.exit(e),this.data.inTable=void 0}function P_(e){this.enter({type:"tableRow",children:[]},e)}function Jl(e){this.exit(e)}function Wm(e){this.enter({type:"tableCell",children:[]},e)}function I_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,$_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function $_(e,n){return n==="|"?n:e}function D_(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
645
- `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,f,b,v){return d(m(p,b,v),p.align)}function c(p,f,b,v){const x=h(p,b,v),y=d([x]);return y.slice(0,y.indexOf(`
646
- `))}function u(p,f,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),S=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),S}function d(p,f){return YE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,b){const v=p.children;let x=-1;const y=[],S=f.enter("table");for(;++x<v.length;)y[x]=h(v[x],f,b);return S(),y}function h(p,f,b){const v=p.children;let x=-1;const y=[],S=f.enter("tableRow");for(;++x<v.length;)y[x]=u(v[x],p,f,b);return S(),y}function g(p,f,b){let v=Wf.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function L_(){return{exit:{taskListCheckValueChecked:Km,taskListCheckValueUnchecked:Km,paragraph:O_}}}function z_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:F_}}}function Km(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function O_(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 F_(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=Wf.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 U_(){return[vE(),FE(),qE(),A_(),L_()]}function B_(e){return{extensions:[yE(),UE(e),VE(),D_(e),z_()]}}const H_={tokenize:J_,partial:!0},Kf={tokenize:Y_,partial:!0},Gf={tokenize:Q_,partial:!0},Jf={tokenize:X_,partial:!0},q_={tokenize:Z_,partial:!0},Yf={name:"wwwAutolink",tokenize:K_,previous:Xf},Qf={name:"protocolAutolink",tokenize:G_,previous:Zf},gi={name:"emailAutolink",tokenize:W_,previous:eg},oi={};function V_(){return{text:oi}}let Pi=48;for(;Pi<123;)oi[Pi]=gi,Pi++,Pi===58?Pi=65:Pi===91&&(Pi=97);oi[43]=gi;oi[45]=gi;oi[46]=gi;oi[95]=gi;oi[72]=[gi,Qf];oi[104]=[gi,Qf];oi[87]=[gi,Yf];oi[119]=[gi,Yf];function W_(e,n,s){const i=this;let r,o;return l;function l(h){return!Yc(h)||!eg.call(i,i.previous)||Dd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Yc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(q_,m,d)(h):h===45||h===95||as(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&&ms(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function K_(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Xf.call(i,i.previous)||Dd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(H_,e.attempt(Kf,e.attempt(Gf,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function G_(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Zf.call(i,i.previous)&&!Dd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(ms(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||Mo(h)||gn(h)||qi(h)||Zo(h)?s(h):e.attempt(Kf,e.attempt(Gf,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function J_(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 Y_(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Jf,u,c)(d):d===null||gn(d)||qi(d)||d!==45&&Zo(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 Q_(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(Jf,n,o)(l):l===null||gn(l)||qi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function X_(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||gn(c)||qi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||gn(c)||qi(c)?n(c):i(c)}function o(c){return ms(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):ms(c)?(e.consume(c),l):s(c)}}function Z_(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return as(o)?s(o):n(o)}}function Xf(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||gn(e)}function Zf(e){return!ms(e)}function eg(e){return!(e===47||Yc(e))}function Yc(e){return e===43||e===45||e===46||e===95||as(e)}function Dd(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 eM={tokenize:lM,partial:!0};function tM(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:aM,continuation:{tokenize:rM},exit:oM}},text:{91:{name:"gfmFootnoteCall",tokenize:iM},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:nM,resolveTo:sM}}}}function nM(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=Gs(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 sM(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 iM(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||gn(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Gs(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return gn(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 aM(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||gn(f))return s(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Gs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return gn(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),tn(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function rM(e,n,s){return e.check($r,n,e.attempt(eM,n,s))}function oM(e){e.exit("gfmFootnoteDefinition")}function lM(e,n,s){const i=this;return tn(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 cM(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&&Cs(g,g.length,0,el(p,l.slice(d+1,u),c)),Cs(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),Cs(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=va(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=va(f);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(f)}}}class dM{constructor(){this.map=[]}add(n,s,i){uM(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 uM(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 mM(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 hM(){return{flow:{null:{name:"table",tokenize:pM,resolveAll:fM}}}}function pM(e,n,s){const i=this;let r=0,o=0,l;return c;function c(E){let T=i.events.length-1;for(;T>-1;){const $=i.events[T][1].type;if($==="lineEnding"||$==="linePrefix")T--;else break}const F=T>-1?i.events[T][1].type:null,K=F==="tableHead"||F==="tableRow"?w:u;return K===w&&i.parser.lazy[i.now().line]?s(E):K(E)}function u(E){return e.enter("tableHead"),e.enter("tableRow"),d(E)}function d(E){return E===124||(l=!0,o+=1),m(E)}function m(E){return E===null?s(E):Et(E)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):Gt(E)?tn(e,m,"whitespace")(E):(o+=1,l&&(l=!1,r+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(E)))}function h(E){return E===null||E===124||gn(E)?(e.exit("data"),m(E)):(e.consume(E),E===92?g:h)}function g(E){return E===92||E===124?(e.consume(E),h):h(E)}function p(E){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(E):(e.enter("tableDelimiterRow"),l=!1,Gt(E)?tn(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):f(E))}function f(E){return E===45||E===58?v(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),b):A(E)}function b(E){return Gt(E)?tn(e,v,"whitespace")(E):v(E)}function v(E){return E===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),x):E===45?(o+=1,x(E)):E===null||Et(E)?j(E):A(E)}function x(E){return E===45?(e.enter("tableDelimiterFiller"),y(E)):A(E)}function y(E){return E===45?(e.consume(E),y):E===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(E))}function S(E){return Gt(E)?tn(e,j,"whitespace")(E):j(E)}function j(E){return E===124?f(E):E===null||Et(E)?!l||r!==o?A(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):A(E)}function A(E){return s(E)}function w(E){return e.enter("tableRow"),_(E)}function _(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),_):E===null||Et(E)?(e.exit("tableRow"),n(E)):Gt(E)?tn(e,_,"whitespace")(E):(e.enter("data"),C(E))}function C(E){return E===null||E===124||gn(E)?(e.exit("data"),_(E)):(e.consume(E),E===92?L:C)}function L(E){return E===92||E===124?(e.consume(E),C):C(E)}}function fM(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 dM;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Gm(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=so(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=so(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=so(g,n,o,r,s,h)):l[1]!==0&&(h=so(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Gm(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=mM(n.events,s))}return e}function so(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},da(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=da(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=da(n.events,s[2]),m=da(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({},da(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Gm(e,n,s,i,r){const o=[],l=da(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 da(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const gM={name:"tasklistCheck",tokenize:xM};function bM(){return{text:{91:gM}}}function xM(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 gn(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 Et(u)?n(u):Gt(u)?e.check({tokenize:vM},n,s)(u):s(u)}}function vM(e,n,s){return tn(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function yM(e){return uf([V_(),tM(),cM(e),hM(),bM()])}const jM={};function fi(e){const n=this,s=e||jM,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(yM(s)),o.push(U_()),l.push(B_(s))}const Jm=500,Ym=100;function Yl(e){return e.length>Jm?e.slice(-Jm):e}function tg(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),y=a.useRef(n),S=a.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const _=b.current,C=++S.current;f.current=!1;const L=e,E=s;async function T(){if(!L)return;l(!0),g(!1);try{const K=await Kd(L,E,{limit:Ym});if(f.current||b.current!==_||S.current!==C)return;r(Yl(K.entries)),u(K.hasMore),m(K.total)}catch{if(f.current||b.current!==_||S.current!==C)return;r([]),u(!1),m(null)}finally{!f.current&&b.current===_&&S.current===C&&l(!1)}const F=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=Qs(`/api/tasks/${L}/logs/stream${F}`,{events:{"agent:log":K=>{if(!(f.current||b.current!==_))try{const $=JSON.parse(K.data);r(R=>Yl([...R,$])),m(R=>R!==null?R+1:null)}catch{}}}})}return T(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const A=a.useCallback(async()=>{if(!e||h)return;const _=b.current,C=i.length,L=e;g(!0);try{const E=await Kd(L,s,{limit:Ym,offset:C});if(f.current||b.current!==_)return;r(T=>{const F=[...E.entries,...T];return Yl(F)}),u(E.hasMore),m(E.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:w,loadMore:A,hasMore:c,total:d,loadingMore:h}}function kM(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 Qm={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})},ng=50,wM={triage:"Plan"};function Xm(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=ng}function Qc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function NM(e){const n=new Map;return e.map(s=>{const i=Qc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function SM(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function CM(e,n){return e.agent?SM(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function EM(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${Qc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=CM(r,l);if(r.type==="text"||r.type==="thinking"){const u=[r];let d=i+1;for(;d<e.length;){const h=e[d];if(h.type!==r.type||h.agent!==r.agent)break;u.push(h),d+=1}const m=n[d-1]??`${Qc(e[d-1])}|fallback`;s.push({kind:r.type,entries:u,key:`${o}->${m}`,showBadge:c}),i=d-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function _M({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),[y,S]=a.useState(!1),[j,A]=a.useState(!0),w=a.useMemo(()=>NM(e),[e]),_=a.useMemo(()=>EM(e,w),[e,w]);a.useLayoutEffect(()=>{const R=d.current;if(!R)return;const I=e.length,H=m.current,J=h.current||R.scrollHeight,Z=w[0]??null,N=w[w.length-1]??null,z=g.current!==Z,P=p.current!==N;if(I>H)if(H===0)R.scrollTop=R.scrollHeight;else{const k=J-(R.scrollTop+R.clientHeight)<=ng,U=P&&!z,V=z&&!P;if(U&&k&&(R.scrollTop=R.scrollHeight),V){const pe=R.scrollHeight-J;pe>0&&(R.scrollTop+=pe)}}m.current=I,h.current=R.scrollHeight,g.current=Z,p.current=N,A(Xm(R))},[e,w]);const C=a.useCallback(()=>{const R=d.current;R&&A(Xm(R))},[]),L=a.useCallback(()=>{const R=d.current;R&&(R.scrollTop=R.scrollHeight,A(!0))},[]),E=a.useCallback(R=>{R.key==="Escape"&&v&&x(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",E),()=>{document.removeEventListener("keydown",E)}},[v,E]);const T=s?.provider&&s?.modelId,F=i?.provider&&i?.modelId,K=r?.provider&&r?.modelId,$=a.useMemo(()=>{const R=[];return T&&R.push({role:"Executor",provider:s.provider,modelId:s.modelId}),F&&R.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),K&&R.push({role:"Planning",provider:r.provider,modelId:r.modelId}),R},[T,s,F,i,K,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",{className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[$.map(R=>t.jsx(Ln,{provider:R.provider,size:"sm"},`${R.role}-${R.provider}-${R.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>S(R=>!R),"aria-label":y?"Collapse model details":"Expand model details","aria-expanded":y,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:y?t.jsx(Yt,{size:14}):t.jsx(kn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(R=>!R),"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(R=>!R),"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(Er,{size:14}):t.jsx(Ho,{size:14})})]}),y&&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?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Ln,{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:"}),F?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Ln,{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:"}),K?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Ln,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),t.jsxs("div",{ref:d,className:"agent-log-viewer-scroll",onScroll:C,children:[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(rt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),_.map(R=>{const I=R.kind==="single"?R.entry:R.entries[0],H=R.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:kM(I.timestamp)}):null,J=R.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",wM[I.agent]??I.agent,"]"]}),H]}):null;if(R.kind==="single"){const{entry:N}=R;if(N.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[J,"⚡ ",N.text,N.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",N.detail]})]},R.key);if(N.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[J,"✓ ",N.text,N.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",N.detail]})]},R.key);if(N.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[J,"✗ ",N.text,N.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",N.detail]})]},R.key)}const Z=R.kind==="single"?I.text:R.entries.map(N=>N.text).join("");return R.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[J,f?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:Qm,children:Z})}):Z]},R.key):t.jsxs("div",{className:"agent-log-text",children:[J,f?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:Qm,children:Z})}):Z]},R.key)}),!j&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:L,"data-testid":"agent-log-return-to-live",children:[t.jsx(Yt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ya(e){return e??void 0}function io(e){return{provider:ya(e.modelProvider),modelId:ya(e.modelId)}}function ao(e){return{provider:ya(e.validatorModelProvider),modelId:ya(e.validatorModelId)}}function ro(e){return{provider:ya(e.planningModelProvider),modelId:ya(e.planningModelId)}}function MM(e,n){return Mp(e,n)}function AM(e,n){return Ap(e,n)}function RM(e,n){return Rp(e,n)}function Ql(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 Xl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Zl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function TM(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 PM({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(()=>io(e)),[v,x]=a.useState(()=>io(e)),[y,S]=a.useState(()=>ao(e)),[j,A]=a.useState(()=>ao(e)),[w,_]=a.useState(()=>ro(e)),[C,L]=a.useState(()=>ro(e)),[E,T]=a.useState(()=>e.thinkingLevel??null),[F,K]=a.useState(()=>e.thinkingLevel??null),[$,R]=a.useState(null),I=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),ps().then(oe=>{o(oe.models),c(oe.favoriteProviders),d(oe.favoriteModels)}).catch(oe=>{p(oe.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const H=a.useCallback(async oe=>{const be=l,Ee=be.includes(oe)?be.filter($e=>$e!==oe):[oe,...be];c(Ee);try{await fn({favoriteProviders:Ee,favoriteModels:u})}catch{c(be),n("Failed to update favorites","error")}},[l,u,n]),J=a.useCallback(async oe=>{const be=u,Ee=be.includes(oe)?be.filter($e=>$e!==oe):[oe,...be];d(Ee);try{await fn({favoriteProviders:l,favoriteModels:Ee})}catch{d(be),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{I.current=e.id;const oe=io(e),be=ao(e),ae=ro(e);b(oe),x(oe),S(be),A(be),_(ae),L(ae);const Ee=e.thinkingLevel??null;T(Ee),K(Ee),R(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const Z=a.useMemo(()=>Xl(f),[f]),N=a.useMemo(()=>Xl(y),[y]),z=a.useMemo(()=>Xl(w),[w]),P=a.useMemo(()=>MM(e,i),[e,i]),k=a.useMemo(()=>AM(e,i),[e,i]),U=a.useMemo(()=>RM(e,i),[e,i]),V=$!==null,pe=a.useCallback(async(oe,be)=>{const ae=e.id,Ee=v,$e=j,He=C;R(oe);try{const ot=s?oe==="executor"?{modelProvider:be.provider??null,modelId:be.modelId??null}:oe==="validator"?{validatorModelProvider:be.provider??null,validatorModelId:be.modelId??null}:{planningModelProvider:be.provider??null,planningModelId:be.modelId??null}:{modelProvider:(oe==="executor"?be:v).provider??null,modelId:(oe==="executor"?be:v).modelId??null,validatorModelProvider:(oe==="validator"?be:j).provider??null,validatorModelId:(oe==="validator"?be:j).modelId??null,planningModelProvider:(oe==="planning"?be:C).provider??null,planningModelId:(oe==="planning"?be:C).modelId??null},Je=await si(ae,ot);if(I.current!==ae)return;const et=io(Je),st=ao(Je),Oe=ro(Je);x(et),b(et),A(st),S(st),L(Oe),_(Oe),s?.(Je),n(TM(oe,{executor:et,validator:st,planning:Oe}[oe]),"success")}catch(ot){if(I.current!==ae)return;oe==="executor"?b(Ee):oe==="validator"?S($e):_(He),n(ke(ot)||"Failed to save model settings","error")}finally{I.current===ae&&R(null)}},[e.id,v,j,C,n,s]),ve=a.useCallback(oe=>{const be=Ql(oe);b(be),!Zl(be,v)&&pe("executor",be)},[v,pe]),se=a.useCallback(oe=>{const be=Ql(oe);S(be),!Zl(be,j)&&pe("validator",be)},[j,pe]),he=a.useCallback(oe=>{const be=Ql(oe);_(be),!Zl(be,C)&&pe("planning",be)},[C,pe]),O=a.useCallback(async oe=>{const be=e.id,ae=F,Ee=oe===""?null:oe;T(Ee),R("thinking");try{const $e=await si(be,{thinkingLevel:Ee});if(I.current!==be)return;const He=$e.thinkingLevel??null;K(He),T(He),s?.($e);const ot=i?.defaultThinkingLevel??"off";n(He===null?`Thinking level set to default (${ot})`:`Thinking level set to ${He}`,"success")}catch($e){if(I.current!==be)return;T(ae),n(ke($e)||"Failed to save thinking level","error")}finally{I.current===be&&R(null)}},[e.id,F,i,n,s]),ue=!v.provider&&!v.modelId,te=!j.provider&&!j.modelId,me=!C.provider&&!C.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),ps().then(oe=>{o(oe.models),c(oe.favoriteProviders),d(oe.favoriteModels)}).catch(oe=>p(oe.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:ue?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",P.provider&&P.modelId?` (${P.provider}/${P.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Ln,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(Kn,{id:"executorModel",label:"Executor Model",value:Z,onChange:ve,models:r,disabled:V,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:H,favoriteModels:u,onToggleModelFavorite:J}),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:te?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",k.provider&&k.modelId?` (${k.provider}/${k.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[j.provider&&t.jsx(Ln,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(Kn,{id:"validatorModel",label:"Reviewer Model",value:N,onChange:se,models:r,disabled:V,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:H,favoriteModels:u,onToggleModelFavorite:J}),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:me?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",U.provider&&U.modelId?` (${U.provider}/${U.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[C.provider&&t.jsx(Ln,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx(Kn,{id:"planningModel",label:"Planning Model",value:z,onChange:he,models:r,disabled:V,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:H,favoriteModels:u,onToggleModelFavorite:J}),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:F===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:F})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:oe=>O(oe.target.value),disabled:V,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:ue&&te&&me&&F===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const IM={open:t.jsx(Oo,{size:16}),closed:t.jsx(Sr,{size:16}),merged:t.jsx(tp,{size:16})};function $M({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[S,j]=a.useState(null),A=a.useCallback(async()=>{if(h.trim()){v(!0);try{const L=await _y(e,{title:h.trim(),body:p.trim()||void 0},n);l(L),m(!1),g(""),f(""),u(`Created PR #${L.number}`,"success")}catch(L){u(ke(L)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),w=a.useCallback(async()=>{if(s){y(!0);try{const L=await My(e,n);j(L),c(L.prInfo),u("PR status refreshed","success")}catch(L){u(ke(L)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ns,{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(Ns,{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(Ns,{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:L=>g(L.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:L=>f(L.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:A,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ns,{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(ln,{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 _=IM[s.status]??t.jsx(Oo,{size:16}),C=S?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Ns,{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:_}),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:w,disabled:x,title:"Refresh PR status",children:t.jsx(Pn,{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:C.length>0?`Waiting for: ${C.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(ji,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Nb,{size:14}),"View on GitHub"]})]})]})]})}const Zm=2e3;function DM(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function LM(e){return e==="agent"||e==="system"}function zM({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((_,C)=>new Date(C.createdAt).getTime()-new Date(_.createdAt).getTime()),[e.comments]),v=o.length>Zm;async function x(){const _=o.trim();if(_){g(!0);try{const C=await iy(e.id,_,r);l(""),n?.(C),s("Comment added","success")}catch(C){s(ke(C)||"Failed to add comment","error")}finally{g(!1)}}}async function y(_){const C=d.trim();if(C){g(!0);try{const L=await Zv(e.id,_,C,r);u(null),m(""),n?.(L),s("Comment updated","success")}catch(L){s(ke(L)||"Failed to update comment","error")}finally{g(!1)}}}async function S(_){f(_);try{const C=await ey(e.id,_,r);n?.(C),s("Comment deleted","success")}catch(C){s(ke(C)||"Failed to delete comment","error")}finally{f(null)}}function j(_){_.key==="Enter"&&(_.ctrlKey||_.metaKey)&&(_.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(_=>{const C=_.author===i,L=c===_.id,E=LM(_.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:[E?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:_.author}),t.jsx("span",{className:"detail-log-timestamp",children:DM(_)})]}),C&&!L?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(_.id),m(_.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(_.id),disabled:p===_.id,children:p===_.id?"Deleting…":"Delete"})]}):null]}),L?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:T=>m(T.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(_.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:_.text})]},_.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:_=>l(_.target.value),onKeyDown:j,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",Zm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function OM(e){return e?e.slice(0,7):"Unknown"}function FM({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:OM(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 sg(e){return e.split(`
647
- `).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}
648
- `},i):t.jsx(xo.Fragment,{children:`${s}
649
- `},i)})}function UM(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function BM({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),g=a.useRef(null);ri(g,e,"fusion:changes-diff-modal-size");const p=Si(l);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const f=a.useCallback(()=>{d(y=>y!==null&&y>0?y-1:y)},[]),b=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),f()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),b())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,f,b]),!e)return null;const v=u!==null?s[u]:null,x=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:g,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Ws,{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:f,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(zo,{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:b,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(kn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(jo,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Pn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[x&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Cr,{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((y,S)=>t.jsxs("button",{className:`changes-diff-file-item ${u===S?"selected":""}`,onClick:()=>d(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:UM(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?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:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.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:sg(v.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(Ws,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function ig(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function ec(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Cr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ws,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(i=>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:ig("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function HM({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,b]=a.useState(new Set),[v,x]=a.useState(null),[y,S]=a.useState(!0),[j,A]=a.useState(!1),w=i==="done",_=w&&!!r?.commitSha,C=i==="in-progress"||i==="in-review"||_,L=a.useCallback(async()=>{if(!C){h(!1);return}try{h(!0),p(null);const $=await jp(e,void 0,s),R=$.files.map(I=>({path:I.path,status:I.status,additions:I.additions,deletions:I.deletions,patch:I.patch}));c(R),d($.stats),R.length>0&&(b(new Set([R[0].path])),x(0))}catch($){p(ke($)||"Failed to load diff")}finally{h(!1)}},[e,s,C]);a.useEffect(()=>{L()},[L]);const E=$=>{b(R=>{const I=new Set(R);if(I.has($))I.delete($);else{I.add($);const H=l.findIndex(J=>J.path===$);H!==-1&&x(H)}return I})},T=$=>{if($<0||$>=l.length)return;const R=l[$].path;b(new Set([R])),x($)},F=v!==null&&v>0,K=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(hs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!w&&!n)return o&&o.length>0?ec(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ws,{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(w&&!_){if(o&&o.length>0)return ec(o,!0,r);const $=r?.filesChanged,R=r?.insertions,I=r?.deletions,H=$!=null||R!=null||I!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ws,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:H?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${R??0} additions, -${I??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?ec(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ws,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:w?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Cr,{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(Ws,{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:()=>F&&T(v-1),disabled:!F,title:"Previous file","aria-label":"Previous file",children:t.jsx(zo,{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:()=>K&&T(v+1),disabled:!K,title:"Next file","aria-label":"Next file",children:t.jsx(kn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S($=>!$),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(jo,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:L,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>A(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Ho,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const R=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${R?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>E($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:R?t.jsx(Yt,{size:14}):t.jsx(kn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:ig($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:t.jsx("bdo",{dir:"ltr",children:$.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),R&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:sg($.patch)})})})]},$.path)})}),t.jsx(BM,{isOpen:j,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>A(!1),onRefresh:L})]})}function eh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function qM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function pL(e,n){const s=qM(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}function VM(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const th=["image/png","image/jpeg","image/gif","image/webp"];function WM(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 ag({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:u,nodeOptions:d,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:g,onPriorityChange:p,executorModel:f,onExecutorModelChange:b,validatorModel:v,onValidatorModelChange:x,planningModel:y,onPlanningModelChange:S,thinkingLevel:j,onThinkingLevelChange:A,presetMode:w,onPresetModeChange:_,selectedPresetId:C,onSelectedPresetIdChange:L,selectedWorkflowSteps:E,onWorkflowStepsChange:T,onDefaultOnApplied:F,pendingImages:K,onImagesChange:$,tasks:R,projectId:I,disabled:H=!1,addToast:J,isActive:Z=!0,onAutoSaveDescription:N,onPlanningMode:z,onSubtaskBreakdown:P,onClose:k,renderBelowPrimary:U,renderBelowModelConfiguration:V,hideDependencies:pe,autoExpandMoreOptionsOnSelection:ve=!0,reviewLevel:se,onReviewLevelChange:he,executionMode:O,onExecutionModeChange:ue}){const te=(pe?!1:o.length>0)||K.length>0||E.length>0||w!=="default"||(g??Ss)!==Ss||f!==""||v!==""||(y||"")!==""||(j||"")!==""||se!==void 0||O==="fast"||(c||"")!=="",[me,oe]=a.useState(!1),[be,ae]=a.useState(ve?te:!1),[Ee,$e]=a.useState(""),[He,ot]=a.useState([]),[Je,et]=a.useState([]),[st,Oe]=a.useState([]),[Ue,re]=a.useState(!1),[Ne,ee]=a.useState(null),[Ae,Fe]=a.useState([]),[fe,_e]=a.useState("idle"),[ze,Xe]=a.useState(!1),[je,ce]=a.useState(!1),[Re,ge]=a.useState(!1),Me=a.useRef(null),Ge=a.useRef(null),Pe=a.useRef(null),pt=a.useRef(null),Y=a.useRef(null),le=a.useRef(null),ye=a.useRef(null),nt=a.useRef(!1),X=a.useRef(te),Qe=a.useRef(n.trim()),lt=a.useRef(n.trim());a.useEffect(()=>{Z&&(re(!0),ps().then(M=>{ot(M.models),et(M.favoriteProviders),Oe(M.favoriteModels)}).catch(()=>{}).finally(()=>re(!1)),Vo(I).then(M=>ee(M)).catch(()=>ee(null)),Wo(I).then(M=>Fe(M.filter(ne=>ne.enabled))).catch(()=>Fe([])))},[Z,I]);const ft=Ne?.modelPresets||[],Mt=ft.find(M=>M.id===C),yt=(pe?!1:o.length>0)||K.length>0||E.length>0||w!=="default"||(g??Ss)!==Ss||f!==""||v!==""||(y||"")!==""||(j||"")!==""||se!==void 0||O==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!Z||!Ne?.autoSelectModelPreset)return;const M=(Ne.defaultPresetBySize,void 0);if(M){const ne=eh(M);L(M.id),_("preset"),b(ne.executorValue),x(ne.validatorValue)}},[Z,Ne,ft,e]);const ht=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!Z||ht.current||Ae.length===0)return;const M=Ae.filter(Le=>Le.defaultOn);if(M.length===0)return;ht.current=!0;const ne=M.map(Le=>Le.id);T(ne),F?.(ne)},[e,Z,Ae]),a.useEffect(()=>{Z||(ht.current=!1)},[Z]),a.useEffect(()=>{if(!ve){X.current=yt;return}yt&&!X.current&&ae(!0),X.current=yt},[yt,ve]),a.useEffect(()=>{be||(oe(!1),$e(""))},[be]),a.useEffect(()=>{e!=="edit"||!Z||pt.current&&(pt.current.focus(),pt.current.select())},[e,Z]),a.useEffect(()=>{if(!me)return;const M=ne=>{Ge.current&&!Ge.current.contains(ne.target)&&oe(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[me]),a.useEffect(()=>{(e!=="edit"||H)&&ge(!1)},[e,H]),a.useEffect(()=>{if(e!=="edit"){_e("idle");return}const M=n.trim();Qe.current=M,lt.current=M,_e("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!N||!Z)return;const M=n.trim(),ne=Qe.current;if(M===ne||M===lt.current){le.current&&(clearTimeout(le.current),le.current=null),nt.current||_e("idle");return}return le.current&&clearTimeout(le.current),le.current=setTimeout(async()=>{if(!nt.current){nt.current=!0,_e("saving");try{await N(M),lt.current=M,_e("saved"),ye.current&&clearTimeout(ye.current),ye.current=setTimeout(()=>{_e("idle"),ye.current=null},2e3)}catch{_e("idle")}finally{nt.current=!1,le.current=null}}},1500),()=>{le.current&&(clearTimeout(le.current),le.current=null)}},[e,n,N,Z]),a.useEffect(()=>()=>{le.current&&clearTimeout(le.current),ye.current&&clearTimeout(ye.current)},[]),a.useEffect(()=>{if(!ze)return;const M=ne=>{Me.current&&!Me.current.contains(ne.target)&&Xe(!1)};return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[ze]);const St=a.useCallback(M=>{const ne=M.clipboardData?.items;if(ne)for(let Le=0;Le<ne.length;Le++){const ut=ne[Le];if(ut.type.startsWith("image/")){const bt=ut.getAsFile();if(bt&&th.includes(bt.type)){M.preventDefault(),$([...K,{file:bt,previewUrl:URL.createObjectURL(bt)}]);return}}}},[K,$]),zt=a.useCallback(M=>{M.preventDefault();const ne=M.dataTransfer.files;for(let Le=0;Le<ne.length;Le++){const ut=ne[Le];if(th.includes(ut.type)){$([...K,{file:ut,previewUrl:URL.createObjectURL(ut)}]);return}}},[K,$]),It=a.useCallback(M=>{const ne=K[M];ne&&URL.revokeObjectURL(ne.previewUrl),$(K.filter((Le,ut)=>ut!==M))},[K,$]),Rt=a.useCallback(M=>{l(o.includes(M)?o.filter(ne=>ne!==M):[...o,M])},[o,l]),$t=(M,ne)=>M.length>ne?M.slice(0,ne)+"…":M,Ot=a.useCallback(M=>{s(M.target.value);const ne=M.target;ne.style.height="auto",ne.style.height=ne.scrollHeight+"px"},[s]),Vt=a.useCallback(()=>{ge(M=>!M)},[]),Dt=a.useCallback(M=>{!Re||M.key!=="Escape"||(M.preventDefault(),M.stopPropagation(),ge(!1))},[Re]),Ft=a.useCallback(async M=>{const ne=n.trim();if(!(!ne||je)){ce(!0);try{const Le=await gp(ne,M,I);s(Le),Xe(!1),J("Description refined with AI","success"),Pe.current&&(Pe.current.style.height="auto",Pe.current.style.height=Pe.current.scrollHeight+"px")}catch(Le){const ut=bp(Le);J(ut,"error")}finally{ce(!1)}}},[n,je,J,s,I]),Ct=a.useCallback(async M=>{const ne=Je,ut=ne.includes(M)?ne.filter(bt=>bt!==M):[M,...ne];et(ut);try{await fn({favoriteProviders:ut,favoriteModels:st})}catch{et(ne)}},[Je,st]),Nt=a.useCallback(async M=>{const ne=st,ut=ne.includes(M)?ne.filter(bt=>bt!==M):[M,...ne];Oe(ut);try{await fn({favoriteProviders:Je,favoriteModels:ut})}catch{Oe(ne)}},[st,Je]),Tt=a.useCallback(M=>{if(M<=0)return;const ne=[...E];[ne[M-1],ne[M]]=[ne[M],ne[M-1]],T(ne)},[E,T]),Zt=a.useCallback(M=>{if(M>=E.length-1)return;const ne=[...E];[ne[M],ne[M+1]]=[ne[M+1],ne[M]],T(ne)},[E,T]),Ut=a.useCallback(M=>{T(E.filter(ne=>ne!==M))},[E,T]),B=new Map;for(const M of Ae)B.set(M.id,{name:M.name,description:M.description});const xe=R.filter(M=>!o.includes(M.id)).sort((M,ne)=>{const Le=ne.createdAt.localeCompare(M.createdAt);if(Le!==0)return Le;const ut=parseInt(M.id.slice(M.id.lastIndexOf("-")+1),10)||0;return(parseInt(ne.id.slice(ne.id.lastIndexOf("-")+1),10)||0)-ut}),Ie=Ee?xe.filter(M=>M.id.toLowerCase().includes(Ee.toLowerCase())||M.title&&M.title.toLowerCase().includes(Ee.toLowerCase())||M.description&&M.description.toLowerCase().includes(Ee.toLowerCase())):xe;return t.jsxs("div",{className:"task-form",onDrop:zt,onDragOver:M=>M.preventDefault(),onPaste:St,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:pt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:M=>r(M.target.value),disabled:H})]}),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${fe==="idle"?"":" is-visible"}`,"aria-live":"polite",children:fe==="saving"?"Saving...":fe==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Re?" description--fullscreen":""}`,ref:Me,onKeyDown:Dt,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(Er,{size:14})})]}),t.jsx("textarea",{ref:Pe,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ot,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:H||je}),(()=>{const M=!!n.trim()&&!H;return t.jsxs(t.Fragment,{children:[!Re&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${M?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Vt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Ho,{size:14})}),M&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${je?"refine-button--loading":""}`,onClick:()=>Xe(ne=>!ne),disabled:je,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(rs,{size:12,style:{verticalAlign:"middle"}}),je?"Refining...":"Refine"]})]})})(),ze&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:M=>M.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("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:()=>Ft("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:()=>Ft("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:()=>Ft("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"&&(z||P)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[z&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const M=n.trim();if(!M){J("Enter a description first","error");return}k?.(),z(M)},disabled:H||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),P&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const M=n.trim();if(!M){J("Enter a description first","error");return}k?.(),P(M)},disabled:H||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),U,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ae(M=>!M),"aria-expanded":be,"aria-controls":"task-form-more-options",disabled:H,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),be?t.jsx(mi,{size:14}):t.jsx(Yt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${be?"":" collapsed"}`,"aria-hidden":!be,hidden:!be,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),K.length>0&&t.jsx("div",{className:"inline-create-previews",children:K.map((M,ne)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:M.previewUrl,alt:M.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>It(ne),disabled:H,title:"Remove image",children:"×"})]},M.previewUrl))}),t.jsx("input",{ref:Y,type:"file",accept:"image/*",onChange:M=>{const ne=M.target.files?.[0];ne&&($([...K,{file:ne,previewUrl:URL.createObjectURL(ne)}]),M.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Y.current?.click(),disabled:H,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),u&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:c??"",onChange:M=>u(M.target.value||void 0),disabled:H||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(M=>t.jsxs("option",{value:M.id,children:[M.name," (",VM(M.status),")"]},M.id))]}),(()=>{const M=(d??[]).find(ne=>ne.id===c);return M?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Bi,{status:M.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!pe&&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:Ge,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>oe(M=>!M),disabled:H,children:o.length>0?`${o.length} selected`:"Add dependencies"}),me&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ee,onChange:M=>$e(M.target.value),onClick:M=>M.stopPropagation()}),Ie.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ie.map(M=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(M.id)?" selected":""}`,onClick:()=>Rt(M.id),onMouseDown:ne=>ne.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:M.id}),t.jsx("span",{className:"dep-dropdown-title",children:$t(M.title||M.description||M.id,30)})]},M.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(M=>t.jsxs("span",{className:"dep-chip",children:[M,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Rt(M),disabled:H,children:"×"})]},M))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),p&&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:g??Ss,onChange:M=>p(M.target.value),disabled:H,children:md.map(M=>t.jsx("option",{value:M,children:M[0].toUpperCase()+M.slice(1)},M))})]}),ue&&O!==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:O,onChange:M=>ue(M.target.value),disabled:H,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ue?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:w==="preset"?C:w,onChange:M=>{const ne=M.target.value;if(ne==="default"){_("default"),L(""),b(""),x("");return}if(ne==="custom"){_("custom"),L("");return}const Le=ft.find(bt=>bt.id===ne),ut=eh(Le);_("preset"),L(ne),b(ut.executorValue),x(ut.validatorValue)},disabled:H,children:[t.jsx("option",{value:"default",children:"Use default"}),ft.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,ft.map(M=>t.jsx("option",{value:M.id,children:M.name},M.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),w==="preset"&&Mt?t.jsxs("small",{children:["Using preset: ",Mt.name]}):null,w==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>_("custom"),disabled:H,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(Kn,{id:"executor-model",label:"Executor Model",value:f,onChange:M=>{_("custom"),L(""),b(M)},models:He,disabled:H||w==="preset",favoriteProviders:Je,onToggleFavorite:Ct,favoriteModels:st,onToggleModelFavorite:Nt})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Kn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:M=>{_("custom"),L(""),x(M)},models:He,disabled:H||w==="preset",favoriteProviders:Je,onToggleFavorite:Ct,favoriteModels:st,onToggleModelFavorite:Nt})]}),S&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Kn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:M=>{_("custom"),L(""),S(M)},models:He,disabled:H||w==="preset",favoriteProviders:Je,onToggleFavorite:Ct,favoriteModels:st,onToggleModelFavorite:Nt})]}),A&&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:j||"",onChange:M=>A(M.target.value),disabled:H||w==="preset",children:[t.jsxs("option",{value:"",children:["Default (",Ne?.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"})]})]}),he&&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:se??"",onChange:M=>he(M.target.value===""?void 0:parseInt(M.target.value,10)),disabled:H,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),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"})]})]})]})]}),V,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:Ae.length>0&&Ae.map(M=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${M.id}`,children:[t.jsx("input",{type:"checkbox",checked:E.includes(M.id),onChange:ne=>{T(ne.target.checked?[...E,M.id]:E.filter(Le=>Le!==M.id))},disabled:H}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[M.name,WM(M.phase||"pre-merge",M.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:M.description})]})]},M.id))})]}),E.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:"}),E.map((M,ne)=>{const Le=B.get(M);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${M}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:ne+1}),t.jsx("span",{className:"workflow-step-order-name",children:Le?.name||M}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Tt(ne),disabled:H||ne===0,"data-testid":`workflow-step-move-up-${M}`,title:"Move up",children:t.jsx(mi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Zt(ne),disabled:H||ne===E.length-1,"data-testid":`workflow-step-move-down-${M}`,title:"Move down",children:t.jsx(Yt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ut(M),disabled:H,"data-testid":`workflow-step-remove-${M}`,title:"Remove",children:t.jsx(Kt,{size:14})})]})]},M)})]})]})]})]})}const nh={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 KM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function GM(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 JM(e){return e?new Date(e).toLocaleString():null}function YM(e){const n=e.split(`
650
- `);return n.length<=1?e:`${n.length} lines`}function oo(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 QM({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 XM({taskId:e,results:n,loading:s,enabledWorkflowSteps:i,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[u,d]=a.useState({}),[m,h]=a.useState({}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,x]=a.useState(!1),y=n.some(k=>k.status==="pending"),{entries:S}=tg(e,!!l&&y,o);a.useEffect(()=>{let k=!1;return Wo(o).then(U=>{k||b(U.filter(V=>V.enabled))}).catch(()=>{k||b([])}),()=>{k=!0}},[o]);const j=i??[],A=a.useMemo(()=>f.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[f]),w=a.useMemo(()=>new Map(A.map(k=>[k.id,k])),[A]),_=k=>{d(U=>({...U,[k]:!U[k]}))},C=k=>{h(U=>{const V=U[k]??"markdown";return{...U,[k]:V==="markdown"?"plain":"markdown"}})},L=k=>{p(k)},E=()=>{p(null)};a.useEffect(()=>{if(!g)return;const k=U=>{U.key==="Escape"&&E()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[g]);const T=a.useCallback((k,U)=>{if(c){if(U){if(j.includes(k)){c(j);return}c([...j,k]);return}c(j.filter(V=>V!==k))}},[c,j]),F=a.useCallback(k=>{if(!c||k<=0)return;const U=[...j];[U[k-1],U[k]]=[U[k],U[k-1]],c(U)},[c,j]),K=a.useCallback(k=>{if(!c||k>=j.length-1)return;const U=[...j];[U[k],U[k+1]]=[U[k+1],U[k]],c(U)},[c,j]),$=a.useCallback(k=>{c&&c(j.filter(U=>U!==k))},[c,j]),R=n.length>0,I=j.length>0;a.useEffect(()=>{r||x(!1)},[r]);const H=a.useMemo(()=>j.map(k=>{const U=w.get(k);return{id:k,name:U?.name||k,description:U?.description||"Step definition not found.",phase:U?.phase||"pre-merge"}}),[j,w]),J=()=>!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:A.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(k.id),onChange:U=>T(k.id,U.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,oo(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),j.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:"}),j.map((k,U)=>{const V=w.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:U+1}),t.jsx("span",{className:"workflow-step-order-name",children:V?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(U),disabled:U===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(mi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(U),disabled:U===j.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(Yt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(Kt,{size:14})})]})]},k)})]})]}),Z=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!R)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(se=>se.status==="passed").length,U=n.filter(se=>se.status==="failed").length,V=n.filter(se=>se.status==="skipped").length,pe=n.filter(se=>se.status==="pending").length,ve=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&ve.push(`${k} passed`),U>0&&ve.push(`${U} failed`),V>0&&ve.push(`${V} skipped`),pe>0&&ve.push(`${pe} 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:ve.join(" · ")}),n.map((se,he)=>{const O=se.phase||"pre-merge",ue=u[se.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${se.status}`,"data-testid":`workflow-result-item-${se.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[se.workflowStepName,oo(O,se.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${se.status}`,"data-testid":`workflow-result-badge-${se.workflowStepId}`,children:KM(se.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[se.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",JM(se.startedAt)]}),se.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:GM(se.startedAt,se.completedAt)})]}),se.status==="pending"&&se.startedAt?t.jsx(QM,{entries:S,startedAt:se.startedAt,stepId:se.workflowStepId}):se.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:()=>_(se.workflowStepId),"data-testid":`workflow-result-toggle-${se.workflowStepId}`,children:ue?"Hide output":"Show output"}),!ue&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${se.workflowStepId}`,children:YM(se.output)}),ue&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(se.workflowStepId),"data-testid":`workflow-result-mode-toggle-${se.workflowStepId}`,title:(m[se.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[se.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>L(se.workflowStepId),"data-testid":`workflow-result-expand-${se.workflowStepId}`,title:"Expand output",children:t.jsx(Ho,{size:12})})]})]}),ue&&t.jsx("div",{className:`workflow-result-output${(m[se.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${se.workflowStepId}`,children:(m[se.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:nh,children:se.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:se.output})})]}):null]},`${se.workflowStepId}-${he}`)})]})},N=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(k=>!k),"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(Bn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(us,{size:14}),"Edit"]})}):null,z=!s&&!R&&I,P=r&&R;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[z?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[H.length," step",H.length===1?"":"s"]})]}),N]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:H.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[k.name,oo(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.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."}),J()]}):t.jsxs(t.Fragment,{children:[P&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),N]}),Z(),J()]}),g&&(()=>{const k=n.find(pe=>pe.workflowStepId===g);if(!k)return null;const U=m[k.workflowStepId]??"markdown",V=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:pe=>{pe.target===pe.currentTarget&&E()},"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:k.workflowStepName}),oo(V,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>C(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:U==="markdown"?"Switch to plain text":"Switch to markdown",children:U==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Kt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${U==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:U==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:nh,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:k.output})})})]})})})()]})}function ZM(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const eA=new Set(["planning","researching","executing","finalizing","merging"]);function tA(e){return e!==void 0&&e!=="online"}function nA({task:e,settings:n,addToast:s,onTaskUpdated:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(null),[m,h]=a.useState(e.nodeId??""),[g,p]=a.useState(!1),f=a.useRef(e.id);a.useEffect(()=>{f.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),d(null),No().then(E=>{o(E)}).catch(E=>{d(ke(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const b=a.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),v=a.useMemo(()=>[...r].sort((E,T)=>E.name.localeCompare(T.name)),[r]),x=n,y=e.nodeId??x?.defaultNodeId??null,S=e.nodeId?"Per-task override":x?.defaultNodeId?"Project default":"No routing",j=y?b.get(y):void 0,A=j?`${j.name} (${j.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||eA.has(e.status),_=w||g||l,C=a.useCallback(async E=>{if(E===m)return;const T=e.id,F=m;h(E),p(!0);try{const K=await si(T,{nodeId:E||null});if(f.current!==T)return;h(K.nodeId??""),i?.(K),s(E?"Node override updated":"Node override cleared","success")}catch(K){if(f.current!==T)return;h(F),s(ke(K)||"Failed to update node override","error")}finally{f.current===T&&p(!1)}},[s,i,m,e.id]),L=a.useCallback(()=>{C("")},[C]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Bi,{status:j.status,compact:!0}):null,A,tA(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:ZM(x?.unavailableNodePolicy)})]})]}),w&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),w?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:_,onChange:E=>{C(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.id))]}),u?t.jsx("div",{className:"routing-tab__error",children:u}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",b.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:w||g,onClick:L,children:"Clear override"})]}):null]})]})}const sA=/^[a-zA-Z0-9_-]{1,64}$/,iA=200;function sh(e){return e?new Date(e).toLocaleString():""}function aA(e,n=iA){return e.length<=n?e:e.substring(0,n)+"…"}function rA({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const[o,l]=a.useState([]),[c,u]=a.useState(!0),[d,m]=a.useState(null),[h,g]=a.useState(""),[p,f]=a.useState(null),[b,v]=a.useState(""),[x,y]=a.useState(null),[S,j]=a.useState([]),[A,w]=a.useState(!1),[_,C]=a.useState(!1),[L,E]=a.useState(""),[T,F]=a.useState(""),[K,$]=a.useState(!1),[R,I]=a.useState(null),[H,J]=a.useState(null),[Z,N]=a.useState(!1),z=a.useCallback(async()=>{try{const O=await ty(e,i);l(O)}catch(O){n(ke(O)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{z()},[z]);async function P(O){d===O.key?(m(null),g(""),f(null),v(""),y(null),j([]),N(!1)):(m(O.key),g(O.content),f(null),v(""),y(null),j([]),N(!1))}async function k(O){if(x===O)y(null),j([]);else{y(O),w(!0);try{const ue=await ny(e,O,i);j(ue)}catch(ue){n(ke(ue)||"Failed to load revisions","error")}finally{w(!1)}}}function U(){d&&(f(d),v(h))}function V(){f(null),v("")}async function pe(){if(!(!p||!b.trim())){$(!0);try{await Gd(e,p,b,{},i),f(null),v(""),await z();const O=o.find(ue=>ue.key===p);O&&g(O.content),n("Document saved","success")}catch(O){n(ke(O)||"Failed to save document","error")}finally{$(!1)}}}async function ve(){const O=L.trim(),ue=T.trim();if(!O){n("Document key is required","error");return}if(!sA.test(O)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ue){n("Content is required","error");return}$(!0);try{await Gd(e,O,ue,{},i),C(!1),E(""),F(""),await z(),n("Document created","success")}catch(te){n(ke(te)||"Failed to create document","error")}finally{$(!1)}}async function se(O){I(O);try{await sy(e,O,i),J(null),I(null),d===O&&(m(null),g("")),x===O&&(y(null),j([])),await z(),n("Document deleted","success")}catch(ue){n(ke(ue)||"Failed to delete document","error")}finally{I(null)}}function he(O){g(O.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"}),_&&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:L,onChange:O=>E(O.target.value),placeholder:"e.g., plan, notes, research",disabled:K}),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:T,onChange:O=>F(O.target.value),rows:6,placeholder:"Enter document content…",disabled:K})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(!1),E(""),F("")},disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ve(),disabled:K||!L.trim()||!T.trim(),children:K?"Creating…":"Create"})]})]}),o.length===0&&!_?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(O=>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(Oi,{size:14}),t.jsx("span",{className:"task-document-key",children:O.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",O.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:O.author}),t.jsx("span",{className:"task-document-timestamp",children:sh(O.updatedAt||O.createdAt)})]})]}),d===O.key&&p!==O.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:()=>N(ue=>!ue),"aria-label":Z?"Switch to plain text":"Switch to markdown","aria-pressed":Z,title:Z?"Switch to plain text":"Switch to markdown",children:Z?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:Z?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===O.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),A?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(ue=>ue.revision<O.revision).sort((ue,te)=>te.revision-ue.revision).map(ue=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>he(ue),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ue.revision]}),t.jsx("span",{className:"revision-author",children:ue.author}),t.jsx("span",{className:"revision-timestamp",children:sh(ue.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:aA(ue.content,100)})]},ue.id))})]})]}),p===O.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:ue=>v(ue.target.value),rows:10,disabled:K}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:V,disabled:K,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void pe(),disabled:K||!b.trim(),children:K?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void P(O),children:d===O.key?t.jsxs(t.Fragment,{children:[t.jsx(mi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Yt,{size:14})," Expand"]})}),d===O.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(O.key),children:[t.jsx(hr,{size:14})," History"]}),r&&p!==O.key&&t.jsx("button",{className:"btn btn-sm",onClick:U,children:"Edit"}),r&&(H===O.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 se(O.key),disabled:R===O.key,children:R===O.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:R===O.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(O.key),children:t.jsx(on,{size:14})}))]})]})]},O.key))}),r&&!_&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>C(!0),children:[t.jsx(ln,{size:14})," New Document"]})]})}function lo(e){return e.toLocaleString()}function tc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ga(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 oA(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const u=new Date(o.completedAt).getTime();if(Number.isNaN(u)||u<l)return null;c=u}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),i=s.reduce((o,l)=>o+l.durationMs,0),r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function lA({tokenUsage:e,loading:n,task:s}){const i=Lp(s?.log??[]),r=i.filter(m=>typeof m.durationMs=="number"),o=r.reduce((m,h)=>m+(h.durationMs??0),0),l=Math.max(o,s?.timedExecutionMs??0),c=r.reduce((m,h)=>!m||(h.durationMs??0)>(m.durationMs??0)?h:m,void 0),u=oA(s?.workflowStepResults??[]),d=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:Ga(l)})]}),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:u.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:Ga(u.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Ga(l+u.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:c?.durationMs?`${c.summary} (${Ga(c.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:u.longestStep?`${u.longestStep.name} (${Ga(u.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:d>0?`${Math.min((s?.currentStep??0)+1,d)} / ${d}`:"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 ${tc(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:lo(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:lo(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:lo(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:lo(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:tc(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:tc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const cA=new Set(["planning","researching","executing","finalizing","merging"]);function dA(e,n){return Mp(e,n)}function uA(e,n){return Ap(e,n)}function mA(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 hA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=mA(n);return i||Rp(e,s)}function pA(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 fA(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 gA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function bA(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 ih(e,n){return e.length>n?e.slice(0,n)+"…":e}function ah(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function nc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function sc(e){return e.trim()}function xA(e){const n=e.trim();return n.length>0?n:void 0}function Ja(e){return typeof e=="string"&&md.includes(e)?e:Ss}function Ya(e){return e==="fast"?"fast":"standard"}function vA(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function yA(e){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:e.sourceAgentId?`Agent (${e.sourceAgentId})`:"Agent"};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:vA(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const ic=200,jA=new Set(["triage","todo"]);function kA({task:e,projectId:n,tasks:s=[],onClose:i,onOpenDetail:r,onMoveTask:o,onDeleteTask:l,onMergeTask:c,onRetryTask:u,onDuplicateTask:d,onTaskUpdated:m,addToast:h,prAuthAvailable:g,initialTab:p="definition"}){const[f,b]=a.useState(p),[v,x]=a.useState(()=>"prompt"in e?e:null),[y,S]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){x(e),S(!1);return}let Q=!1;return S(!0),x(null),gr(e.id,n).then(Ve=>{Q||(x(Ve),S(!1))}).catch(()=>{Q||S(!1)}),()=>{Q=!0}},[e.id,n]);const j=v?{...v,...e,prompt:v.prompt,log:v.log}:{...e,prompt:""},A=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,w=yA(j);a.useEffect(()=>{b(p)},[p]),a.useEffect(()=>{E(!1)},[e.id]);const[_,C]=a.useState("activity"),[L,E]=a.useState(!1),[T,F]=a.useState(e.attachments||[]),[K,$]=a.useState(!1),[R,I]=a.useState(e.dependencies||[]),[H,J]=a.useState(!1),[Z,N]=a.useState(""),[z,P]=a.useState(null),[k,U]=a.useState([]),[V,pe]=a.useState(!1),[ve,se]=a.useState(!1),[he,O]=a.useState(!1),[ue,te]=a.useState(!1),[me,oe]=a.useState(!1),[be,ae]=a.useState(j.prompt||""),[Ee,$e]=a.useState(""),[He,ot]=a.useState(!1),[Je,et]=a.useState(""),[st,Oe]=a.useState(!1),[Ue,re]=a.useState(!1),[Ne,ee]=a.useState(e.title||""),[Ae,Fe]=a.useState(e.description||""),[fe,_e]=a.useState(e.dependencies||[]),[ze,Xe]=a.useState(""),[je,ce]=a.useState(""),[Re,ge]=a.useState(""),[Me,Ge]=a.useState(""),[Pe,pt]=a.useState("default"),[Y,le]=a.useState(void 0),[ye,nt]=a.useState(Ss),[X,Qe]=a.useState(e.nodeId),[lt,ft]=a.useState(Ya(e.executionMode)),[Mt,yt]=a.useState(""),[ht,St]=a.useState(e.enabledWorkflowSteps||[]),[zt,It]=a.useState(e.sourceIssue?.provider??""),[Rt,$t]=a.useState(e.sourceIssue?.repository??""),[Ot,Vt]=a.useState(e.sourceIssue?.externalIssueId??""),[Dt,Ft]=a.useState(e.sourceIssue?.url??""),[Ct,Nt]=a.useState([]),[Tt,Zt]=a.useState(!1),Ut=a.useRef(!1),[B,xe]=a.useState(!1),[Ie,M]=a.useState(!1),[ne,Le]=a.useState(!1),ut=a.useRef(null),bt=a.useRef(null),Pt=a.useRef(null),At=a.useRef(null);ri(At,!0,"fusion:task-detail-modal-size");const{getSlotsForId:nn}=Cp(n),zn=nn("task-detail-tab");a.useEffect(()=>(Ut.current=!0,()=>{Ut.current=!1}),[]);const[hn,en]=a.useState(void 0),[On,we]=a.useState([]),[it,un]=a.useState(!1),[Nn,Tn]=a.useState(e.enabledWorkflowSteps||[]),Ce=e.column==="in-progress"||cA.has(e.status);a.useEffect(()=>{ee(e.title||""),Fe(e.description||""),It(e.sourceIssue?.provider??""),$t(e.sourceIssue?.repository??""),Vt(e.sourceIssue?.externalIssueId??""),Ft(e.sourceIssue?.url??""),ft(Ya(e.executionMode)),Le(!1),re(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{Tn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Q=!1;return Vo(n).then(Ve=>{Q||en(Ve)}).catch(()=>{}),()=>{Q=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Q=!1;return un(!0),Mj(e.id,n).then(Ve=>{Q||we(Ve)}).catch(Ve=>{Q||h(`Failed to load workflow results: ${ke(Ve)}`,"error")}).finally(()=>{Q||un(!1)}),()=>{Q=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Q=n?`?projectId=${encodeURIComponent(n)}`:"",Ve=ct=>{try{const Bt=JSON.parse(ct.data);Bt.id===e.id&&Array.isArray(Bt.workflowStepResults)&&we(Bt.workflowStepResults)}catch{}};return Qs(`/api/events${Q}`,{events:{"task:updated":Ve}})},[f,e.id,n]),a.useEffect(()=>{H||N("")},[H]),a.useEffect(()=>{if(!e.assignedAgentId){P(null);return}const Q=k.find(ct=>ct.id===e.assignedAgentId);if(Q){P(Q);return}let Ve=!1;return vp(e.assignedAgentId,n).then(ct=>{Ve||P(ct)}).catch(()=>{Ve||P(null)}),()=>{Ve=!0}},[e.assignedAgentId,n,k]),a.useEffect(()=>{pe(!1)},[e.id]),a.useEffect(()=>{if(!(B||Ie))return;const Ve=ct=>{const Bt=ct.target,As=ut.current?.contains(Bt),ss=Pt.current?.contains(Bt);!As&&B&&xe(!1),!ss&&Ie&&M(!1)};return document.addEventListener("mousedown",Ve),()=>document.removeEventListener("mousedown",Ve)},[B,Ie]),a.useEffect(()=>{if(!(B||Ie))return;const Ve=ct=>{ct.key==="Escape"&&(ct.stopPropagation(),B&&xe(!1),Ie&&M(!1))};return document.addEventListener("keydown",Ve),()=>document.removeEventListener("keydown",Ve)},[B,Ie]),a.useEffect(()=>{oe(!1),ae(j.prompt||""),$e("")},[e.id,j.prompt]);const Ye=jA.has(e.column)&&!Tt,dt=a.useCallback(()=>{if(!Ye)return;re(!0),ee(e.title||""),Fe(e.description||""),_e(e.dependencies||[]);const Q=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Ve=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Xe(Q),ce(Ve),ge(ct),Ge(e.thinkingLevel??""),Qe(e.nodeId),pt(Q||Ve||ct?"custom":"default"),yt(""),St(e.enabledWorkflowSteps||[]),ft(Ya(e.executionMode)),It(e.sourceIssue?.provider??""),$t(e.sourceIssue?.repository??""),Vt(e.sourceIssue?.externalIssueId??""),Ft(e.sourceIssue?.url??""),Nt([]),le(e.reviewLevel),nt(Ja(e.priority))},[Ye,e]),vt=a.useCallback(()=>{re(!1),ee(e.title||""),Fe(e.description||""),_e(e.dependencies||[]),Qe(e.nodeId),It(e.sourceIssue?.provider??""),$t(e.sourceIssue?.repository??""),Vt(e.sourceIssue?.externalIssueId??""),Ft(e.sourceIssue?.url??""),nt(Ja(e.priority)),ft(Ya(e.executionMode)),Ct.forEach(Q=>URL.revokeObjectURL(Q.previewUrl)),Nt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Ct]),Qt=a.useCallback(async()=>{Zt(!0);try{const Q={},Ve=Ne.trim(),ct=Ae.trim();Ve&&Ve!==(e.title??"")&&(Q.title=Ve),ct&&ct!==(e.description??"")&&(Q.description=ct),ah(fe,e.dependencies??[])||(Q.dependencies=fe),ah(ht,e.enabledWorkflowSteps??[])||(Q.enabledWorkflowSteps=ht);const Bt=nc(ze),As=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";ze!==As&&(Q.modelProvider=Bt?.provider??null,Q.modelId=Bt?.modelId??null);const ss=nc(je),Br=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";je!==Br&&(Q.validatorModelProvider=ss?.provider??null,Q.validatorModelId=ss?.modelId??null);const Da=nc(Re),Qi=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Re!==Qi&&(Q.planningModelProvider=Da?.provider??null,Q.planningModelId=Da?.modelId??null);const al=e.thinkingLevel??"";Me!==al&&(Q.thinkingLevel=Me!==""?Me:null),(e.nodeId??void 0)!==X&&(Q.nodeId=X??null);const rl=e.reviewLevel;Y!==rl&&(Q.reviewLevel=Y);const ol=Ja(e.priority);ye!==ol&&(Q.priority=ye);const La=Ya(e.executionMode);lt!==La&&(Q.executionMode=lt==="fast"?"fast":null);const Xi=sc(zt),Zi=sc(Rt),_i=sc(Ot),za=xA(Dt);if(Xi.length===0&&Zi.length===0&&_i.length===0&&!za)e.sourceIssue&&(Q.sourceIssue=null);else{if(!Xi||!Zi||!_i){h("Source issue provider, repository, and issue identifier are required","error"),Zt(!1);return}const Rs=Number.parseInt(_i,10),q=e.sourceIssue?.issueNumber??Rs;if(!Number.isFinite(q)||q<=0){h("Source issue identifier must be numeric for new metadata","error"),Zt(!1);return}const Se={provider:Xi,repository:Zi,externalIssueId:_i,issueNumber:q,...za?{url:za}:{}},Te=e.sourceIssue;(!Te||Te.provider!==Se.provider||Te.repository!==Se.repository||Te.externalIssueId!==Se.externalIssueId||Te.issueNumber!==Se.issueNumber||(Te.url??void 0)!==Se.url)&&(Q.sourceIssue=Se)}if(Object.keys(Q).length>0){const Rs=await si(e.id,Q,n);m?.(Rs)}if(Ct.length>0){const Rs=[];for(const q of Ct)try{const Se=await br(e.id,q.file,n);F(Te=>[...Te,Se])}catch{Rs.push(q.file.name)}Rs.length>0&&h(`Failed to upload: ${Rs.join(", ")}`,"error")}Ct.forEach(Rs=>URL.revokeObjectURL(Rs.previewUrl)),Nt([]),h(`Updated ${e.id}`,"success"),re(!1)}catch(Q){h(`Failed to update ${e.id}: ${ke(Q)}`,"error")}finally{Ut.current&&Zt(!1)}},[e,Ne,Ae,fe,ze,je,Re,Me,X,Y,ye,lt,ht,zt,Rt,Ot,Dt,Ct,h,n,m]),bn=a.useCallback(async Q=>{try{await si(e.id,{description:Q},n),h("Description saved","success")}catch(Ve){h(`Failed to save: ${ke(Ve)}`,"error")}},[e.id,h,n]),Jt=a.useCallback(Q=>{Ue&&(Q.key==="Escape"?(Q.preventDefault(),vt()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),Qt()))},[Ue,vt,Qt]);a.useEffect(()=>{if(Ue)return document.addEventListener("keydown",Jt),()=>document.removeEventListener("keydown",Jt)},[Ue,Jt]);const Xt=a.useRef(null),{nodes:_n}=Yo(),{confirm:sn}=Ys(),{entries:ls,loading:cs,loadMore:cn,hasMore:kt,total:G,loadingMore:De}=tg(e.id,f==="logs"&&_==="agent-log",n);a.useEffect(()=>{const Q=Ve=>{Ve.key==="Escape"&&!Ue&&i()};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[i,Ue]);const tt=Si(i),at=a.useCallback(async Q=>{try{await o(e.id,Q),i(),h(`Moved to ${Dn[Q]}`,"success")}catch(Ve){h(ke(Ve),"error")}},[e.id,o,i,h]),wt=a.useCallback(async()=>{if(await sn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Ve){const ct=bA(Ve);if(!ct||ct.dependentIds.length===0){h(ke(Ve),"error");return}const Bt=ct.dependentIds.join(", ");if(!await sn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Bt}.
651
-
652
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await l(e.id,{removeDependencyReferences:!0}),i(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(ss){h(ke(ss),"error")}}},[e.id,l,i,h,sn]),_t=a.useCallback(async()=>{await sn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Ve=>{const ct=Ve.merged?`Merged ${e.id} (branch: ${Ve.branch})`:`Closed ${e.id} (${Ve.error||"no branch to merge"})`;h(ct,"success")}).catch(Ve=>{h(ke(Ve),"error")}))},[e.id,c,i,h,sn]),Lt=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Q=>{h(ke(Q),"error")}))},[e.id,u,i,h]),Jn=a.useCallback(async()=>{if(!(!d||!await sn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Ve=await d(e.id);i(),h(`Duplicated ${e.id} → ${Ve.id}`,"success")}catch(Ve){h(ke(Ve),"error")}},[e.id,d,i,h,sn]),Fs=a.useCallback(async()=>{try{e.paused?(await qv(e.id,n),h(`Unpaused ${e.id}`,"success")):(await mp(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Q){h(ke(Q),"error")}},[e.id,e.paused,i,h]),li=a.useCallback(async()=>{try{await Gv(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Q){h(ke(Q),"error")}},[e.id,i,h]),_s=a.useCallback(async()=>{if(await sn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Jv(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Ve){h(ke(Ve),"error")}},[e.id,i,h,sn]),Us=a.useCallback(async()=>{if(await sn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await ry(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(Ve){h(ke(Ve),"error")}},[e.id,n,i,h,sn]),ie=a.useCallback(()=>{ot(!0),et("")},[]),de=a.useCallback(()=>{xe(!1),M(!1)},[]),qe=a.useCallback(Q=>{de(),at(Q)},[de]),mt=a.useCallback(Q=>{de(),Q()},[de]),jt=a.useCallback(()=>{de(),_t()},[de,_t]),pn=a.useCallback(()=>{ot(!1),et(""),Oe(!1)},[]),mn=a.useCallback(async()=>{if(!Je.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Je.length>2e3){h("Feedback must be 2000 characters or less","error");return}Oe(!0);try{const Q=await oy(e.id,Je.trim(),n);h(`Refinement task created: ${Q.id}`,"success"),i()}catch(Q){h(ke(Q),"error")}finally{Oe(!1)}},[e.id,Je,h,i]),an=a.useCallback(async Q=>{$(!0);try{const Ve=await br(e.id,Q,n);F(ct=>[...ct,Ve]),h("Screenshot attached","success")}catch(Ve){h(ke(Ve),"error")}finally{$(!1)}},[e.id,h]),xn=a.useCallback(async Q=>{const Ve=Q.target.files?.[0];Ve&&(await an(Ve),Xt.current&&(Xt.current.value=""))},[an]);a.useEffect(()=>{const Q=Ve=>{const ct=Ve.clipboardData?.items;if(ct)for(let Bt=0;Bt<ct.length;Bt++){const As=ct[Bt];if(As.type.startsWith("image/")){const ss=As.getAsFile();if(ss){Ve.preventDefault(),an(ss);return}}}};return document.addEventListener("paste",Q),()=>document.removeEventListener("paste",Q)},[an]);const Fn=a.useCallback(Q=>{Q.preventDefault()},[]),Yn=a.useCallback(Q=>{Q.preventDefault();const Ve=Q.dataTransfer.files;for(let ct=0;ct<Ve.length;ct++){const Bt=Ve[ct];if(Bt.type.startsWith("image/")){an(Bt);return}}},[an]),Qn=a.useCallback(async Q=>{try{await Xv(e.id,Q,n),F(Ve=>Ve.filter(ct=>ct.filename!==Q)),h("Attachment deleted","info")}catch(Ve){h(ke(Ve),"error")}},[e.id,h]),In=a.useCallback(async Q=>{const Ve=Nn;Tn(Q);try{const ct=await si(e.id,{enabledWorkflowSteps:Q},n);h("Workflow steps updated","success"),m?.(ct)}catch(ct){Tn(Ve),h(`Failed to update workflow steps: ${ke(ct)}`,"error")}},[e.id,n,Nn,m,h]),Xn=a.useCallback(async()=>{se(!0);try{const Q=await Ea(void 0,n);U(Q),pe(!0)}catch(Q){h(`Failed to load agents: ${ke(Q)}`,"error"),pe(!1)}finally{se(!1)}},[n,h]),Hn=a.useCallback(async Q=>{try{const Ve=await au(e.id,Q,n),ct=k.find(Bt=>Bt.id===Q)??null;P(ct||(Bt=>Bt?.id===Q?Bt:null)),pe(!1),m?.(Ve),h("Assigned agent updated","success")}catch(Ve){h(`Failed to assign agent: ${ke(Ve)}`,"error")}},[e.id,n,k,m,h]),gs=a.useCallback(async()=>{try{const Q=await au(e.id,null,n);P(null),pe(!1),m?.(Q),h("Agent unassigned","success")}catch(Q){h(`Failed to unassign agent: ${ke(Q)}`,"error")}},[e.id,n,m,h]),Mn=a.useCallback(async Q=>{const Ve=[...R,Q];I(Ve);try{await si(e.id,{dependencies:Ve},n)}catch(ct){I(R),h(ke(ct),"error")}},[e.id,R,h]),qn=a.useCallback(async(Q,Ve)=>{Q.stopPropagation();const ct=R.filter(Bt=>Bt!==Ve);I(ct);try{await si(e.id,{dependencies:ct},n)}catch(Bt){I(R),h(ke(Bt),"error")}},[e.id,R,h]),ns=a.useCallback(async Q=>{try{const Ve=await gr(Q,n);r(Ve)}catch{h(`Failed to load dependency ${Q}`,"error")}},[r,h]),Ms=a.useCallback(async Q=>{O(!0);try{await si(j.id,{prompt:Q},n),h("Spec updated","success"),v&&(v.prompt=Q)}catch(Ve){throw h(ke(Ve),"error"),Ve}finally{O(!1)}},[j,v,h]),ds=a.useCallback(async Q=>{te(!0);try{await ay(e.id,Q,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(Ve){const ct=ke(Ve);ct.includes("done")||ct.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(ct,"error")}finally{te(!1)}},[e.id,h,i]),An=a.useCallback(()=>{oe(!0),ae(j.prompt||""),$e("")},[j.prompt]),Rn=a.useCallback(()=>{oe(!1),ae(j.prompt||""),$e("")},[j.prompt]),js=a.useCallback(async()=>{if(be===(j.prompt||"")){Rn();return}oe(!1);try{await Ms(be)}catch(Q){throw oe(!0),Q}},[be,j.prompt,Ms,Rn]),Ta=a.useCallback(async()=>{Ee.trim()&&await ds(Ee.trim())},[Ee,ds]),Ji=a.useCallback(Q=>{Q.key==="Escape"?(Q.preventDefault(),Rn()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),js())},[Rn,js]),Lr=s.filter(Q=>Q.id!==e.id&&!R.includes(Q.id)).sort((Q,Ve)=>{const ct=Ve.createdAt.localeCompare(Q.createdAt);if(ct!==0)return ct;const Bt=parseInt(Q.id.slice(Q.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ve.id.slice(Ve.id.lastIndexOf("-")+1),10)||0)-Bt}),Bs=z?.name??e.assignedAgentId??null,Pa=a.useMemo(()=>{const Q=[];return j.modelProvider&&Q.push(j.modelProvider),j.validatorModelProvider&&!Q.includes(j.validatorModelProvider)&&Q.push(j.validatorModelProvider),j.planningModelProvider&&!Q.includes(j.planningModelProvider)&&Q.push(j.planningModelProvider),Q},[j.modelProvider,j.validatorModelProvider,j.planningModelProvider]),zr=$c[e.column]||[],il=["todo","in-progress"],Or=e.column==="in-review"?il:zr,Zn=Or[0],Hs=Or.slice(1),Un=Hs.length>0,Ei=a.useCallback(()=>{xe(!1),bt.current?.focus()},[]),Ia=a.useCallback(Q=>{if(!Un){Zn&&qe(Zn);return}const Ve=Q.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Q.target instanceof Element&&Q.target.closest(".detail-move-btn__arrow")||Ve&&Q.clientX>0&&Q.clientX>=Ve.getBoundingClientRect().left)){xe(Bt=>!Bt),M(!1);return}Zn&&qe(Zn)},[Un,Zn,qe]),Fr=a.useCallback(Q=>{!Un||!(Q.key==="ArrowDown"||Q.altKey&&Q.key==="ArrowDown")||(Q.preventDefault(),xe(!0),M(!1))},[Un]),Yi=a.useCallback(Q=>{Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),Ei())},[Ei]);a.useEffect(()=>{if(!B)return;ut.current?.querySelector(".detail-move-menu-item")?.focus()},[B]);const Ur={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},$a=e.status?Ur[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...tt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:At,onDragOver:Fn,onDrop:Yn,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:Dn[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Ue&&Ye&&t.jsx("button",{className:"modal-edit-btn",onClick:dt,title:"Edit task","aria-label":"Edit task",children:t.jsx(us,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&_==="agent-log"&&!Ue?" detail-body--agent-log":""}`,children:[Ue?t.jsx("div",{className:"modal-edit-form",children:t.jsx(ag,{mode:"edit",title:Ne,onTitleChange:ee,description:Ae,onDescriptionChange:Fe,dependencies:fe,onDependenciesChange:_e,executorModel:ze,onExecutorModelChange:Xe,validatorModel:je,onValidatorModelChange:ce,planningModel:Re,onPlanningModelChange:ge,thinkingLevel:Me,onThinkingLevelChange:Ge,presetMode:Pe,onPresetModeChange:pt,selectedPresetId:Mt,onSelectedPresetIdChange:yt,selectedWorkflowSteps:ht,onWorkflowStepsChange:St,pendingImages:Ct,onImagesChange:Nt,tasks:s.filter(Q=>Q.id!==e.id),projectId:n,disabled:Tt,addToast:h,isActive:Ue,onAutoSaveDescription:bn,reviewLevel:Y,onReviewLevelChange:le,priority:ye,onPriorityChange:nt,nodeId:X,onNodeIdChange:Qe,nodeOptions:_n,nodeOverrideDisabled:Ce,nodeOverrideDisabledReason:Ce?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:lt,onExecutionModeChange:ft,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:zt,onChange:Q=>It(Q.target.value),disabled:Tt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Rt,onChange:Q=>$t(Q.target.value),disabled:Tt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Ot,onChange:Q=>Vt(Q.target.value),disabled:Tt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Dt,onChange:Q=>Ft(Q.target.value),disabled:Tt,"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 Q=e.title||e.description||e.id,Ve=!L&&Q.length>ic;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Ve?Q.slice(0,ic)+"…":Q}),Q.length>ic&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>E(!L),children:L?"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)]}),w&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Js,{"aria-hidden":"true"}),t.jsxs("span",{children:["Created via ",w.label,w.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>ns(w.parentTaskId),children:w.parentTaskId})]}),w.contextInfo?` (${w.contextInfo})`:""]})]})]})]}),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})]})]}),!Ue&&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"}),t.jsx("button",{className:`detail-tab${f==="routing"?" detail-tab-active":""}`,onClick:()=>b("routing"),children:"Routing"}),zn.map((Q,Ve)=>{const ct=`plugin-${Ve}`;return t.jsx("button",{className:`detail-tab${f===ct?" detail-tab-active":""}`,onClick:()=>b(ct),children:Q.slot.label},`plugin-tab-${Q.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(XM,{taskId:e.id,results:On,loading:it,enabledWorkflowSteps:Nn,canEdit:Ye,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:In})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(PM,{task:e,addToast:h,onTaskUpdated:m,settings:hn})}):f==="logs"?t.jsxs("div",{className:`detail-section${_==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${_==="activity"?" log-subview-btn-active":""}`,onClick:()=>C("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${_==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>C("agent-log"),children:"Agent Log"})]}),_==="agent-log"?t.jsx(_M,{entries:ls,loading:cs,executorModel:dA(e,hn),validatorModel:uA(e,hn),planningModel:hA(e,ls,hn),hasMore:kt,onLoadMore:cn,loadingMore:De,totalCount:G}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((Q,Ve)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:fA(Q.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Q.action})]}),Q.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Q.outcome})]},Ve))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(HM,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(zM,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(rA,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Ye}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Go,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(lA,{tokenUsage:j.tokenUsage,loading:y,task:j})}):f==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(nA,{task:e,settings:hn,addToast:h,onTaskUpdated:m})}):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(pi,{remarkPlugins:[fi],children:e.summary})})]}),t.jsx(FM,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":ne,"aria-label":ne?"Collapse source issue details":"Expand source issue details",onClick:()=>Le(Q=>!Q),children:t.jsx(kn,{size:16,className:ne?"detail-source-chevron--expanded":void 0})})]}),ne&&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:[Pa.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Pa.map(Q=>t.jsx(Ln,{provider:Q,size:"sm"},Q))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Sn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Bs?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Sn,{size:14}),Bs,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void gs(),title:"Unassign agent",children:t.jsx(Kt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{V?pe(!1):Xn()},children:"Assign Agent"}),V&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ve&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ve&&k.filter(Q=>Q.state!=="terminated").map(Q=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Q.id?" selected":""}`,onClick:()=>void Hn(Q.id),children:[t.jsx(Sn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Q.name}),t.jsx("span",{className:"agent-picker-role",children:Q.role})]},Q.id)),!ve&&k.filter(Q=>Q.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"}),j.steps&&j.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:j.steps.map((Q,Ve)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Q.status}`,"data-tooltip":`${Q.name} (${Q.status})`,style:{backgroundColor:pA(Q.status)}},Ve))}),t.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(Q=>Q.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!me&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:An,children:"Edit"})}),me?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:be,onChange:Q=>ae(Q.target.value),onKeyDown:Ji,disabled:he,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:Rn,disabled:he,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void js(),disabled:be===(j.prompt||"")||he,children:he?"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:Q=>$e(Q.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ue,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 Ta(),disabled:!Ee.trim()||ue,children:ue?"Requesting…":"Request AI Revision"})]})]})]}):y?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],children:j.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"}),T.length>0?t.jsx("div",{className:"detail-attachments-grid",children:T.map(Q=>{const Ve=ai(`/api/tasks/${e.id}/attachments/${Q.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Ve,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Ve,alt:Q.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Q.originalName," (",gA(Q.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Qn(Q.filename),title:"Delete attachment",children:"×"})]},Q.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Xt,type:"file",accept:"image/*",onChange:xn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Xt.current?.click(),disabled:K,children:K?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),R.length>0?t.jsx("ul",{className:"detail-dep-list",children:R.map(Q=>{const Ve=s.find(Bt=>Bt.id===Q),ct=Ve?.title||Ve?.description||Q;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>ns(Q),onKeyDown:Bt=>{(Bt.key==="Enter"||Bt.key===" ")&&(Bt.preventDefault(),ns(Q))},role:"link",tabIndex:0,title:`Click to view ${Q}`,children:[t.jsx("span",{className:"detail-dep-id",children:Q}),t.jsx("span",{className:"detail-dep-label",children:ih(ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Bt=>qn(Bt,Q),title:`Remove dependency ${Q}`,children:"×"})]},Q)})}):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:()=>{H&&N(""),J(Q=>!Q)},children:"Add Dependency"}),H&&(()=>{const Q=Z.toLowerCase(),Ve=Q?Lr.filter(ct=>ct.id.toLowerCase().includes(Q)||ct.title&&ct.title.toLowerCase().includes(Q)||ct.description&&ct.description.toLowerCase().includes(Q)):Lr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Z,onChange:ct=>N(ct.target.value),onClick:ct=>ct.stopPropagation()}),Ve.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ve.map(ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Mn(ct.id),J(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:ih(ct.title||ct.description||ct.id,30)})]},ct.id))]})})()]})]}),e.column==="in-review"&&t.jsx($M,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:hn?.autoMerge??!1,prAuthAvailable:g??!1,onPrCreated:Q=>{e.prInfo=Q,h(`PR #${Q.number} created`,"success")},onPrUpdated:Q=>{e.prInfo=Q},addToast:h})]})]})]}),t.jsx("div",{className:"modal-actions",children:Ue?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:vt,disabled:Tt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Qt,disabled:Tt,children:Tt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&j.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:li,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:_s,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!A&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:wt,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||A||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Pt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{M(Q=>!Q),xe(!1)},"aria-haspopup":"menu","aria-expanded":Ie,children:["Actions",t.jsx(Yt,{size:12})]}),Ie&&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:()=>mt(wt),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mt(Jn),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mt(ie),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mt(Us),children:"Respecify"}),A&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mt(Lt),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>mt(Fs),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:ut,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:bt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Ia,onKeyDown:Fr,disabled:!Zn,"aria-label":Zn?`Move to ${Dn[Zn]}`:void 0,"aria-haspopup":Un?"menu":void 0,"aria-expanded":Un?B:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Zn?Dn[Zn]:""]}),Un&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Yt,{size:12})})]}),B&&Un&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Yi,children:Hs.map(Q=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>qe(Q),onKeyDown:Yi,children:Q==="in-progress"?"Back to In Progress":`Move to ${Dn[Q]}`},Q))})]}),$a?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:$a}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:jt,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:bt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Ia,onKeyDown:Fr,disabled:!Zn,"aria-label":Zn?`Move to ${Dn[Zn]}`:void 0,"aria-haspopup":Un?"menu":void 0,"aria-expanded":Un?B:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Zn?Dn[Zn]:""]}),Un&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Yt,{size:12})})]}),B&&Un&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Yi,children:Hs.map(Q=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>qe(Q),onKeyDown:Yi,children:["Move to ",Dn[Q]]},Q))})]})})]})}),He&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:pn,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Q=>Q.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:pn,"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:Je,onChange:Q=>et(Q.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:[Je.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:mn,disabled:!Je.trim()||st,children:st?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:pn,disabled:st,children:"Cancel"})})]})})]})})}const wA=640;function NA({isOpen:e,onClose:n,onImport:s,tasks:i,projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(""),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState("issues"),[b,v]=a.useState([]),[x,y]=a.useState(null),[S,j]=a.useState([]),[A,w]=a.useState(null),[_,C]=a.useState(null),[L,E]=a.useState(!1),[T,F]=a.useState([]),[K,$]=a.useState(!1),[R,I]=a.useState(""),H=a.useRef(!1),J=a.useRef(null);ri(J,e,"fusion:github-modal-size");const Z=Si(n),[N,z]=a.useState(!1),[P,k]=a.useState("list"),U=a.useRef(null),V=new Set;for(const fe of i){const _e=fe.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);_e&&V.add(_e[1]);const ze=fe.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);ze&&V.add(ze[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),j([]),w(null),f("issues"),C(null),E(!1),F([]),$(!0),I(""),U.current=null,H.current=!0,ky().then(fe=>{if(H.current)if(F(fe),$(!1),fe.length===1){const _e=fe[0];l(_e.owner),u(_e.repo),I(_e.name)}else fe.length>1&&(l(""),u(""),I(""))}).catch(()=>{H.current&&$(!1)}),()=>{H.current=!1}},[e]);const pe=a.useCallback(fe=>{if(I(fe),fe==="")l(""),u("");else{const _e=T.find(ze=>ze.name===fe);_e&&(l(_e.owner),u(_e.repo))}},[T]),ve=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),v([]),y(null);try{const fe=d.split(",").map(ze=>ze.trim()).filter(Boolean),_e=await xy(o.trim(),c.trim(),30,fe.length>0?fe:void 0);v(_e),_e.length===0&&C("No open issues found")}catch(fe){C(ke(fe)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),se=a.useCallback(async()=>{if(!o.trim()||!c.trim()){C("Repository must be selected");return}g(!0),C(null),j([]),w(null);try{const fe=await yy(o.trim(),c.trim(),30);j(fe),fe.length===0&&C("No open pull requests found")}catch(fe){C(ke(fe)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||L)return;const fe={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};U.current?.owner===fe.owner&&U.current?.repo===fe.repo&&U.current?.labels===fe.labels&&U.current?.tab===fe.tab||(U.current=fe,p==="issues"?ve():se())},[o,c,d,p,e,h,L,ve,se]),a.useEffect(()=>{if(!e)return;const fe=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[e,n]),a.useEffect(()=>{if(!e)return;const fe=()=>{z(window.innerWidth<=wA)};return fe(),window.addEventListener("resize",fe),()=>window.removeEventListener("resize",fe)},[e]);const he=a.useCallback(fe=>{y(fe),N&&k("preview")},[N]),O=a.useCallback(fe=>{w(fe),N&&k("preview")},[N]),ue=a.useCallback(()=>{k("list")},[]),te=a.useCallback(async()=>{if(p==="issues"){if(x===null)return;E(!0),C(null);try{const fe=await vy(o.trim(),c.trim(),x,r);s(fe),y(null),N&&P==="preview"&&k("list")}catch(fe){const _e=ke(fe);_e?.includes("already imported")?C(_e):C(_e||"Failed to import issue")}finally{E(!1)}}else{if(A===null)return;E(!0),C(null);try{const fe=await jy(o.trim(),c.trim(),A,r);s(fe),w(null),N&&P==="preview"&&k("list")}catch(fe){const _e=ke(fe);_e?.includes("already imported")?C(_e):C(_e||"Failed to import pull request")}finally{E(!1)}}},[p,x,A,o,c,s,N,P]),me=b.find(fe=>fe.number===x),oe=S.find(fe=>fe.number===A);if(!e)return null;const be=T.length>0,ae=T.length===1,Ee=b.filter(fe=>V.has(fe.html_url)).length,$e=S.filter(fe=>V.has(fe.html_url)).length,He=_==="No open issues found",ot=_==="No open pull requests found",Je=p==="issues"?He:ot,et=!!_&&!He&&b.length===0&&!h,st=!!_&&!ot&&S.length===0&&!h,Oe=p==="issues"?et:st,Ue=h||b.length>0||He||et,re=h||S.length>0||ot||st,Ne=p==="issues"?Ue:re,ee=!!_&&b.length>0&&!He,Ae=!!_&&S.length>0&&!ot,Fe=p==="issues"?ee:Ae;return t.jsx("div",{className:"modal-overlay open",...Z,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:J,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"),w(null)},disabled:h||L,children:[t.jsx(Oo,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{f("pulls"),y(null)},disabled:h||L,children:[t.jsx(Ns,{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:K?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(rt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):be?ae?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:T[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[T[0].owner,"/",T[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:R,onChange:fe=>pe(fe.target.value),disabled:h||L,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),T.map(fe=>t.jsxs("option",{value:fe.name,children:[fe.name," (",fe.owner,"/",fe.repo,")"]},fe.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:fe=>m(fe.target.value),onKeyDown:fe=>fe.key==="Enter"&&ve(),disabled:h||L||!be,"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"?ve:se,disabled:h||L||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Pn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!K&&!be&&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"})]}),Fe&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:_}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${N?"mobile":""} ${P==="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:[Ee," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[$e," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Ne&&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(rt,{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."})]})]}),Oe&&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:_})]})}),Je&&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(fe=>{const _e=V.has(fe.html_url);return t.jsxs("div",{className:`issue-item ${x===fe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&he(fe.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===fe.number,onChange:()=>he(fe.number),disabled:_e,"aria-label":`Select issue #${fe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",fe.number]}),t.jsx("span",{className:"issue-title",children:fe.title})]}),fe.labels.length>0&&t.jsx("span",{className:"issue-labels",children:fe.labels.map(ze=>t.jsx("span",{className:"label-chip",children:ze.name},ze.name))})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},fe.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(fe=>{const _e=V.has(fe.html_url);return t.jsxs("div",{className:`issue-item ${A===fe.number?"selected":""} ${_e?"imported":""}`,onClick:()=>!_e&&O(fe.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:A===fe.number,onChange:()=>O(fe.number),disabled:_e,"aria-label":`Select pull request #${fe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",fe.number]}),t.jsx("span",{className:"issue-title",children:fe.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[fe.headBranch," → ",fe.baseBranch]})]}),_e&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},fe.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${N?"mobile":""} ${P==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[N&&t.jsxs("button",{className:"github-import-back-button",onClick:ue,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ca,{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"&&me?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",me.number]}),t.jsx("div",{className:"preview-title",children:me.title}),t.jsx("div",{className:"preview-body",children:me.body?me.body.slice(0,200)+(me.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"&&oe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",oe.number]}),t.jsx("div",{className:"preview-title",children:oe.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",oe.headBranch," → ",oe.baseBranch]}),t.jsx("div",{className:"preview-body",children:oe.body?oe.body.slice(0,200)+(oe.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:L,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:te,disabled:(p==="issues"?x===null:A===null)||L,children:L?t.jsx(rt,{size:14,className:"spin"}):"Import"})]})]})})}const SA=["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 CA(e,n){return e&&n?`${e}/${n}`:""}function EA(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 _A({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:i,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[u,d]=a.useState(""),[m,h]=a.useState({type:"initial"}),[g,p]=a.useState(null),[f,b]=a.useState([]),[v,x]=a.useState([]),[y,S]=a.useState(null),j=a.useRef(!1),A=a.useRef(!1),[w,_]=a.useState(""),[C,L]=a.useState(!0),[E,T]=a.useState(!1),[F,K]=a.useState(!1),[$,R]=a.useState(null),[I,H]=a.useState(0),J=a.useRef(null),Z=a.useRef(null),N=a.useRef(null),z=a.useRef(null),[P,k]=a.useState(c??null),U=a.useMemo(()=>Ki(),[]),{isLockedByOther:V,takeControl:pe,isLoading:ve}=Xo(e?P:null),{activeTabMap:se,broadcastUpdate:he,broadcastCompleted:O,broadcastLock:ue,broadcastUnlock:te,broadcastHeartbeat:me}=Ma(),[oe,be]=a.useState(void 0),[ae,Ee]=a.useState(void 0),[$e,He]=a.useState([]),[ot,Je]=a.useState(!1),[et,st]=a.useState(null),[Oe,Ue]=a.useState([]),[re,Ne]=a.useState([]),ee=a.useRef(null),[Ae,Fe]=a.useState([]),[fe,_e]=a.useState(!1),[ze,Xe]=a.useState(c??null),[je,ce]=a.useState(!!c),[Re,ge]=a.useState(null),Me=a.useRef(!1),Ge=a.useRef(null);ri(Z,e,"fusion:planning-modal-size"),a.useEffect(()=>{const B=Ge.current;if(!B)return;B.scrollHeight-B.scrollTop-B.clientHeight<32&&(B.scrollTop=B.scrollHeight)},[w]),a.useEffect(()=>{if(m.type!=="loading"){R(null),H(0);return}const B=Date.now();R(B),H(0);const xe=setInterval(()=>{H(Math.max(0,Math.floor((Date.now()-B)/1e3)))},1e3);return()=>clearInterval(xe)},[m.type]);const Pe=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),b([]),x([]),S(null),_(""),T(!1),K(!1),be(void 0),Ee(void 0),z.current=null,k(null)},[]),pt=CA(oe,ae),Y=a.useCallback((B,xe)=>{if(!B||!xe)return"Using default";const Ie=$e.find(M=>M.provider===B&&M.id===xe);return Ie?`${Ie.provider}/${Ie.id}`:`${B}/${xe}`},[$e]),le=a.useCallback(async()=>{Je(!0),st(null);try{const B=await ps();He(B.models),Ue(B.favoriteProviders),Ne(B.favoriteModels)}catch(B){st(ke(B)||"Failed to load models")}finally{Je(!1)}},[]),ye=a.useCallback(B=>{Ue(xe=>{const Ie=xe,ne=Ie.includes(B)?Ie.filter(Le=>Le!==B):[B,...Ie];return fn({favoriteProviders:ne,favoriteModels:re}).catch(()=>{Ue(Ie)}),ne})},[re]),nt=a.useCallback(B=>{Ne(xe=>{const Ie=xe,ne=Ie.includes(B)?Ie.filter(Le=>Le!==B):[B,...Ie];return fn({favoriteProviders:Oe,favoriteModels:ne}).catch(()=>{Ne(Ie)}),ne})},[Oe]),X=a.useCallback(B=>{N.current?.close();const xe=jj(B,l,{onThinking:Ie=>{_(M=>M+Ie),he({sessionId:B,status:"generating",needsInput:!1,owningTabId:U,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:Ie=>{T(!1),K(!1),sa(l),h({type:"question",session:{sessionId:B,currentQuestion:Ie,summary:null}}),_(""),he({sessionId:B,status:"awaiting_input",needsInput:!0,owningTabId:U,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:Ie=>{T(!1),K(!1),sa(l),h({type:"summary",session:{sessionId:B,currentQuestion:null,summary:Ie},summary:Ie}),S(Ie),_(""),he({sessionId:B,status:"complete",needsInput:!1,owningTabId:U,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:Ie=>{const M=Ie||"Session failed while contacting the AI.";T(!0),(async()=>{try{const ne=await ui(B);if(ne&&(ne.status==="generating"||ne.status==="awaiting_input")){X(B);return}}catch{}T(!1),K(!1),p(null),h(ne=>ne.type==="question"||ne.type==="summary"||ne.type==="error"?{type:"error",session:ne.session,errorMessage:M}:{type:"error",session:{sessionId:B,currentQuestion:null,summary:null},errorMessage:M}),_(""),z.current=B,he({sessionId:B,status:"error",needsInput:!1,owningTabId:U,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),O({sessionId:B,status:"error"})})()},onComplete:()=>{T(!1),K(!1),z.current=null,O({sessionId:B,status:"complete"})},onConnectionStateChange:Ie=>{T(Ie==="reconnecting")}});N.current=xe},[O,he,u,l,U]),Qe=a.useCallback(async B=>{const xe=B??u;if(xe.trim()){p(null),_(""),x([]),b([]),T(!1),h({type:"loading"});try{const Ie=oe&&ae?{planningModelProvider:oe,planningModelId:ae}:void 0,{sessionId:M}=await ij(xe.trim(),l,Ie);z.current=M,k(M),Xe(M),X(M),b([])}catch(Ie){T(!1),p(ke(Ie)||"Failed to start planning session"),h({type:"initial"}),z.current=null,k(null)}}},[X,u,ae,oe,l]);a.useEffect(()=>{e&&m.type==="initial"&&J.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&le()},[e,le]),a.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){d(o);const B=setTimeout(()=>{j.current=!0,Qe(o)},0);return()=>clearTimeout(B)}else if(e&&!o&&!j.current&&!A.current&&m.type==="initial"){A.current=!0;const B=b1(l);B&&d(B)}},[e,o,m.type,Qe,l]);const lt=a.useCallback(async B=>{N.current?.close(),N.current=null,p(null),_(""),b([]),x([]),S(null),K(!1),h({type:"loading"});try{const xe=await ui(B);if(!xe){Xe(null),ce(!1),h({type:"initial"});return}z.current=B,k(B);const Ie=xa(xe.conversationHistory);if(x(Ie),b(Ie.map(M=>M.response).filter(M=>!!(M&&typeof M=="object"&&!Array.isArray(M)))),xe.status==="awaiting_input"&&xe.currentQuestion){sa(l);const M=JSON.parse(xe.currentQuestion);h({type:"question",session:{sessionId:B,currentQuestion:M,summary:null}}),xe.thinkingOutput&&_(xe.thinkingOutput),X(B)}else if(xe.status==="complete"&&xe.result){sa(l);const M=JSON.parse(xe.result);h({type:"summary",session:{sessionId:B,currentQuestion:null,summary:M},summary:M}),S(M)}else xe.status==="generating"?(h({type:"loading"}),xe.thinkingOutput&&_(xe.thinkingOutput),X(B)):xe.status==="error"&&h({type:"error",session:{sessionId:B,currentQuestion:null,summary:null},errorMessage:xe.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[X,l]);a.useEffect(()=>{!e||!c||z.current!==c&&(Xe(c),ce(!0),lt(c))},[e,c,lt]),a.useEffect(()=>{e&&ze&&(c&&c===ze||N.current?.isConnected()||lt(ze))},[e]);const ft=a.useCallback(async()=>{_e(!0);try{const xe=(await ld(l)).filter(Ie=>Ie.type==="planning").sort((Ie,M)=>Date.parse(M.updatedAt)-Date.parse(Ie.updatedAt));Fe(xe)}catch{}finally{_e(!1)}},[l]);a.useEffect(()=>{e&&ft()},[e,ft]),a.useEffect(()=>{if(!e)return;const B=l?`?projectId=${encodeURIComponent(l)}`:"",xe=M=>{try{const ne=JSON.parse(M.data);if(ne.type!=="planning")return;Fe(Le=>{const ut=Le.findIndex(Pt=>Pt.id===ne.id);return(ut>=0?[...Le.slice(0,ut),ne,...Le.slice(ut+1)]:[ne,...Le]).sort((Pt,At)=>Date.parse(At.updatedAt)-Date.parse(Pt.updatedAt))})}catch{}},Ie=M=>{try{const ne=JSON.parse(M.data);Fe(Le=>Le.filter(ut=>ut.id!==ne))}catch{}};return Qs(`/api/events${B}`,{events:{"ai_session:updated":xe,"ai_session:deleted":Ie},onReconnect:()=>{ft()}})},[e,l,ft]);const Mt=a.useCallback(B=>{if(ze===B){ce(!0);return}Xe(B),ce(!0),lt(B)},[lt,ze]),yt=a.useCallback(()=>{N.current?.close(),N.current=null,Pe(),Xe(null),ce(!0)},[Pe]),ht=a.useCallback(()=>{ce(!1)},[]),St=a.useCallback(async B=>{const xe=M=>M==="generating"||M==="awaiting_input",Ie=Ae.find(M=>M.id===B);if(Ie&&xe(Ie.status))try{await fp(B,l,U)}catch{}try{await Np(B)}catch{}O({sessionId:B,status:"complete",timestamp:Date.now()}),Fe(M=>M.filter(ne=>ne.id!==B)),ze===B&&(N.current?.close(),N.current=null,Pe(),Xe(null),ce(!1)),ge(null)},[O,Ae,l,Pe,ze,U]);a.useEffect(()=>{e||(j.current=!1,A.current=!1,T(!1),K(!1),k(null))},[e]),a.useEffect(()=>{if(!e){ee.current&&(te(ee.current,U),ee.current=null);return}if(P&&ee.current!==P){ee.current&&te(ee.current,U),ue(P,U),ee.current=P;return}!P&&ee.current&&(te(ee.current,U),ee.current=null)},[ue,te,e,P,U]),a.useEffect(()=>{if(!e||!P||ee.current!==P)return;me(U);const B=setInterval(()=>{me(U)},3e4);return()=>{clearInterval(B)}},[me,e,P,U]),a.useEffect(()=>()=>{N.current?.close(),N.current=null,ee.current&&(te(ee.current,U),ee.current=null)},[te,U]),a.useEffect(()=>{if(!e)return;const B=()=>{N.current?.close(),N.current=null};return window.addEventListener("beforeunload",B),()=>window.removeEventListener("beforeunload",B)},[e]);const zt=a.useCallback(()=>{u&&m.type==="initial"&&g1(u,l),N.current?.close(),N.current=null,T(!1),K(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const B=xe=>{xe.key==="Escape"&&zt()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,zt]);const It=a.useCallback(async B=>{if(m.type!=="question")return;const{session:xe}=m,Ie=xe.sessionId,M=xe.currentQuestion;if(!M){p("No active question in session");return}p(null),b(ne=>[...ne,B]),x(ne=>[...ne,{question:M,response:B}]),h({type:"loading"}),_("");try{await aj(Ie,B,l,U)}catch(ne){p(ke(ne)||"Failed to submit response"),h({type:"question",session:xe})}},[l,U,m]),Rt=a.useCallback(async()=>{const B=z.current;if(B){try{await oj(B,l,U)}catch{}N.current?.close(),N.current=null,T(!1),K(!1),h({type:"error",session:{sessionId:B,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),_("")}},[l,U]),$t=a.useCallback(async()=>{if(m.type!=="error")return;const B=m.session;p(null),K(!0),_(""),h({type:"loading"}),X(B.sessionId);try{z.current=B.sessionId,k(B.sessionId),await rj(B.sessionId,l,U)}catch(xe){let Ie=xe;if((ke(xe)||"").includes("not in an error state"))try{const ne=await ui(B.sessionId);if(!ne)throw new Error("Failed to refresh planning session.");if(z.current=ne.id,k(ne.id),ne.status==="generating")_(ne.thinkingOutput??""),h({type:"loading"});else if(ne.status==="awaiting_input"){if(!ne.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Le=JSON.parse(ne.currentQuestion);sa(l),h({type:"question",session:{sessionId:ne.id,currentQuestion:Le,summary:null}}),N.current?.isConnected()||X(ne.id)}else if(ne.status==="complete"){if(!ne.result)throw new Error("Planning session is complete but has no result.");const Le=JSON.parse(ne.result);sa(l),h({type:"summary",session:{sessionId:ne.id,currentQuestion:null,summary:Le},summary:Le}),S(Le)}else ne.status==="error"&&h({type:"error",session:{sessionId:ne.id,currentQuestion:null,summary:null},errorMessage:ne.error||"Retry failed. Please try again."});T(!1);return}catch(ne){Ie=ne}N.current?.close(),N.current=null,h({type:"error",session:B,errorMessage:ke(Ie)||"Retry failed. Please try again."}),T(!1)}finally{K(!1)}},[X,l,U,m]),Ot=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const B=m.session.sessionId,xe=await lj(B,y??void 0,l);s(xe),Xe(null),Fe(Ie=>Ie.filter(M=>M.id!==B)),O({sessionId:B,status:"complete",timestamp:Date.now()}),zt()}catch(B){p(ke(B)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[O,y,m,l,s,zt]),Vt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const B=await cj(m.session.sessionId,y??void 0,l);k(B.sessionId),h({type:"breakdown",sessionId:B.sessionId,subtasks:B.subtasks,dirty:!1})}catch(B){p(ke(B)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Dt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const B=m.sessionId,xe=await dj(B,m.subtasks,l);i(xe.tasks),Fe(Ie=>Ie.filter(M=>M.id!==B)),O({sessionId:B,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),b([]),x([]),S(null),_(""),be(void 0),Ee(void 0),z.current=null,k(null),Xe(null),n()}catch(B){p(ke(B)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[O,m,i,n,l]),Ft=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const B=f.slice(0,-1);b(B),h({type:"question",session:m.session})}},[m,f]),Ct=()=>m.type==="question"?Math.min(f.length+1,3):3,Nt=P?se.get(P):null,Tt=Nt&&Nt.tabId!==U,Zt=!!(Tt&&!Nt.stale),Ut=V&&(!Tt||Nt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:B=>{Me.current=B.target===B.currentTarget},onClick:B=>{B.target===B.currentTarget&&Me.current&&zt(),Me.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:Z,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[je&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:ht,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(zo,{size:18})}),t.jsx(ii,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:zt,"aria-label":"Close",children:t.jsx(Kt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${je?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(PA,{sessions:Ae,loading:fe,selectedSessionId:ze,pendingDeleteId:Re,onSelectSession:Mt,onNewSession:yt,onRequestDelete:ge,onConfirmDelete:B=>void St(B),onCancelDelete:()=>ge(null)}),t.jsxs("div",{className:"planning-detail",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),E&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Zt&&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(rs,{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:J,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:B=>d(B.target.value),onKeyDown:B=>{B.key==="Enter"&&!B.shiftKey&&u.trim()&&(B.preventDefault(),Qe())}})]}),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:SA.map((B,xe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(B),children:B.length>40?B.slice(0,40)+"...":B},xe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",ot&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Kn,{id:"planning-modal-model",label:"Planning Model",value:pt,onChange:B=>{const{provider:xe,modelId:Ie}=EA(B);be(xe),Ee(Ie)},models:$e,disabled:ot,favoriteProviders:Oe,onToggleFavorite:ye,favoriteModels:re,onToggleModelFavorite:nt}),et&&t.jsxs("div",{className:"form-hint form-hint-error",children:[et," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{le()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${oe&&ae?"model-badge-custom":"model-badge-default"}`,children:Y(oe,ae)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Qe(),disabled:!u.trim(),children:[t.jsx(ii,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),$&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",I,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>L(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void Rt(),children:[t.jsx(ob,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),C&&w&&t.jsx("div",{className:"planning-thinking-output",ref:Ge,children:t.jsx("pre",{children:w})})]})]}),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(Os,{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 $t(),disabled:F,children:[F?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Pn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:zt,disabled:F,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(rt,{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(MA,{question:m.session.currentQuestion,progress:Ct(),historyEntries:v,onSubmit:It,onBack:f.length>0?Ft:void 0})}),m.type==="summary"&&y&&t.jsx(AA,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:Ot,onBreakIntoTasks:Vt,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(TA,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:B=>h({...m,subtasks:B,dirty:!0}),onCreateTasks:Dt,onBack:()=>{const xe={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:xe,summary:y})}})]}),V&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Bo,{size:16}),t.jsx("span",{children:Ut?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ut&&t.jsx("button",{type:"button",onClick:()=>{pe()},disabled:ve,className:"btn btn-primary session-lock-take-control",children:ve?"Taking control...":"Take Control"})]})})]})]})}):null}function MA({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(Os,{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(wn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Kt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Ca,{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(Nr,{size:16,className:"icon-ml-4"})]})]})]})}function AA({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(Os,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{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(Ca,{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(rt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Uo,{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(rt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function rh(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 RA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function TA({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(_=>!_.title.trim())?!0:rh(e),[e]),f=a.useCallback((_,C)=>{i(e.map(L=>L.id===_?{...L,...C}:L))},[e,i]),b=a.useCallback(()=>{i([...e,RA(e.length+1)])},[e,i]),v=a.useCallback(_=>{i(e.filter(C=>C.id!==_).map(C=>({...C,dependsOn:C.dependsOn.filter(L=>L!==_)})))},[e,i]),x=a.useCallback((_,C)=>{if(C<0||C>=e.length)return;const L=[...e],[E]=L.splice(_,1);L.splice(C,0,E),i(L)},[e,i]),y=a.useCallback(_=>C=>{c(_),C.dataTransfer.setData("text/plain",_),C.dataTransfer.effectAllowed="move"},[]),S=a.useCallback(()=>{c(null),d(null),h(null)},[]),j=a.useCallback(_=>C=>{if(C.preventDefault(),_===l)return;const L=C.currentTarget.getBoundingClientRect(),E=L.top+L.height/2,T=C.clientY<E?"before":"after";d(_),h(T)},[l]),A=a.useCallback(_=>C=>{C.preventDefault();const L=C.dataTransfer.getData("text/plain");if(!L||L===_){S();return}const E=e.findIndex(R=>R.id===L),T=e.findIndex(R=>R.id===_);if(E===-1||T===-1){S();return}const F=[...e],[K]=F.splice(E,1);let $=T;m==="after"&&E<T&&$--,m==="after"&&$++,F.splice($,0,K),i(F),S()},[e,m,i,S]),w=a.useCallback(_=>{const C=_.currentTarget.getBoundingClientRect(),L=_.clientX,E=_.clientY;(L<C.left||L>C.right||E<C.top||E>C.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(Uo,{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((_,C)=>{const L=l===_.id,E=u===_.id,T=["task-detail-section","subtask-item",L?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&m==="before"?"subtask-item-drop-before":"",E&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:T,"data-testid":`subtask-item-${C}`,draggable:!s,onDragStart:y(_.id),onDragEnd:S,onDragOver:j(_.id),onDrop:A(_.id),onDragLeave:w,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(id,{size:16}),t.jsx("strong",{children:_.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(C,C-1),disabled:s||C===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Di,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(C,C+1),disabled:s||C===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(wr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(_.id),disabled:s,children:[t.jsx(on,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:F=>{g.current[C]=F},value:_.title,onChange:F=>f(_.id,{title:F.target.value}),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),C<e.length-1&&g.current[C+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:_.description,onChange:F=>f(_.id,{description:F.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:_.suggestedSize,onChange:F=>f(_.id,{suggestedSize:F.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,C).filter(F=>F.id!==_.id).map(F=>{const K=_.dependsOn.includes(F.id);return t.jsxs("label",{className:`planning-dep-chip ${K?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:K,onChange:()=>{const $=K?_.dependsOn.filter(R=>R!==F.id):[..._.dependsOn,F.id];f(_.id,{dependsOn:$})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:F.id}),t.jsx("span",{className:"planning-dep-title",children:F.title||"Untitled"})]},F.id)}),C===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),C>0&&e.slice(0,C).filter(F=>F.id!==_.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},_.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(ln,{size:16,className:"icon-mr-6"})," Add subtask"]}),rh(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(Ca,{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(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function PA({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:i,onSelectSession:r,onNewSession:o,onRequestDelete:l,onConfirmDelete:c,onCancelDelete:u}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:o,type:"button",children:[t.jsx(yx,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(d=>{const m=d.id===s,h=i===d.id;return t.jsxs("div",{className:`planning-sidebar-item ${m?"selected":""} ${h?"pending-delete":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>r(d.id),children:[t.jsx(IA,{status:d.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:d.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx($A,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:DA(d.updatedAt)})]})]})]}),h?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>c(d.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,children:"Cancel"})]}):t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:g=>{g.stopPropagation(),l(d.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(on,{size:14})})]},d.id)})]})]})}function IA({status:e}){switch(e){case"generating":return t.jsx(rt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(kc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(wn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(hs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(wi,{size:14,className:"planning-sidebar-status-icon"})}}function $A({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function DA(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const i=Math.floor(s/60);if(i<60)return`${i}m ago`;const r=Math.floor(i/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function LA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function oh(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 zA({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:i,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,u]=a.useState({type:"initial"}),[d,m]=a.useState([]),[h,g]=a.useState([]),[p,f]=a.useState(""),[b,v]=a.useState(!0),[x,y]=a.useState(!1),[S,j]=a.useState(!1),[A,w]=a.useState(s),[_,C]=a.useState(null),[L,E]=a.useState(!1),[T,F]=a.useState(null),[K,$]=a.useState(null),[R,I]=a.useState(null),H=a.useRef(null),J=a.useRef([]),Z=a.useRef(!1),N=a.useRef(null),z=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,P=a.useMemo(()=>Ki(),[]),{isLockedByOther:k,takeControl:U,isLoading:V}=Xo(e?z:null),{activeTabMap:pe,broadcastUpdate:ve,broadcastCompleted:se,broadcastLock:he,broadcastUnlock:O,broadcastHeartbeat:ue}=Ma(),te=a.useMemo(()=>d.length===0||d.some(ce=>!ce.title.trim())?!0:oh(d),[d]),me=c.type==="generating"||c.type==="editing"||c.type==="error",oe=z?pe.get(z):null,{confirm:be}=Ys(),ae=oe&&oe.tabId!==P,Ee=!!(ae&&!oe.stale),$e=k&&(!ae||oe.stale),He=a.useCallback(()=>{A&&x1(A,o),H.current?.close(),H.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),j(!1),C(null),E(!1),Z.current=!1},[A,o]),ot=a.useCallback(()=>{H.current?.close(),H.current=null,n()},[n]),Je=a.useCallback(async()=>{if(!((L||c.type==="editing"||c.type==="creating")&&!await be({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(z)try{await xp(z,o,P)}catch{}He(),n()}},[L,n,He,z,P,c.type,o,be]),et=a.useCallback(ce=>{H.current?.close(),H.current=Lj(ce,o,{onThinking:Re=>{f(ge=>ge+Re),ve({sessionId:ce,status:"generating",needsInput:!1,owningTabId:P,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Re=>{y(!1),j(!1),Cl(o),m(Re),u({type:"editing",sessionId:ce}),E(!1),ve({sessionId:ce,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:o??null})},onError:Re=>{const ge=Re||"Session failed while contacting the AI.";y(!1),j(!1),C(null),u({type:"error",sessionId:ce,errorMessage:ge}),ve({sessionId:ce,status:"error",needsInput:!1,owningTabId:P,type:"subtask",title:A.trim()||"Subtask breakdown",projectId:o??null}),se({sessionId:ce,status:"error"})},onComplete:()=>{se({sessionId:ce,status:"complete"})},onConnectionStateChange:Re=>{y(Re==="reconnecting")}})},[se,ve,A,o,P]),st=a.useCallback(async()=>{if(A.trim()){C(null),g([]),f(""),y(!1);try{const{sessionId:ce}=await Ij(A.trim(),o);u({type:"generating",sessionId:ce}),et(ce)}catch(ce){C(ke(ce)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[et,A,o]);a.useEffect(()=>{if(!e){He();return}if(e&&s&&!Z.current)w(s),Z.current=!0,st();else if(e&&!s&&!Z.current){const ce=v1(o);ce&&w(ce)}},[e,s,st,He]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const ce=await ui(l);if(!ce)return;const Re=xa(ce.conversationHistory);if(g(Re),ce.status==="generating"||ce.status==="awaiting_input")f(ce.thinkingOutput??""),u({type:"generating",sessionId:l}),et(l);else if(ce.status==="complete"&&ce.result){Cl(o);const ge=JSON.parse(ce.result);m(ge),u({type:"editing",sessionId:l})}else ce.status==="error"&&(C(null),u({type:"error",sessionId:l,errorMessage:ce.error??"Session encountered an error"}))}catch(ce){C(ke(ce)||"Failed to resume session")}})()},[et,e,l,c.type,o]),a.useEffect(()=>{if(!e){N.current&&(O(N.current,P),N.current=null);return}if(z&&N.current!==z){N.current&&O(N.current,P),he(z,P),N.current=z;return}!z&&N.current&&(O(N.current,P),N.current=null)},[he,O,e,z,P]),a.useEffect(()=>{if(!e||!z||N.current!==z)return;ue(P);const ce=setInterval(()=>{ue(P)},3e4);return()=>{clearInterval(ce)}},[ue,e,z,P]),a.useEffect(()=>()=>{H.current?.close(),N.current&&(O(N.current,P),N.current=null)},[O,P]),a.useEffect(()=>{if(!e)return;const ce=Re=>{Re.key==="Escape"&&(Re.preventDefault(),Je())};return document.addEventListener("keydown",ce),()=>document.removeEventListener("keydown",ce)},[e,Je]);const Oe=a.useCallback((ce,Re)=>{m(ge=>ge.map(Me=>Me.id===ce?{...Me,...Re}:Me)),E(!0)},[]),Ue=a.useCallback(()=>{m(ce=>[...ce,LA(ce.length+1)]),E(!0)},[]),re=a.useCallback(ce=>{m(Re=>Re.filter(ge=>ge.id!==ce).map(ge=>({...ge,dependsOn:ge.dependsOn.filter(Me=>Me!==ce)}))),E(!0)},[]),Ne=a.useCallback(ce=>Re=>{F(ce),Re.dataTransfer.setData("text/plain",ce),Re.dataTransfer.effectAllowed="move"},[]),ee=a.useCallback(()=>{F(null),$(null),I(null)},[]),Ae=a.useCallback(ce=>Re=>{if(Re.preventDefault(),ce===T)return;const ge=Re.currentTarget.getBoundingClientRect(),Me=ge.top+ge.height/2,Ge=Re.clientY<Me?"before":"after";$(ce),I(Ge)},[T]),Fe=a.useCallback(ce=>Re=>{Re.preventDefault();const ge=Re.dataTransfer.getData("text/plain");if(!ge||ge===ce){F(null),$(null),I(null);return}m(Me=>{const Ge=Me.findIndex(ye=>ye.id===ge),Pe=Me.findIndex(ye=>ye.id===ce);if(Ge===-1||Pe===-1)return Me;const pt=[...Me],[Y]=pt.splice(Ge,1);let le=Pe;return R==="after"&&Ge<Pe&&le--,R==="after"&&le++,pt.splice(le,0,Y),pt}),E(!0),F(null),$(null),I(null)},[R]),fe=a.useCallback(ce=>{const Re=ce.currentTarget.getBoundingClientRect(),ge=ce.clientX,Me=ce.clientY;(ge<Re.left||ge>Re.right||Me<Re.top||Me>Re.bottom)&&($(null),I(null))},[]),_e=a.useCallback((ce,Re)=>{Re<0||Re>=d.length||(m(ge=>{const Me=[...ge],[Ge]=Me.splice(ce,1);return Me.splice(Re,0,Ge),Me}),E(!0))},[d.length]),ze=a.useCallback(ce=>{J.current[ce+1]?.focus()},[]),Xe=a.useCallback(async()=>{if(!(!z||te)){C(null),u({type:"creating",sessionId:z});try{const ce=await zj(z,d,r,o);i(ce.tasks),He(),n()}catch(ce){C(ke(ce)||"Failed to create tasks"),u({type:"editing",sessionId:z})}}},[te,n,i,r,o,He,z,d]),je=a.useCallback(async()=>{if(c.type!=="error")return;const ce=c.sessionId;C(null),j(!0),f(""),u({type:"generating",sessionId:ce}),et(ce);try{await $j(ce,o,P)}catch(Re){let ge=Re;if((ke(Re)||"").includes("not in an error state"))try{const Ge=await ui(ce);if(!Ge)throw new Error("Failed to refresh subtask session.");if(g(xa(Ge.conversationHistory)),Ge.status==="generating"||Ge.status==="awaiting_input")f(Ge.thinkingOutput??""),u({type:"generating",sessionId:Ge.id}),H.current?.isConnected()||et(Ge.id);else if(Ge.status==="complete"){if(!Ge.result)throw new Error("Subtask session is complete but has no result.");Cl(o);const Pe=JSON.parse(Ge.result);m(Pe),u({type:"editing",sessionId:Ge.id}),E(!1)}else Ge.status==="error"&&u({type:"error",sessionId:Ge.id,errorMessage:Ge.error??"Retry failed. Please try again."});y(!1);return}catch(Ge){ge=Ge}H.current?.close(),H.current=null,u({type:"error",sessionId:ce,errorMessage:ke(ge)||"Retry failed. Please try again."}),y(!1)}finally{j(!1)}},[et,o,P,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:ce=>ce.target===ce.currentTarget&&void Je(),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(Uo,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[me&&t.jsx("button",{className:"modal-send-to-background",onClick:ot,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Je(),"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[_&&t.jsx("div",{className:"form-error planning-error",children:_}),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:A})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Os,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(rt,{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(Os,{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 je(),disabled:S,children:[S?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Pn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:S?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Je(),disabled:S,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(Os,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(wn,{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((ce,Re)=>{const ge=T===ce.id,Me=K===ce.id,Ge=["task-detail-section","subtask-item",ge?"subtask-item-dragging":"",Me?"subtask-item-drop-target":"",Me&&R==="before"?"subtask-item-drop-before":"",Me&&R==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Ge,"data-testid":`subtask-item-${Re}`,draggable:c.type!=="creating",onDragStart:Ne(ce.id),onDragEnd:ee,onDragOver:Ae(ce.id),onDrop:Fe(ce.id),onDragLeave:fe,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(id,{size:16}),t.jsx("strong",{children:ce.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Re,Re-1),disabled:c.type==="creating"||Re===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Di,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(Re,Re+1),disabled:c.type==="creating"||Re===d.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(wr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>re(ce.id),disabled:c.type==="creating",children:[t.jsx(on,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:Pe=>{J.current[Re]=Pe},value:ce.title,onChange:Pe=>Oe(ce.id,{title:Pe.target.value}),onKeyDown:Pe=>{Pe.key==="Enter"&&(Pe.preventDefault(),ze(Re))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:ce.description,onChange:Pe=>Oe(ce.id,{description:Pe.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:ce.suggestedSize,onChange:Pe=>Oe(ce.id,{suggestedSize:Pe.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,Re).filter(Pe=>Pe.id!==ce.id).map(Pe=>{const pt=ce.dependsOn.includes(Pe.id);return t.jsxs("label",{className:`planning-dep-chip ${pt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:pt,onChange:()=>{const Y=pt?ce.dependsOn.filter(le=>le!==Pe.id):[...ce.dependsOn,Pe.id];Oe(ce.id,{dependsOn:Y})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Pe.id}),t.jsx("span",{className:"planning-dep-title",children:Pe.title||"Untitled"})]},Pe.id)}),Re===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Re>0&&d.slice(0,Re).filter(Pe=>Pe.id!==ce.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},ce.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ue,disabled:c.type==="creating",children:[t.jsx(ln,{size:16,className:"icon-mr-6"})," Add subtask"]}),oh(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 Je(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void Xe(),disabled:c.type==="creating"||te,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),k&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Bo,{size:16}),t.jsx("span",{children:$e?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),$e&&t.jsx("button",{type:"button",onClick:()=>{U()},disabled:V,className:"btn btn-primary session-lock-take-control",children:V?"Taking control...":"Take Control"})]})})]})]})}):null}const OA=5,FA=1e3,UA=45e3;function co(){return{scrollback:null,connected:null,data:[]}}function BA(e,n){const[s,i]=a.useState("disconnected"),r=a.useRef(0),o=a.useRef(e),l=a.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const u=a.useRef(null),d=a.useRef(0),m=a.useRef(null),h=a.useRef(null),g=a.useRef(!1),p=a.useRef(new Set),f=a.useRef(new Set),b=a.useRef(new Set),v=a.useRef(new Set),x=a.useRef(new Set),y=a.useRef(co()),S=a.useCallback($=>{p.current.add($);const R=y.current;return R.data.length>0&&(R.data.forEach(I=>$(I)),R.data=[]),()=>p.current.delete($)},[]),j=a.useCallback($=>(f.current.add($),()=>f.current.delete($)),[]),A=a.useCallback($=>{b.current.add($);const R=y.current;return R.connected&&($(R.connected),R.connected=null),()=>b.current.delete($)},[]),w=a.useCallback($=>{v.current.add($);const R=y.current;return R.scrollback&&($(R.scrollback),R.scrollback=null),()=>v.current.delete($)},[]),_=a.useCallback($=>(x.current.add($),()=>x.current.delete($)),[]),C=a.useCallback($=>{const R=u.current;R?.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"input",data:$}))},[]),L=a.useCallback(($,R)=>{const I=u.current;I?.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"resize",cols:$,rows:R}))},[]),E=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(u.current.onopen=null,u.current.onmessage=null,u.current.onclose=null,u.current.onerror=null,u.current.close(),u.current=null),y.current=co()},[]),T=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),y.current=co()},[]),F=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 I=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(I+=`&projectId=${encodeURIComponent(n)}`);const H=new WebSocket(ai(I));u.current=H,H.onopen=()=>{if(r.current!==$){H.close();return}y.current=co(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===$&&H.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"ping"}))},UA)},H.onmessage=J=>{if(r.current===$)try{const Z=JSON.parse(J.data),N=y.current;switch(Z.type){case"data":Z.data&&(p.current.size===0&&N.data.push(Z.data),p.current.forEach(z=>z(Z.data)));break;case"scrollback":Z.data&&(N.scrollback=Z.data,v.current.forEach(z=>z(Z.data)));break;case"connected":Z.shell&&Z.cwd&&(N.connected={shell:Z.shell,cwd:Z.cwd},b.current.forEach(z=>z({shell:Z.shell,cwd:Z.cwd})));break;case"exit":Z.exitCode!==void 0&&f.current.forEach(z=>z(Z.exitCode));break;case"ping":H.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},H.onclose=J=>{if(r.current!==$)return;if(u.current=null,h.current&&(clearInterval(h.current),h.current=null),g.current){i("disconnected");return}if(J.code===4e3||J.code===4004){i("disconnected"),J.code===4004&&x.current.forEach(z=>z());return}if(d.current++,d.current>OA){i("disconnected");return}const Z=FA*Math.pow(2,d.current-1);i("reconnecting");const N=r.current;m.current=setTimeout(()=>{r.current===N&&(g.current||F())},Math.min(Z,16e3))},H.onerror=()=>{}},[e,n]),K=a.useCallback(()=>{d.current=0,T(),F()},[T,F]);return a.useEffect(()=>(c&&(E(),d.current=0,i("disconnected")),e?F():i("disconnected"),T),[e,n,c,F,T,E]),{connectionStatus:s,sendInput:C,resize:L,onData:S,onExit:j,onConnect:A,onScrollback:w,reconnect:K,onSessionInvalid:_}}const rg="kb-terminal-tabs",HA=15e3,qA=15e3;function lh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function ch(e){if(typeof window>"u")return[];try{const n=Gn(rg,e);if(n)return JSON.parse(n)}catch{}return[]}function ac(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function dh(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 VA(e){const[n,s]=a.useState(()=>ch(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(ch(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{xs(rg,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let A=!1;const w=h.current;return(async()=>{if(!A)try{const C=await dh(Ry(e),HA,"listTerminalSessions");if(A||w!==h.current)return;const L=new Set(C.map(E=>E.id));l(!0),s(E=>{if(A||w!==h.current)return E;const F=E.map(R=>({...R,_verified:L.has(R.sessionId)})).filter(R=>R._verified);if(F.length===0)return[];const K=F.map(({_verified:R,...I})=>I);return K.find(R=>R.isActive)?K:K.map((R,I)=>({...R,isActive:I===0}))}),r(!0)}catch(C){if(A||w!==h.current)return;const L=ac(C);L||console.warn("Failed to validate terminal sessions with server:",C),l(!L),r(!0)}})(),()=>{A=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const A=h.current,w=setTimeout(()=>{dh(qr(void 0,void 0,void 0,e),qA,"createTerminalSession").then(_=>{if(A!==h.current)return;const C={id:lh(),sessionId:_.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(L=>L.length>0?L:[...L.map(T=>({...T,isActive:!1})),C]),u(null)}).catch(_=>{if(A!==h.current)return;ac(_)||console.error(_);const C=_ instanceof Error?_.message:typeof _=="string"?_:"Failed to create terminal session";u(C)})},0);return()=>clearTimeout(w)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const A=await qr(void 0,void 0,void 0,e),w={id:lh(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(_=>[..._.map(L=>({...L,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(A=>{s(w=>{const _=w.find(T=>T.id===A);if(!_)return w;Jd(_.sessionId,e).catch(T=>{console.warn(`Failed to kill terminal session ${_.sessionId}:`,T)});const C=w.findIndex(T=>T.id===A),L=_.isActive,E=w.filter(T=>T.id!==A);if(E.length===0)return[];if(L){const T=Math.min(C,E.length-1);return E.map((F,K)=>({...F,isActive:K===T}))}return E})},[]),b=a.useCallback(A=>{s(w=>{let _=!1;const C=w.map(L=>L.id===A?(_=!0,{...L,isActive:!0}):{...L,isActive:!1});return _?C:w})},[]),v=a.useCallback((A,w)=>{s(_=>_.map(C=>C.id===A?{...C,title:w}:C))},[]),x=a.useCallback(async()=>{s(_=>{const C=_.find(L=>L.isActive);return C&&Jd(C.sessionId,e).catch(L=>{console.warn(`Failed to kill old session ${C.sessionId}:`,L)}),_});const A=n.find(_=>_.isActive);if(!A)return;const w=await qr(void 0,void 0,void 0,e);s(_=>_.map(C=>C.id===A.id?{...C,sessionId:w.sessionId}:C))},[n]),y=a.useCallback(async()=>{const A=n.find(w=>w.isActive);if(A)try{const w=await qr(void 0,void 0,void 0,e);s(_=>_.map(C=>C.id===A.id?{...C,sessionId:w.sessionId}:C)),u(null)}catch(w){ac(w)||console.error(w);const _=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";u(_)}},[n]),S=n.find(A=>A.isActive)??null,j=a.useCallback(()=>{u(null),h.current+=1,m(A=>A+1)},[]);return{tabs:n,activeTab:S,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:j,replaceActiveTabSession:y}}const WA=1e4,KA=[500,1500,3e3],og="kb-terminal-font-size",rr=14,GA=8,JA=32;function YA(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 QA(e){return`\x1B${e}`}const XA=[{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 or(e){return Math.min(JA,Math.max(GA,e))}function ZA(){if(typeof window>"u")return rr;try{const e=window.localStorage.getItem(og);if(!e)return rr;const n=Number.parseInt(e,10);return Number.isFinite(n)?or(n):rr}catch{return rr}}function eR(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 tR(e){return new Promise(n=>setTimeout(n,e))}async function nR(e,n=KA){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!eR(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 tR(o)}throw s??new Error("Dynamic import failed")}function uh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function sR(){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=iR()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let rc=null;function iR(){return rc===null&&(rc=window.innerHeight),rc}function aR({isOpen:e,onClose:n,initialCommand:s,projectId:i}){const[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(0),[f,b]=a.useState(0),[v,x]=a.useState(null),[y,S]=a.useState(()=>ZA()),[j,A]=a.useState(!1),[w,_]=a.useState(null),C=a.useRef(null),L=a.useRef(null),E=a.useRef(!1);ri(L,e,"fusion:terminal-modal-size");const T=a.useRef(null),F=a.useRef(null),K=a.useRef(!1),$=a.useRef(!1),R=a.useRef(null),I=a.useRef(()=>{}),H=a.useRef(null),J=a.useRef(0),Z=a.useRef(y),N=a.useRef(null),z=a.useRef(i);J.current=f,Z.current=y;const P=a.useCallback(ge=>{if(ge&&$.current!==ge)return;const Me=F.current,Ge=T.current,Pe=R.current;if(!(!Me||!Ge)&&!(ge&&$.current!==ge))try{Me.fit(),Pe&&Pe(Ge.cols,Ge.rows)}catch{}},[]);a.useEffect(()=>{e&&p(ge=>ge+1)},[e]),a.useEffect(()=>{if(!e||!uh())return;const ge=window.visualViewport;if(!ge)return;const Me=()=>{const Ge=sR();b(Ge),x(ge.height),Ge>0&&L.current?.scrollIntoView&&L.current.scrollIntoView({block:"end",behavior:"smooth"}),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const Pe=typeof $.current=="string"?$.current:void 0;N.current=requestAnimationFrame(()=>{N.current=null,P(Pe)})};return Me(),ge.addEventListener("resize",Me),ge.addEventListener("scroll",Me),()=>{ge.removeEventListener("resize",Me),ge.removeEventListener("scroll",Me),N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),b(0),x(null)}},[P,e]),a.useEffect(()=>{if(!e)return;const ge=L.current;if(!ge||typeof ResizeObserver>"u")return;let Me=null;const Ge=new ResizeObserver(()=>{Me!==null&&cancelAnimationFrame(Me),Me=requestAnimationFrame(()=>{Me=null;const Pe=typeof $.current=="string"?$.current:void 0;P(Pe)})});return Ge.observe(ge),()=>{Ge.disconnect(),Me!==null&&cancelAnimationFrame(Me)}},[P,e]);const{tabs:k,activeTab:U,isReady:V,bootstrapError:pe,createTab:ve,closeTab:se,setActiveTab:he,updateTabTitle:O,restartActiveTab:ue,retryBootstrap:te,replaceActiveTabSession:me}=VA(i),{connectionStatus:oe,sendInput:be,resize:ae,onData:Ee,onConnect:$e,onExit:He,onScrollback:ot,reconnect:Je,onSessionInvalid:et}=BA(U?.sessionId??null,i);R.current=ae,I.current=be,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(og,String(y))}catch{}},[y]);const st=a.useCallback(()=>{const ge=T.current;if(ge)try{F.current?.fit(),ae(ge.cols,ge.rows)}catch{}},[ae]);a.useEffect(()=>{if(!e||!V)return;const ge=U?.sessionId;if(!ge)return;const Me=z.current!==i;if(Me&&(z.current=i),$.current===ge&&T.current&&!Me)return;T.current&&($.current!==ge||Me)&&(T.current.dispose(),T.current=null,F.current=null,$.current=!1,H.current&&(window.removeEventListener("resize",H.current),H.current=null),d(!1),h(null));let Ge=!0,Pe;return(async()=>{const Y=nR(()=>Promise.all([dn(()=>import("./vendor-xterm-DzcZoU0P.js").then(X=>X.x),__vite__mapDeps([0,1,2])),dn(()=>import("./addon-fit-C7jRorKK.js").then(X=>X.a),__vite__mapDeps([3,1])),dn(()=>import("./addon-web-links-CkJwd4cQ.js").then(X=>X.a),__vite__mapDeps([4,1]))])),le=new Promise((X,Qe)=>{Pe=setTimeout(()=>{Qe(new Error("xterm initialization timed out"))},WA)});let ye,nt;try{const[{Terminal:X},{FitAddon:Qe},{WebLinksAddon:lt}]=await Promise.race([Y,le]);if(!Ge||!C.current||T.current)return;ye=new X({cursorBlink:!0,cursorStyle:"block",fontSize:Z.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}),nt=new Qe,ye.loadAddon(nt);const ft=new lt;if(ye.loadAddon(ft),!uh())try{const{WebglAddon:ht}=await dn(async()=>{const{WebglAddon:zt}=await import("./addon-webgl-BjvOw43o.js").then(It=>It.a);return{WebglAddon:zt}},__vite__mapDeps([5,1])),St=new ht;St.onContextLoss(()=>{St.dispose()}),ye.loadAddon(St)}catch{}ye.open(C.current),Pe&&clearTimeout(Pe);const Mt=C.current?.querySelector(".xterm-helper-textarea");if(Mt&&Mt.focus(),C.current)try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{nt.fit();const ht=C.current?.querySelector(".xterm-helper-textarea");ht&&ht.focus()},50),T.current=ye,F.current=nt,$.current=ge,J.current>0&&(N.current!==null&&(cancelAnimationFrame(N.current),N.current=null),N.current=requestAnimationFrame(()=>{N.current=null,P(ge)})),ye.onData(ht=>{$.current===ge&&I.current(ht)});const yt=()=>{if($.current===ge&&F.current&&T.current)try{F.current.fit();const{cols:ht,rows:St}=T.current;R.current?.(ht,St)}catch{}};window.addEventListener("resize",yt),H.current&&window.removeEventListener("resize",H.current),H.current=yt,d(!0),h(null)}catch(X){if(Pe&&clearTimeout(Pe),!Ge)return;const Qe=X instanceof Error?X.message:"xterm initialization failed";h(Qe)}})(),()=>{Ge=!1,Pe&&clearTimeout(Pe)}},[P,e,V,U?.sessionId,i]),a.useEffect(()=>{e||(T.current&&(T.current.dispose(),T.current=null),F.current=null,$.current=!1,H.current&&(window.removeEventListener("resize",H.current),H.current=null),d(!1),h(null),K.current=!1,o(null),c(null),A(!1),_(null))},[e]),a.useEffect(()=>{if(!u||!T.current||!U)return;const ge=U.sessionId,Me=le=>{$.current===ge&&T.current?.write(le)},Ge=Ee(le=>{Me(le)}),Pe=ot(le=>{Me(le)}),pt=$e(le=>{O(U.id,ud(le.shell)||le.shell)}),Y=He(le=>{$.current===ge&&(c(le),T.current?.write(`\r
653
- \x1B[33m[Process exited with code ${le}]\x1B[0m\r
654
- `))});return()=>{Ge(),Pe(),pt(),Y()}},[u,U?.sessionId,U?.id,U,oe,Ee,ot,$e,He,O]),a.useEffect(()=>{oe==="connected"&&s&&K.current!==s&&U&&(K.current=s,setTimeout(()=>{be(s+`
655
- `)},500))},[oe,s,be,U,g]),a.useEffect(()=>{if(!u||!T.current)return;T.current.options.fontSize=y,N.current!==null&&(cancelAnimationFrame(N.current),N.current=null);const ge=requestAnimationFrame(()=>{N.current=null,st()});return N.current=ge,()=>{N.current===ge&&(cancelAnimationFrame(ge),N.current=null)}},[y,u,st]),a.useEffect(()=>{if(!e)return;const ge=Me=>{if(!(!Me.ctrlKey&&!Me.metaKey)){if(Me.code==="Equal"||Me.code==="NumpadAdd"){Me.preventDefault(),S(Ge=>or(Ge+1));return}if(Me.code==="Minus"||Me.code==="NumpadSubtract"){Me.preventDefault(),S(Ge=>or(Ge-1));return}if(Me.code==="Digit0"||Me.code==="Numpad0"){Me.preventDefault(),S(rr);return}}};return window.addEventListener("keydown",ge),()=>window.removeEventListener("keydown",ge)},[e,st]),a.useEffect(()=>{if(!e)return;const ge=Me=>{Me.key==="Escape"&&n()};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[e,n]),a.useEffect(()=>{oe==="connected"&&T.current&&setTimeout(()=>{if(!T.current||!C.current)return;const ge=C.current.querySelector(".xterm-helper-textarea");ge&&ge.focus();try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[oe]);const Oe=a.useCallback(()=>{if(!C.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;T.current?.focus();const Me=C.current.querySelector(".xterm-helper-textarea");if(!Me)return;Me.autocapitalize="off",Me.autocomplete="off",Me.autocorrect="off",Me.spellcheck=!1,Me.setAttribute("inputmode","text");try{Me.focus({preventScroll:!0})}catch{Me.focus()}const Ge=Me.value.length;Me.setSelectionRange(Ge,Ge)},[]);a.useEffect(()=>et(()=>{T.current?.clear(),c(null),K.current=!1,T.current&&(T.current.dispose(),T.current=null),F.current=null,$.current=!1,H.current&&(window.removeEventListener("resize",H.current),H.current=null),d(!1),h(null),me().catch(Me=>{console.error("Failed to replace invalid terminal session:",Me)})}),[et,me]);const Ue=a.useCallback(ge=>{ge.target===ge.currentTarget&&(E.current=!0)},[]),re=a.useCallback(ge=>{E.current&&ge.target===ge.currentTarget&&n(),E.current=!1},[n]),Ne=a.useCallback(()=>{T.current?.clear()},[]),ee=a.useCallback(async()=>{T.current?.clear(),c(null),K.current=!1;try{await ue()}catch(ge){o(ke(ge)||"Failed to restart terminal session")}},[ue]),Ae=a.useCallback(()=>{T.current&&(T.current.dispose(),T.current=null),F.current=null,$.current=!1,H.current&&(window.removeEventListener("resize",H.current),H.current=null),h(null),d(!1)},[]),Fe=a.useCallback(()=>{window.location.reload()},[]),fe=a.useCallback(()=>{S(ge=>or(ge+1))},[]),_e=a.useCallback(()=>{S(ge=>or(ge-1))},[]),ze=a.useCallback(ge=>{_(Me=>Me===ge?null:ge)},[]),Xe=a.useCallback(ge=>{if(w==="ctrl"){be(YA(ge)),_(null);return}if(w==="alt"){be(QA(ge)),_(null);return}be(ge)},[be,w]),je=a.useCallback(ge=>{be(ge),_(null)},[be]);if(!e)return null;const ce=()=>{switch(oe){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}},Re=!V||!U&&!pe;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ue,onMouseUp:re,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:L,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:[k.map(ge=>t.jsxs("div",{className:`terminal-tab ${ge.isActive?"terminal-tab--active":""}`,onClick:()=>he(ge.id),title:ge.title,role:"tab","aria-selected":ge.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:ge.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Me=>{Me.stopPropagation(),se(ge.id)},title:"Close tab",children:"×"})]},ge.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ve,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(di,{size:16}),ce()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[oe==="disconnected"&&U&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Je,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Pn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:ee,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Pn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ne,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(on,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>A(ge=>!ge),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(ax,{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(Kt,{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:[Re&&!pe&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),pe&&!U&&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: ",pe]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:te,"data-testid":"terminal-retry-btn",children:[t.jsx(Pn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Pn,{size:14}),"Refresh page"]})]})]})}),m&&U&&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:Ae,"data-testid":"terminal-reinit-btn",children:[t.jsx(Pn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Pn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:C,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Oe,onTouchStart:Oe},U?.sessionId)]}),j&&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 ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>ze("ctrl"),"aria-pressed":w==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>ze("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>je("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>je(" "),children:"Tab"})]}),XA.map(ge=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Xe(ge.key),title:ge.description,children:ge.label},ge.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${oe}`,children:[oe==="connected"&&"Connected",oe==="connecting"&&"Connecting...",oe==="reconnecting"&&"Reconnecting...",oe==="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:_e,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Nx,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:fe,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(ln,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Qa={name:"",command:""};function mh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function rR(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function oR({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(Qa),[b,v]=a.useState(!1),[x,y]=a.useState(null),[S,j]=a.useState(null),A=Si(n),w=a.useCallback(async()=>{try{u(!0);const I=await vr(i);l(I)}catch(I){s(ke(I)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&w()},[e,w]);const _=a.useCallback(()=>{m(!0),g(null),f(Qa),j(null)},[]),C=a.useCallback((I,H)=>{g(I),m(!1),f({name:I,command:H}),j(null)},[]),L=a.useCallback(()=>{g(null),m(!1),f(Qa),j(null)},[]),E=a.useCallback(I=>{f(H=>({...H,name:I})),I&&!mh(I)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),T=a.useCallback(async()=>{const I=p.name.trim(),H=p.command.trim();if(!I){s("Script name is required","error");return}if(!mh(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!H){s("Script command is required","error");return}v(!0);try{await Tj(I,H,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Qa),j(null),await w()}catch(J){const Z=ke(J);Z?.includes("already exists")?s("A script with this name already exists","error"):s(Z||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,i]),F=a.useCallback(async I=>{try{await Pj(I,i),s("Script deleted","success"),y(null),h===I&&(g(null),f(Qa)),await w()}catch(H){s(ke(H)||"Failed to delete script","error")}},[h,s,w,i]),K=a.useCallback((I,H)=>{r&&r(I,H)},[r]);if(!e)return null;const $=d||h!==null,R=Object.entries(o).map(([I,H])=>({name:I,command:H}));return t.jsx("div",{className:"modal-overlay open",...A,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(di,{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(rt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):$?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:I=>E(I.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),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:I=>f(H=>({...H,command:I.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:L,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:T,disabled:b||!!S,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(rt,{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:R.length===0?"No scripts defined":`${R.length} script${R.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:_,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(ln,{size:14}),"Add Script"]})]}),R.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(di,{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:R.map(I=>t.jsx("div",{className:"script-card","data-testid":`script-${I.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:I.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.command,children:rR(I.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:()=>K(I.name,I.command),title:"Run script","aria-label":`Run ${I.name}`,"data-testid":`run-script-${I.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Cn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>C(I.name,I.command),title:"Edit","aria-label":`Edit ${I.name}`,"data-testid":`edit-script-${I.name}`,children:t.jsx(ln,{size:14,style:{transform:"rotate(45deg)"}})}),x===I.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>F(I.name),title:"Confirm delete","aria-label":`Confirm delete ${I.name}`,"data-testid":`confirm-delete-script-${I.name}`,style:{color:"var(--color-error)"},children:t.jsx(on,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${I.name}`,children:t.jsx(Kt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(I.name),title:"Delete","aria-label":`Delete ${I.name}`,"data-testid":`delete-script-${I.name}`,children:t.jsx(on,{size:14})})]})]})},I.name))})]})})]})})}function lR(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 Jy(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(ke(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 cR(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(S=>{o(S),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let S=!1;async function j(){h(!0),b(null);try{const A=await Yy(e,n,i);S||(o(A.content),c(A.content),d(A.mtime))}catch(A){S||(b(ke(A)||"Failed to load file"),o(""),c(""),d(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,i]);const x=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const S=await Qy(e,n,r,i);c(r),d(S.mtime)}catch(S){throw b(ke(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:x,mtime:u}}const dR=1e4;function uR(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function mR(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function hR(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 Gy(e);if(d)return;s(uR(g.project)),r(g.tasks.map(mR)),u(null)}catch(g){d||u(ke(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},dR);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function pR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function fR(e){return e?new Date(e).toLocaleDateString():""}function hh(e,n){return vw(e,n)}const Xa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},oc={type:null,entry:null,entryFullPath:""},gR=200,bR=500,ph=10;function xR({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,b=g?.offsetLeft??0,v=g?.offsetTop??0,x=8;let y=e-b,S=n-v;y+h.width>p-x&&(y=p-x-h.width),S+h.height>f-x&&(S=f-x-h.height),y<x&&(y=x),S<x&&(S=x),c({x:y+b,y:S+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:zi,disabled:!1},{id:"move",label:"Move",icon:Ex,disabled:!1},{id:"rename",label:"Rename",icon:us,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Lo,disabled:!1}]:[{id:"download",label:"Download",icon:vb,disabled:!1}],{id:"divider",label:"",icon:zi,disabled:!0},{id:"delete",label:"Delete",icon:on,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 vR({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 yR({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(Xa),[g,p]=a.useState(oc),[f,b]=a.useState(!1),[v,x]=a.useState(null),[y,S]=a.useState(!1),[j,A]=a.useState(null),w=a.useRef(null),_=a.useRef(null),C=a.useRef(null),L=a.useRef(!1),E=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),_.current!==null&&(window.clearTimeout(_.current),_.current=null)},[]),T=a.useCallback(()=>{E(),C.current=null,S(!1),A(null)},[E]);a.useEffect(()=>()=>{E()},[E]);const F=a.useCallback((z,P,k,U)=>{h({visible:!0,x:z,y:P,entry:k,entryFullPath:U})},[]),K=a.useCallback((z,P,k)=>{if(z.touches.length!==1)return;const U=z.touches[0];U&&(T(),C.current={x:U.clientX,y:U.clientY},_.current=window.setTimeout(()=>{S(!0),A(k)},gR),w.current=window.setTimeout(()=>{const V=C.current;V&&(L.current=!0,S(!1),A(null),E(),F(V.x,V.y,P,k))},bR))},[T,E,F]),$=a.useCallback(z=>{const P=C.current,k=z.touches[0];!P||!k||(Math.abs(k.clientX-P.x)>ph||Math.abs(k.clientY-P.y)>ph)&&T()},[T]),R=a.useCallback(()=>{T()},[T]);a.useEffect(()=>{if(!m.visible)return;const z=document.querySelector(".file-browser-list"),P=()=>{L.current=!1,T(),h(Xa)};return z?.addEventListener("scroll",P),()=>z?.removeEventListener("scroll",P)},[T,m.visible]),a.useEffect(()=>{if(!m.visible)return;const z=P=>{P.key==="Escape"&&(L.current=!1,h(Xa))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m.visible]);const I=a.useCallback((z,P)=>{z.preventDefault(),z.stopPropagation(),T(),L.current=!1,F(z.clientX,z.clientY,P,hh(n,P.name))},[T,n,F]),H=a.useCallback(z=>{if(!m.entry)return;L.current=!1;const P=m.entry,k=m.entryFullPath;if(h(Xa),z==="download"){if(!c)return;const U=pp(c,k,d);window.open(ai(U),"_blank");return}if(z==="download-zip"){if(!c)return;const U=sj(c,k,d);window.open(ai(U),"_blank");return}p({type:z,entry:P,entryFullPath:k}),x(null)},[m,c,d]),J=a.useCallback(async z=>{if(!(!g.type||!g.entry||!c)){b(!0),x(null);try{switch(g.type){case"copy":await Zy(c,g.entryFullPath,z,d);break;case"move":await ej(c,g.entryFullPath,z,d);break;case"rename":await nj(c,g.entryFullPath,z,d);break;case"delete":await tj(c,g.entryFullPath,d);break}p(oc),u?.()}catch(P){x(ke(P)||"Operation failed")}finally{b(!1)}}},[g,c,u,d]),Z=a.useCallback(()=>{p(oc),x(null)},[]),N=a.useCallback((z,P)=>{if(L.current){L.current=!1;return}m.visible||(z.type==="directory"?i(P):s(P))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(rt,{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:()=>{i(yw(n))},children:[t.jsx(kn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":_a(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(z=>{const P=hh(n,z.name),k=y&&j===P;return t.jsxs("div",{className:`file-node file-node--${z.type} ${k?"file-node--long-pressing":""}`,onClick:()=>N(z,P),onContextMenu:U=>I(U,z),onTouchStart:U=>K(U,z,P),onTouchMove:$,onTouchEnd:R,onTouchCancel:R,children:[t.jsx("div",{className:"file-node-icon",children:z.type==="directory"?t.jsx(Wn,{size:16}):t.jsx(ep,{size:16})}),t.jsx("div",{className:"file-node-name",children:z.name}),z.type==="file"&&z.size!==void 0&&t.jsx("div",{className:"file-node-size",children:pR(z.size)}),z.mtime&&t.jsx("div",{className:"file-node-time",children:fR(z.mtime)})]},z.name)})}),m.visible&&m.entry&&t.jsx(xR,{x:m.x,y:m.y,entry:m.entry,onAction:H,onClose:()=>{L.current=!1,h(Xa)}}),g.type&&g.entry&&t.jsx(vR,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:J,onCancel:Z,loading:f,error:v})]})}function jR(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function kR({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=jR(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(Zh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(ha,{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(jo,{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(jo,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],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 wR(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function NR({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(Od,{size:14}):t.jsx(Cc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Yt,{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(Od,{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(Cc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:wR(c.title)})]},c.id))]})]})]})}const SR=768,CR=280,uo=180,mo=500,fh="fusion:file-browser-sidebar-width",lg=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),ER=new Set([...lg,".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 gh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ER.has(n)}function _R(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return lg.has(n)}function MR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=hR(i),l=a.useRef(null);ri(l,!0,"fusion:files-modal-size");const c=Si(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[g,p]=a.useState(!1),[f,b]=a.useState("list"),[v,x]=a.useState(CR),{entries:y,currentPath:S,setPath:j,loading:A,error:w,refresh:_}=lR(u,!0,i),{content:C,setContent:L,originalContent:E,loading:T,saving:F,error:K,save:$,hasChanges:R,mtime:I}=cR(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const se=()=>{p(window.innerWidth<=SR)};return se(),window.addEventListener("resize",se),()=>window.removeEventListener("resize",se)},[]),a.useEffect(()=>{m||b("list")},[m]),a.useEffect(()=>{try{const se=localStorage.getItem(fh);if(!se)return;const he=Number.parseInt(se,10);if(!Number.isNaN(he)){const O=Math.max(uo,Math.min(mo,he));x(O)}}catch{}},[]),a.useEffect(()=>{const se=he=>{he.key==="Escape"&&n(),(he.metaKey||he.ctrlKey)&&he.key==="s"&&(he.preventDefault(),R&&!F&&$())};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[n,R,F,$]);const H=a.useCallback(se=>{h(se),g&&b("editor")},[g]),J=a.useCallback(()=>{b("list")},[]),Z=a.useCallback(()=>{L(E)},[E,L]),N=a.useCallback(se=>{d(se),h(null),b("list"),s?.(se)},[s]),z=a.useCallback(se=>{try{localStorage.setItem(fh,String(se))}catch{}},[]),P=a.useCallback(se=>{if(g)return;se.preventDefault(),se.stopPropagation();const he=se.currentTarget;typeof he.setPointerCapture=="function"&&he.setPointerCapture(se.pointerId);const O=se.clientX,ue=v;let te=ue;document.body.style.userSelect="none";const me=be=>{const ae=be.clientX-O,Ee=Math.max(uo,Math.min(mo,ue+ae));te=Ee,x(Ee)},oe=be=>{typeof he.releasePointerCapture=="function"&&he.releasePointerCapture(be.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",me),document.removeEventListener("pointerup",oe),z(te)};document.addEventListener("pointermove",me),document.addEventListener("pointerup",oe)},[g,z,v]),k=a.useCallback(se=>{if(g)return;const he=20;if(se.key!=="ArrowLeft"&&se.key!=="ArrowRight")return;se.preventDefault();const O=se.key==="ArrowLeft"?-he:he,ue=Math.max(uo,Math.min(mo,v+O));x(ue),z(ue)},[g,z,v]),V=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(se=>se.id===u)?.id??u,[u,o])}`,pe=a.useMemo(()=>!m||!_R(m)?null:pp(u,m,i),[m,u,i]),ve=se=>{const he=new Blob([se]).size;return he<1024?`${he} B`:`${(he/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(Wn,{size:18}),t.jsx("span",{children:V}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(NR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:N}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${g?"mobile":""} ${f==="list"?"active":""}`,style:g?void 0:{width:`${v}px`},children:t.jsx(yR,{entries:y,currentPath:S,onSelectFile:H,onNavigate:j,loading:A,error:w,onRetry:_,workspace:u,onRefresh:_,projectId:i})}),!g&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":uo,"aria-valuemax":mo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:P,onKeyDown:k}),t.jsx("div",{className:`file-browser-content ${g?"mobile":""} ${f==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[g&&f==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:J,"aria-label":"Back to file list",children:[t.jsx(Ca,{size:16}),t.jsx("span",{children:"Back"})]}),m,gh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(zb,{size:12}),"Binary file — read only"]}),I&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(I).toLocaleString()]}),T&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!pe&&R&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:Z,disabled:F,children:[t.jsx(zx,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void $(),disabled:F,children:[t.jsx(rp,{size:14}),F?"Saving...":"Save"]})]})})]}),K&&!pe&&t.jsx("div",{className:"file-browser-error-banner",children:K}),pe?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:pe,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(kR,{content:C,onChange:L,filePath:m,readOnly:gh(m)})}),!pe&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:ve(C)}),R&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Wn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function AR(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 ly();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:ke(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 RR(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 TR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const cg="kb-usage-hidden-windows";function bh(e){const n=Gn(cg,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 PR(e,n){xs(cg,JSON.stringify(e),n)}function dg(e,n,s){return s[e]?.includes(n)??!1}function IR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=TR(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),y=Math.floor(x/24),S=x%24;y>0&&S>0?d=`resets in ${y}d ${S}h`:y>0?d=`resets in ${y}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}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(ha,{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:RR(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(ad,{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(rv,{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(wn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function $R(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")||n.includes("antigravity")?"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 DR({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(Ln,{provider:$R(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),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,")"]})]}),t.jsx("div",{className:"usage-provider-actions",children:l()})]}),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=dg(e.name,c.label,s);return t.jsx(IR,{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 LR(){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 zR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=AR({autoRefresh:e}),[d,m]=a.useState(!1),[h,g]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,f]=a.useState("used"),[b,v]=a.useState(()=>bh(s)),x=a.useRef(null),y=a.useRef(e),S=a.useRef(!1);a.useEffect(()=>{e||(S.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(S.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const R=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",R),()=>window.removeEventListener("resize",R)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const R=Gn("kb-usage-view-mode",s);if(R==="used"||R==="remaining"){f(R);return}f("used")},[s]);const j=a.useCallback(R=>{f(R),xs("kb-usage-view-mode",R,s)},[s]);a.useEffect(()=>{v(bh(s))},[s]),a.useEffect(()=>{PR(b,s)},[b,s]);const A=a.useCallback((R,I)=>{v(H=>{if(dg(R,I,H)){const J=(H[R]??[]).filter(Z=>Z!==I);if(J.length===0){const{[R]:Z,...N}=H;return N}return{...H,[R]:J}}return{...H,[R]:[...H[R]??[],I]}})},[]),w=a.useCallback(R=>{v(I=>{if(!I[R])return I;const{[R]:H,...J}=I;return J})},[]),_=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const R=I=>{I.key==="Escape"&&n()};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,n]);const C=a.useCallback(R=>{R.target===R.currentTarget&&n()},[n]);if(!e)return null;const L=!!(i&&h),F=L?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,K=L?Math.max(window.innerWidth-(i?.right??0),0):void 0,$=t.jsxs("div",{className:`usage-modal${L?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:L?{position:"fixed",top:F,right:K}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(zs,{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 ${p==="used"?"active":""}`,onClick:()=>j("used"),"aria-pressed":p==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${p==="remaining"?"active":""}`,onClick:()=>j("remaining"),"aria-pressed":p==="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(Kt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:x,children:(o||!S.current&&!l)&&r.length===0?t.jsx(LR,{}):l&&r.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:l}),t.jsx("button",{className:"btn btn-sm",onClick:_,children:"Retry"})]}):r.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:r.map(R=>t.jsx(DR,{provider:R,viewMode:p,hiddenWindows:b,onToggleWindow:A,onShowAllHidden:w},R.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:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:_,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Pn,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return L?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),$]}):t.jsx("div",{className:"modal-overlay open",onClick:C,"data-testid":"usage-modal-overlay",children:$})}function ug(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 Po(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 OR={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},mg={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},FR={cron:Qh,webhook:lp,api:Xh,manual:Vn},UR={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},BR={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function HR({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(wn,{size:12}):t.jsx(Sr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:ug(n)})]})}function qR({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"} ${Po(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(wn,{size:12}):t.jsx(Sr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Po(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:mg[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:ug(r)}),s?t.jsx(mi,{size:12}):t.jsx(Yt,{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 VR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Ys(),m=a.useCallback(async()=>{await d({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,d]),h=OR[e.trigger.type],g=FR[e.trigger.type],p=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"}${o?" running":""}`,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:h,color:h},children:[t.jsx(g,{size:10}),mg[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(Fo,{size:10}):t.jsx(Wn,{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:o?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Cn,{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(Ks,{size:14}):t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(us,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(on,{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(Fi,{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"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(wi,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:UR[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:BR[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:Po(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:Po(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(HR,{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})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>u(f=>!f),"aria-expanded":c,children:[c?t.jsx(mi,{size:12}):t.jsx(Yt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((f,b)=>t.jsx(qR,{result:f,index:b},`${f.startedAt}-${b}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function WR({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(di,{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(ux,{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(rs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function lc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function KR(e){return e==="command"?{id:lc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:lc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:lc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function GR({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[b,v]=a.useState(e.taskTitle??""),[x,y]=a.useState(e.taskDescription??""),[S,j]=a.useState(e.taskColumn??"triage"),[A,w]=a.useState(e.timeoutMs),[_,C]=a.useState(e.continueOnFailure??!1),[L,E]=a.useState({}),[T,F]=a.useState([]),[K,$]=a.useState(!1),[R,I]=a.useState(null);a.useEffect(()=>{let z=!1;return $(!0),I(null),ps().then(P=>{z||F(P.models)}).catch(P=>{z||I(P instanceof Error?P.message:"Failed to load models")}).finally(()=>{z||$(!1)}),()=>{z=!0}},[]);const H=a.useCallback(()=>{const z={};return i.trim()||(z.name="Step name is required"),o==="command"&&!c.trim()&&(z.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(z.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(z.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(z.modelProvider="Both model provider and model ID must be set together"),A!==void 0&&A<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(z),Object.keys(z).length===0},[i,o,c,d,x,h,p,A]),J=h&&p?`${h}/${p}`:"",Z=a.useCallback(z=>{if(!z)g(""),f("");else{const P=z.indexOf("/");P!==-1&&(g(z.slice(0,P)),f(z.slice(P+1)))}},[]),N=a.useCallback(()=>{if(!H())return;const z={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?S: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:A||void 0,continueOnFailure:_};o!=="ai-prompt"&&delete z.prompt,o!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[H,n,e,i,o,c,d,b,x,S,h,p,A,_]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:z=>r(z.target.value),"aria-invalid":!!L.name}),L.name&&t.jsx("small",{className:"field-error",children:L.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:z=>l(z.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:z=>u(z.target.value),rows:2,"aria-invalid":!!L.command}),L.command&&t.jsx("small",{className:"field-error",children:L.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:z=>m(z.target.value),rows:3,"aria-invalid":!!L.prompt}),L.prompt&&t.jsx("small",{className:"field-error",children:L.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Kn,{id:`step-model-${e.id}`,label:"Model",models:T,value:J,onChange:Z,placeholder:"Use default",disabled:K}),R&&t.jsx("small",{className:"field-error",children:R}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:z=>v(z.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:z=>y(z.target.value),rows:4,"aria-invalid":!!L.taskDescription}),L.taskDescription&&t.jsx("small",{className:"field-error",children:L.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:S,onChange:z=>j(z.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(Kn,{id:`step-task-model-${e.id}`,label:"Model",models:T,value:J,onChange:Z,placeholder:"Use default",disabled:K}),R&&t.jsx("small",{className:"field-error",children:R}),L.modelProvider&&t.jsx("small",{className:"field-error",children:L.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:A??"",onChange:z=>w(z.target.value?Number(z.target.value):void 0),"aria-invalid":!!L.timeoutMs}),L.timeoutMs&&t.jsx("small",{className:"field-error",children:L.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:_,onChange:z=>C(z.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,children:"Save Step"})]})]})}function JR({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=KR(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(GR,{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(id,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(WR,{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(mi,{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(Yt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(us,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(on,{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(ln,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(ln,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(ln,{size:14}),"Add Create Task Step"]})]})]})}const hg={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},YR={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function QR(e){const n=e.trim();for(const[s,i]of Object.entries(hg))if(i===n)return s;return"custom"}function XR(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function ZR(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 eT(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 tT=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],nT=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function xh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function vh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?eT(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":QR(c.cronExpression)),[y,S]=a.useState(c.webhookPath),[j,A]=a.useState(c.webhookSecret),[w,_]=a.useState(c.endpoint),[C,L]=a.useState(e?.executionPolicy??"queue"),[E,T]=a.useState(e?.catchUpPolicy??"run_one"),[F,K]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,R=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[I,H]=a.useState(e?.steps&&e.steps.length>0&&!$&&!R?"advanced":"simple"),[J,Z]=a.useState(()=>$?"ai-prompt":R?"create-task":"command"),[N,z]=a.useState(e?.command??""),[P,k]=a.useState(e?.steps??[]),[U,V]=a.useState(!1),[pe,ve]=a.useState(e?.timeoutMs??3e5),[se,he]=a.useState($?e.steps?.[0]?.prompt??"":""),[O,ue]=a.useState(R?e.steps?.[0]?.taskTitle??"":""),[te,me]=a.useState(R?e.steps?.[0]?.taskDescription??"":""),[oe,be]=a.useState(R?e.steps?.[0]?.taskColumn??"triage":"triage"),[ae,Ee]=a.useState($||R?e.steps?.[0]?.modelProvider??"":""),[$e,He]=a.useState($||R?e.steps?.[0]?.modelId??"":""),[ot,Je]=a.useState([]),[et,st]=a.useState(!1),[Oe,Ue]=a.useState(null),[re,Ne]=a.useState(i??"global"),[ee,Ae]=a.useState({}),[Fe,fe]=a.useState(!1),_e=a.useRef(!0);a.useEffect(()=>()=>{_e.current=!1},[]),a.useEffect(()=>{i&&Ne(i)},[i]),a.useEffect(()=>{let X=!1;return st(!0),Ue(null),ps().then(Qe=>{X||Je(Qe.models)}).catch(Qe=>{X||Ue(Qe instanceof Error?Qe.message:"Failed to load models")}).finally(()=>{X||st(!1)}),()=>{X=!0}},[]);const ze=ae&&$e?`${ae}/${$e}`:"",Xe=a.useCallback(X=>{if(!X){Ee(""),He("");return}const Qe=X.indexOf("/");Qe!==-1&&(Ee(X.slice(0,Qe)),He(X.slice(Qe+1)))},[]),je=a.useCallback(()=>{const X={};if(u.trim()||(X.name="Name is required"),re==="project"&&!r&&(X.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?XR(f)||(X.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):X.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(X.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(X.endpoint="API endpoint is required"),I==="simple")J==="command"&&!N.trim()&&(X.command="Command is required"),J==="ai-prompt"&&!se.trim()&&(X.prompt="Prompt is required"),J==="create-task"&&!te.trim()&&(X.taskDescription="Task description is required"),(ae.trim()&&!$e.trim()||!ae.trim()&&$e.trim())&&(X.model="Both model provider and model ID must be set, or both must be empty");else{P.length===0&&(X.steps="At least one step is required"),U&&(X.stepsEditing="Please save or cancel all step edits before saving the routine");const Qe=[];P.forEach((lt,ft)=>{lt.name?.trim()||Qe.push(`Step ${ft+1}: Name is required`),lt.type==="command"&&!lt.command?.trim()&&Qe.push(`Step ${ft+1}: Command is required`),lt.type==="ai-prompt"&&!lt.prompt?.trim()&&Qe.push(`Step ${ft+1}: Prompt is required`),lt.type==="create-task"&&!lt.taskDescription?.trim()&&Qe.push(`Step ${ft+1}: Task description is required`)}),Qe.length>0&&(X.steps=Qe.join("; "))}return pe<1e3&&(X.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ae(X),Object.keys(X).length===0},[u,g,f,v,y,w,re,r,I,J,N,se,te,ae,$e,P,U,pe]),ce=a.useCallback(async X=>{if(X.preventDefault(),!!je()){fe(!0);try{let Qe=e?.scope??re??(r?"project":"global");Qe==="project"&&!r&&(Qe="global");const lt=ZR(g,f,y,j,w);let ft,Mt;I==="simple"?J==="command"?ft=N.trim()||void 0:J==="ai-prompt"?Mt=[{id:xh(),type:"ai-prompt",name:u.trim(),prompt:se.trim(),modelProvider:ae.trim()||void 0,modelId:$e.trim()||void 0}]:Mt=[{id:xh(),type:"create-task",name:u.trim(),taskTitle:O.trim()||void 0,taskDescription:te.trim(),taskColumn:oe,modelProvider:ae.trim()||void 0,modelId:$e.trim()||void 0}]:Mt=P;const yt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:lt,command:ft,steps:Mt,timeoutMs:pe,executionPolicy:C,catchUpPolicy:E,enabled:F,scope:Qe};await n(yt)}finally{_e.current&&fe(!1)}}},[je,n,u,m,g,f,y,j,w,I,J,N,se,ae,$e,O,te,oe,P,pe,C,E,F,re,r,e?.scope,e?.agentId]),Re="routine-name-error",ge="routine-cron-error",Me="routine-webhook-error",Ge="routine-endpoint-error",Pe="routine-command-error",pt="routine-prompt-error",Y="routine-task-description-error",le="routine-model-error",ye="routine-timeout-error",nt=a.useCallback(X=>{x(X),X!=="custom"&&b(hg[X])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ce,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:X=>d(X.target.value),"aria-invalid":!!ee.name,"aria-describedby":ee.name?Re:void 0}),ee.name&&t.jsx("small",{id:Re,className:"field-error",children:ee.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:X=>h(X.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${re==="global"?" active":""}`,onClick:()=>{Ne("global"),o?.("global")},role:"radio","aria-checked":re==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Fo,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{Ne("project"),o?.("project")},role:"radio","aria-checked":re==="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(Wn,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":re==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ee.scope&&t.jsx("small",{className:"field-error",children:ee.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(Qh,{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(lp,{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(Xh,{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:X=>nt(X.target.value),children:Object.entries(YR).map(([X,Qe])=>t.jsx("option",{value:X,children:Qe},X))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:X=>b(X.target.value),disabled:v!=="custom","aria-invalid":!!ee.cronExpression,"aria-describedby":ee.cronExpression?ge:void 0}),ee.cronExpression?t.jsx("small",{id:ge,className:"field-error",children:ee.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:X=>S(X.target.value),"aria-invalid":!!ee.webhookPath,"aria-describedby":ee.webhookPath?Me:void 0}),ee.webhookPath?t.jsx("small",{id:Me,className:"field-error",children:ee.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:j,onChange:X=>A(X.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:w,onChange:X=>_(X.target.value),"aria-invalid":!!ee.endpoint,"aria-describedby":ee.endpoint?Ge:void 0}),ee.endpoint?t.jsx("small",{id:Ge,className:"field-error",children:ee.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${I==="simple"?" active":""}`,onClick:()=>H("simple"),role:"radio","aria-checked":I==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${I==="advanced"?" active":""}`,onClick:()=>H("advanced"),role:"radio","aria-checked":I==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:I==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),I==="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${J==="command"?" active":""}`,onClick:()=>Z("command"),role:"radio","aria-checked":J==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="ai-prompt"?" active":""}`,onClick:()=>Z("ai-prompt"),role:"radio","aria-checked":J==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="create-task"?" active":""}`,onClick:()=>Z("create-task"),role:"radio","aria-checked":J==="create-task",children:"Create Task"})]})]}),J==="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:N,onChange:X=>z(X.target.value),"aria-invalid":!!ee.command,"aria-describedby":ee.command?Pe:void 0}),ee.command?t.jsx("small",{id:Pe,className:"field-error",children:ee.command}):t.jsx("small",{children:"Shell command to execute."})]}):J==="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:se,onChange:X=>he(X.target.value),rows:3,"aria-invalid":!!ee.prompt,"aria-describedby":ee.prompt?pt:void 0}),ee.prompt?t.jsx("small",{id:pt,className:"field-error",children:ee.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(Kn,{id:"routine-model",label:"Model",models:ot,value:ze,onChange:Xe,placeholder:"Use default",disabled:et}),Oe&&t.jsx("small",{className:"field-error",children:Oe}),ee.model&&t.jsx("small",{id:le,className:"field-error",children:ee.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:O,onChange:X=>ue(X.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:te,onChange:X=>me(X.target.value),rows:4,"aria-invalid":!!ee.taskDescription,"aria-describedby":ee.taskDescription?Y:void 0}),ee.taskDescription?t.jsx("small",{id:Y,className:"field-error",children:ee.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:oe,onChange:X=>be(X.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(Kn,{id:"routine-task-model",label:"Executor Model",models:ot,value:ze,onChange:Xe,placeholder:"Use default",disabled:et}),Oe&&t.jsx("small",{className:"field-error",children:Oe}),ee.model&&t.jsx("small",{id:le,className:"field-error",children:ee.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(JR,{steps:P,onChange:k,onEditingChange:V}),ee.steps&&t.jsx("small",{className:"field-error",children:ee.steps}),ee.stepsEditing&&t.jsx("small",{className:"field-error",children:ee.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:pe,onChange:X=>ve(Number(X.target.value)),"aria-invalid":!!ee.timeoutMs,"aria-describedby":ee.timeoutMs?ye:void 0}),ee.timeoutMs?t.jsx("small",{id:ye,className:"field-error",children:ee.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:C,onChange:X=>L(X.target.value),children:tT.map(X=>t.jsx("option",{value:X.value,children:X.label},X.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:E,onChange:X=>T(X.target.value),children:nT.map(X=>t.jsx("option",{value:X.value,children:X.label},X.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:F,onChange:X=>K(X.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:Fe,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Fe,children:Fe?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const sT=3e4;function iT({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,f]=a.useState({}),b=a.useRef(null);ri(b,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),x=a.useCallback(async()=>{try{const $=await kj(v);l($),f(R=>{const I={...R};for(const H of $){const J=I[H.id];if(!J||!H.lastRunResult)continue;const Z=H.lastRunResult;Z.success===J.success&&(Z.output||"")===J.output&&(Z.error||"")===(J.error||"")&&delete I[H.id]}return I})}catch($){n(ke($)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{x()},[x]),a.useEffect(()=>{const $=setInterval(()=>{x()},sT);return()=>clearInterval($)},[x]),a.useEffect(()=>{const $=R=>{R.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const y=Si(e),S=a.useCallback(async $=>{try{await wj($,v),n("Routine created","success"),u("list"),await x()}catch(R){n(ke(R)||"Failed to create routine","error")}},[n,x,v]),j=a.useCallback($=>{m($),u("edit")},[]),A=a.useCallback(async $=>{if(d)try{await tu(d.id,$,v),n("Routine updated","success"),u("list"),m(void 0),await x()}catch(R){n(ke(R)||"Failed to update routine","error")}},[d,n,x,v]),w=a.useCallback(async $=>{try{await Nj($.id,v),n(`Deleted "${$.name}"`,"success"),await x()}catch(R){n(ke(R)||"Failed to delete routine","error")}},[n,x,v]),_=a.useCallback(async $=>{g($.id);try{const{result:R}=await Sj($.id,v);f(I=>({...I,[$.id]:{output:R.output||"",error:R.error,success:R.success}})),R.success?n(`"${$.name}" completed successfully`,"success"):n(`"${$.name}" failed: ${R.error||"Unknown error"}`,"error"),await x()}catch(R){n(ke(R)||"Failed to run routine","error")}finally{g(null)}},[n,x,v]),C=a.useCallback(async $=>{try{await tu($.id,{enabled:!$.enabled},v),n(`"${$.name}" ${$.enabled?"disabled":"enabled"}`,"success"),await x()}catch(R){n(ke(R)||"Failed to toggle routine","error")}},[n,x,v]),L=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const E=a.useCallback($=>{r($),u("list"),m(void 0),f({})},[]),T=()=>c==="create"?t.jsx(vh,{onSubmit:S,onCancel:L,scope:i,projectId:s}):c==="edit"&&d?t.jsx(vh,{routine:d,onSubmit:A,onCancel:L,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(ln,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map($=>t.jsx(VR,{routine:$,onEdit:j,onDelete:w,onRun:_,onToggle:C,running:h===$.id,lastRunOutput:p[$.id]??null},$.id))}),F=()=>T(),K=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:b,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",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.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Kt,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",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(Fo,{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(Wn,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Vn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:K&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(ln,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:F()})]})})}const aT=3e4,Xc=new Map,cc=new Map;function yh(e){return e??"default"}function jh(e){const n=Xc.get(e);return n?Date.now()>=n.expiresAt?(Xc.delete(e),null):n:null}function rT(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 oT(e){const n=cc.get(e);if(n)return n;const s=xr().then(({providers:i,ghCli:r})=>{const l={...rT(i,r),ghCli:r,expiresAt:Date.now()+aT};return Xc.set(e,l),l}).finally(()=>{cc.delete(e)});return cc.set(e,s),s}function pg(e){const n=yh(e),s=jh(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=yh(e),p=jh(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 oT(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 fg({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(Kt,{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 lT({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Ys(),[d,m]=a.useState(""),[h,g]=a.useState([]),[p,f]=a.useState([]),[b,v]=a.useState(!1),[x,y]=a.useState(""),[S,j]=a.useState(""),[A,w]=a.useState(""),[_,C]=a.useState(""),[L,E]=a.useState(""),[T,F]=a.useState("default"),[K,$]=a.useState(!1),[R,I]=a.useState([]),[H,J]=a.useState(!1),[Z,N]=a.useState(void 0),[z,P]=a.useState(Ss),[k,U]=a.useState(void 0),[V,pe]=a.useState(null),[ve,se]=a.useState([]),[he,O]=a.useState(!1),[ue,te]=a.useState(!1),me=a.useRef(null),[oe,be]=a.useState(!1),[ae,Ee]=a.useState(""),$e=a.useRef(null),{hasAiProvider:He,hasGithub:ot,loading:Je}=pg(s),{nodes:et}=Yo(),st=a.useCallback(je=>{J(!0),I(je)},[]),Oe=a.useCallback(()=>{J(!1)},[]),Ue=a.useCallback(async()=>{if(ve.length>0){O(!0);return}te(!0);try{const je=await Ea(void 0,s);se(je),O(!0)}catch(je){const ce=ke(je);o(ce?`Failed to load agents: ${ce}`:"Failed to load agents","error"),O(!1)}finally{te(!1)}},[ve.length,s,o]);a.useEffect(()=>{if(!he)return;const je=ce=>{me.current&&!me.current.contains(ce.target)&&O(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[he]),a.useEffect(()=>{if(!oe)return;const je=ce=>{$e.current&&!$e.current.contains(ce.target)&&(be(!1),Ee(""))};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[oe]);const re=i.filter(je=>!h.includes(je.id)).sort((je,ce)=>{const Re=ce.createdAt.localeCompare(je.createdAt);if(Re!==0)return Re;const ge=parseInt(je.id.slice(je.id.lastIndexOf("-")+1),10)||0;return(parseInt(ce.id.slice(ce.id.lastIndexOf("-")+1),10)||0)-ge}),Ne=ae?re.filter(je=>je.id.toLowerCase().includes(ae.toLowerCase())||je.title&&je.title.toLowerCase().includes(ae.toLowerCase())||je.description&&je.description.toLowerCase().includes(ae.toLowerCase())):re,ee=(je,ce)=>je.length>ce?je.slice(0,ce)+"…":je;a.useEffect(()=>{const je=d.trim()!==""||h.length>0||p.length>0||x!==""||S!==""||A!==""||_!==""||R.length>0||V!==null||Z!==void 0||z!==Ss||k!==void 0;$(je)},[d,h,p,x,S,A,_,R,V,Z,z,k]);const Ae=a.useCallback(async()=>{K&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(je=>URL.revokeObjectURL(je.previewUrl)),f([]),m(""),g([]),y(""),j(""),w(""),C(""),E(""),F("default"),I([]),J(!1),pe(null),O(!1),N(void 0),P(Ss),U(void 0),$(!1),n())},[K,n,p,u]),Fe=a.useCallback(async()=>{const je=d.trim();if(!(!je||b)){v(!0);try{const ce=x.indexOf("/"),Re=S.indexOf("/"),ge=A.indexOf("/"),Me=await r({title:void 0,description:je,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:H?R.length>0?R:[]:void 0,...V?{assignedAgentId:V}:{},modelPresetId:T==="preset"&&L||void 0,modelProvider:x&&ce!==-1?x.slice(0,ce):void 0,modelId:x&&ce!==-1?x.slice(ce+1):void 0,validatorModelProvider:S&&Re!==-1?S.slice(0,Re):void 0,validatorModelId:S&&Re!==-1?S.slice(Re+1):void 0,planningModelProvider:A&&ge!==-1?A.slice(0,ge):void 0,planningModelId:A&&ge!==-1?A.slice(ge+1):void 0,thinkingLevel:_!==""?_:void 0,reviewLevel:Z,priority:z,nodeId:k});if(p.length>0){const Ge=[];for(const Pe of p)try{await br(Me.id,Pe.file,s)}catch{Ge.push(Pe.file.name)}Ge.length>0&&o(`Failed to upload: ${Ge.join(", ")}`,"error")}p.forEach(Ge=>URL.revokeObjectURL(Ge.previewUrl)),f([]),m(""),g([]),y(""),j(""),w(""),C(""),E(""),F("default"),I([]),J(!1),pe(null),O(!1),N(void 0),P(Ss),U(void 0),o(`Created ${Me.id}`,"success"),n()}catch(ce){o(ke(ce)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,x,S,A,_,b,r,o,n,s,T,L,R,H,V,Z,z,k]),fe=a.useCallback(je=>{je.key==="Escape"&&(je.preventDefault(),Ae())},[Ae]),ze=(V?ve.find(je=>je.id===V):void 0)?.name??V,Xe=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:$e,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>be(je=>!je),disabled:b,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),oe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ae,onChange:je=>Ee(je.target.value),onClick:je=>je.stopPropagation()}),Ne.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ne.map(je=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(je.id)?" selected":""}`,onClick:()=>{g(h.includes(je.id)?h.filter(ce=>ce!==je.id):[...h,je.id]),be(!1),Ee("")},onMouseDown:ce=>ce.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:je.id}),t.jsx("span",{className:"dep-dropdown-title",children:ee(je.title||je.description||je.id,30)})]},je.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(je=>t.jsxs("span",{className:"dep-chip",children:[je,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter(ce=>ce!==je)),disabled:b,children:"×"})]},je))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:me,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{he?O(!1):Ue()},disabled:b,"data-testid":"new-task-agent-button",children:[t.jsx(Sn,{size:12,style:{verticalAlign:"middle"}}),ze?` ${ze}`:" Assign agent"]}),he&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:je=>je.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ue&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ue&&ve.filter(je=>je.state!=="terminated").map(je=>t.jsxs("div",{className:`dep-dropdown-item${V===je.id?" selected":""}`,onMouseDown:ce=>ce.preventDefault(),onClick:()=>{pe(je.id===V?null:je.id),O(!1)},"data-testid":`agent-option-${je.id}`,children:[t.jsx(Sn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:je.role}),t.jsx("span",{className:"dep-dropdown-title",children:je.name})]},je.id)),!ue&&ve.filter(je=>je.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),V&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:je=>je.preventDefault(),onClick:()=>{pe(null),O(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Ae,onKeyDown:fe,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:je=>je.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ae,disabled:b,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Je&&t.jsx(fg,{hasAiProvider:He,hasGithub:ot}),t.jsx(ag,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:x,onExecutorModelChange:y,validatorModel:S,onValidatorModelChange:j,presetMode:T,onPresetModeChange:F,selectedPresetId:L,onSelectedPresetIdChange:E,selectedWorkflowSteps:R,onWorkflowStepsChange:st,onDefaultOnApplied:Oe,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:b,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ae,planningModel:A,onPlanningModelChange:w,thinkingLevel:_,onThinkingLevelChange:C,reviewLevel:Z,onReviewLevelChange:N,priority:z,onPriorityChange:P,nodeId:k,onNodeIdChange:U,nodeOptions:et,renderBelowPrimary:Xe,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Fe,disabled:!d.trim()||b,children:b?"Creating...":"Create Task"})]})]})}):null}function Vs(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function kh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function cT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function dT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function uT(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function dc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function mT(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function hT({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,g]=a.useState(90),[p,f]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(null),[S,j]=a.useState(null),[A,w]=a.useState(null),_=a.useCallback(async U=>{l(!0);try{const V=await Qj(s);r(V),u(null),w(Date.now()),U?.preserveKillResult||y(null)}catch(V){u(V instanceof Error?V.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;_();const U=window.setInterval(()=>{_()},5e3);return()=>{window.clearInterval(U)}},[e,_]),a.useEffect(()=>{if(!e)return;(async()=>{try{const V=await Wi();m(V.vitestAutoKillEnabled??!0),g(V.vitestKillThresholdPct??90),j(null)}catch(V){j(V instanceof Error?V.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const U=V=>{V.key==="Escape"&&n()};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[e,n]);const C=a.useMemo(()=>{if(!i)return[];const U=i.systemStats,V=dc(cT(U.heapUsed,U.heapLimit)),pe=dc(dT(U.rss,U.systemTotalMem));return[{label:"RSS",value:Vs(U.rss),detail:kh(U.rss,U.systemTotalMem),className:pe},{label:"Heap Used",value:Vs(U.heapUsed),detail:`of ${Vs(U.heapTotal)}`,className:V},{label:"Heap Limit",value:Vs(U.heapLimit),detail:"V8 limit"},{label:"External",value:Vs(U.external)},{label:"Array Buffers",value:Vs(U.arrayBuffers)}]},[i]),L=a.useCallback(async U=>{m(U);try{await fn({vitestAutoKillEnabled:U}),j(null)}catch(V){j(V instanceof Error?V.message:"Failed to save vitest settings")}},[]),E=a.useCallback(async U=>{const V=Math.min(99,Math.max(50,Number.isFinite(U)?Math.round(U):90));g(V);try{await fn({vitestKillThresholdPct:V}),j(null)}catch(pe){j(pe instanceof Error?pe.message:"Failed to save vitest settings")}},[]),T=a.useCallback(async()=>{if(!p){if(!b){v(!0);return}f(!0);try{const U=await Xj(s);y(U),v(!1),await _({preserveKillResult:!0})}catch(U){u(U instanceof Error?U.message:"Failed to kill vitest processes")}finally{f(!1)}}},[b,p,_,s]);if(!e)return null;const F=i?.systemStats,K=o&&!!i,$=A?`Updated ${new Date(A).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",R=i?.taskStats,I=F?F.systemTotalMem-F.systemFreeMem:0,H=F?uT(I,F.systemTotalMem):"normal",J=F?dc(H):"",Z=F&&Number.isFinite(F.systemTotalMem)&&F.systemTotalMem>0?Math.max(0,Math.min(100,I/F.systemTotalMem*100)):0,N=F?`System memory used: ${Z.toFixed(1)}% (${Vs(I)} of ${Vs(F.systemTotalMem)})`:"System memory usage unavailable",z=i?.vitestProcessCount,P=x?x.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",k=mT(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:U=>{U.target===U.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(pr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:$})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void _(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Pn,{size:16,className:K?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:C.map(U=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:U.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${U.className}`.trim(),children:U.value}),U.detail?t.jsx("span",{className:"system-stats-modal__detail",children:U.detail}):null]})]},U.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:F?.loadAvg.map(U=>U.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:F?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:F?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:F?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:F?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${J}`.trim(),children:F?Vs(I):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:F?`${kh(I,F.systemTotalMem)} of ${Vs(F.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${H}`,role:"progressbar","aria-valuenow":Math.round(Z),"aria-valuemin":0,"aria-valuemax":100,"aria-label":N,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${H}`,style:{width:`${Z}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:F?Vs(F.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:R?.total??0})]}),Object.entries(R?.byColumn??{}).map(([U,V])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:U}),t.jsx("dd",{children:V})]},U))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:R?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:R?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:R?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:R?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Kx,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:z??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void T(),disabled:p||z===0,children:[t.jsx(Qx,{}),t.jsx("span",{children:b?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:U=>{L(U.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:U=>{const V=Number.parseInt(U.target.value,10);E(Number.isNaN(V)?90:V)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:U=>{const V=Number.parseInt(U.target.value,10);E(Number.isNaN(V)?90:V)},onBlur:()=>{E(h)}})]})]}),x&&t.jsxs("p",{className:P,children:["Killed ",x.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",k]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const pT=5e3;function fT(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 S;o?S=await lu({limit:i,projectId:n,type:s}):S=(await nu({limit:i,type:s,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),c(S),p(S.length===i),S.length>0&&(b.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let S;o?S=await lu({limit:i,projectId:n,type:s,since:b.current}):S=(await nu({limit:i,type:s,since:b.current,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===i),S.length>0&&(b.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},pT),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:x}}const uc={"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"},gT={"task:created":t.jsx(ln,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Nr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Pn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Kt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(wn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Sr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(lr,{size:14,className:"activity-icon settings"})};function bT(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 xT({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:S,refresh:j,hasMore:A}=fT({projectId:b,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),w=x.map(T=>({id:T.id,timestamp:T.timestamp,type:T.type,taskId:T.taskId,taskTitle:T.taskTitle,details:T.details,metadata:T.metadata,projectId:T.projectId,projectName:T.projectName})),_=async()=>{try{await Cj(),j(),p(!1)}catch{p(!1)}},C=T=>{i&&i(T)},L=T=>{h(T),l?.(T==="all"?void 0:T)};a.useEffect(()=>{if(!e)return;const T=F=>{F.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[e,n,g]);const E=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>{T.target===T.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children: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(hr,{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(Wn,{size:14}),t.jsxs("select",{value:m,onChange:T=>L(T.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(T=>t.jsx("option",{value:T.id,children:T.name},T.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(yo,{size:14}),t.jsxs("select",{value:u,onChange:T=>d(T.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(uc).map(([T,F])=>t.jsx("option",{value:T,children:F},T))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Pn,{size:14})}),w.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(on,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&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(T=>T.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",uc[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:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(hs,{size:16}),t.jsx("span",{children:S})]}),w.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(hr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&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:w.map(T=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:gT[T.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:uc[T.type]}),t.jsx("span",{className:"activity-log-entry-time",children:bT(T.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[T.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>C(T.taskId),"data-testid":"activity-task-link",children:T.taskId}),T.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:T.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:T.details})]}),T.metadata&&Object.keys(T.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof T.metadata.from=="string"&&typeof T.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[T.metadata.from," → ",T.metadata.to]}),typeof T.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${T.metadata.merged?"success":"error"}`,children:T.metadata.merged?"Merged":"Not merged"})]})]})]},T.id))}),A&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(rt,{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:_,children:"Clear Log"})]})]})})]})}):null}const Za=[{id:"status",label:"Status",icon:ap},{id:"changes",label:"Changes",icon:Sc},{id:"commits",label:"Commits",icon:Cr},{id:"branches",label:"Branches",icon:Js},{id:"worktrees",label:"Worktrees",icon:Xb},{id:"stashes",label:"Stashes",icon:Lo},{id:"remotes",label:"Remotes",icon:tp}];function wh({status:e}){switch(e){case"added":case"untracked":return t.jsx(Pb,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Zh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Ab,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Oi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx($b,{size:14,className:"gm-file-icon"})}}function Nh({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 vT(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 ja(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 yT({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Ys(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);ri(g,e,"fusion:git-modal-size");const p=Si(n),f=vT(i),[b,v]=a.useState(null),[x,y]=a.useState([]),[S,j]=a.useState(new Set),[A,w]=a.useState(""),[_,C]=a.useState(!1),[L,E]=a.useState(null),[T,F]=a.useState(!1),[K,$]=a.useState(null),[R,I]=a.useState(null),H=a.useRef(0),[J,Z]=a.useState([]),[N,z]=a.useState(null),[P,k]=a.useState(null),[U,V]=a.useState(!1),[pe,ve]=a.useState(20),[se,he]=a.useState(""),[O,ue]=a.useState([]),[te,me]=a.useState(""),[oe,be]=a.useState(""),[ae,Ee]=a.useState(""),[$e,He]=a.useState(null),[ot,Je]=a.useState([]),[et,st]=a.useState(!1),[Oe,Ue]=a.useState(null),[re,Ne]=a.useState(null),[ee,Ae]=a.useState(!1),[Fe,fe]=a.useState([]),[_e,ze]=a.useState([]),[Xe,je]=a.useState(""),[ce,Re]=a.useState(null),[ge,Me]=a.useState(null),[Ge,Pe]=a.useState(null),pt=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const B=await qs(r);v(B);break}case"changes":{const[B,xe]=await Promise.all([qs(r),ta(r)]);v(B),y(xe),j(new Set),I(null),E(null),$(null);break}case"commits":{const B=await Ty(pe,r);Z(B);break}case"branches":{const[B,xe]=await Promise.all([Oa(r),qs(r)]);ue(B),v(xe);break}case"worktrees":{const B=await Dy(r);fe(B);break}case"stashes":{const B=await Vr(r);ze(B);break}case"remotes":{const B=await qs(r);v(B);break}}}catch(B){h(ke(B)||"Failed to fetch git data"),i(ke(B)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,pe,i,r]);a.useEffect(()=>{e&&pt()},[pt,e]),a.useEffect(()=>{if(!e)return;const B=xe=>{if(xe.key==="Escape"){n();return}if((xe.key==="ArrowUp"||xe.key==="ArrowDown")&&xe.altKey){xe.preventDefault();const Ie=Za.findIndex(M=>M.id===l);xe.key==="ArrowUp"&&Ie>0?c(Za[Ie-1].id):xe.key==="ArrowDown"&&Ie<Za.length-1&&c(Za[Ie+1].id)}};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n,l]);const Y=a.useCallback(async B=>{try{await Qd(B,r),i(`Staged ${B.length} file(s)`,"success");const xe=await ta(r);y(xe),j(new Set),I(null),E(null),$(null)}catch(xe){i(ke(xe)||"Failed to stage files","error")}},[i,r]),le=a.useCallback(async B=>{try{await Wy(B,r),i(`Unstaged ${B.length} file(s)`,"success");const xe=await ta(r);y(xe),j(new Set),I(null),E(null),$(null)}catch(xe){i(ke(xe)||"Failed to unstage files","error")}},[i,r]),ye=a.useCallback(async B=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${B.length} file(s)? This cannot be undone.`,danger:!0}))try{await Ky(B,r),i(`Discarded changes to ${B.length} file(s)`,"success");const[Ie,M]=await Promise.all([ta(r),qs(r)]);y(Ie),v(M),j(new Set),I(null),E(null),$(null)}catch(Ie){i(ke(Ie)||"Failed to discard changes","error")}},[i,r,confirm]),nt=a.useCallback(async B=>{if(B.preventDefault(),!!A.trim()){C(!0);try{const xe=await Xd(A.trim(),r);i(`Committed: ${xe.hash}`,"success"),w("");const[Ie,M]=await Promise.all([ta(r),qs(r)]);y(Ie),v(M),I(null),E(null),$(null)}catch(xe){i(ke(xe)||"Failed to commit","error")}finally{C(!1)}}},[A,i,r]),X=a.useCallback(async()=>{if(A.trim()){C(!0);try{const B=x.filter(ne=>!ne.staged).map(ne=>ne.file);B.length>0&&await Qd(B,r);const xe=await Xd(A.trim(),r);i(`Committed: ${xe.hash}`,"success"),w("");const[Ie,M]=await Promise.all([ta(r),qs(r)]);y(Ie),v(M),I(null),E(null),$(null)}catch(B){i(ke(B)||"Failed to commit","error")}finally{C(!1)}}},[A,x,i,r]),Qe=a.useCallback(async(B,xe)=>{I({file:B,staged:xe}),F(!0),$(null);const Ie=H.current+1;H.current=Ie;try{const M=await Vy(B,xe,r);if(H.current!==Ie)return;E(M)}catch(M){if(H.current!==Ie)return;const ne=ke(M)||"Failed to load file diff";E(null),$(ne),i(ne,"error")}finally{H.current===Ie&&F(!1)}},[i,r]),lt=a.useCallback(B=>{j(xe=>{const Ie=new Set(xe);return Ie.has(B)?Ie.delete(B):Ie.add(B),Ie})},[]),ft=a.useCallback(async B=>{if(N===B){z(null),k(null);return}z(B),V(!0);try{const xe=await wo(B,r);k(xe)}catch(xe){i(ke(xe)||"Failed to load diff","error"),k(null)}finally{V(!1)}},[N,i,r]),Mt=a.useCallback(()=>{ve(B=>Math.min(B+20,100))},[]),yt=a.useMemo(()=>{if(!se.trim())return J;const B=se.toLowerCase();return J.filter(xe=>xe.message.toLowerCase().includes(B)||xe.author.toLowerCase().includes(B)||xe.shortHash.toLowerCase().includes(B))},[J,se]),ht=a.useCallback(async B=>{if(B.preventDefault(),!!te.trim()){d(!0);try{await Ly(te.trim(),oe.trim()||void 0,r),i(`Created branch ${te}`,"success"),me(""),be("");const xe=await Oa(r);ue(xe)}catch(xe){i(ke(xe)||"Failed to create branch","error")}finally{d(!1)}}},[te,oe,i,r]),St=a.useCallback(async B=>{d(!0);try{await zy(B,r),i(`Switched to ${B}`,"success");const[xe,Ie]=await Promise.all([qs(r),Oa(r)]);v(xe),ue(Ie)}catch(xe){i(ke(xe)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),zt=a.useCallback(async B=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${B}"?`,danger:!0})){d(!0);try{await Yd(B,void 0,r),i(`Deleted branch ${B}`,"success");const Ie=await Oa(r);ue(Ie)}catch(Ie){if(ke(Ie).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Yd(B,!0,r),i(`Force deleted branch ${B}`,"success");const ne=await Oa(r);ue(ne)}catch(ne){i(ke(ne)||"Failed to delete branch","error")}}else i(ke(Ie)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),It=a.useMemo(()=>{if(!ae.trim())return O;const B=ae.toLowerCase();return O.filter(xe=>xe.name.toLowerCase().includes(B))},[O,ae]),Rt=a.useCallback(async B=>{if($e===B){He(null),Je([]),Ue(null),Ne(null);return}He(B),Je([]),Ue(null),Ne(null),st(!0);try{const xe=await $y(B,10,r);Je(xe)}catch{Je([])}finally{st(!1)}},[$e,r]),$t=a.useCallback(async B=>{if(Oe===B){Ue(null),Ne(null);return}Ue(B),Ne(null),Ae(!0);try{const xe=await wo(B,r);Ne(xe)}catch{Ne(null)}finally{Ae(!1)}},[Oe,r]),Ot=a.useCallback(()=>{He(null),Je([]),Ue(null),Ne(null)},[]),Vt=a.useCallback(async B=>{B.preventDefault(),Re("create");try{await By(Xe.trim()||void 0,r),i("Changes stashed","success"),je("");const xe=await Vr(r);ze(xe)}catch(xe){i(ke(xe)||"Failed to stash changes","error")}finally{Re(null)}},[Xe,i,r]),Dt=a.useCallback(async(B,xe=!1)=>{Re(`apply-${B}`);try{await Hy(B,xe,r),i(xe?"Stash popped":"Stash applied","success");const Ie=await Vr(r);ze(Ie)}catch(Ie){i(ke(Ie)||"Failed to apply stash","error")}finally{Re(null)}},[i,r]),Ft=a.useCallback(async B=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${B}}? This cannot be undone.`,danger:!0})){Re(`drop-${B}`);try{await qy(B,r),i("Stash dropped","success");const Ie=await Vr(r);ze(Ie)}catch(Ie){i(ke(Ie)||"Failed to drop stash","error")}finally{Re(null)}}},[i,r,confirm]),Ct=a.useCallback(async()=>{Me("fetch");try{const B=await Oy(void 0,r);Pe(B),i(B.message||"Fetch completed",B.fetched?"success":"info");const xe=await qs(r);v(xe)}catch(B){i(ke(B)||"Fetch failed","error")}finally{Me(null)}},[i,r]),Nt=a.useCallback(async()=>{Me("pull");try{const B=await Fy(r);Pe(B),B.conflict?i("Merge conflict detected. Resolve manually.","error"):i(B.message||"Pull completed","success");const xe=await qs(r);v(xe)}catch(B){i(ke(B)||"Pull failed","error")}finally{Me(null)}},[i,r]),Tt=a.useCallback(async()=>{Me("push");try{const B=await Uy(r);Pe(B),i(B.message||"Push completed","success");const xe=await qs(r);v(xe)}catch(B){i(ke(B)||"Push failed","error")}finally{Me(null)}},[i,r]),Zt=a.useMemo(()=>x.filter(B=>B.staged),[x]),Ut=a.useMemo(()=>x.filter(B=>!B.staged),[x]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Cc,{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:pt,disabled:u,title:"Refresh",children:t.jsx(Pn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Kt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Za.map(B=>{const xe=B.icon;return t.jsxs("button",{role:"tab","aria-selected":l===B.id,className:`gm-nav-item${l===B.id?" active":""}`,onClick:()=>c(B.id),children:[t.jsx(xe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:B.label})]},B.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(hs,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:pt,children:"Retry"})]}),l==="status"&&!u&&b&&t.jsx(jT,{status:b,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(kT,{status:b,stagedFiles:Zt,unstagedFiles:Ut,selectedFiles:S,toggleFileSelection:lt,onStageFiles:Y,onUnstageFiles:le,onDiscardChanges:ye,onSelectDiffFile:Qe,selectedDiffTarget:R,changeDiff:L,loadingChangeDiff:T,changeDiffError:K,commitMessage:A,setCommitMessage:w,onCommit:nt,onStageAllAndCommit:X,committing:_}),l==="commits"&&!u&&t.jsx(wT,{commits:yt,commitSearch:se,setCommitSearch:he,selectedCommit:N,commitDiff:P,loadingDiff:U,onCommitClick:ft,onLoadMore:Mt,canLoadMore:J.length>=pe&&pe<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(NT,{branches:It,branchSearch:ae,setBranchSearch:Ee,newBranchName:te,setNewBranchName:me,branchBase:oe,setBranchBase:be,onCreateBranch:ht,onCheckoutBranch:St,onDeleteBranch:zt,loading:u,allBranches:O,selectedBranch:$e,branchCommits:ot,loadingBranchCommits:et,expandedBranchCommit:Oe,branchCommitDiff:re,loadingBranchCommitDiff:ee,onSelectBranch:Rt,onBranchCommitClick:$t,onCloseBranchDetails:Ot}),l==="worktrees"&&!u&&t.jsx(ST,{worktrees:Fe}),l==="stashes"&&!u&&t.jsx(CT,{stashes:_e,stashMessage:Xe,setStashMessage:je,onCreateStash:Vt,onApplyStash:Dt,onDropStash:Ft,stashLoading:ce}),l==="remotes"&&!u&&t.jsx(ET,{status:b,remoteLoading:ge,lastRemoteResult:Ge,onFetch:Ct,onPull:Nt,onPush:Tt,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function jT({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(Js,{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(zi,{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(hs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(wn,{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(Di,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(wr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(wn,{size:12}),"Up to date"]})]})]})]})]})}function kT({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(j=>i.has(`unstaged:${j.file}`)),S=n.filter(j=>i.has(`staged:${j.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(Js,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(j=>j.file)),title:"Stage selected",children:[t.jsx(ln,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(j=>j.file)),title:"Discard selected",children:t.jsx(Sr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.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(j=>{const A=d?.file===j.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${A?" active":""}`,onClick:()=>u(j.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(wh,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Nh,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx(ln,{size:12})})]},`unstaged:${j.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:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.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(j=>{const A=d?.file===j.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${A?" active":""}`,onClick:()=>u(j.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(wh,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Nh,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(Kt,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:d||h||m||g?t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Sc,{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(rt,{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("div",{className:"gm-diff-empty",children:[t.jsx(Sc,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>f(j.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(rt,{size:14,className:"spin"}):t.jsx($i,{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 wT({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(yi,{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:ja(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(zi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{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 NT({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:j}){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(yi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:A=>s(A.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:A=>r(A.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:A=>l(A.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(A=>t.jsx("option",{value:A.name,children:A.name},A.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(ln,{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(A=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${A.isCurrent?" current":""}${g===A.name?" selected":""}`,onClick:()=>y(A.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[A.isCurrent&&t.jsx(Bn,{size:14,className:"gm-current-icon"}),A.name]}),A.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",A.remote]}),A.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:ja(A.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!A.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),u(A.name)},disabled:m,title:"Checkout",children:t.jsx(Js,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),d(A.name)},disabled:m,title:"Delete",children:t.jsx(on,{size:14})})]})})]}),g===A.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(Cr,{size:14}),"Commits on ",A.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(Kt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(rt,{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(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ja(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{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"})})]},w.hash))})]})]},A.name))})]})}function ST({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:ud(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Js,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function CT({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(rt,{size:14,className:"spin"}):t.jsx(Lo,{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(Js,{size:12}),c.branch]}),t.jsx("span",{children:ja(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(rt,{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(rt,{size:14,className:"spin"}):t.jsx(on,{size:14})})]})]},c.index))})]})}function ET({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=ee=>{try{return new URL(ee).hostname}catch{return ee.replace(/^git@/,"").split(":")[0]||ee}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[v,x]=a.useState(""),[y,S]=a.useState(""),[j,A]=a.useState(null),[w,_]=a.useState(""),[C,L]=a.useState(""),[E,T]=a.useState(!1),[F,K]=a.useState([]),[$,R]=a.useState(!1),[I,H]=a.useState(null),[J,Z]=a.useState([]),[N,z]=a.useState(!1),[P,k]=a.useState(null),U=m.find(ee=>ee.name===I),[V,pe]=a.useState(null),[ve,se]=a.useState(null),[he,O]=a.useState(!1),[ue,te]=a.useState(null),[me,oe]=a.useState(null),[be,ae]=a.useState(!1);a.useEffect(()=>{Ee()},[]),a.useEffect(()=>{e&&e.ahead>0?$e():e&&e.ahead===0&&K([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!I&&H(m[0].name)},[m]),a.useEffect(()=>{I?He(I):(Z([]),k(null))},[I]),a.useEffect(()=>{I&&!m.find(ee=>ee.name===I)&&H(m.length>0?m[0].name:null)},[m,I]);const Ee=async()=>{p(!0);try{const ee=await wy(c);h(ee)}catch(ee){l(ke(ee)||"Failed to load remotes","error")}finally{p(!1)}},$e=async()=>{R(!0);try{const ee=await Py(c);K(ee)}catch{K([])}finally{R(!1)}},He=async ee=>{z(!0),k(null);try{const Ae=await Iy(ee,void 0,10,c);Z(Ae)}catch(Ae){k(ke(Ae)||"Failed to load remote commits"),Z([])}finally{z(!1)}},ot=Ys(),Je=async ee=>{if(ee.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await Ny(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),S(""),T(!1),await Ee()}catch(Ae){l(ke(Ae)||"Failed to add remote","error")}finally{b(null)}}},et=async ee=>{if(await ot.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${ee}'?`,danger:!0})){b(`remove-${ee}`);try{await Sy(ee,c),l(`Remote '${ee}' removed`,"success"),await Ee()}catch(Fe){l(ke(Fe)||"Failed to remove remote","error")}finally{b(null)}}},st=async ee=>{if(C.trim()){b(`rename-${ee}`);try{await Cy(ee,C.trim(),c),l(`Remote renamed to '${C.trim()}'`,"success"),A(null),L(""),await Ee()}catch(Ae){l(ke(Ae)||"Failed to rename remote","error")}finally{b(null)}}},Oe=async ee=>{if(w.trim()){b(`url-${ee}`);try{await Ey(ee,w.trim(),c),l("Remote URL updated","success"),A(null),_(""),await Ee()}catch(Ae){l(ke(Ae)||"Failed to update remote URL","error")}finally{b(null)}}},Ue=a.useCallback(async(ee,Ae)=>{if(Ae==="ahead"){if(V===ee){pe(null),se(null);return}pe(ee),se(null),O(!0);try{const Fe=await wo(ee);se(Fe)}catch{se(null)}finally{O(!1)}}else{if(ue===ee){te(null),oe(null);return}te(ee),oe(null),ae(!0);try{const Fe=await wo(ee);oe(Fe)}catch{oe(null)}finally{ae(!1)}}},[V,ue]),re=ee=>{A(`url-${ee.name}`),_(ee.pushUrl||ee.fetchUrl)},Ne=ee=>{A(`name-${ee.name}`),L(ee.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:()=>T(!E),disabled:f!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(Kt,{size:14}):t.jsx(ln,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Je,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:ee=>x(ee.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:ee=>S(ee.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||f==="add",children:[f==="add"?t.jsx(rt,{size:12,className:"spin"}):t.jsx(ln,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(ee=>t.jsxs("div",{className:`gm-remote-selector-item${I===ee.name?" selected":""}`,onClick:()=>H(ee.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[ee.name,ee.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(ee.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ae=>{Ae.stopPropagation(),et(ee.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(on,{size:14})})]},ee.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[I&&U?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:I}),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(Di,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(wr,{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(rt,{size:14,className:"spin"}):t.jsx(Pn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Ns,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Di,{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:"}),j===`url-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:ee=>_(ee.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Oe(I),disabled:f===`url-${I}`,children:f===`url-${I}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Bn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),_("")},title:"Cancel",children:t.jsx(Kt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:U.fetchUrl,children:U.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(zi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(U),disabled:f!==null,title:"Edit remote URL",children:t.jsx(us,{size:14})})]})]}),U.pushUrl&&U.pushUrl!==U.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:U.pushUrl,children:U.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(zi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:C,onChange:ee=>L(ee.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>st(I),disabled:f===`rename-${I}`,children:f===`rename-${I}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Bn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),L("")},title:"Cancel",children:t.jsx(Kt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ne(U),disabled:f!==null,title:"Edit remote name",children:t.jsx(us,{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(Di,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading..."]}):F.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:F.map(ee=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ue(ee.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:ee.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ee.message,children:ee.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ee.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ja(ee.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:V===ee.hash?t.jsx(Yt,{size:14}):t.jsx(kn,{size:14})})]}),V===ee.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:he?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):ve?t.jsxs(t.Fragment,{children:[ee.message&&t.jsx("div",{className:"gm-commit-message-full",children:ee.message}),ve.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ve.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ve.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ee.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(ap,{size:14}),"Recent commits on ",I]})}),N?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading commits..."]}):P?t.jsxs("div",{className:"gm-error",children:[t.jsx(hs,{size:14}),P]}):J.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",I,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:J.map(ee=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ue(ee.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:ee.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ee.message,children:ee.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ee.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ja(ee.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:ue===ee.hash?t.jsx(Yt,{size:14}):t.jsx(kn,{size:14})})]}),ue===ee.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:be?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):me?t.jsxs(t.Fragment,{children:[ee.message&&t.jsx("div",{className:"gm-commit-message-full",children:ee.message}),me.stat&&t.jsx("pre",{className:"gm-diff-stat",children:me.stat}),t.jsx("pre",{className:"gm-diff-patch",children:me.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ee.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 er={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function _T(e,n){return e&&n?`${e}/${n}`:""}function MT(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 AT(e){switch(e){case"file-text":return Oi;case"check-circle":return wn;case"shield":return Jx;case"zap":return Vn;case"eye":return ha;case"globe":return Fo;case"layout-grid":return Ui;default:return wn}}function RT(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 TT({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,b]=a.useState(null),[v,x]=a.useState(!1),[y,S]=a.useState(er),[j,A]=a.useState(!1),[w,_]=a.useState(!1),[C,L]=a.useState(null),[E,T]=a.useState(null),[F,K]=a.useState({}),[$,R]=a.useState([]),I=a.useRef(null);ri(I,e,"fusion:workflow-steps-modal-size");const H=a.useCallback(async()=>{try{d(!0);const O=await Wo(i);o(O)}catch(O){s(ke(O)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),J=a.useCallback(async()=>{try{const O=await vr(i);K(O||{})}catch{}},[i]),Z=a.useCallback(async()=>{try{const O=await ps();R(O.models||[])}catch{}},[]),N=a.useCallback(async()=>{try{h(!0);const O=await Aj();c(O.templates)}catch(O){s(ke(O)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(H(),N(),J(),Z())},[e,H,N,J,Z]);const z=a.useCallback(()=>{x(!0),b(null),S(er)},[]),P=a.useCallback(O=>{b(O.id),x(!1),S({name:O.name,description:O.description,mode:O.mode||"prompt",phase:O.phase||"pre-merge",prompt:O.prompt,scriptName:O.scriptName||"",enabled:O.enabled,defaultOn:O.defaultOn||!1,modelProvider:O.modelProvider||"",modelId:O.modelId||""})},[]),k=a.useCallback(()=>{b(null),x(!1),S(er)},[]),U=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}A(!0);try{const O=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const ue={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...O};await su(ue,i),s("Workflow step created","success")}else f&&(await Ej(f,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...O},i),s("Workflow step updated","success"));x(!1),b(null),S(er),await H()}catch(O){s(ke(O)||"Failed to save workflow step","error")}finally{A(!1)}},[y,v,f,s,H]),V=a.useCallback(async O=>{try{await _j(O,i),s("Workflow step deleted","success"),L(null),f===O&&(b(null),S(er)),await H()}catch(ue){s(ke(ue)||"Failed to delete workflow step","error")}},[f,s,H]),pe=a.useCallback(async()=>{if(!(!f&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}A(!0);try{const O=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},ue={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...O},te=await su(ue,i);x(!1),b(te.id),_(!0);const me=await iu(te.id,i);S(oe=>({...oe,prompt:me.prompt})),s("Prompt refined with AI","success"),await H()}catch(O){s(ke(O)||"Failed to refine prompt","error")}finally{A(!1),_(!1)}return}if(f){_(!0);try{const O=await iu(f,i);S(ue=>({...ue,prompt:O.prompt})),s("Prompt refined with AI","success"),await H()}catch(O){s(ke(O)||"Failed to refine prompt","error")}finally{_(!1)}}}},[f,v,y,s,H]),ve=a.useCallback(async O=>{T(O.id);try{await Rj(O.id,i),s(`Added ${O.name} workflow step`,"success"),await H(),p("my-steps")}catch(ue){const te=ke(ue);te?.includes("already exists")?s(`A workflow step named '${O.name}' already exists`,"error"):s(te||"Failed to add workflow step from template","error")}finally{T(null)}},[s,H]),se=Si(n);if(!e)return null;const he=v||f!==null;return t.jsx("div",{className:"modal-overlay open",...se,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:I,className:"modal workflow-step-manager-modal",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:[!he&&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(qg,{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(Ui,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!he&&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(O=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${O.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:O.name}),t.jsx("span",{className:`wfm-badge ${O.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:O.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(O.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(O.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(O.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(O.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),O.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:O.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>P(O),title:"Edit","aria-label":`Edit ${O.name}`,children:t.jsx(us,{size:14})}),C===O.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>V(O.id),title:"Confirm delete","aria-label":`Confirm delete ${O.name}`,children:t.jsx(Bn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>L(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Kt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>L(O.id),title:"Delete","aria-label":`Delete ${O.name}`,children:t.jsx(on,{size:14})})]})]})},O.id))})]}),g==="templates"&&!he&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(rt,{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(O=>{const ue=AT(O.icon),te=RT(O.category),me=E===O.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${O.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ue,{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:O.name}),t.jsx("span",{className:te,children:O.category})]}),t.jsx("div",{className:"wfm-template-desc",children:O.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ve(O),disabled:me,"data-testid":`add-template-${O.id}`,children:me?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(ln,{size:12}),"Add"]})})]})]})},O.id)})})}),he&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:O=>S(ue=>({...ue,name:O.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:O=>S(ue=>({...ue,description:O.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(ji,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(di,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(O=>({...O,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:pe,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?t.jsx(rt,{size:12,className:"spin"}):t.jsx(rs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:O=>S(ue=>({...ue,prompt:O.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>S(O=>({...O,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Kt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(Kn,{models:$,value:_T(y.modelProvider,y.modelId),onChange:O=>{const ue=MT(O);S(te=>({...te,modelProvider:ue.provider,modelId:ue.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(F).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:O=>S(ue=>({...ue,scriptName:O.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([O,ue])=>t.jsxs("option",{value:O,children:[O," (",ue,")"]},O))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:O=>S(ue=>({...ue,enabled:O.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:O=>S(ue=>({...ue,defaultOn:O.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:k,disabled:j,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:U,disabled:j||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:j?"Saving...":v?"Create":"Save"})]})]})]})]})}),!he&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:z,"data-testid":"add-workflow-step",children:[t.jsx(ln,{size:14}),"Add Workflow Step"]})})]})})}const PT=36e5,IT=3e5,mc=[{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 $T(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 DT(e){return typeof e!="number"||!Number.isFinite(e)?PT:Math.max(IT,Math.round(e))}function fL(e){if(mc.some(s=>s.value===e))return[...mc];const n={value:e,label:`${$T(e)} (custom)`};return[...mc,n].sort((s,i)=>s.value-i.value)}const LT=4,zT=5*6e4;function OT(e){const n=DT(e?.heartbeatIntervalMs);return Math.max(n*LT,zT)}function FT(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 UT(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=FT(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(ws,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(zs,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Ks,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(zs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Ks,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Sn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=OT(o);return d>m?{label:"Unresponsive",icon:t.jsx(zs,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(ex,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const tr=[{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 BT({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 P=Gn("fn-agent-view",i);return P==="board"||P==="list"?P:"list"});a.useEffect(()=>{const P=Gn("fn-agent-view",i);if(P==="board"||P==="list"){x(P);return}x("list")},[i]),a.useEffect(()=>{xs("fn-agent-view",v,i)},[i,v]);const[y,S]=a.useState(null),j=a.useRef(null),[A,w]=a.useState(new Set),[_,C]=a.useState(new Map),{confirm:L}=Ys(),E=a.useMemo(()=>_.size===0?r:r.map(P=>{const k=_.get(P.id);return k?{...P,state:k}:P}),[r,_]),T=a.useMemo(()=>f==="all"?E.filter(P=>P.state!=="terminated"):E,[E,f]),F=a.useCallback(async()=>{c(!0);try{const k=await Ea(f!=="all"?{state:f}:void 0,i);o(k)}catch(P){s(`Failed to load agents: ${ke(P)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&F()},[e,F]),a.useEffect(()=>{if(!e)return;const P=setInterval(()=>{F()},3e4);return()=>{clearInterval(P)}},[e,F]);const K=async()=>{if(m.trim())try{await Fj({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),F()}catch(P){s(`Failed to create agent: ${ke(P)}`,"error")}},$=async(P,k)=>{if(!A.has(P)){w(U=>new Set(U).add(P)),C(U=>{const V=new Map(U);return V.set(P,k),V});try{await Bj(P,k,i),s(`Agent state updated to ${k}`,"success"),await F(),C(U=>{const V=new Map(U);return V.delete(P),V})}catch(U){C(V=>{const pe=new Map(V);return pe.delete(P),pe}),s(`Failed to update state: ${ke(U)}`,"error")}finally{w(U=>{const V=new Set(U);return V.delete(P),V})}}},R=async(P,k)=>{if(await L({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await Hj(P,i),s(`Agent "${k}" deleted`,"success"),F()}catch(V){s(`Failed to delete agent: ${ke(V)}`,"error")}},I=async(P,k)=>{const U=r.find(V=>V.id===P);if(U){if(U.role===k){S(null);return}try{await Uj(P,{role:k},i),s(`Agent role updated to ${tr.find(V=>V.value===k)?.label??k}`,"success"),S(null),F()}catch(V){s(`Failed to update role: ${ke(V)}`,"error")}}},H=(P,k)=>{P.key==="Escape"&&S(null)},J=P=>tr.find(k=>k.value===P)?.label??P,Z=P=>tr.find(k=>k.value===P)?.icon??"◆",N=P=>UT(P),z=P=>P.color==="var(--state-active-text)"?"active":P.color==="var(--state-paused-text)"?"paused":P.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>P.target===P.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(Sn,{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(Ui,{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(Ec,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void F(),title:"Refresh",disabled:l,children:t.jsx(Pn,{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(yo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:P=>b(P.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-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(ln,{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:P=>h(P.target.value),onKeyDown:P=>P.key==="Enter"&&K(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:P=>p(P.target.value),children:tr.map(P=>t.jsxs("option",{value:P.value,children:[P.icon," ",P.label]},P.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void K(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:T.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Sn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?T.map(P=>{const k=N(P),U=z(k);return t.jsxs("div",{className:"agent-board-card","data-state":P.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:Z(P.role)}),t.jsx("span",{className:"agent-board-badge","data-state":P.state,children:P.state}),t.jsx("span",{className:"agent-board-health","data-health":U,title:k.label,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:P.name,children:P.name}),t.jsx("div",{className:"agent-board-id",children:P.id}),t.jsxs("div",{className:"agent-board-actions",children:[P.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Activate",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:t.jsx(on,{size:14})})]}),P.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:A.has(P.id),title:"Pause",children:t.jsx(Ks,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:t.jsx(ws,{size:14})})]}),P.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Resume",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:t.jsx(ws,{size:14})})]}),P.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:A.has(P.id),title:"Pause",children:t.jsx(Ks,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:t.jsx(ws,{size:14})})]}),P.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Retry",children:t.jsx(Cn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:t.jsx(ws,{size:14})})]}),P.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:t.jsx(on,{size:14})})]})]},P.id)}):T.map(P=>{const k=N(P),U=z(k);return t.jsxs("div",{className:"agent-card","data-state":P.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===P.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:P.role,onChange:V=>void I(P.id,V.target.value),onKeyDown:V=>H(V,P.id),onBlur:()=>S(null),autoFocus:!0,children:tr.map(V=>t.jsxs("option",{value:V.value,children:[V.icon," ",V.label]},V.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(P.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:V=>{(V.key==="Enter"||V.key===" ")&&S(P.id)},children:Z(P.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:P.name}),t.jsx("span",{className:"agent-id text-secondary",children:P.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":P.state,children:P.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":U,title:k.label,children:[k.icon,!k.stateDerived&&` ${k.label}`]}),t.jsx("span",{className:"badge text-secondary",children:J(P.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[P.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:P.taskId})]}),P.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(P.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[P.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Activate",children:[t.jsx(Cn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:[t.jsx(on,{size:14})," Delete"]})]}),P.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:A.has(P.id),title:"Pause",children:[t.jsx(Ks,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:[t.jsx(ws,{size:14})," Stop"]})]}),P.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Resume",children:[t.jsx(Cn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:[t.jsx(ws,{size:14})," Stop"]})]}),P.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"paused"),disabled:A.has(P.id),title:"Pause",children:[t.jsx(Ks,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:[t.jsx(ws,{size:14})," Stop"]})]}),P.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Retry",children:[t.jsx(Cn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(P.id,"terminated"),disabled:A.has(P.id),title:"Stop",children:[t.jsx(ws,{size:14})," Stop"]})]}),P.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void $(P.id,"active"),disabled:A.has(P.id),title:"Start",children:[t.jsx(Cn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(P.id,P.name),title:"Delete",children:[t.jsx(on,{size:14})," Delete"]})]})]})]},P.id)})})]})]})}):null}function HT({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 cy();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const y=await dy(x);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(rt,{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(Ln,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(qT,{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(Sh,{status:i,authenticated:e}),c&&t.jsx(Ch,{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(Ln,{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(Sh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Ch,{action:c})]})}function qT({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 Sh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(rt,{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 Ch({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 VT(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),i=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(i);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function hc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=VT(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),c=a.useCallback(async()=>{const u=r??e;try{await navigator.clipboard.writeText(u),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const u=o.current===null&&r!==null;if(o.current=r,!u)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((u,d,m)=>t.jsxs("span",{children:[u,d<m.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:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Bn,{size:12}):t.jsx(zi,{size:12})})]})]},d))}):e})}const WT=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),KT=/^[a-z][a-z0-9-]*$/,Eh=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function _h(){return{id:"",name:"",reasoning:!1}}function GT({initialConfig:e,onSave:n,onCancel:s,saving:i=!1,error:r}){const o=!!e,[l,c]=a.useState(e?.id??""),[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.baseUrl??""),[g,p]=a.useState(e?.api??"openai-completions"),[f,b]=a.useState(e?.apiKey??""),[v,x]=a.useState(e?.models?.length?e.models:[_h()]),[y,S]=a.useState(null),j=v.length>1,A=a.useMemo(()=>y??r??null,[y,r]);function w(E,T){x(F=>F.map((K,$)=>$===E?{...K,...T}:K))}function _(E){x(T=>T.length<=1?T:T.filter((F,K)=>K!==E))}function C(){if(!l.trim())return"Provider ID is required.";if(!KT.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&WT.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const E=new URL(m.trim());if(E.protocol!=="http:"&&E.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Eh.includes(g)?v.length===0?"At least one model is required.":v.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function L(E){E.preventDefault();const T=C();S(T),!T&&await n({id:l.trim(),name:u.trim()||void 0,baseUrl:m.trim(),api:g,apiKey:f.trim()||void 0,models:v.map(F=>({id:F.id.trim(),name:F.name?.trim()||void 0,reasoning:!!F.reasoning,contextWindow:F.contextWindow,maxTokens:F.maxTokens}))})}return t.jsxs("form",{onSubmit:L,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:E=>c(E.target.value),disabled:o||i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:u,onChange:E=>d(E.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:E=>h(E.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:g,onChange:E=>p(E.target.value),disabled:i,children:Eh.map(E=>t.jsx("option",{value:E,children:E},E))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:f,onChange:E=>b(E.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((E,T)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${T+1}`,placeholder:"Model ID",value:E.id,onChange:F=>w(T,{id:F.target.value}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Model name ${T+1}`,placeholder:"Display name",value:E.name??"",onChange:F=>w(T,{name:F.target.value}),disabled:i}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:F=>w(T,{reasoning:F.target.checked}),disabled:i}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${T+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:F=>w(T,{contextWindow:F.target.value?Number(F.target.value):void 0}),disabled:i}),t.jsx("input",{className:"input","aria-label":`Max tokens ${T+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:F=>w(T,{maxTokens:F.target.value?Number(F.target.value):void 0}),disabled:i}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_(T),disabled:i||!j,"aria-label":`Remove model ${T+1}`,children:"×"})]},`${T}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>x(E=>[...E,_h()]),disabled:i,children:"+ Add model"})]}),A?t.jsx("div",{className:"form-error",children:A}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:i,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:i,children:i?"Saving...":"Save Provider"})]})]})}const Vi="fusion_model_onboarding_state",ka=[],wa=[],Io=!1,$o=!1,Na={},JT=void 0,vi=["ai-setup","github","project-setup","first-task"],YT={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Es(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Vi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?QT(n):null}catch{return null}}function QT(e){const n=e.postOnboardingDismissedAt??JT;return{...e,completedSteps:e.completedSteps??ka,skippedSteps:e.skippedSteps??wa,dismissed:e.dismissed??Io,completed:e.completed??$o,stepData:e.stepData??Na,...n?{postOnboardingDismissedAt:n}:{}}}function ho(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:ka,skippedSteps:wa,dismissed:Io,completed:$o,stepData:Na};try{localStorage.setItem(Vi,JSON.stringify(s))}catch{}return}try{const s=Es(),i=new Date().toISOString(),r=n.completed??$o;let o=n.dismissed??Io;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??ka,c=n.skippedSteps??s?.skippedSteps??wa,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(Vi,JSON.stringify(d))}catch{}}}function XT(e){if(!(typeof window>"u"))try{const n=Es(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:ka,skippedSteps:[e],dismissed:Io,completed:$o,stepData:Na};localStorage.setItem(Vi,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(Vi,JSON.stringify(r))}catch{}}function Mh(){if(!(typeof window>"u"))try{const e=Es(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:ka,skippedSteps:wa,dismissed:!1,completed:!0,stepData:Na};localStorage.setItem(Vi,JSON.stringify(s))}catch{}}function Sa(){const e=Es();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function ZT(){if(!(typeof window>"u"))try{const e=Es(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ka,skippedSteps:wa,dismissed:!1,completed:!1,stepData:Na,postOnboardingDismissedAt:n};localStorage.setItem(Vi,JSON.stringify(s))}catch{}}function gg(){const e=Es();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function eP(){const e=Es();return!e||Sa()?!1:e.currentStep!=="complete"}function tP(){const e=Es();if(!e||Sa()||e.currentStep==="complete")return null;const n=e.currentStep,s=YT[n]??iP(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function nP(){const e=Es();return e?e.skippedSteps:wa}function sP(e){const n=Es();return!n||!n.stepData?null:n.stepData[e]??null}function iP(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const bg="fusion_onboarding_events",Ah="fusion_onboarding_session_id",aP=200,rP=50;function $s(e,n={}){if(!(typeof window>"u"))try{const s=lP(),i=uP(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:oP()},o=dP([...s,r]);cP(o)}catch{}}function oP(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Ah);if(e)return e;const n=Rh();return sessionStorage.setItem(Ah,n),n}catch{return Rh()}}function Rh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function lP(){try{const e=localStorage.getItem(bg);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(mP):[]}catch{return[]}}function cP(e){try{localStorage.setItem(bg,JSON.stringify(e))}catch{}}function dP(e){const n=[...e];for(;n.length>aP;)n.splice(0,rP);return n}function uP(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function mP(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 hP=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),pP={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"}}},xg={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:"..."}},fP={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Th={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 Zc(e){if(Th[e])return Th[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 pc=["anthropic","openai","google","gemini","ollama"],gP=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],bP={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"},xP={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function ed(e){return bP[e]??e}function Ph(e){const n=ed(e),s=gP.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Ih(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Ph(e.id),i=Ph(n.id);if(s!==i)return s-i;const r=ed(e.id),o=ed(n.id);if(r!==o)return r.localeCompare(o);const l=xP[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 vP(e,n){const s=n.trim();if(!s)return"API key is required";const i=xg[e]??fP;return i.pattern.test(s)?null:`${Zc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const vg={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"},yP={description:"AI provider — connect to start using AI models",apiKeyInfo:vg};function td(e){return pP[e]??yP}function jP(e){return td(e.id).apiKeyInfo??vg}function ni({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(kn,{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 kP({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 wP({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=xg[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(ni,{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(ni,{summary:"Advanced setup details",children:f})]})}const NP=150;function SP({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=Es(),d=u?.currentStep,m=d==="complete"?"ai-setup":vi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??nP(),[p,f]=a.useState(!0),[b,v]=a.useState(m),[x,y]=a.useState(h),[S,j]=a.useState(g),[A,w]=a.useState(!1),[_,C]=a.useState(""),[L,E]=a.useState(!1),[T,F]=a.useState(null),[K,$]=a.useState(null),[R,I]=a.useState([]),[H,J]=a.useState(void 0),[Z,N]=a.useState(!0),[z,P]=a.useState(null),[k,U]=a.useState({}),[V,pe]=a.useState([]),[ve,se]=a.useState(""),[he,O]=a.useState(!1),[ue,te]=a.useState({}),[me,oe]=a.useState({}),[be,ae]=a.useState({}),[Ee,$e]=a.useState([]),[He,ot]=a.useState(!1),[Je,et]=a.useState(!1),[st,Oe]=a.useState(),Ue=a.useRef({}),re=a.useRef(null),Ne=a.useRef(null),ee=a.useRef(null),[Ae,Fe]=a.useState({}),[fe,_e]=a.useState(()=>Es()?.stepData?.github?.skipped===!0),ze=a.useRef(0),Xe=a.useRef(l),je=a.useRef(!1),ce=u?.currentStep,Re=!!u&&u.currentStep!=="complete";ri(Ne,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const G=re.current;G&&(G.scrollTop=0)},[b]);const[ge,Me]=a.useState(()=>Es()?.stepData?.["ai-setup"]?.skippedProviders??{}),Ge=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Pe=Ge.findIndex(G=>G.key===b),pt=b==="complete"?Ge.length:Pe;a.useEffect(()=>{b!=="complete"&&ho(b,{completedSteps:x,skippedSteps:S})},[b,x,S]),a.useEffect(()=>{je.current||(je.current=!0,$s("onboarding:wizard-opened",{source:Re?"resume":"initial",resumedFromStep:ce}))},[Re,ce]),a.useEffect(()=>{const G=Xe.current!=null,De=l!=null;!G&&De&&w(!0),De||w(!1),Xe.current=l},[l]);const Y=a.useRef(m);a.useEffect(()=>{if(Y.current==="ai-setup"&&b!=="ai-setup"&&!R.some(De=>De.id!=="github"&&De.authenticated)){const De={};for(const tt of R)tt.id!=="github"&&!tt.authenticated&&!ge[tt.id]&&(De[tt.id]=!0);if(Object.keys(De).length>0){const tt={...ge,...De};Me(tt),ho(b,{stepData:{"ai-setup":{skippedProviders:tt}}})}}Y.current=b},[b,R,ge]);const le=a.useCallback(async()=>{try{const{providers:G,ghCli:De}=await xr();I(G),J(De),U(tt=>{const at={};for(const[wt,_t]of Object.entries(tt)){const Lt=G.find(Jn=>Jn.id===wt);Lt&&!Lt.authenticated&&(at[wt]=_t)}return Object.keys(at).length===Object.keys(tt).length?tt:at}),Me(tt=>{const at={...tt};for(const wt of G)wt.authenticated&&at[wt.id]&&delete at[wt.id];return Object.keys(at).length===Object.keys(tt).length?tt:at})}catch{}},[]),ye=a.useCallback(async()=>{try{const G=await uy();$e((G.providers??[]).map(hP))}catch{}},[]),nt=a.useCallback(async G=>{et(!0),Oe(void 0);try{await hy(G),await ye(),await ps().then(De=>pe(De.models??[])),ot(!1)}catch(De){Oe(ke(De)||"Failed to create custom provider")}finally{et(!1)}},[ye]),X=a.useRef(!1);a.useEffect(()=>{b==="ai-setup"&&ye(),X.current&&le(),X.current=b!=="ai-setup"},[b,le,ye]);const Qe=R.find(G=>G.id==="github"),lt=!!Qe,ft=Qe?.authenticated??!1,Mt=H?.authenticated??!1,yt=ft||Mt,ht=!ft&&Mt,St=a.useCallback(G=>{if(G.authenticated)return"connected";const De=Ae?.[G.id];return De==="timeout"||De==="failed"?"retry":ge[G.id]?"skipped":"not-connected"},[Ae,ge]);function zt({status:G}){const De={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:tt,className:at}=De[G];return t.jsx("span",{"data-testid":"provider-status-badge",className:at,"data-status":G,children:tt})}const It=a.useCallback(()=>{if(yt)return"connected";const G=Ae.github;return G==="pending"?"pending":G==="failed"||G==="timeout"?"failed":fe?"skipped":"not-connected"},[yt,Ae,fe]);function Rt({status:G}){const De={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:tt,className:at}=De[G];return t.jsx("span",{"data-testid":"github-status-badge",className:at,"data-status":G,children:tt})}const $t=a.useCallback(async()=>{try{const G=await ps();pe(G.models)}catch{}},[]),Ot=a.useCallback(async()=>{try{const G=await Wi();if(G.defaultProvider&&G.defaultModelId){const De=`${G.defaultProvider}/${G.defaultModelId}`;se(De)}}catch{}},[]);a.useEffect(()=>{Promise.all([le(),$t(),Ot()]).finally(()=>N(!1))},[le,$t,Ot]),a.useEffect(()=>{const G=sP("ai-setup");if(G?.loginOutcomes){const De=G.loginOutcomes,tt={};for(const[at,wt]of Object.entries(De))wt!=="pending"&&(tt[at]=wt);Object.keys(tt).length>0&&Fe(tt)}},[]);const Vt=a.useCallback((G,De)=>{ho(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[G]:De}}}})},[b,x]);a.useEffect(()=>{const G=Object.entries(Ae).filter(([De,tt])=>tt!=="pending");for(const[De,tt]of G)Vt(De,tt)},[Ae,Vt]),a.useEffect(()=>()=>{ee.current&&clearInterval(ee.current),Object.values(Ue.current).forEach(clearTimeout),Ue.current={}},[]);const Dt=a.useCallback(G=>{_e(G),ho(b,{completedSteps:x,stepData:{github:{skipped:G}}})},[b,x]),Ft=a.useCallback(G=>G==="complete"?-1:vi.indexOf(G),[]),Ct=a.useCallback(()=>{y(De=>[...new Set([...De,b])]),j(De=>De.filter(tt=>tt!==b)),$s("onboarding:step-completed",{step:b}),b==="github"&&!ft&&Dt(!1);const G=Ft(b);G>=0&&G<vi.length-1&&v(vi[G+1])},[b,ft,Dt,Ft]),Nt=a.useCallback(()=>{j(De=>[...new Set([...De,b])]),XT(b),$s("onboarding:step-skipped",{step:b}),b==="github"&&!ft&&Dt(!0);const G=Ft(b);G>=0&&G<vi.length-1&&v(vi[G+1])},[b,ft,Dt,Ft]),Tt=a.useCallback(()=>{const G=b;y(tt=>tt.filter(at=>at!==G)),j(tt=>tt.filter(at=>at!==G)),G==="github"&&!ft&&Dt(!1);const De=Ft(b);De>0&&v(vi[De-1])},[b,ft,Dt,Ft]),Zt=a.useCallback(()=>{Nt()},[Nt]),Ut=a.useCallback(async G=>{Fe(De=>{const tt=De[G];if(tt&&tt!=="pending"){const{[G]:at,...wt}=De;return wt}return De}),U(De=>{if(!(G in De))return De;const tt={...De};return delete tt[G],tt}),Fe(De=>({...De,[G]:"pending"})),P(G),ze.current=0;try{const{url:De,instructions:tt}=await py(G);tt?.trim()&&U(at=>({...at,[G]:tt})),window.open(ai(De),"_blank"),ee.current=setInterval(async()=>{if(ze.current++,ze.current>=NP){ee.current&&(clearInterval(ee.current),ee.current=null),P(null),Fe(at=>({...at,[G]:"timeout"})),U(at=>{if(!(G in at))return at;const wt={...at};return delete wt[G],wt}),n("Login timed out. Please try again.","warning");return}try{const{providers:at,ghCli:wt}=await xr();I(at),J(wt),at.find(Lt=>Lt.id===G)?.authenticated&&(ee.current&&(clearInterval(ee.current),ee.current=null),P(null),Fe(Lt=>({...Lt,[G]:"success"})),U(Lt=>{if(!(G in Lt))return Lt;const Jn={...Lt};return delete Jn[G],Jn}),G==="github"&&Dt(!1),n("Login successful","success"))}catch{}},2e3)}catch(De){De instanceof Error&&De.message.includes("already in progress")||De&&typeof De=="object"&&"status"in De&&De.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Fe(at=>({...at,[G]:"failed"}))):(n(De instanceof Error?De.message:"Login failed","error"),Fe(at=>({...at,[G]:"failed"}))),P(null),U(at=>{if(!(G in at))return at;const wt={...at};return delete wt[G],wt})}},[n,Dt]),B=a.useCallback(G=>{ee.current&&(clearInterval(ee.current),ee.current=null),P(null),ze.current=0,Fe(De=>({...De,[G]:"cancelled"})),U(De=>{if(!(G in De))return De;const tt={...De};return delete tt[G],tt})},[]),xe=a.useCallback((G,De)=>{te(at=>({...at,[G]:De}));const tt=Ue.current[G];tt&&(clearTimeout(tt),delete Ue.current[G]),oe(at=>{if(!at[G])return at;const wt={...at};return delete wt[G],wt}),ae(at=>{if(!at[G])return at;const wt={...at};return delete wt[G],wt})},[]),Ie=a.useCallback(()=>{const G=re.current;if(!G)return;const De=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof G.scrollTo=="function"){G.scrollTo({top:0,behavior:De?"auto":"smooth"});return}}catch{}G.scrollTop=0},[]),M=a.useCallback(async(G,De)=>{const tt=(De??ue[G]??"").trim(),at=vP(G,tt);if(at){oe(_t=>({..._t,[G]:at}));return}const wt=Ue.current[G];wt&&(clearTimeout(wt),delete Ue.current[G]),P(G),oe(_t=>{const Lt={..._t};return delete Lt[G],Lt}),ae(_t=>{if(!_t[G])return _t;const Lt={..._t};return delete Lt[G],Lt});try{await gy(G,tt),await le(),Ie(),te(_t=>{const Lt={..._t};return delete Lt[G],Lt}),oe(_t=>{if(!_t[G])return _t;const Lt={..._t};return delete Lt[G],Lt}),ae(_t=>({..._t,[G]:"✓ Key saved"})),Ue.current[G]=setTimeout(()=>{ae(_t=>{if(!_t[G])return _t;const Lt={..._t};return delete Lt[G],Lt}),delete Ue.current[G]},3e3),n("API key saved","success")}catch(_t){const Lt=_t instanceof TypeError&&_t.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":_t instanceof Error?_t.message:"Failed to save API key";oe(Jn=>({...Jn,[G]:Lt})),ae(Jn=>{if(!Jn[G])return Jn;const Fs={...Jn};return delete Fs[G],Fs}),n(Lt,"error")}finally{P(null)}},[ue,n,le,Ie]),ne=a.useCallback(async G=>{P(G);try{await by(G),await le(),n("API key removed","success")}catch(De){n(De instanceof Error?De.message:"Failed to clear API key","error")}finally{P(null)}},[n,le]),Le=a.useCallback(async G=>{P(G);try{await fy(G),await le(),n("Logged out","success")}catch(De){n(De instanceof Error?De.message:"Logout failed","error")}finally{P(null)}},[n,le]),ut=a.useCallback(G=>{se(G)},[]),bt=a.useCallback(async()=>{try{const G={modelOnboardingComplete:!0};if(ve){const De=ve.indexOf("/"),tt=De!==-1?ve.slice(0,De):void 0,at=De!==-1?ve.slice(De+1):ve,wt=V.find(_t=>_t.id===at);wt?(G.defaultProvider=wt.provider,G.defaultModelId=wt.id):tt&&at&&(G.defaultProvider=tt,G.defaultModelId=at)}await fn(G),Mh()}catch{}},[ve,V,fn,Mh]),Pt=a.useCallback(async()=>{const G=[...new Set([...x,"first-task"])];O(!0);try{await bt(),$s("onboarding:completed",{completedSteps:G,skippedSteps:S}),y(G),j(De=>De.filter(tt=>tt!=="first-task")),v("complete")}finally{O(!1)}},[bt,x,S]),At=a.useCallback(async()=>{if(!s)return;const G=_.trim();if(!G){F("Please enter a task description.");return}F(null),E(!0);let De=!1;try{const tt=await up({description:G,source:{sourceType:"dashboard_ui"}},s);$(tt),w(!0),$s("onboarding:first-task-created",{taskId:tt?.id}),n("Task created","success"),De=!0}catch(tt){const at=tt instanceof Error?tt.message:"Something went wrong creating your task. Please try again.";F(at),n(at,"error")}finally{E(!1)}De&&bt()},[s,_,n,bt]),nn=a.useCallback(async()=>{O(!0);try{await bt()}finally{O(!1)}$s("onboarding:open-new-task",{}),r?.()},[bt,r]),zn=a.useCallback(async()=>{if(yt){O(!0);try{await bt()}finally{O(!1)}f(!1),e(),$s("onboarding:open-github-import",{}),o?.()}},[bt,yt,e,o]),hn=a.useCallback(async()=>{$s("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:S}),O(!0);try{await fn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[b,x,S,e]),en=a.useCallback(()=>{$s("onboarding:finished",{}),f(!1),e()},[e]),On=a.useCallback(()=>{const G=l??K;G&&(bt(),c?.(G),e())},[l,K,bt,c,e]),we=a.useCallback(()=>{bt(),e()},[bt,e]);if(!p)return null;const it=It(),un=R.filter(G=>G.id!=="github"),Nn=[...un].sort(Ih),Tn=Nn.some(G=>!G.type||G.type==="oauth"),Ce=Nn.some(G=>G.type==="api_key"),Ye=un.filter(G=>G.authenticated),dt=Ye.length>0,vt=!!s,Qt=b==="github"&&!dt,bn=(()=>{if(!ve)return"";const G=ve.indexOf("/"),De=G===-1?void 0:ve.slice(0,G),tt=G===-1?ve:ve.slice(G+1),at=V.find(wt=>wt.id===tt&&(!De||wt.provider===De));return at?.name?at.name:De?`${Zc(De)} ${tt}`:ve})(),Jt=[];if(vt?Jt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Jt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),dt){const G=Zc(Ye[0]?.id??"");Jt.push({label:"AI Provider",status:"connected",detail:`${G} connected — AI agents can work on tasks`})}else un.length>0&&un.some(G=>ge[G.id])?Jt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Jt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});yt?Jt.push({label:"GitHub",status:"connected",detail:ht?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!lt||fe?Jt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Jt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),bn&&Jt.push({label:"Default Model",status:"connected",detail:bn});const Xt=l??K,_n=Xt?.description?.split(`
656
- `)[0]?.trim()||Xt?.title||"",sn=new Set(pc),ls=Nn.filter(G=>sn.has(G.id)).sort((G,De)=>{const tt=pc.indexOf(G.id),at=pc.indexOf(De.id);return tt!==at?tt-at:Ih(G,De)}),cs=Nn.filter(G=>G.authenticated&&!sn.has(G.id)),cn=Nn.filter(G=>!G.authenticated&&!sn.has(G.id)),kt=G=>{if(G.id==="claude-cli"&&G.type==="cli")return t.jsx(HT,{authenticated:G.authenticated,onToggled:()=>{le()}},G.id);if(G.type==="api_key"){const De=td(G.id),tt=jP(G);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${G.id}`,"aria-hidden":"true",children:t.jsx(Ln,{provider:G.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(sp,{size:14,className:"onboarding-provider-key-icon"}),G.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:De.description}),t.jsx(zt,{status:St(G)}),G.authenticated&&G.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",G.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(wP,{provider:G,apiKeyInfo:tt,inputValue:ue[G.id]??"",isSaving:z===G.id,error:me[G.id],success:be[G.id],isConnected:G.authenticated,onInputChange:xe,onSave:M,onClear:ne})})]},G.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${G.id}`,className:`onboarding-provider-card${G.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${G.id}`,"aria-hidden":"true",children:t.jsx(Ln,{provider:G.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:G.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:td(G.id).description}),t.jsx(zt,{status:St(G)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===G.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:G.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>B(G.id),children:"Cancel"})]}):G.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Le(G.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Ut(G.id),children:"Login"})}),z===G.id&&k[G.id]&&t.jsx(hc,{instructions:k[G.id],"data-testid":`onboarding-login-instructions-${G.id}`}),Ae[G.id]==="timeout"&&z!==G.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ae[G.id]==="failed"&&z!==G.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},G.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",ref:Ne,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(Ns,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Fd,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Fd,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(wn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:hn,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Kt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Ge.map((G,De)=>{const tt=pt>De,at=x.includes(G.key)&&tt,wt=S.includes(G.key)&&!x.includes(G.key)&&tt,_t=at||wt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[De>0&&t.jsx("div",{className:`model-onboarding-step-connector ${De<=pt?"done":""}`}),_t?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===G.key?"active":""} ${at?"done":""} ${wt?"skipped":""}`,onClick:()=>v(G.key),"aria-label":`Go back to ${G.label}`,title:`Review ${G.label}`,children:[t.jsx("span",{className:"step-number",children:at?t.jsx(wn,{size:14}):wt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):De+1}),t.jsx("span",{className:"step-label",children:G.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===G.key?"active":""} ${at?"done":""} ${wt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:at?t.jsx(wn,{size:14}):wt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):De+1}),t.jsx("span",{className:"step-label",children:G.label})]})]},G.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:re,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."}),!Z&&R.length>0&&(()=>{const G=R.filter(_t=>_t.id!=="github"&&_t.authenticated).length,De=R.filter(_t=>_t.id!=="github").length,tt=Object.keys(ge).filter(_t=>!R.find(Lt=>Lt.id===_t)?.authenticated).length;if(De===0)return null;let at="onboarding-provider-summary",wt="";return G>0?(at+=" onboarding-provider-summary--connected",wt=`✓ ${G} of ${De} provider${De!==1?"s":""} connected`):tt>0?(at+=" onboarding-provider-summary--skipped",wt=`${tt} provider${tt!==1?"s":""} skipped`):(at+=" onboarding-provider-summary--none",wt="No providers connected yet"),t.jsx("div",{className:at,"data-testid":"provider-summary",children:wt})})(),t.jsx(ni,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),R.length>0&&!R.some(G=>G.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),Z?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(rt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):R.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),ls.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ls.map(G=>kt(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),cs.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:cs.map(G=>kt(G))})]}),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(ni,{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."})}),V.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(Kn,{models:V,value:ve,onChange:ut,placeholder:"Select a default model…",label:"Default model"})}),ve&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",V.find(G=>G.id===ve)?.name??ve]})})]}),t.jsx(ni,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[cn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:cn.map(G=>kt(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Ee.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Ee.map(G=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Ln,{provider:G.id,size:"sm"}),t.jsx("span",{children:G.name||G.id})]},G.id))}):null,He?t.jsx(GT,{onSave:nt,onCancel:()=>{ot(!1),Oe(void 0)},saving:Je,error:st}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ot(!0),children:"Add custom provider"})]})}),Tn&&t.jsx(ni,{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."})}),Ce&&t.jsx(ni,{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."})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[yt?t.jsx("p",{className:"model-onboarding-description",children:ht?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):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."}),!yt&&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"})]})}),Qt&&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(ni,{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."})}),lt?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(Ns,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Rt,{status:it})})]}),ft&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Le("github"),children:"Disconnect"}))]}),(it==="not-connected"||it==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="github"?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>B("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Ut("github"),children:[t.jsx(Ns,{size:16}),"Connect"]}),z==="github"&&k.github&&t.jsx(hc,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]}),it==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:ht?"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."}),it==="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:()=>Ut("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Zt,children:"Skip for now"})]})]}),it==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),it==="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:()=>Ut("github"),children:"Connect anyway"})})]}),it==="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("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(Ln,{provider:"github",size:"lg"})}),ht?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard 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.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:ht?"Continue with gh CLI auth →":"Continue without GitHub →"}),ht&&(z==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(rt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Ut("github"),children:[t.jsx(Ln,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),ht&&z==="github"&&k.github&&t.jsx(hc,{instructions:k.github,"data-testid":"onboarding-login-instructions-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."}),vt?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(ni,{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."}),A&&Xt?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(wn,{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:Xt.id}),_n&&t.jsx("p",{className:"onboarding-task-created__description",children:_n}),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:On,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:we,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[vt?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:_,onChange:G=>{C(G.target.value),F(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:At,disabled:L,"data-testid":"onboarding-first-task-submit",children:L?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),T&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:T}),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(kP,{items:Jt}),vt&&t.jsxs(t.Fragment,{children:[t.jsx(ni,{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:nn,disabled:he,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ln,{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${yt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:zn,disabled:he||!yt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Ns,{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"}),!yt&&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(wn,{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:hn,disabled:he,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Nt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ct,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Tt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Nt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ct,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Tt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Ct,disabled:!vt,children:"Next →"})]}),b==="first-task"&&!A&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Tt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Pt,disabled:he,children:he?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:en,children:[t.jsx(wn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function yg({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 CP=a.lazy(()=>dn(()=>import("./SetupWizardModal-1qSn8Yl0.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),EP=a.lazy(()=>dn(()=>import("./SettingsModal-EEQwF0Ql.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function _P(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{dn(()=>import("./SettingsModal-EEQwF0Ql.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function MP({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=c.detailTask?(()=>{const _=n.find(C=>C.id===c.detailTask?.id);return _?"prompt"in c.detailTask?{...c.detailTask,..._,prompt:c.detailTask.prompt,log:c.detailTask.log}:_:c.detailTask})():null,y=p??c.closeSettings,S=a.useCallback(()=>{c.openNewTask()},[c]),j=a.useCallback(()=>{c.openGitHubImport()},[c]),A=a.useCallback(_=>{v(null),c.closeModelOnboarding(),c.openDetailTask(_)},[c]),w=a.useCallback(async _=>{const C=await d.handleModalCreate(_);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{_P()},[]),t.jsxs(t.Fragment,{children:[x&&t.jsx(Ri,{children:t.jsx(kA,{task:x,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(Ri,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(EP,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(NA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ri,{children:t.jsx(_A,{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(Ri,{children:t.jsx(zA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(aR,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(oR,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(MR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(zR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(hT,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(iT,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ri,{children:t.jsx(lT,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(xT,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:_=>{const C=n.find(L=>L.id===_);C&&c.openDetailTask(C)}}),t.jsx(Ri,{children:t.jsx(yT,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ri,{children:t.jsx(TT,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(BT,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(CP,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(SP,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:b,onViewTask:A}),t.jsx(yg,{toasts:o,onRemove:l})]})}function AP({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 nd=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function RP(e,n){if(n==="ready")return"done";const s=nd.findIndex(r=>r.id===n),i=nd.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function TP({stage:e}){const[n]=a.useState(()=>fv());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:nd.map(s=>{const i=RP(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(rt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const PP=5e3;function IP(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function $P(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++,Co(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 DP(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 Yj(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()},PP),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=$P(e,s,i),f=IP(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const LP={planning:ii,subtask:Fi,mission_interview:vs,milestone_interview:vs,slice_interview:vs},zP={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function OP({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ys(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),g=a.useRef(null),{activeTabMap:p}=Ma(),f=a.useMemo(()=>Ki(),[]);if(a.useEffect(()=>{if(!l)return;const x=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),a.useEffect(()=>{const x=new Set,y=new Map;for(const S of e){const j=p.get(S.id),A=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),w=h.current.get(S.id);w&&w!==A&&x.add(S.id),y.set(S.id,A)}if(h.current=y,x.size!==0)return d(x),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(new Set),g.current=null},500),()=>{g.current&&(clearTimeout(g.current),g.current=null)}},[p,e]),e.length===0)return null;const b=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(x=>!x),title:`${b} background AI task${b!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(rt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(kc,{size:12}),t.jsxs("span",{children:["AI ",b]})]}),l&&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(x=>{const y=LP[x.type],S=x.status==="generating",j=x.status==="awaiting_input",A=x.status==="error",w=p.get(x.id),_=w?.tabId??x.lockedByTab??null,C=!!(_&&_!==f&&!w?.stale),L=u.has(x.id);return t.jsxs("div",{className:`background-tasks-indicator__item${L?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:L?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:L?"translateY(-1px)":void 0},onClick:async()=>{C&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(x),c(!1))},children:[A?t.jsx(hs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{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:x.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[A?"Failed":zP[x.type],S&&" — generating...",j&&!C&&" — needs input",j&&C&&" — active in another tab"]})]}),S&&t.jsx(rt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!C&&t.jsx(kc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&C&&t.jsx(Bo,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(x.id)},title:"Dismiss",children:t.jsx(Kt,{size:12})})]},x.id)})})]})]})}function FP(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 UP(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Cn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Ks};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Vn}}}function BP({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}=DP(e,n,s,u),[f,b]=a.useState(!1),v=a.useMemo(()=>UP(h.executorState),[h.executorState]),x=a.useMemo(()=>FP(h.lastActivityAt),[h.lastActivityAt]),y=v.icon;return p?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(ad,{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(OP,{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(S=>!S),"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(Wn,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(wi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const HP={planning:ii,subtask:Fi,mission_interview:vs,milestone_interview:vs,slice_interview:vs},qP={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Ii=new Set;function VP({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(Ii.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of Ii){const x=f.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(Ii.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!Ii.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=>{Ii.add(f),l()},g=f=>{Ii.delete(f.id),l(),n(f)},p=()=>{for(const f of c)Ii.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(hs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Kt,{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=HP[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(hs,{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":qP[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(Kt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function WP({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(Kt,{size:16,"aria-hidden":"true"})})]})}function KP({onResume:e}){const n=tP();if(!n)return null;const s=n.completedSteps.length,i=vi.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(rs,{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:()=>{$s("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Cn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function GP({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Sa(),i=gg(),[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[S,j]=await Promise.all([xr(),Wi()]);if(x)return;const A=S.providers??[],w=A.find(T=>T.id==="github"),C=!A.some(T=>T.id!=="github"&&T.authenticated),L=!j.defaultProvider&&!j.defaultModelId,E=w?!w.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:L,needsGitHub:E})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const g=a.useCallback(()=>{ZT(),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:sp}),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:Ns}),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(ii,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(hs,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Kt,{size:16,"aria-hidden":!0})})]})}function JP({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 fc(e){return e>99?"99+":String(e)}function YP({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:g,onOpenScripts:p,onToggleTerminal:f,onOpenFiles:b,onOpenGitHubImport:v,onOpenPlanning:x,onResumePlanning:y,activePlanningSessionCount:S=0,onOpenUsage:j,onRunScript:A,projectId:w,onViewAllProjects:_,showSkillsTab:C,experimentalFeatures:L}){const E=Pr(),[T,F]=a.useState(!1),[K,$]=a.useState(!1),[R,I]=a.useState({}),[H,J]=a.useState(!1),Z=a.useMemo(()=>Object.entries(R).sort(([O],[ue])=>O.localeCompare(ue)),[R]);a.useEffect(()=>{if(!K)return;let O=!1;return J(!0),vr(w).then(ue=>{O||I(ue)}).catch(()=>{O||I({})}).finally(()=>{O||J(!1)}),()=>{O=!0}},[K,w]);const N=a.useCallback(()=>F(!1),[]),z=a.useCallback(O=>{N(),O?.()},[N]);if(a.useEffect(()=>{if(!T)return;const O=ue=>{ue.key==="Escape"&&F(!1)};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[T]),E!=="mobile"||i||r)return null;const P=S>0&&y?y:x,k=!!L?.roadmap,U=!!C,V=!!L?.todoView,pe=k&&(!U||e==="roadmaps"),ve=U&&(!k||e!=="roadmaps"),se=U&&!ve,he=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&V||e==="roadmaps"&&!pe||e==="skills"&&!ve;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(Ui,{}),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(Sn,{}),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(vs,{}),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(ji,{}),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(fa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:fc(d)})]}),ve&&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"})]}),pe&&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(_c,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${he?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>F(O=>!O),children:[t.jsx(wc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),T&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:N}),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:()=>z(u),children:[t.jsx(fa,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:fc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>z(l),children:[t.jsx(zs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>z(c),children:[t.jsx(pr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>z(m),children:[t.jsx(Js,{}),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:()=>z(f),children:[t.jsx(di,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(O=>!O),"aria-expanded":K,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(kn,{size:14,className:`mobile-more-chevron${K?" mobile-more-chevron--open":""}`})})]}),K&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:H?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(rt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Z.length>0?t.jsxs(t.Fragment,{children:[Z.map(([O,ue])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${O}`,onClick:()=>{A&&A(O,ue),N(),$(!1)},children:[t.jsx(Cn,{size:14}),t.jsx("span",{children:O})]},O)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{N(),$(!1),p()},children:[t.jsx(Ws,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{N(),$(!1),p()},children:[t.jsx(Ws,{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:()=>z(b),children:[t.jsx(Wn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>z(P),children:[t.jsx(ii,{}),t.jsx("span",{children:"Planning"}),S>0&&t.jsx("span",{className:"mobile-more-item-badge",children:fc(S)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>z(h),children:[t.jsx(Ac,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>z(g),children:[t.jsx(wi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>z(v),children:[t.jsx(JP,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>z(j),children:[t.jsx(zs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>z(_),children:[t.jsx(np,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>z(()=>n("documents")),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Documents"})]}),se&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>z(()=>n("skills")),children:[t.jsx(Vn,{}),t.jsx("span",{children:"Skills"})]}),k&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>z(()=>n("roadmaps")),children:[t.jsx(_c,{}),t.jsx("span",{children:"Roadmaps"})]}),L?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>z(()=>n("research")),children:[t.jsx(yi,{}),t.jsx("span",{children:"Research"})]}),L?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>z(()=>n("insights")),children:[t.jsx(rs,{}),t.jsx("span",{children:"Insights"})]}),L?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>z(()=>n("memory")),children:[t.jsx(vo,{}),t.jsx("span",{children:"Memory"})]}),L?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{z(()=>n("dev-server"))},children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),V&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>z(()=>n("todos")),children:[t.jsx(op,{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:()=>z(o),children:[t.jsx(lr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function QP({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(Sn,{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 Ld="__fn_agent__";function jg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function $h(e,n,s){const i=typeof e=="string"?e.trim():"",r=jg(n,s),o=i||(r.modelProvider&&r.modelId?Ld:"");return o?{agentId:o,...r}:null}function gc(e,n,s){const i=jg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function XP(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 Dh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:XP(e.metadata),createdAt:e.createdAt}}function ZP(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,b]=a.useState(""),[v,x]=a.useState([]),[y,S]=a.useState(""),j=a.useRef(null),A=a.useRef(!1),w=a.useRef(""),_=a.useRef(null),C=a.useRef(""),L=a.useRef(null);a.useEffect(()=>{w.current=y},[y]);const E=a.useCallback(async N=>{const z={agentId:N.agentId};return N.modelProvider&&N.modelId&&(z.modelProvider=N.modelProvider,z.modelId=N.modelId),(await dw(z,e)).session},[e]),T=a.useCallback(async(N,z,P)=>{const k=$h(N,z,P);if(!k)return;const U=gc(k.agentId,k.modelProvider,k.modelId);o(!0);try{const{session:V}=await cw({agentId:k.agentId,modelProvider:k.modelProvider,modelId:k.modelId},e);if(V)i(V),C.current=U;else{const pe=await E(k);i(pe),C.current=U}}catch(V){console.error("[useQuickChat] Failed to initialize session:",V),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,E]),F=a.useCallback(async()=>{if(s){d(!0);try{const N=await uu(s.id,{limit:50},e);c(N.messages.map(Dh))}catch(N){console.error("[useQuickChat] Failed to load messages:",N)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?F():c([])},[s,F]);const K=a.useCallback(async()=>{if(s){d(!0);try{const N=await uu(s.id,{limit:50},e);c(N.messages.map(Dh))}catch(N){console.error("[useQuickChat] Failed to reload messages:",N)}finally{d(!1)}}},[s,e]),$=a.useCallback(async(N,z,P)=>{const k=$h(N,z,P);if(!k)return;const U=gc(k.agentId,k.modelProvider,k.modelId);L.current=k;const V=U===C.current&&s;if(V||(j.current&&(j.current.close(),j.current=null),p(""),b(""),x([]),h(!1)),V){await K();return}i(null),c([]),C.current=U,await T(k.agentId,k.modelProvider,k.modelId)},[T,K,s]),R=a.useCallback(async(N,z)=>{await $(Ld,N,z)},[$]),I=a.useCallback(async()=>{const N=L.current;if(!N)return;const z=gc(N.agentId,N.modelProvider,N.modelId);j.current&&(j.current.close(),j.current=null),p(""),b(""),x([]),h(!1),c([]),i(null),o(!0);try{const P=await E(N);i(P),C.current=z}catch(P){console.error("[useQuickChat] Failed to start a fresh session:",P),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,E]),H=a.useCallback(()=>{s&&(A.current=!0,j.current?.close(),j.current=null,uw(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),J=a.useCallback(()=>{w.current="",S("")},[]),Z=a.useCallback((N,z)=>{if(!s||!N.trim()&&(!z||z.length===0))return Promise.resolve();if(m)return z&&z.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(w.current=N,S(N),Promise.resolve());const P=new Promise((k,U)=>{_.current={resolve:k,reject:U},A.current=!1,j.current&&(j.current.close(),j.current=null);const pe={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:N,createdAt:new Date().toISOString()};c(ue=>[...ue,pe]),p(""),b(""),x([]),h(!0);let ve="",se="",he=[];const O={onThinking:ue=>{se+=ue,b(se)},onText:ue=>{ve+=ue,p(ve)},onToolStart:ue=>{he=[...he,{toolName:ue.toolName,args:ue.args,isError:!1,status:"running"}],x(he)},onToolEnd:ue=>{const te=[...he];for(let me=te.length-1;me>=0;me--){const oe=te[me];if(oe?.toolName===ue.toolName&&oe.status==="running"){te[me]={...oe,status:"completed",isError:ue.isError,result:ue.result},he=te,x(te);return}}he=[...te,{toolName:ue.toolName,isError:ue.isError,result:ue.result,status:"completed"}],x(he)},onDone:ue=>{const te={id:ue.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:ve,thinkingOutput:se||void 0,toolCalls:he.length>0?he:void 0,createdAt:new Date().toISOString()};c(oe=>[...oe,te]),p(""),b(""),x([]),h(!1),j.current=null,_.current?.resolve(),_.current=null;const me=w.current.trim();me&&(w.current="",S(""),Z(me))},onError:ue=>{if(p(""),b(""),x([]),h(!1),j.current=null,console.error("[useQuickChat] Stream error:",ue),n?.("Failed to get response","error"),_.current?.reject(new Error(typeof ue=="string"?ue:"Failed to get response")),_.current=null,!A.current){const te=w.current.trim();te&&(w.current="",S(""),Z(te))}K()}};j.current=mw(s.id,N,O,z,e)});return P.catch(()=>{}),P},[s,m,e,n,K]);return a.useEffect(()=>()=>{j.current&&(j.current.close(),j.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:Z,stopStreaming:H,clearPendingMessage:J,switchSession:$,startModelChat:R,startFreshSession:I,loadMessages:F,reloadMessages:K}),[s,r,l,u,m,g,f,v,y,Z,H,J,$,R,I,F,K])}function e4(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 Ea({...f,...g,includeEphemeral:g?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await qj(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||!Pw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function t4({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=xw(l.path),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(ep,{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 n4=200;function s4(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((w,_)=>{if(_<0||_>w.length){r(!1);return}const C=L=>/[a-zA-Z0-9/_.-]/.test(L);for(let L=_-1;L>=0;L--){if(w[L]==="#")if(L===0){const E=w.slice(L+1,_);u(L),l(E),f(0),r(!0);return}else{const E=w[L-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const T=w.slice(L+1,_);u(L),l(T),f(0),r(!0);return}r(!1);return}if(!C(w[L])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async w=>{if(!w.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const _=await Xy(w,s,n);m(_.files),f(0)}catch(_){_.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{S(o)},n4),()=>{b.current&&clearTimeout(b.current)}},[o,i,S]);const j=a.useCallback((w,_)=>{if(!i||c<0)return _;const C=_.slice(0,c),L=_.slice(c+1),E=L.match(/[\s]|$/),T=E?E.index:L.length,F=L.slice(T);return`${C}#${w.path}${F}`},[i,c]),A=a.useCallback((w,_)=>{if(!i||d.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),f(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return w.preventDefault(),f(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:x,selectFile:j,dismissMention:y,handleKeyDown:A}}function i4(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let bc=null;function a4(){return bc===null&&(bc=window.innerHeight),bc}function r4(){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=a4()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function kg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!i4()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=r4();s(c),r(c>0?o.height:null)};return l(),o.addEventListener("resize",l),o.addEventListener("scroll",l),()=>{o.removeEventListener("resize",l),o.removeEventListener("scroll",l),s(0),r(null)}},[e]),{keyboardOverlap:n,viewportHeight:i}}function o4(e){return`${e.name?.trim()||e.id} (${e.role})`}function l4(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 c4(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 bo(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function d4(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${bo(r,50)}`}).join(", ")}function u4(e){if(e===void 0)return null;if(typeof e=="string")return bo(e,200);try{return bo(JSON.stringify(e),200)}catch{return bo(String(e),200)}}function Lh(e,n=!1){if(!e||e.length===0)return null;const s=(g,p)=>{const f=g.status==="running",b=g.status==="completed"&&g.isError,v=d4(g.args),x=u4(g.result),y=f?v:x?`result: ${x}`:v?`args: ${v}`:null,S=n?null:y,j=f?"running":b?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${f?" chat-tool-call--running":""}${b?" chat-tool-call--error":""}`,open:f,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",title:g.toolName,children:g.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&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:v})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${b?" 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:x})]})]})]},`${g.toolName}-${p}`)},i=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:i,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Bd,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(g=>g.status==="running").length,o=e.filter(g=>g.status==="completed"&&g.isError).length,l=r>0,c=Array.from(new Set(e.map(g=>g.toolName))),u=c.slice(0,5),d=Math.max(0,c.length-u.length),m=d>0?`${u.join(", ")}, +${d} more`:u.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:i,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Bd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((g,p)=>s(g,p))]})})}const m4={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 h4(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}}const po={width:320,height:400},p4=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),f4=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function g4(e){return e.type.startsWith("image/")}function b4(e){if(p4.has(e.type))return!0;const n=e.name.toLowerCase();return f4.some(s=>n.endsWith(s))}const oa={width:280,height:260},Do=768,la=8;function x4(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,S=window.innerWidth>768?s():0,j=window.innerWidth-v-x,A=window.innerHeight-v-x-y-S;return{x:Math.max(x,Math.min(j,b.x)),y:Math.max(x,Math.min(A,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,S=u.current.y-x,j=m({x:y,y:S});o(j)}},[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 v4(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Do,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const b=Math.max(oa.width,window.innerWidth-p-la),v=Math.max(oa.height,window.innerHeight-f-la);return{width:Math.max(oa.width,Math.min(b,g.width)),height:Math.max(oa.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Do)return po;try{const g=localStorage.getItem(i);if(!g)return po;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?po:{width:p.width,height:p.height}}catch{return po}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const g={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,g.right,g.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(g=>{if(!r())return;const p=g.currentTarget.dataset.resizeDirection;if(!p)return;g.preventDefault(),g.stopPropagation();const f=g.currentTarget;typeof f.setPointerCapture=="function"&&f.setPointerCapture(g.pointerId);const b={pointerX:g.clientX,pointerY:g.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-b.pointerX,j=y.clientY-b.pointerY;let A=b.width,w=b.height,_=b.anchorRight,C=b.anchorBottom;if(p.includes("w")&&(A=b.width-S),p.includes("e")){const $=S;A=b.width+$,_=b.anchorRight-$}if(p.includes("n")&&(w=b.height-j),p.includes("s")){const $=j;w=b.height+$,C=b.anchorBottom-$}const L=n+_,E=s+C,T=o({width:A,height:w},L,E),F=Math.max(la-n,Math.min(window.innerWidth-n-oa.width-la,_)),K=Math.max(la-s,Math.min(window.innerHeight-s-oa.height-la,C));u(T),m({right:F,bottom:K})},x=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",x)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function y4({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=e4(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?Ce=>{r?.(typeof Ce=="function"?Ce(p):Ce)}:h,{keyboardOverlap:b,viewportHeight:v}=kg({enabled:p}),x=b>0?{"--keyboard-overlap":`${b}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[j,A]=a.useState(""),[w,_]=a.useState([]),[C,L]=a.useState(!1),[E,T]=a.useState(""),[F,K]=a.useState(""),[$,R]=a.useState(""),[I,H]=a.useState(""),[J,Z]=a.useState(!1),[N,z]=a.useState(0),[P,k]=a.useState(-1),[U,V]=a.useState(()=>new Set),[pe,ve]=a.useState([]),[se,he]=a.useState(!1),[,O]=a.useState(!1),[ue,te]=a.useState({top:0,left:0}),me=s4({projectId:e}),oe=a.useCallback(Ce=>{if(!Ce||!me.mentionActive)return;const Ye=Ce.getBoundingClientRect();te({top:Ye.top-260,left:Ye.left+8})},[me.mentionActive]),be=a.useRef(!1),ae=a.useRef(!1),Ee=a.useRef(""),$e=a.useRef(0),He=a.useRef(null),ot=a.useRef(0),{position:Je,isDragging:et,handlePointerDown:st,handlePointerMove:Oe,handlePointerUp:Ue}=x4(e,be),re=Je.y+60,{panelSize:Ne,anchorOffset:ee,handleResizeStart:Ae}=v4(e,Je.x,re),Fe=typeof window<"u"&&window.innerWidth>Do,{activeSession:fe,messages:_e,isStreaming:ze,streamingText:Xe,streamingThinking:je,streamingToolCalls:ce,sessionsLoading:Re,messagesLoading:ge,sendMessage:Me,stopStreaming:Ge,pendingMessage:Pe,clearPendingMessage:pt,switchSession:Y,startModelChat:le,startFreshSession:ye}=ZP(e,n),nt=a.useRef(null),X=a.useRef(null),Qe=a.useRef(null),lt=a.useRef(null),ft=a.useRef(null),Mt=a.useRef([]),yt=a.useRef(!1),ht=E||F,St=a.useMemo(()=>l4(ht),[ht]),zt=a.useMemo(()=>w.find(Ce=>`${Ce.provider}/${Ce.id}`===ht)??null,[w,ht]),It=a.useMemo(()=>c4(zt,St),[zt,St]),Rt=a.useMemo(()=>y==="model"?St?`${Ld}::${St.modelProvider}/${St.modelId}`:"":j?`${j}::`:"",[y,St,j]),$t=y==="agent"?!!j:!!St,Ot=!$t||!fe;a.useEffect(()=>{if(d.length===0){A(""),S("model");return}d.some(Ye=>Ye.id===j)||A(d[0]?.id??"")},[d,j]),a.useEffect(()=>{!p||ae.current||(ae.current=!0,L(!0),ps().then(Ce=>{const Ye=Ce.models??[];if(_(Ye),E||Ye.length===0)return;const dt=Ce.defaultProvider,vt=Ce.defaultModelId;if(dt&&vt){const bn=`${dt}/${vt}`;if(Ye.some(Xt=>`${Xt.provider}/${Xt.id}`===bn)){K(bn),T(bn),S("model");return}}K("");const Qt=Ye[0];Qt&&T(`${Qt.provider}/${Qt.id}`)}).catch(Ce=>{console.error("[QuickChatFAB] Failed to load models:",Ce),_([]),K("")}).finally(()=>{L(!1)}))},[p,d.length,E]),a.useEffect(()=>{if(!p){Ee.current="";return}if(!Rt){Ee.current="";return}const Ce=Rt===Ee.current&&!fe&&!Re;if(!(Rt===Ee.current&&!Ce)){if(Ee.current=Rt,y==="model"&&St){le(St.modelProvider,St.modelId);return}y==="agent"&&j&&Y(j)}},[p,y,St,j,Rt,fe,Re,le,Y]),a.useEffect(()=>{p||(Z(!1),H(""),k(-1),Mt.current.forEach(Ce=>{Ce.previewUrl&&URL.revokeObjectURL(Ce.previewUrl)}),ve([]))},[p]),a.useEffect(()=>{Mt.current=pe},[pe]),a.useEffect(()=>{if(!p){yt.current=!1;return}typeof window>"u"||(yt.current=window.innerWidth<=Do)},[p]),a.useEffect(()=>{if(!p||Ot||!yt.current)return;const Ce=lt.current;if(!Ce)return;const Ye=document.activeElement,dt=Ye?nt.current?.contains(Ye):!1,vt=Ye===document.body;if(!dt&&!vt){yt.current=!1;return}const Qt=requestAnimationFrame(()=>{Ce.focus(),yt.current=!1});return()=>cancelAnimationFrame(Qt)},[p,Ot]),a.useEffect(()=>()=>{Mt.current.forEach(Ce=>{Ce.previewUrl&&URL.revokeObjectURL(Ce.previewUrl)})},[]);const Vt=a.useCallback(Ce=>{A(Ce)},[]),Dt=a.useCallback(Ce=>{T(Ce)},[]),Ft=a.useCallback(()=>{!$t||Re||ye()},[$t,Re,ye]),Ct=a.useMemo(()=>d.find(Ce=>Ce.id===j)??null,[d,j]),Nt=a.useMemo(()=>{const Ce=I.trim().toLowerCase();return Ce?d.filter(Ye=>Ye.name.toLowerCase().includes(Ce)):d},[d,I]),Tt=a.useMemo(()=>{const Ce=new Map;for(const Ye of d)Ce.set(Ye.name.toLowerCase(),Ye);return Ce},[d]);a.useEffect(()=>{z(0)},[I,J]),a.useEffect(()=>()=>{He.current!==null&&(window.clearTimeout(He.current),He.current=null)},[]),a.useEffect(()=>{if(!p)return;const Ce=dt=>{const vt=dt.target;nt.current?.contains(vt)||X.current?.contains(vt)||vt.closest(".model-combobox-dropdown--portal")||f(!1)},Ye=dt=>{dt.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Ce),document.addEventListener("keydown",Ye),()=>{document.removeEventListener("mousedown",Ce),document.removeEventListener("keydown",Ye)}},[p,f]),a.useEffect(()=>{if(!p)return;const Ce=Qe.current;Ce&&(Ce.scrollTop=Ce.scrollHeight)},[_e,Xe,je,p]);const Zt=a.useMemo(()=>y==="agent"?Ct?`Message ${Ct.name||Ct.id}`:"Select an agent to start chatting":It?`Message ${It}`:"Select a model to start chatting",[y,Ct,It]),Ut=Pe.length>50?`${Pe.slice(0,50)}…`:Pe,B=a.useCallback(Ce=>{if(!Ce||Ce.length===0)return;const Ye=[];for(let dt=0;dt<Ce.length;dt+=1){const vt=Ce[dt];b4(vt)&&Ye.push({file:vt,previewUrl:g4(vt)?URL.createObjectURL(vt):""})}Ye.length>0&&ve(dt=>[...dt,...Ye])},[]),xe=a.useCallback(Ce=>{ve(Ye=>{const dt=Ye[Ce];return dt?.previewUrl&&URL.revokeObjectURL(dt.previewUrl),Ye.filter((vt,Qt)=>Qt!==Ce)})},[]),Ie=a.useCallback(Ce=>{B(Ce.clipboardData?.files)},[B]),M=a.useCallback(async()=>{const Ce=$.trim(),Ye=Mt.current;if(!(!Ce&&Ye.length===0)&&!Ot){R(""),Z(!1),H(""),k(-1);try{await Me(Ce,Ye.map(dt=>dt.file)),Ye.forEach(dt=>{dt.previewUrl&&URL.revokeObjectURL(dt.previewUrl)}),ve(dt=>dt.filter(vt=>!Ye.includes(vt)))}catch{}}},[Me,Ot,$]),ne=a.useCallback(Ce=>{Ce.preventDefault(),ot.current+=1,he(!0)},[]),Le=a.useCallback(Ce=>{Ce.preventDefault(),Ce.dataTransfer.dropEffect="copy",he(!0)},[]),ut=a.useCallback(Ce=>{Ce.preventDefault(),ot.current=Math.max(0,ot.current-1),ot.current===0&&he(!1)},[]),bt=a.useCallback(Ce=>{Ce.preventDefault(),ot.current=0,he(!1),B(Ce.dataTransfer?.files)},[B]),Pt=a.useCallback((Ce,Ye)=>{const dt=h4(Ce,Ye);if(dt){Z(!0),H(dt.filter),k(dt.start);return}Z(!1),H(""),k(-1)},[]),At=a.useCallback(Ce=>{const Ye=lt.current;if(!Ye||P<0)return;const dt=Ye.selectionStart??$e.current,vt=Ye.selectionEnd??dt,Qt=Math.max(dt,vt),bn=Math.min(P,Qt),Xt=`${`@${Ce.name.replace(/\s+/g,"_")}`} `,_n=$.slice(0,bn)+Xt+$.slice(Qt),sn=bn+Xt.length;R(_n),Z(!1),H(""),z(0),k(-1),window.requestAnimationFrame(()=>{lt.current&&(lt.current.focus(),lt.current.setSelectionRange(sn,sn))})},[P,$]),nn=a.useCallback(Ce=>{const Ye=Ce.target.value,dt=Ce.target.selectionStart??Ye.length;$e.current=dt,R(Ye),Pt(Ye,dt),me.detectMention(Ye,dt),O(me.mentionActive),me.mentionActive&&oe(Ce.target)},[Pt,me,oe]),zn=a.useCallback(()=>{He.current!==null&&window.clearTimeout(He.current),He.current=window.setTimeout(()=>{Z(!1),H(""),k(-1),O(!1),me.dismissMention(),He.current=null},120)},[me]),hn=a.useCallback(()=>{He.current!==null&&(window.clearTimeout(He.current),He.current=null)},[]),en=a.useCallback(Ce=>{const Ye=Ce.currentTarget,dt=Ye.selectionStart??Ye.value.length;$e.current=dt,Pt(Ye.value,dt),me.detectMention(Ye.value,dt),O(me.mentionActive),me.mentionActive&&oe(Ye)},[Pt,me,oe]),On=a.useCallback(Ce=>{Ce.key!=="Escape"&&en(Ce)},[en]),we=a.useCallback(Ce=>{const Ye=/@([\w-]+)/g,dt=[];let vt=0,Qt=Ye.exec(Ce);for(;Qt;){const[bn,Jt=""]=Qt,Xt=Qt.index;Xt>vt&&dt.push(Ce.slice(vt,Xt));const _n=Jt.replace(/_/g," ").toLowerCase(),sn=Tt.get(_n);sn?dt.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",sn.name.replace(/\s+/g,"_")]},`${sn.id}-${Xt}`)):dt.push(bn),vt=Xt+bn.length,Qt=Ye.exec(Ce)}return vt<Ce.length&&dt.push(Ce.slice(vt)),dt.length===0?Ce:dt},[Tt]),it=a.useCallback(Ce=>{V(Ye=>{const dt=new Set(Ye);return dt.has(Ce)?dt.delete(Ce):dt.add(Ce),dt})},[]),un=a.useCallback((Ce,Ye=!1)=>Ye?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Ce}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(pi,{remarkPlugins:[fi],components:m4,children:Ce})}),[]),Nn=a.useCallback(Ce=>{if($e.current=Ce.currentTarget.selectionStart??$e.current,me.mentionActive&&me.files.length>0){if(me.handleKeyDown(Ce,$),Ce.key==="Enter"||Ce.key==="Tab"){const Ye=me.files[me.selectedIndex];if(Ye){const dt=me.selectFile(Ye,$);R(dt),me.dismissMention(),O(!1)}}return}if(J&&Ce.key==="ArrowDown"){Ce.preventDefault(),Nt.length>0&&z(Ye=>(Ye+1)%Nt.length);return}if(J&&Ce.key==="ArrowUp"){Ce.preventDefault(),Nt.length>0&&z(Ye=>Ye===0?Nt.length-1:Ye-1);return}if(J&&Ce.key==="Enter"){Ce.preventDefault();const Ye=Nt[N]??Nt[0];Ye&&At(Ye);return}if(J&&Ce.key==="Escape"){Ce.preventDefault(),Ce.stopPropagation(),Z(!1),H(""),k(-1);return}Ce.key!=="Enter"||Ce.shiftKey||(Ce.preventDefault(),M())},[J,Nt,N,At,M,me,$]),Tn=a.useCallback(()=>{if(be.current){be.current=!1;return}f(Ce=>!Ce)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:X,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":et?"true":"false",style:{right:Je.x,bottom:Je.y},onPointerDown:st,onPointerMove:Oe,onPointerUp:Ue,onClick:Tn,children:t.jsx(ji,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:nt,"data-testid":"quick-chat-panel",style:{right:Je.x+ee.right,bottom:re+ee.bottom,...Fe?{width:Ne.width,height:Ne.height}:{},...x},children:[Fe&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Ae,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Ae,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Ae,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Ae,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Ae,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:Ae,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:Ae,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:Ae,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),y==="model"&&It&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:It,children:It})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[d.length>0&&t.jsxs("div",{className:"quick-chat-header-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{S("agent"),T("")},"aria-label":"Switch to agent mode",title:"Agent mode",children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{S("model"),A("")},"aria-label":"Switch to model mode",title:"Model mode",children:"Model"})]}),t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:Ft,disabled:!$t||Re,children:t.jsx(ln,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Kt,{size:16})})]})]}),y==="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:j,onChange:Ce=>Vt(Ce.target.value),"data-testid":"quick-chat-agent-select",children:d.map(Ce=>t.jsx("option",{value:Ce.id,children:o4(Ce)},Ce.id))})]}),y==="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(Kn,{id:"quick-chat-model-override",models:w,value:E,onChange:Dt,label:"Select model override",placeholder:C?"Loading models…":"Select a model",disabled:C||w.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Qe,"data-testid":"quick-chat-messages",children:Re||ge?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):_e.length===0&&!Xe&&!je&&!ze?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[_e.map(Ce=>{const Ye=Ce.role==="user",dt=!Ye&&U.has(Ce.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-${Ce.id}`,children:[Ye?t.jsx("p",{children:we(Ce.content)}):t.jsxs(t.Fragment,{children:[un(Ce.content,dt),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${dt?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":dt?"Show rendered markdown":"Show plain text",onClick:()=>it(Ce.id),children:dt?t.jsx(Nc,{size:14}):t.jsx(ha,{size:14})})]}),Lh(Ce.toolCalls,!0)]},Ce.id)}),ze&&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:[Xe?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:un(Xe,U.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${U.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":U.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>it("__streaming__"),children:U.has("__streaming__")?t.jsx(Nc,{size:14}):t.jsx(ha,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Lh(ce,!0),je&&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:je})]})]})]})}),pe.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:pe.map((Ce,Ye)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ye}`,children:[Ce.previewUrl?t.jsx("img",{src:Ce.previewUrl,alt:Ce.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:Ce.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ye}`,"aria-label":`Remove ${Ce.file.name}`,onClick:()=>xe(Ye),children:"×"})]},`${Ce.file.name}-${Ye}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${se?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:ne,onDragOver:Le,onDragLeave:ut,onDrop:bt,children:[t.jsx("input",{ref:ft,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:Ce=>{B(Ce.target.files),Ce.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>ft.current?.click(),children:t.jsx(ip,{size:16})}),t.jsx("input",{ref:lt,type:"text",value:$,onChange:nn,onKeyDown:Nn,onKeyUp:On,onClick:en,onBlur:zn,onFocus:hn,onPaste:Ie,placeholder:Zt,disabled:Ot,"data-testid":"quick-chat-input"}),ze?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onClick:Ge,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ws,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onClick:()=>{M()},disabled:Ot||$.trim().length===0&&pe.length===0,"data-testid":"quick-chat-send",children:t.jsx($i,{size:16})})]}),t.jsx(QP,{agents:d,filter:I,highlightedIndex:N,visible:J,onSelect:At,position:"above"}),t.jsx(t4,{visible:me.mentionActive&&!J,position:ue,files:me.files,selectedIndex:me.selectedIndex,onSelect:Ce=>{const Ye=me.selectFile(Ce,$);R(Ye),me.dismissMention(),O(!1),lt.current?.focus()},loading:me.loading}),Pe&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ut}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:pt,children:"×"})]})]})})]})]})}function nr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function zh(e){return e.status==="generating"||e.status==="awaiting_input"}function sr(e){return e==="complete"||e==="error"}function j4(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ma(),d=a.useCallback(()=>{ld(e).then(p=>{const f=p.filter(v=>{const x=nr(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of f)b.set(v.id,nr(v.updatedAt));i.current=b,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(x<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&x<=S)continue;if(S!==void 0&&x>S&&!sr(v.status)&&r.current.delete(v.sessionId),sr(v.status)){b.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,x);continue}const j=b.get(v.sessionId),A=v.type??j?.type,w=v.title??j?.title;if(!j&&(!A||!w))continue;const _={id:v.sessionId,type:A??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??j?.projectId??e??null,lockedByTab:v.owningTabId??j?.lockedByTab??null,updatedAt:v.updatedAt??j?.updatedAt??new Date(x).toISOString()},C=b.get(v.sessionId);(!C||C.status!==_.status||C.title!==_.title||C.type!==_.type||C.projectId!==_.projectId||C.lockedByTab!==_.lockedByTab||C.updatedAt!==_.updatedAt)&&(b.set(v.sessionId,_),i.current.set(v.sessionId,x),f=!0)}return f?[...b.values()].sort((v,x)=>nr(x.updatedAt)-nr(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const x=JSON.parse(v.data),y=nr(x.updatedAt)||Date.now();s(S=>{const j=i.current.get(x.id)??0;if(y<j)return S;const A=r.current.get(x.id);if(A!==void 0&&y<=A)return S;if(A!==void 0&&y>A&&!sr(x.status)&&r.current.delete(x.id),i.current.set(x.id,y),sr(x.status))return S.filter(_=>_.id!==x.id);const w=S.findIndex(_=>_.id===x.id);if(w>=0){const _=[...S];return _[w]=x,_}return zh(x)?[x,...S]:S}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),sr(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data),y=Date.now();r.current.set(x,y),i.current.set(x,Math.max(i.current.get(x)??0,y)),c({sessionId:x,status:"complete",timestamp:y}),s(S=>S.filter(j=>j.id!==x))}catch{}};return Qs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":b},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const b=n.find(S=>S.id===p)?.type,v=Ki();let x=!1;if(b==="planning")try{await fp(p,e,v)}catch(S){x=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(b==="subtask")try{await xp(p,e,v)}catch(S){x=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(b==="mission_interview")try{await wp(p,e,v)}catch(S){x=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Np(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>zh(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 ts(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 Oh(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function k4(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function xc(e,n){if(Oh(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return k4(e,n);const i=Oh(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function w4(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),b=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=a.useCallback(async I=>{const H=++m.current,J=n,Z=I?.searchQueryOverride??g.current,N=I?.includeArchivedOverride??u.current;try{const z=await Lv(void 0,void 0,J,Z,N);if(m.current!==H||n!==J)return;o(z.map(ts)),f.current=Date.now()}catch{if(m.current!==H||n!==J)return;if(I?.clearOnError){o([]);return}o(z=>z)}},[n]);p.current=y;const S=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const I=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{y({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const H=Date.now();H-h.current<x||(h.current=H,y())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[y]),a.useEffect(()=>{if(i===!1)return;const I=b.current,H=n?`?projectId=${encodeURIComponent(n)}`:"",J=()=>b.current!==I;let Z=!0;const N=pe=>{if(J())return;const ve=ts(JSON.parse(pe.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(se=>{const he=se.findIndex(me=>me.id===ve.id);if(he===-1)return[...se,ve];const O=se[he],ue=xc(O,ve);if(ue===O)return se;const te=[...se];return te[he]=ue,te}),f.current=Date.now()},z=pe=>{if(J())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ve,to:se}=JSON.parse(pe.data),he=ts(ve);o(O=>O.map(ue=>ue.id===he.id?{...he,column:se}:ue)),f.current=Date.now()},P=pe=>{if(J())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ve=ts(JSON.parse(pe.data));o(se=>se.map(he=>he.id!==ve.id?he:xc(he,ve))),f.current=Date.now()},k=pe=>{if(J())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ve=ts(JSON.parse(pe.data));o(se=>se.filter(he=>he.id!==ve.id))},U=pe=>{if(J())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ve}=JSON.parse(pe.data),se=ts(ve);o(he=>he.map(O=>O.id===se.id?{...se,column:"done"}:O))},V=Qs(`/api/events${H}`,{events:{"task:created":N,"task:moved":z,"task:updated":P,"task:deleted":k,"task:merged":U},onReconnect:()=>{Z&&(J()||p.current())}});return()=>{Z=!1,V()}},[n,i]);const j=a.useCallback(async I=>{const H=ts(await up(I,n));return o(J=>J.some(Z=>Z.id===H.id)?J:[...J,H]),H},[n]),A=a.useCallback(async(I,H)=>ts(await Ov(I,H,n)),[n]),w=a.useCallback(async I=>ts(await mp(I,n)),[n]),_=a.useCallback(async I=>ts(await Fv(I,n)),[n]),C=a.useCallback(async I=>Uv(I,n),[n]),L=a.useCallback(async I=>ts(await Bv(I,n)),[n]),E=a.useCallback(async I=>{const H=ts(await Hv(I,n));return o(J=>J.some(Z=>Z.id===H.id)?J:[...J,H]),H},[n]),T=a.useCallback(async(I,H)=>{const J=d.current.find(N=>N.id===I),Z=J?{...J,...H,updatedAt:new Date().toISOString()}:void 0;Z&&o(N=>N.map(z=>z.id===I?Z:z));try{const N=ts(await si(I,H,n));return o(z=>z.map(P=>P.id===I?N:P)),N}catch(N){throw J&&o(z=>z.map(P=>P.id===I?J:P)),N}},[n]),F=a.useCallback(async I=>{const H=ts(await Vv(I,n));return o(J=>J.map(Z=>Z.id===I?H:Z)),H},[n]),K=a.useCallback(async I=>{const H=ts(await Wv(I,n));return o(J=>J.map(Z=>Z.id===I?H:Z)),H},[n]),$=a.useCallback(async()=>{const H=(await Kv(n)).map(ts);return o(J=>J.map(Z=>H.find(z=>z.id===Z.id)||Z)),H},[n]),R=a.useCallback(I=>{if(I.length===0)return;if(g.current){p.current({searchQueryOverride:g.current});return}const H=I.map(ts);o(J=>{let Z=J;for(const N of H){const z=Z.findIndex(U=>U.id===N.id);if(z===-1){Z===J&&(Z=[...J]),Z.push(N);continue}const P=Z[z],k=xc(P,N);k!==P&&(Z===J&&(Z=[...J]),Z[z]=k)}return Z}),f.current=Date.now()},[]);return{tasks:r,createTask:j,moveTask:A,pauseTask:w,deleteTask:_,mergeTask:C,retryTask:L,duplicateTask:E,updateTask:T,archiveTask:F,unarchiveTask:K,archiveAllDone:$,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:R,lastFetchTimeMs:f.current}}const N4=5e3,S4=1e3;function C4(){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 ru();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 ru(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),cr("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),cr("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<S4||(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()},N4),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Jj(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await tk(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await yp(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 E4="kb-dashboard-current-project";function _4(e){return e??"local"}function M4(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=_4(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await Wi();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(E4);if(x){const y=JSON.parse(x);y?.id&&e.some(j=>j.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await fn({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,fn({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,fn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,fn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const wg=a.createContext(null);function A4({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()},[]),xo.createElement(wg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function R4(){const e=a.useContext(wg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Ng="kb-dashboard-theme-mode",Sg="kb-dashboard-color-theme",Cg=[...Rw],sd="theme-data",vc="theme-data.css";function T4(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${vc}`:e.replace(/\/[^/]+$/,`/${vc}`):`/${vc}`}const Ls=typeof window<"u",P4=Ls?a.useLayoutEffect:a.useEffect;function Eg(e){return e==="dark"||e==="light"||e==="system"}function Fh(){if(!Ls)return"dark";try{const e=localStorage.getItem(Ng);if(Eg(e))return e}catch{}return"dark"}function Uh(){if(!Ls)return"default";try{const e=localStorage.getItem(Sg);if(e&&Cg.includes(e))return e}catch{}return"default"}function Bh(e){if(Ls)try{localStorage.setItem(Ng,e)}catch{}}function Hh(e){if(Ls)try{localStorage.setItem(Sg,e)}catch{}}function I4(e,n){return e==="system"?n?"dark":"light":e}function $4(e,n,s){if(!Ls)return;const i=I4(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function qh(){if(!Ls)return;const e=T4(),n=document.getElementById(sd);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=sd,document.head.appendChild(s)}function Vh(){if(!Ls)return;const e=document.getElementById(sd);e&&e.remove()}function D4(){const[e,n]=a.useState(()=>Fh()),[s,i]=a.useState(()=>Uh()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ls?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(!Ls||!r)return;let f=!1;return Wi().then(b=>{f||(Eg(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),Fh()!==b.themeMode&&Bh(b.themeMode)),b.colorTheme&&Cg.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Uh()!==b.colorTheme&&Hh(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(!Ls)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{c(v.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),P4(()=>{$4(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ls||r||(s!=="default"?qh():Vh())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Bh(f),fn({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),Hh(f),f!=="default"?qh():Vh(),fn({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 L4(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(void 0),[v,x]=a.useState(null),[y,S]=a.useState("definition"),[j,A]=a.useState(!1),[w,_]=a.useState(void 0),[C,L]=a.useState(!1),[E,T]=a.useState(!1),[F,K]=a.useState(!1),[$,R]=a.useState(null),[I,H]=a.useState(!1),[J,Z]=a.useState(!1),[N,z]=a.useState(void 0),[P,k]=a.useState(!1),[U,V]=a.useState("project"),[pe,ve]=a.useState(!1),[se,he]=a.useState(!1),[O,ue]=a.useState(!1),[te,me]=a.useState(!1),[oe,be]=a.useState(!1),[ae,Ee]=a.useState(!1),[$e,He]=a.useState(!1),ot=!!(v||j||s||r||m||J||P||pe||se||O||oe||te||F||I||C||E||ae||$e),Je=a.useCallback(()=>i(!0),[]),et=a.useCallback(()=>i(!1),[]),st=a.useCallback(()=>o(!0),[]),Oe=a.useCallback(B=>{c(B),o(!0)},[]),Ue=a.useCallback(()=>{const B=n[0];B&&(d(B.id),o(!0))},[n]),re=a.useCallback(B=>{d(B),o(!0)},[]),Ne=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ee=a.useCallback(B=>{p(B),h(!0)},[]),Ae=a.useCallback(B=>{b(B),h(!0)},[]),Fe=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),fe=a.useCallback((B,xe="definition")=>{x(B),S(xe)},[]),_e=a.useCallback(B=>{x(B),S("changes")},[]),ze=a.useCallback(B=>{x(xe=>xe&&{...xe,...B})},[]),Xe=a.useCallback(()=>{x(null)},[]),je=a.useCallback(B=>{_(B),A(!0)},[]),ce=a.useCallback(()=>{A(!1),_(void 0)},[]),Re=a.useCallback(()=>L(!0),[]),ge=a.useCallback(()=>L(!1),[]),Me=a.useCallback(()=>T(!0),[]),Ge=a.useCallback(()=>T(!1),[]),Pe=a.useCallback(B=>{R(B??null),K(!0)},[]),pt=a.useCallback(()=>{K(!1),R(null)},[]),Y=a.useCallback(()=>H(!0),[]),le=a.useCallback(()=>H(!1),[]),ye=a.useCallback(()=>{Z(B=>!B)},[]),nt=a.useCallback(()=>{Z(!1),z(void 0)},[]),X=a.useCallback(()=>k(!0),[]),Qe=a.useCallback(()=>k(!1),[]),lt=a.useCallback(B=>{V(B)},[]),ft=a.useCallback(()=>ve(!0),[]),Mt=a.useCallback(()=>ve(!1),[]),yt=a.useCallback(()=>he(!0),[]),ht=a.useCallback(()=>he(!1),[]),St=a.useCallback(()=>ue(!0),[]),zt=a.useCallback(()=>ue(!1),[]),It=a.useCallback(()=>me(!0),[]),Rt=a.useCallback(()=>me(!1),[]),$t=a.useCallback(()=>be(!0),[]),Ot=a.useCallback(()=>be(!1),[]),Vt=a.useCallback(async(B,xe)=>{be(!1),z(xe),Z(!0)},[]),Dt=a.useCallback(()=>Ee(!0),[]),Ft=a.useCallback(()=>Ee(!1),[]),Ct=a.useCallback(()=>He(!0),[]),Nt=a.useCallback(()=>He(!1),[]),Tt=a.useCallback((B,xe)=>{xe(`Created ${B.id} from planning mode`,"success"),o(!1),c(null)},[]),Zt=a.useCallback((B,xe)=>{const Ie=B.map(M=>M.id).join(", ");xe(`Created ${Ie} from planning mode`,"success"),o(!1),c(null)},[]),Ut=a.useCallback((B,xe)=>{const Ie=B.map(M=>M.id).join(", ");xe(`Created ${Ie} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:j,settingsInitialSection:w,schedulesOpen:C,githubImportOpen:E,usageOpen:F,usageAnchorRect:$,systemStatsOpen:I,terminalOpen:J,terminalInitialCommand:N,filesOpen:P,fileBrowserWorkspace:U,activityLogOpen:pe,gitManagerOpen:se,workflowStepsOpen:O,agentsOpen:te,scriptsOpen:oe,setupWizardOpen:ae,modelOnboardingOpen:$e,anyModalOpen:ot,openNewTask:Je,closeNewTask:et,openPlanning:st,openPlanningWithInitialPlan:Oe,resumePlanning:Ue,openPlanningWithSession:re,closePlanning:Ne,openSubtaskBreakdown:ee,openSubtaskWithSession:Ae,closeSubtask:Fe,openDetailTask:fe,openDetailWithChangesTab:_e,updateDetailTask:ze,closeDetailTask:Xe,openSettings:je,closeSettings:ce,openSchedules:Re,closeSchedules:ge,openGitHubImport:Me,closeGitHubImport:Ge,openUsage:Pe,closeUsage:pt,openSystemStats:Y,closeSystemStats:le,toggleTerminal:ye,closeTerminal:nt,openFiles:X,closeFiles:Qe,setFileWorkspace:lt,openActivityLog:ft,closeActivityLog:Mt,openGitManager:yt,closeGitManager:ht,openWorkflowSteps:St,closeWorkflowSteps:zt,openAgents:It,closeAgents:Rt,openScripts:$t,closeScripts:Ot,runScript:Vt,openSetupWizard:Dt,closeSetupWizard:Ft,openModelOnboarding:Ct,closeModelOnboarding:Nt,onPlanningTaskCreated:Tt,onPlanningTasksCreated:Zt,onSubtaskTasksCreated:Ut}}function z4(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[b,v]=a.useState(!1),[x,y]=a.useState(!1),[S,j]=a.useState({}),[A,w]=a.useState(!1),[_,C]=a.useState(!1),[L,E]=a.useState(!1),[T,F]=a.useState(!1),[K,$]=a.useState(!1),R=a.useCallback(async()=>{const[N,z]=await Promise.allSettled([Yv(e),Vo(e)]);if(N.status==="fulfilled"&&(s(N.value.maxConcurrent),r(N.value.rootDir)),z.status==="fulfilled"){const P=z.value;l(!!P.autoMerge),u(!!P.globalPause),m(!!P.enginePaused),v(!!P.prAuthAvailable),g(P.taskStuckTimeoutMs),f(P.showQuickChatFAB===!0),j(P.experimentalFeatures??{});const k=P.experimentalFeatures??{};w(k.insights===!0),C(k.roadmap===!0),E(k.memoryView===!0),F(k.devServerView===!0||k.devServer===!0),$(k.todoView===!0)}y(!0)},[e]);a.useEffect(()=>{y(!1),j({}),w(!1),C(!1),E(!1),F(!1),$(!1),R()},[R]);const I=a.useCallback(async()=>{const N=!o;l(N);try{await Hr({autoMerge:N},e)}catch{l(!N)}},[o,e]),H=a.useCallback(async()=>{const N=!c;u(N);try{await Hr({globalPause:N,globalPauseReason:N?"manual":void 0},e)}catch{u(!N)}},[c,e]),J=a.useCallback(async()=>{const N=!d;m(N);try{await Hr({enginePaused:N},e)}catch{m(!N)}},[d,e]),Z=a.useCallback(async()=>{const N=!p;f(N);try{await Hr({showQuickChatFAB:N},e)}catch{f(!N)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,settingsLoaded:x,experimentalFeatures:S,insightsEnabled:A,roadmapEnabled:_,memoryEnabled:L,devServerEnabled:T,todosEnabled:K,toggleAutoMerge:I,toggleGlobalPause:H,toggleEnginePause:J,toggleShowQuickChatFAB:Z,refresh:R}}function O4(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,gr(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 F4(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{ps().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 fn({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 fn({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 U4({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;xr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Wi().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!Sa()?l=!0:!d&&!Sa()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?($s("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&($s("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Wh="kb-update-banner-dismissed";function B4(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(Wh)==="true";d(h);let g=!1;return Qv().then(p=>{g||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{g||n(!1)}),()=>{g=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Wh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const H4=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Kh(e){return e!==null&&H4.includes(e)}function q4(e){return e==="devserver"?"dev-server":e}function V4(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=Gn("kb-dashboard-task-view");return Kh(x)?x:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Gn("kb-dashboard-task-view",r?.id);if(Kh(x)){const y=!f.current&&x==="devserver";p(y?"devserver":q4(x))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{xs("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(u),S=x[(y+1)%x.length];d(S)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function W4(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(C=>{n(C),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(C=>{h(),n(C),i("project"),u(`Project ${C.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),S=a.useCallback(async C=>{try{await Zj(C.id),u(`Project ${C.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${C.name}`,"error")}},[u,o]),j=a.useCallback(async C=>{try{await ek(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),A=a.useCallback(async C=>{try{await yp(C.id),u(`Project ${C.name} removed`,"success"),r?.id===C.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${C.name}`,"error")}},[r,s,i,u,o]),w=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),_=a.useCallback(async C=>{try{await c(C)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:A,handleToggleFavorite:w,handleToggleModelFavorite:_}}function K4(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:i,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=a.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=a.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=a.useCallback(p=>{s([p]),i(p,l)},[l,s,i]),m=a.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=a.useCallback(p=>{s(p),o(p,l)},[l,s,o]),g=a.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:u,handlePlanningTaskCreated:d,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:g}}async function G4(e){return Ko("/health",{nodeId:e})}async function J4(e){return Ko("/projects",{nodeId:e})}async function Y4(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Ko(`/tasks?${i.toString()}`,{nodeId:e})}async function Q4(e,n){return Ko(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function gL(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function bL(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function xL(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function vL(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function X4(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const x=new AbortController;f.current=x,h(!0),p(null);try{const y=[G4(e),J4(e)];s&&(y.push(Y4(e,s,i)),y.push(Q4(e,s)));const S=await Promise.allSettled(y);if(x.signal.aborted)return;const j=S[0],A=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(d(j.value),A.status==="rejected"){p(`Failed to fetch projects: ${A.reason}`),h(!1);return}if(o(A.value),s&&S[2]){const w=S[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function Z4(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 eI="fusion-dashboard-current-node",_g=a.createContext(null);function tI({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 Wi();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(eI);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(l.current=b.id,await fn({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,fn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,fn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,fn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(_g.Provider,{value:d,children:e})}function nI(){const e=a.useContext(_g);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function sI({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&&(Cv(l),window.location.reload())},[n]),o=a.useCallback(()=>{Ev(),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 iI=200,aI=a.lazy(()=>dn(()=>import("./AgentsView-DcEnemu0.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),rI=a.lazy(()=>dn(()=>import("./DocumentsView-CNbnZ7Q3.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),oI=a.lazy(()=>dn(()=>import("./InsightsView-CmJwV-ZC.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),lI=a.lazy(()=>dn(()=>import("./ResearchView-CQDI2y7Q.js"),__vite__mapDeps([24,1,0,2,25])).then(e=>({default:e.ResearchView}))),cI=a.lazy(()=>dn(()=>import("./NodesView-1pZii99I.js"),__vite__mapDeps([26,1,18,0,2,27])).then(e=>({default:e.NodesView}))),dI=a.lazy(()=>dn(()=>import("./ChatView-CTc6mP8y.js"),__vite__mapDeps([28,1,0,2])).then(e=>({default:e.ChatView}))),uI=a.lazy(()=>dn(()=>import("./RoadmapsView-BTo3BT0I.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.RoadmapsView}))),mI=a.lazy(()=>dn(()=>import("./SkillsView-CY3I5OYc.js"),__vite__mapDeps([31,1,0,2,32])).then(e=>({default:e.SkillsView}))),hI=a.lazy(()=>dn(()=>import("./MemoryView-Bwi5p79s.js"),__vite__mapDeps([33,1,12,13,0,2,34])).then(e=>({default:e.MemoryView}))),pI=a.lazy(()=>dn(()=>import("./DevServerView-LOrDrAYm.js"),__vite__mapDeps([35,1,0,2,36])).then(e=>({default:e.DevServerView}))),fI=a.lazy(()=>dn(()=>import("./TodoView-B1GDwwhR.js"),__vite__mapDeps([37,1,38,0,2,39])).then(e=>({default:e.TodoView})));function gI(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{dn(()=>import("./AgentsView-DcEnemu0.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),dn(()=>import("./DocumentsView-CNbnZ7Q3.js"),__vite__mapDeps([20,1,0,2,21])),dn(()=>import("./InsightsView-CmJwV-ZC.js"),__vite__mapDeps([22,1,14,0,2,23])),dn(()=>import("./ResearchView-CQDI2y7Q.js"),__vite__mapDeps([24,1,0,2,25])),dn(()=>import("./NodesView-1pZii99I.js"),__vite__mapDeps([26,1,18,0,2,27])),dn(()=>import("./ChatView-CTc6mP8y.js"),__vite__mapDeps([28,1,0,2])),dn(()=>import("./RoadmapsView-BTo3BT0I.js"),__vite__mapDeps([29,1,0,2,30])),dn(()=>import("./SkillsView-CY3I5OYc.js"),__vite__mapDeps([31,1,0,2,32])),dn(()=>import("./MemoryView-Bwi5p79s.js"),__vite__mapDeps([33,1,12,13,0,2,34])),dn(()=>import("./DevServerView-LOrDrAYm.js"),__vite__mapDeps([35,1,0,2,36])),dn(()=>import("./TodoView-B1GDwwhR.js"),__vite__mapDeps([37,1,38,0,2,39]))})}const yc="kb-setup-warning-dismissed";function bI(){const{toasts:e,addToast:n,removeToast:s}=R4(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{gI()},[]);const{projects:r,loading:o,error:l,refresh:c}=C4(),{nodes:u}=Yo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=nI(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:x}=M4(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:j,hasWarnings:A}=pg(f?.id),{updateAvailable:w,latestVersion:_,currentVersion:C,dismissed:L,dismiss:E}=B4();a.useEffect(()=>{if(m&&!d&&u.length>0){const de=u.find(qe=>qe.id===m);if(de){g(de);return}}m&&u.length>0&&(u.some(qe=>qe.id===m)||p())},[m,d,u,g,p]);const[T,F]=a.useState(""),K=X4(m,{projectId:f?.id,searchQuery:T||void 0});Z4(m);const $=h&&K.projects.length>0?K.projects:r,{themeMode:R,colorTheme:I,setThemeMode:H,setColorTheme:J}=D4(),{sessions:Z,generating:N,needsInput:z,planningSessions:P,dismissSession:k}=j4(f?.id),U=Z.filter(de=>de.status==="awaiting_input"||de.status==="error"),V=L4({projectId:f?.id,planningSessions:P}),{viewMode:pe,setViewMode:ve,taskView:se,handleChangeTaskView:he}=V4({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:f,projectsLength:r.length,setupWizardOpen:V.setupWizardOpen,openSetupWizard:V.openSetupWizard,themeMode:R,setThemeMode:H}),O=a.useCallback(de=>{de==="missions"&&(ye(void 0),X(void 0),lt(void 0)),he(de)},[he]),ue=se==="board"||se==="list",{tasks:te,createTask:me,moveTask:oe,pauseTask:be,deleteTask:ae,mergeTask:Ee,retryTask:$e,updateTask:He,duplicateTask:ot,archiveTask:Je,unarchiveTask:et,archiveAllDone:st,loadArchivedTasks:Oe,ingestCreatedTasks:Ue,lastFetchTimeMs:re}=w4({...f?{projectId:f.id}:{},searchQuery:T||void 0,sseEnabled:ue}),[Ne,ee]=a.useState(!1),Ae=a.useRef(performance.now()),Fe=a.useRef(!1),fe=a.useRef(!1),_e=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!Fe.current){Fe.current=!0;const de=`projects loaded at ${Math.round(performance.now()-Ae.current)}ms from mount`;console.log(`[App] ${de}`),cr("[App]",de)}if(!x&&!fe.current){fe.current=!0;const de=`current-project resolved at ${Math.round(performance.now()-Ae.current)}ms from mount`;console.log(`[App] ${de}`),cr("[App]",de)}},[o,x]),a.useEffect(()=>{if(Ne||o||x)return;const de=performance.now(),qe=window.setTimeout(()=>{const mt=`dashboard ready at ${Math.round(performance.now()-Ae.current)}ms from mount (settle delay=${Math.round(performance.now()-de)}ms)`;console.log(`[App] ${mt}`),cr("[App]",mt),ee(!0)},iI);return()=>{window.clearTimeout(qe)}},[Ne,o,x]);const Xe=Pr()==="mobile",{keyboardOverlap:je}=kg({enabled:Xe}),ce=Xe&&je>0,[Re,ge]=a.useState(0),Me=a.useCallback(()=>{Sp(f?.id).then(de=>{ge(de.unreadCount)}).catch(de=>{console.warn("[App] Failed to fetch mailbox unread count:",de)})},[f?.id]);a.useEffect(()=>{Me();const de=new URLSearchParams;f?.id&&de.set("projectId",f.id);const qe=de.size>0?`?${de.toString()}`:"";return Qs(`/api/events${qe}`,{events:{"message:sent":Me,"message:received":Me,"message:read":Me,"message:deleted":Me}})},[f?.id,Me]);const[Ge,Pe]=a.useState(!1),[pt,Y]=a.useState(!1),[le,ye]=a.useState(void 0),[nt,X]=a.useState(void 0),[Qe,lt]=a.useState(void 0),[ft,Mt]=a.useState(!1),[yt,ht]=a.useState(!1),[St,zt]=a.useState(()=>Gn(yc,f?.id)==="true");a.useEffect(()=>{zt(Gn(yc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const de=()=>{ht(!0)};return window.addEventListener(Pc,de),()=>{window.removeEventListener(Pc,de)}},[]);const It=a.useCallback(()=>{xs(yc,"true",f?.id),zt(!0)},[f?.id]),{maxConcurrent:Rt,autoMerge:$t,globalPaused:Ot,enginePaused:Vt,taskStuckTimeoutMs:Dt,showQuickChatFAB:Ft,prAuthAvailable:Ct,settingsLoaded:Nt,experimentalFeatures:Tt,insightsEnabled:Zt,roadmapEnabled:Ut,memoryEnabled:B,devServerEnabled:xe,todosEnabled:Ie,toggleAutoMerge:M,toggleGlobalPause:ne,toggleEnginePause:Le,refresh:ut}=z4(f?.id),bt=Tt.skillsView===!0,Pt=Tt.nodesView===!0,At=Tt.researchView===!0,nn=!0;a.useEffect(()=>{Nt&&(se==="skills"&&!bt&&he("board"),se==="insights"&&!Zt&&he("board"),se==="roadmaps"&&!Ut&&he("board"),se==="memory"&&!B&&he("board"),(se==="devserver"||se==="dev-server")&&!xe&&he("board"),se==="todos"&&!Ie&&he("board"),se==="research"&&!At&&he("board"))},[se,Nt,bt,Zt,Ut,he,nn,B,xe,Ie,At]),a.useEffect(()=>{Ge&&!Pt&&Pe(!1)},[Ge,Pt]);const{availableModels:zn,favoriteProviders:hn,favoriteModels:en,toggleFavoriteProvider:On,toggleFavoriteModel:we}=F4();U4({projectId:f?.id,setupWizardOpen:V.setupWizardOpen,openModelOnboarding:V.openModelOnboarding,openSettings:V.openSettings});const{handleSelectProject:it,handleViewAllProjects:un,handleOpenSettings:Nn,handleAddProject:Tn,handleSetupComplete:Ce,handleModelOnboardingComplete:Ye,handlePauseProject:dt,handleResumeProject:vt,handleRemoveProject:Qt,handleToggleFavorite:bn,handleToggleModelFavorite:Jt}=W4({setCurrentProject:b,clearCurrentProject:v,setViewMode:ve,currentProject:f,refreshProjects:c,toggleFavoriteProvider:On,toggleFavoriteModel:we,addToast:n,openSettings:V.openSettings,openSetupWizard:V.openSetupWizard,closeSetupWizard:V.closeSetupWizard,closeModelOnboarding:V.closeModelOnboarding}),{handleDetailClose:Xt}=O4({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:V.openDetailTask,closeTaskDetail:V.closeDetailTask}),{handleBoardQuickCreate:_n,handleModalCreate:sn,handlePlanningTaskCreated:ls,handlePlanningTasksCreated:cs,handleSubtaskTasksCreated:cn,handleGitHubImport:kt}=K4({createTask:me,ingestCreatedTasks:Ue,onPlanningTaskCreated:V.onPlanningTaskCreated,onPlanningTasksCreated:V.onPlanningTasksCreated,onSubtaskTasksCreated:V.onSubtaskTasksCreated,addToast:n}),G=a.useCallback((de,qe)=>{if(qe==="changes"){V.openDetailWithChangesTab(de);return}V.openDetailTask(de,qe)},[V]),De=a.useCallback(async de=>{try{const qe=await gr(de,f?.id);V.openDetailTask(qe,"logs")}catch(qe){n(`Failed to open task logs: ${qe.message}`,"error")}},[V,f?.id,n]),tt=a.useCallback(()=>{Pt&&Pe(de=>!de)},[Pt]),at=a.useCallback(()=>{V.setFileWorkspace("project"),V.openFiles()},[V]),wt=a.useCallback(async()=>{Y(!0);try{await c()}finally{Y(!1)}},[c]),_t=a.useCallback(de=>{X(de),ye(void 0),he("missions")},[he]),Lt=a.useCallback(de=>{de.type==="planning"?V.openPlanningWithSession(de.id):de.type==="subtask"?V.openSubtaskWithSession(de.id):de.type==="mission_interview"?(X(void 0),ye(de.id),lt(void 0),he("missions")):(de.type==="milestone_interview"||de.type==="slice_interview")&&(ye(void 0),X(void 0),lt(de.id),he("missions"))},[he,V]),Jn=a.useCallback(()=>{},[]),Fs=a.useCallback(()=>{},[]),li=!o&&!x&&r.length===0&&!f&&!!l,_s=()=>li?t.jsx(AP,{errorMessage:l??"Failed to fetch projects",isRetrying:pt,onRetry:wt}):Ge?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(cI,{addToast:n,onClose:()=>Pe(!1)})})})}):pe==="overview"?t.jsx(is,{children:t.jsx(o1,{projects:r,loading:o,onSelectProject:it,onAddProject:Tn,onPauseProject:dt,onResumeProject:vt,onRemoveProject:Qt,nodes:u})}):se==="skills"?!Nt||!bt?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(mI,{addToast:n,projectId:f?.id,onClose:()=>he("board")})})}):se==="chat"?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(dI,{addToast:n,projectId:f?.id})})}):se==="mailbox"?t.jsx(is,{children:t.jsx(Z1,{projectId:f?.id,addToast:n,onUnreadCountChange:ge})}):se==="roadmaps"?!Nt||!Ut?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(uI,{addToast:n,projectId:f?.id})})}):se==="missions"?t.jsx(is,{children:t.jsx(J1,{isInline:!0,isOpen:!0,onClose:()=>{X(void 0),ye(void 0),lt(void 0),he("board")},addToast:n,projectId:f?.id,onSelectTask:de=>{const qe=te.find(mt=>mt.id===de);qe&&V.openDetailTask(qe)},availableTasks:te.map(de=>({id:de.id,title:de.title})),resumeSessionId:le,targetMissionId:nt,milestoneSliceResumeSessionId:Qe,onMilestoneSliceResumeFetchError:()=>lt(void 0)})}):se==="agents"&&nn?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(aI,{addToast:n,projectId:f?.id,onOpenTaskLogs:De})})}):se==="documents"?t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(rI,{projectId:f?.id,addToast:n,onOpenDetail:V.openDetailTask})})}):se==="insights"?!Nt||!Zt?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(oI,{projectId:f?.id,addToast:n,onClose:()=>he("board")})})}):se==="research"?!Nt||!At?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(lI,{projectId:f?.id,addToast:n})})}):se==="memory"?!Nt||!B?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(hI,{addToast:n,projectId:f?.id})})}):se==="todos"?!Nt||!Ie?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(fI,{addToast:n,projectId:f?.id})})}):se==="devserver"||se==="dev-server"?!Nt||!xe?null:t.jsx(is,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(pI,{addToast:n,projectId:f?.id})})}):se==="board"?t.jsx(is,{children:t.jsx(KN,{tasks:h&&K.tasks.length>0?K.tasks:te,projectId:f?.id,maxConcurrent:Rt,onMoveTask:oe,onPauseTask:be,onOpenDetail:V.openDetailTask,addToast:n,onQuickCreate:_n,onNewTask:V.openNewTask,onPlanningMode:V.openPlanningWithInitialPlan,onSubtaskBreakdown:V.openSubtaskBreakdown,autoMerge:$t,onToggleAutoMerge:M,globalPaused:Ot,onUpdateTask:He,onRetryTask:$e,onArchiveTask:Je,onUnarchiveTask:et,onDeleteTask:ae,onArchiveAllDone:st,onLoadArchivedTasks:Oe,searchQuery:T,availableModels:zn,onOpenDetailWithTab:G,favoriteProviders:hn,favoriteModels:en,onToggleFavorite:bn,onToggleModelFavorite:Jt,taskStuckTimeoutMs:Dt,onOpenMission:_t,lastFetchTimeMs:re})}):t.jsx(is,{children:t.jsx(QN,{tasks:h&&K.tasks.length>0?K.tasks:te,projectId:f?.id,onMoveTask:oe,onRetryTask:$e,onOpenDetail:V.openDetailTask,addToast:n,globalPaused:Ot,onNewTask:V.openNewTask,onQuickCreate:_n,onPlanningMode:V.openPlanningWithInitialPlan,onSubtaskBreakdown:V.openSubtaskBreakdown,availableModels:zn,favoriteProviders:hn,favoriteModels:en,onToggleFavorite:bn,onToggleModelFavorite:Jt,taskStuckTimeoutMs:Dt,searchQuery:T,lastFetchTimeMs:re})});if(!Ne)return t.jsxs(t.Fragment,{children:[t.jsx(TP,{stage:_e}),t.jsx(yg,{toasts:e,onRemove:s})]});const Us=!V.modelOnboardingOpen&&eP(),ie=!V.modelOnboardingOpen&&!Us&&Sa()&&!gg();return t.jsxs(t.Fragment,{children:[t.jsx(kw,{isElectron:i,onOpenSettings:Nn,onOpenGitHubImport:V.openGitHubImport,onOpenPlanning:V.openPlanning,onResumePlanning:V.resumePlanning,activePlanningSessionCount:P.length,onOpenUsage:V.openUsage,onOpenActivityLog:V.openActivityLog,onOpenSystemStats:V.openSystemStats,onOpenMailbox:()=>O("mailbox"),mailboxUnreadCount:Re,onOpenSchedules:V.openSchedules,onOpenGitManager:V.openGitManager,onOpenNodes:tt,showNodesButton:Pt,onOpenWorkflowSteps:V.openWorkflowSteps,onOpenScripts:V.openScripts,onRunScript:V.runScript,onToggleTerminal:V.toggleTerminal,onOpenFiles:V.openFiles,filesOpen:V.filesOpen,globalPaused:Ot,enginePaused:Vt,onToggleGlobalPause:ne,onToggleEnginePause:Le,view:se,onChangeView:pe==="project"&&f?O:void 0,showSkillsTab:bt,showAgentsTab:nn,searchQuery:T,onSearchChange:F,projects:$,currentProject:f,onSelectProject:it,onViewAllProjects:un,projectId:f?.id,mobileNavEnabled:Xe,availableNodes:u,currentNode:d,onSelectNode:de=>{de===null?p():g(de)},isRemote:h,experimentalFeatures:{insights:Zt,roadmap:Ut,memoryView:B,devServer:xe,devServerView:xe,todoView:Ie,researchView:At}}),pe==="project"&&f&&!Ge&&se!=="missions"&&!V.isPlanningOpen&&t.jsx(VP,{sessions:U,onResumeSession:Lt,onDismissSession:Jn,onDismissAll:Fs}),pe==="project"&&f&&Us&&t.jsx(KP,{onResume:V.openModelOnboarding}),pe==="project"&&f&&ie&&t.jsx(GP,{onOpenModelOnboarding:V.openModelOnboarding,onOpenSettings:de=>V.openSettings(de)}),pe==="project"&&f&&w&&_&&C&&!L&&t.jsx(WP,{latestVersion:_,currentVersion:C,onDismiss:E}),pe==="project"&&f&&!j&&A&&!St&&t.jsx(fg,{hasAiProvider:y,hasGithub:S,onDismiss:It}),t.jsx("div",{className:`project-content${pe==="project"&&f?" project-content--with-footer":""}${Xe&&!ce?" project-content--with-mobile-nav":""}`,children:_s()}),pe==="project"&&f&&!Ge&&t.jsx(BP,{tasks:h&&K.tasks.length>0?K.tasks:te,projectId:f.id,taskStuckTimeoutMs:Dt,backgroundSessions:Z,backgroundGenerating:N,backgroundNeedsInput:z,onOpenBackgroundSession:Lt,onDismissBackgroundSession:k,lastFetchTimeMs:re,currentProjectPath:f.path,onOpenProjectDirectory:at}),t.jsx(YP,{view:se,onChangeView:pe==="project"&&f?O:()=>{},footerVisible:pe==="project"&&!!f,modalOpen:V.anyModalOpen,keyboardOpen:ce,onOpenSettings:Nn,onOpenActivityLog:V.openActivityLog,onOpenSystemStats:V.openSystemStats,onOpenMailbox:()=>O("mailbox"),mailboxUnreadCount:Re,onOpenGitManager:V.openGitManager,onOpenWorkflowSteps:V.openWorkflowSteps,onOpenSchedules:V.openSchedules,onOpenScripts:V.openScripts,onToggleTerminal:V.toggleTerminal,onOpenFiles:V.openFiles,onOpenGitHubImport:V.openGitHubImport,onOpenPlanning:V.openPlanning,onResumePlanning:V.resumePlanning,activePlanningSessionCount:P.length,onOpenUsage:()=>V.openUsage(null),onViewAllProjects:un,onRunScript:V.runScript,projectId:f?.id,showSkillsTab:bt,experimentalFeatures:{insights:Zt,roadmap:Ut,memoryView:B,devServer:xe,devServerView:xe,todoView:Ie,researchView:At}}),pe==="project"&&f&&se!=="chat"&&se!=="mailbox"&&se!=="insights"&&se!=="devserver"&&se!=="dev-server"&&t.jsx(y4,{projectId:f.id,addToast:n,showFAB:Ft,open:ft,onOpenChange:Mt,favoriteProviders:hn,favoriteModels:en,onToggleFavorite:bn,onToggleModelFavorite:Jt}),t.jsx(MP,{projectId:f?.id,tasks:te,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:V,projectActions:{handleAddProject:Tn,handleSetupComplete:Ce,handleModelOnboardingComplete:Ye},taskHandlers:{handleModalCreate:sn,handlePlanningTaskCreated:ls,handlePlanningTasksCreated:cs,handleSubtaskTasksCreated:cn,handleGitHubImport:kt},taskOperations:{moveTask:oe,deleteTask:ae,mergeTask:Ee,retryTask:$e,duplicateTask:ot},deepLink:{handleDetailClose:Xt},settings:{prAuthAvailable:Ct,themeMode:R,colorTheme:I,setThemeMode:H,setColorTheme:J},onSettingsClose:()=>{V.closeSettings(),ut()},onReopenOnboarding:()=>{V.closeSettings(),V.openModelOnboarding()}}),t.jsx(sI,{open:yt})]})}function xI(){return t.jsx(A4,{children:t.jsx(tI,{children:t.jsx(Dw,{children:t.jsx(bI,{})})})})}Iv();vv();Mg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(yv,{children:t.jsx(xI,{})})}));"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{Hj as $,zs as A,Sn as B,wn as C,ln as D,yo as E,Oi as F,Fo as G,fL as H,kn as I,mc as J,Cn as K,rt as L,Ks as M,on as N,Yt as O,Ln as P,UT as Q,Pn as R,yi as S,ad as T,Uj as U,IT as V,$T as W,Kt as X,Bj as Y,Vn as Z,L$ as _,xs as a,nD as a$,dn as a0,n$ as a1,s$ as a2,Yy as a3,Nc as a4,ha as a5,Ca as a6,pi as a7,fi as a8,mi as a9,lr as aA,vb as aB,us as aC,rp as aD,Yo as aE,C4 as aF,KD as aG,uu as aH,yr as aI,dw as aJ,GD as aK,JD as aL,uw as aM,mw as aN,s4 as aO,Pr as aP,kg as aQ,ep as aR,zo as aS,ip as aT,QP as aU,t4 as aV,ws as aW,$i as aX,ji as aY,Bd as aZ,eD as a_,YD as aa,ZD as ab,XD as ac,QD as ad,eL as ae,rs as af,hs as ag,rv as ah,ii as ai,Nb as aj,Lo as ak,wi as al,tL as am,sL as an,lL as ao,oL as ap,rL as aq,aL as ar,iL as as,nL as at,xL as au,gL as av,bL as aw,vL as ax,fr as ay,Jx as az,W$ as b,ND as b$,tD as b0,sD as b1,iD as b2,aD as b3,rD as b4,oD as b5,lD as b6,cD as b7,dD as b8,uD as b9,y$ as bA,v$ as bB,C$ as bC,x$ as bD,j$ as bE,k$ as bF,w$ as bG,N$ as bH,vj as bI,S$ as bJ,od as bK,gj as bL,bj as bM,xj as bN,fj as bO,b$ as bP,Er as bQ,Ho as bR,Kx as bS,pr as bT,Fx as bU,xD as bV,vD as bW,yD as bX,jD as bY,kD as bZ,wD as b_,mD as ba,hD as bb,fD as bc,gD as bd,pD as be,Bn as bf,id as bg,zi as bh,VD as bi,qD as bj,WD as bk,DI as bl,$I as bm,II as bn,LI as bo,WI as bp,KI as bq,HI as br,FI as bs,UI as bt,BI as bu,OI as bv,zI as bw,PI as bx,qI as by,kR as bz,Be as c,Mw as c$,bD as c0,up as c1,ga as c2,Jj as c3,Cv as c4,Ev as c5,OD as c6,a$ as c7,i$ as c8,FD as c9,wy as cA,py as cB,ai as cC,fy as cD,gy as cE,by as cF,QI as cG,G$ as cH,J$ as cI,Y$ as cJ,Si as cK,dL as cL,uL as cM,Z$ as cN,CI as cO,kc as cP,Wn as cQ,yR as cR,HT as cS,hc as cT,Go as cU,_I as cV,NI as cW,EI as cX,MI as cY,AI as cZ,Bi as c_,r$ as ca,p$ as cb,u$ as cc,o$ as cd,m$ as ce,l$ as cf,h$ as cg,c$ as ch,d$ as ci,qg as cj,uy as ck,f$ as cl,my as cm,g$ as cn,ri as co,lR as cp,GI as cq,X$ as cr,jI as cs,kI as ct,xr as cu,K$ as cv,wI as cw,SI as cx,TI as cy,RI as cz,q$ as d,Jo as d0,mL as d1,eh as d2,hL as d3,pL as d4,VI as d5,SD as d6,ED as d7,AD as d8,_D as d9,PD as dA,E$ as dB,ID as dC,zx as dD,Mc as dE,UD as dF,LD as dG,DD as dH,zD as dI,$D as dJ,Q$ as dK,cL as dL,XI as dM,JI as dN,YI as dO,e$ as dP,t$ as dQ,ZI as dR,CD as da,MD as db,RD as dc,vp as dd,Kd as de,ex as df,TD as dg,O$ as dh,I$ as di,D$ as dj,$$ as dk,B$ as dl,U$ as dm,Zh as dn,T$ as dp,R$ as dq,PT as dr,z$ as ds,Sr as dt,_M as du,M$ as dv,_$ as dw,Qy as dx,A$ as dy,P$ as dz,V$ as e,gr as f,Gn as g,HD as h,ps as i,Ea as j,BD as k,Kn as l,Fj as m,H$ as n,e4 as o,Ys as p,Vo as q,DT as r,Qs as s,Hr as t,fn as u,ke as v,Pw as w,F$ as x,Ec as y,Js as z};