@runfusion/fusion 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/bin.js +434 -103
  2. package/dist/client/assets/{AgentDetailView-Ca1euvPo.js → AgentDetailView-khrspqE3.js} +3 -3
  3. package/dist/client/assets/{AgentsView-pile-9ZM.js → AgentsView-DvN5EsoE.js} +11 -11
  4. package/dist/client/assets/AgentsView-MotzGhZJ.css +1 -0
  5. package/dist/client/assets/{ChatView-C4SCF_Hj.js → ChatView-DsETFRQp.js} +1 -1
  6. package/dist/client/assets/{DevServerView-1HvWligZ.js → DevServerView-D1_7SL1h.js} +1 -1
  7. package/dist/client/assets/{DirectoryPicker-B1eztZna.js → DirectoryPicker-BBcm5G9F.js} +1 -1
  8. package/dist/client/assets/{DocumentsView-D4m9s6Ye.js → DocumentsView-OuVpmTPp.js} +1 -1
  9. package/dist/client/assets/InsightsView-4KiUKzbz.css +1 -0
  10. package/dist/client/assets/InsightsView-DMC_bLUc.js +11 -0
  11. package/dist/client/assets/{MemoryView-DEmn8fA2.js → MemoryView-cI4IK-lz.js} +1 -1
  12. package/dist/client/assets/{NodesView-Blg8NHiu.js → NodesView-C_LWLFNr.js} +2 -2
  13. package/dist/client/assets/{PiExtensionsManager-DkXenPK0.js → PiExtensionsManager-DCTHvy2u.js} +1 -1
  14. package/dist/client/assets/{PluginManager-Czso7ZUF.js → PluginManager-BXMpkZx-.js} +1 -1
  15. package/dist/client/assets/{RoadmapsView-DATopkaE.js → RoadmapsView-BHTePn2u.js} +1 -1
  16. package/dist/client/assets/SettingsModal-2s-L1oWD.js +31 -0
  17. package/dist/client/assets/{SettingsModal-D_mcRJO2.js → SettingsModal-BSZIno8y.js} +1 -1
  18. package/dist/client/assets/{SetupWizardModal-JBNr-XIW.js → SetupWizardModal-DVoRhy_V.js} +1 -1
  19. package/dist/client/assets/{SkillsView-CkT6-elZ.js → SkillsView-CK52SRz5.js} +1 -1
  20. package/dist/client/assets/{TodoView-CstzLvjw.js → TodoView-BKqIV8P6.js} +1 -1
  21. package/dist/client/assets/{folder-open-BEDPztlF.js → folder-open-C0SfzRFt.js} +1 -1
  22. package/dist/client/assets/index-DawWARY5.css +1 -0
  23. package/dist/client/assets/index-DiC9GfBH.js +656 -0
  24. package/dist/client/assets/{list-checks-DgZgg3rh.js → list-checks-D5c428sr.js} +1 -1
  25. package/dist/client/assets/{star-DXieIAlP.js → star-GGmbVi2b.js} +1 -1
  26. package/dist/client/assets/{upload-Cbvs_TSB.js → upload-CrJJybRJ.js} +1 -1
  27. package/dist/client/assets/{users-DAMIrlue.js → users-C56SMdh4.js} +1 -1
  28. package/dist/client/index.html +2 -2
  29. package/dist/client/version.json +1 -1
  30. package/dist/extension.js +427 -103
  31. package/dist/pi-claude-cli/package.json +1 -1
  32. package/package.json +1 -1
  33. package/dist/client/assets/AgentsView-Cq-SEhLc.css +0 -1
  34. package/dist/client/assets/InsightsView-6LHF7OdE.css +0 -1
  35. package/dist/client/assets/InsightsView-u535o96R.js +0 -11
  36. package/dist/client/assets/SettingsModal-Cs5qO84M.js +0 -31
  37. package/dist/client/assets/index-CPStj9Az.css +0 -1
  38. package/dist/client/assets/index-DZB5f-Bl.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-JBNr-XIW.js","assets/DirectoryPicker-B1eztZna.js","assets/folder-open-BEDPztlF.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-Cs5qO84M.js","assets/SettingsModal-D_mcRJO2.js","assets/SettingsModal-xVaD-0tP.css","assets/users-DAMIrlue.js","assets/star-DXieIAlP.js","assets/SettingsModal-YjpwLH2V.css","assets/AgentsView-pile-9ZM.js","assets/upload-Cbvs_TSB.js","assets/AgentsView-Cq-SEhLc.css","assets/DocumentsView-D4m9s6Ye.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-u535o96R.js","assets/InsightsView-6LHF7OdE.css","assets/NodesView-Blg8NHiu.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-C4SCF_Hj.js","assets/RoadmapsView-DATopkaE.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-CkT6-elZ.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-DEmn8fA2.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-1HvWligZ.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-CstzLvjw.js","assets/list-checks-DgZgg3rh.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
2
- import{r as a,j as t,R as po,a as da,g as Uh,c as wg}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 Bh=(...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 Ng=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 Sg=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 Id=e=>{const n=Sg(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 ol={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 Cg=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Eg=a.createContext({}),Mg=()=>a.useContext(Eg),_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=""}=Mg()??{},f=i??h?Number(s??m)*24/Number(n??d):s??m;return a.createElement("svg",{ref:u,...ol,width:n??d??ol.width,height:n??d??ol.height,stroke:e??g,strokeWidth:f,className:Bh("lucide",p,r),...!o&&!Cg(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>a.createElement(x,v)),...Array.isArray(o)?o:[o]])});/**
33
- * @license lucide-react v1.7.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const Ue=(e,n)=>{const s=a.forwardRef(({className:i,...r},o)=>a.createElement(_g,{ref:o,iconNode:n,className:Bh(`lucide-${Ng(Id(e))}`,`lucide-${e}`,i),...r}));return s.displayName=Id(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 Ag=[["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"}]],Ts=Ue("activity",Ag);/**
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 Rg=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],To=Ue("archive",Rg);/**
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 Tg=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],wr=Ue("arrow-down",Tg);/**
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 Pg=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ma=Ue("arrow-left",Pg);/**
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 Ig=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Nr=Ue("arrow-right",Ig);/**
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 $g=[["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"}]],Hh=Ue("arrow-up-down",$g);/**
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 Dg=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],zi=Ue("arrow-up",Dg);/**
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 Lg=[["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"}]],zg=Ue("book-open",Lg);/**
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 Og=[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]],Nn=Ue("bot",Og);/**
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 Fg=[["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"}]],gc=Ue("box",Fg);/**
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 Ug=[["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"}]],fo=Ue("brain",Ug);/**
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 Bg=[["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=Ue("calendar",Bg);/**
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 Hg=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],qg=Ue("check-check",Hg);/**
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 Vg=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Ln=Ue("check",Vg);/**
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 Wg=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qt=Ue("chevron-down",Wg);/**
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 Kg=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Po=Ue("chevron-left",Kg);/**
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 Gg=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],vn=Ue("chevron-right",Gg);/**
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 Jg=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],mi=Ue("chevron-up",Jg);/**
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 Yg=[["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"}]],as=Ue("circle-alert",Yg);/**
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 Qg=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],yn=Ue("circle-check-big",Qg);/**
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 Xg=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Io=Ue("circle-dot",Xg);/**
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 Zg=[["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"}]],xc=Ue("circle-question-mark",Zg);/**
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 ex=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],tx=Ue("circle-stop",ex);/**
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 nx=[["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=Ue("circle-x",nx);/**
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 sx=[["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"}]],ix=Ue("clipboard-list",sx);/**
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 ax=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],wi=Ue("clock",ax);/**
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 rx=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Vh=Ue("code",rx);/**
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 ox=[["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"}]],lx=Ue("columns-3",ox);/**
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 cx=[["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"}]],Fi=Ue("copy",cx);/**
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 dx=[["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"}]],ux=Ue("cpu",dx);/**
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 mx=[["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"}]],hx=Ue("download",mx);/**
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 px=[["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"}]],fx=Ue("ellipsis-vertical",px);/**
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 gx=[["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"}]],bc=Ue("ellipsis",gx);/**
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 xx=[["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"}]],bx=Ue("external-link",xx);/**
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 vx=[["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"}]],vc=Ue("eye-off",vx);/**
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 yx=[["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"}]],fa=Ue("eye",yx);/**
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 jx=[["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"}]],Fs=Ue("file-code",jx);/**
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 kx=[["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"}]],Wh=Ue("file-diff",kx);/**
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 wx=[["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"}]],Nx=Ue("file-minus",wx);/**
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 Sx=[["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"}]],Kh=Ue("file-pen",Sx);/**
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 Cx=[["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"}]],Ex=Ue("file-plus",Cx);/**
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 Mx=[["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"}]],_x=Ue("file-question-mark",Mx);/**
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 Ax=[["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"}]],Ui=Ue("file-text",Ax);/**
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 Rx=[["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"}]],Tx=Ue("file-type",Rx);/**
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 Px=[["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"}]],Gh=Ue("file",Px);/**
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 Ix=[["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"}]],yc=Ue("folder-git-2",Ix);/**
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 $x=[["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"}]],$d=Ue("folder-root",$x);/**
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 Dx=[["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"}]],Hn=Ue("folder",Dx);/**
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 Lx=[["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"}]],go=Ue("funnel",Lx);/**
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 zx=[["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"}]],Xs=Ue("git-branch",zx);/**
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 Ox=[["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=Ue("git-commit-horizontal",Ox);/**
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 Fx=[["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"}]],Jh=Ue("git-merge",Fx);/**
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 Ux=[["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"}]],bs=Ue("git-pull-request",Ux);/**
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 Bx=[["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"}]],$o=Ue("globe",Bx);/**
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 Hx=[["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"}]],Yh=Ue("grid-3x3",Hx);/**
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 qx=[["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"}]],Zc=Ue("grip-vertical",qx);/**
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 Vx=[["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"}]],Wx=Ue("hard-drive",Vx);/**
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 Kx=[["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"}]],Gx=Ue("heart",Kx);/**
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 Jx=[["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"}]],mr=Ue("history",Jx);/**
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 Yx=[["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"}]],sr=Ue("inbox",Yx);/**
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 Qx=[["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"}]],Qh=Ue("key",Qx);/**
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 Xx=[["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"}]],Zx=Ue("keyboard",Xx);/**
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 eb=[["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"}]],Bi=Ue("layers",eb);/**
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 tb=[["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"}]],Hi=Ue("layout-grid",tb);/**
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 nb=[["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"}]],Zs=Ue("lightbulb",nb);/**
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 sb=[["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"}]],ga=Ue("link",sb);/**
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 ib=[["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"}]],ab=Ue("list-plus",ib);/**
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 rb=[["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"}]],Do=Ue("list-tree",rb);/**
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 ob=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],jc=Ue("list",ob);/**
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 lb=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rt=Ue("loader-circle",lb);/**
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 cb=[["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"}]],Lo=Ue("lock",cb);/**
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 db=[["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"}]],xa=Ue("mail",db);/**
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 ub=[["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"}]],kc=Ue("map",ub);/**
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 mb=[["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"}]],zo=Ue("maximize-2",mb);/**
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 hb=[["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"}]],pb=Ue("message-square-plus",hb);/**
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 fb=[["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=Ue("message-square",fb);/**
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 gb=[["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=Ue("minimize-2",gb);/**
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 xb=[["path",{d:"M5 12h14",key:"1ays0h"}]],bb=Ue("minus",xb);/**
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 vb=[["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"}]],hr=Ue("monitor",vb);/**
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 yb=[["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"}]],jb=Ue("move",yb);/**
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 kb=[["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"}]],wc=Ue("package",kb);/**
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 wb=[["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"}]],Xh=Ue("paperclip",wb);/**
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 Nb=[["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"}]],Us=Ue("pause",Nb);/**
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 Sb=[["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"}]],ss=Ue("pencil",Sb);/**
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 Cb=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]],Sn=Ue("play",Cb);/**
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 Eb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],an=Ue("plus",Eb);/**
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 Mb=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Zh=Ue("radio",Mb);/**
473
- * @license lucide-react v1.7.0 - ISC
474
- *
475
- * This source code is licensed under the ISC license.
476
- * See the LICENSE file in the root directory of this source tree.
477
- */const _b=[["path",{d:"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"}]],Tn=Ue("refresh-cw",_b);/**
478
- * @license lucide-react v1.7.0 - ISC
479
- *
480
- * This source code is licensed under the ISC license.
481
- * See the LICENSE file in the root directory of this source tree.
482
- */const Ab=[["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}],["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09",key:"u4xsad"}],["path",{d:"M9 12a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.4 22.4 0 0 1-4 2z",key:"676m9"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 .05 5 .05",key:"92ym6u"}]],Dd=Ue("rocket",Ab);/**
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 Rb=[["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"}]],Tb=Ue("rotate-ccw",Rb);/**
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 Pb=[["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"}]],Ib=Ue("rotate-cw",Pb);/**
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 $b=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]],ep=Ue("save",$b);/**
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 Db=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],ma=Ue("search",Db);/**
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 Lb=[["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"}]],Li=Ue("send",Lb);/**
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 zb=[["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"}]],pr=Ue("server",zb);/**
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 Ob=[["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"}]],or=Ue("settings",Ob);/**
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 Fb=[["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"}]],Ub=Ue("shield-alert",Fb);/**
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 Bb=[["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"}]],Hb=Ue("shield",Bb);/**
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 qb=[["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"}]],Vb=Ue("skull",qb);/**
533
- * @license lucide-react v1.7.0 - ISC
534
- *
535
- * This source code is licensed under the ISC license.
536
- * See the LICENSE file in the root directory of this source tree.
537
- */const Wb=[["path",{d:"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"}]],Zn=Ue("sparkles",Wb);/**
538
- * @license lucide-react v1.7.0 - ISC
539
- *
540
- * This source code is licensed under the ISC license.
541
- * See the LICENSE file in the root directory of this source tree.
542
- */const Kb=[["path",{d:"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"}]],tp=Ue("square-check-big",Kb);/**
543
- * @license lucide-react v1.7.0 - ISC
544
- *
545
- * This source code is licensed under the ISC license.
546
- * See the LICENSE file in the root directory of this source tree.
547
- */const Gb=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],xs=Ue("square",Gb);/**
548
- * @license lucide-react v1.7.0 - ISC
549
- *
550
- * This source code is licensed under the ISC license.
551
- * See the LICENSE file in the root directory of this source tree.
552
- */const Jb=[["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"}]],us=Ue("target",Jb);/**
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 Yb=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],di=Ue("terminal",Yb);/**
558
- * @license lucide-react v1.7.0 - ISC
559
- *
560
- * This source code is licensed under the ISC license.
561
- * See the LICENSE file in the root directory of this source tree.
562
- */const Qb=[["path",{d:"m16 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"}]],xo=Ue("text-wrap",Qb);/**
563
- * @license lucide-react v1.7.0 - ISC
564
- *
565
- * This source code is licensed under the ISC license.
566
- * See the LICENSE file in the root directory of this source tree.
567
- */const Xb=[["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"}]],sn=Ue("trash-2",Xb);/**
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 Zb=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],ev=Ue("trending-up",Zb);/**
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 tv=[["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"}]],ed=Ue("triangle-alert",tv);/**
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 nv=[["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"}]],Ld=Ue("unlink",nv);/**
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 sv=[["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"}]],ta=Ue("user",sv);/**
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 iv=[["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"}]],np=Ue("webhook",iv);/**
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 av=[["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"}]],Nc=Ue("workflow",av);/**
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 rv=[["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"}]],zd=Ue("wrench",rv);/**
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 ov=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Gt=Ue("x",ov);/**
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 lv=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],Bn=Ue("zap",lv),Sc="fusion:version-reload",Cc="fusion:version-update";function cv(){try{if(sessionStorage.getItem(Cc))return sessionStorage.removeItem(Cc),!0}catch{}return!1}function sp(e){if(sessionStorage.getItem(Sc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(Sc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function dv(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 uv(e){return dv(e)?(sp(`chunk load error: ${e?.message??e}`),!0):!1}async function mv(){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 ll=!1;async function cl(){if(!(ll||document.visibilityState!=="visible")){ll=!0;try{const e=await mv();if(e&&e!=="mokjluto-00d998f7"){try{sessionStorage.setItem(Cc,"1")}catch{}sp(`build version changed: mokjluto-00d998f7 -> ${e}`)}}finally{ll=!1}}}function hv(){window.setTimeout(()=>sessionStorage.removeItem(Sc),5e3),document.addEventListener("visibilitychange",()=>{cl()}),window.addEventListener("focus",()=>{cl()}),window.setTimeout(()=>void cl(),2e3)}class Oo extends a.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!uv(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(ed,{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 ns({children:e,onError:n}){return t.jsx(Oo,{level:"page",onError:n,children:e})}function Pi({children:e,onError:n}){return t.jsx(Oo,{level:"modal",onError:n,children:e})}function pv({children:e,onError:n}){return t.jsx(Oo,{level:"root",onError:n,children:e})}const fv="modulepreload",gv=function(e){return"/"+e},Od={},un=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=gv(d),d in Od)return;Od[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":fv,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)})},td="fn.authToken",Fd="token",xv="fn_token";let ha,Ud=!1,bo=!1;const Ec="fn:auth-token-recovery-required";function bv(){try{const e=window.localStorage.getItem(td);return e&&e.length>0?e:void 0}catch{return}}function ip(e){try{window.localStorage.setItem(td,e)}catch{}}function vv(){if(!(Ud||typeof window>"u")){Ud=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Fd);if(!n)return;ip(n),e.searchParams.delete(Fd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ba(){if(ha!==void 0)return ha;const e=vv();if(e)return ha=e,e;const n=bv();if(n)return ha=n,n}function yv(e){ha=e,bo=!1,ip(e)}function jv(){ha=void 0,bo=!1;try{window.localStorage.removeItem(td)}catch{}}function Bd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function kv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function wv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!kv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Bd(e.protocol)===Bd(n.protocol);return s&&i&&r}function Nv(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 ei(e){const n=ba();if(!n||typeof window>"u")return e;const s=Nv(e);return!s||!wv(s.parsed)?e:(s.parsed.searchParams.set(xv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function hi(e){const n=ba();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Sv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Cv(){typeof window>"u"||bo||(bo=!0,window.dispatchEvent(new CustomEvent(Ec)))}async function Ev(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();Sv(i)&&Cv()}catch{}}function Mv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ba();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ba(),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=>(Ev(u),u))}}class _v extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function Av(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function rs(e){return`/api${e}`}async function L(e,n={}){const s=rs(e),i=ba(),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")||Av(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 sI(){return L("/health")}function iI(){return L("/updates/check")}function Rv(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return L(`/tasks${l}`)}async function fr(e,n){const i=rs(K(`/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 ap(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:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:N,priority:k}=e;return L(K("/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:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:N,priority:k})})}function Qs(e,n,s){return L(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Tv(e,n,s,i,r,o,l,c,u){return L(K("/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 Pv(e,n,s){return L(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Iv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function $v(e,n){return L(K(`/tasks/${e}/merge`,n),{method:"POST"})}function Dv(e,n){return L(K(`/tasks/${e}/retry`,n),{method:"POST"})}function Lv(e,n){return L(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function rp(e,n){return L(K(`/tasks/${e}/pause`,n),{method:"POST"})}function zv(e,n){return L(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function Ov(e,n){return L(K(`/tasks/${e}/archive`,n),{method:"POST"})}function Fv(e,n){return L(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Uv(e){return L(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Bv(e,n){return L(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Hv(e,n){return L(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function qv(e){return L(K("/config",e))}function Fo(e){return L(K("/settings",e))}function Br(e,n){return L(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Vv(e){return L(K("/update-check",e))}function aI(e){return L(K("/remote/settings",e))}function rI(e,n){return L(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function oI(e){return L(K("/remote/status",e))}function lI(e){return L(K("/remote/install-cloudflared",e),{method:"POST"})}function cI(e){return L(K("/remote/tunnel/start",e),{method:"POST"})}function dI(e){return L(K("/remote/tunnel/stop",e),{method:"POST"})}function uI(e){return L(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function mI(e,n){return L(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function op(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 hI(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=op(null,s,i);return L(K(`/remote/url${r}`,n))}function pI(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=op(e,i,r);return L(K(`/remote/qr${o}`,s))}function fI(e){return L(K("/memory",e))}function gI(e,n){return L(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function xI(e){return L(K("/memory/files",e))}function bI(e,n){const s=`path=${encodeURIComponent(e)}`;return L(K(`/memory/file?${s}`,n))}function vI(e,n,s){return L(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function yI(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return L(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function jI(e){return L(K("/memory/dream",e),{method:"POST"})}function kI(e){return L(K("/memory/insights",e))}function wI(e,n){return L(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function NI(e){return L(K("/memory/extract",e),{method:"POST"})}function SI(e){return L(K("/memory/audit",e))}function CI(e){return L(K("/memory/stats",e))}function EI(e){return L(K("/memory/backend",e))}function MI(e){return L(K("/memory/install-qmd",e),{method:"POST"})}function _I(e,n){return L(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ki(){return L("/settings/global")}function mn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function AI(e){return L(K("/settings/scopes",e))}function RI(e){return L(K("/settings/pi-extensions",e))}function TI(e,n){return L(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function PI(e,n,s){return L(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function II(){return L("/pi-settings")}async function $I(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function DI(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function LI(e){return L(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function gr(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(rs(K(`/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 Wv(e,n,s){return L(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Hd(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=K(`/tasks/${e}/logs${r}`,n),l=await fetch(rs(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 Kv(e,n,s,i){return L(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Gv(e,n,s){return L(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Jv(e,n){return L(K(`/tasks/${e}/documents`,n))}function Yv(e,n,s){return L(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function zI(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return L(K(r,n))}function OI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return L(K(r,e))}function qd(e,n,s,i,r){return L(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Qv(e,n,s){return L(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Xv(e,n,s){return L(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Zv(e,n,s){return L(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ey(e,n){return L(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function ty(e,n,s){return L(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function ms(){return L("/models")}function ny(){return L("/usage")}function sy(){return L("/providers/claude-cli/status")}async function FI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/hermes/status${n}`)}async function UI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await L(`/providers/hermes/profiles${n}`)).profiles??[]}async function BI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/openclaw/status${n}`)}async function HI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),L(`/providers/paperclip/status?${n.toString()}`)}async function qI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function VI(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function WI(e){return L("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function KI(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function GI(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 L(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function JI(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await L(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function YI(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function iy(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function xr(){return L("/auth/status")}function ay(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function ry(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function oy(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function ly(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function cy(e,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function dy(e,n,s,i){return L(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function uy(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function my(e,n,s,i){return L(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function hy(e){return L(K("/git/remotes",e))}function py(e){return L(K("/git/remotes/detailed",e))}function fy(e,n,s){return L(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function gy(e,n){return L(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function by(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function vy(e,n,s){return L(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function yy(e,n){return L(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function jy(e,n){return(await L(K("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Hr(e,n,s,i){return L(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Vd(e,n){return L(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ky(e){return L(K("/terminal/sessions",e))}function Os(e){return L(K("/git/status",e))}function wy(e,n){const s=e?`?limit=${e}`:"";return L(K(`/git/commits${s}`,n))}function vo(e,n){return L(K(`/git/commits/${e}/diff`,n))}function Ny(e){return L(K("/git/commits/ahead",e))}function Sy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function za(e){return L(K("/git/branches",e))}function Cy(e,n,s){const i=`?limit=${n}`;return L(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function Ey(e){return L(K("/git/worktrees",e))}function My(e,n,s){return L(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function _y(e,n){return L(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Wd(e,n,s){const i=n?"?force=true":"";return L(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function Ay(e,n){return L(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Ry(e){return L(K("/git/pull",e),{method:"POST"})}function Ty(e){return L(K("/git/push",e),{method:"POST"})}function qr(e){return L(K("/git/stashes",e))}function Py(e,n){return L(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Iy(e,n,s){return L(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function $y(e,n){return L(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function Dy(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),L(K(`/git/diff/file?${i.toString()}`,s))}function na(e){return L(K("/git/changes",e))}function Kd(e,n){return L(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Ly(e,n){return L(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Gd(e,n){return L(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function zy(e,n){return L(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Oy(e){return L(K("/workspaces",e))}function Fy(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),L(`/files?${i.toString()}`)}function Uy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function By(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Hy(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),L(`/files/search?${i.toString()}`)}function qy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Vy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Wy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Ky(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function lp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Gy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Jy(e,n,s){return L(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Yy(e,n,s,i){return L(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Qy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Xy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function cp(e,n,s){return L(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Zy(e,n,s){return L(K("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function ej(e,n,s){return L(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function tj(e,n,s){return L(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Mc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Mc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function nj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Mr(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 x=Number.parseInt(f,10);return Number.isFinite(x)?u!==null&&x<=u?!1:(u=x,!0):!0},h=()=>{if(o)return;const p=nj(e,u),f=new EventSource(ei(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))f.addEventListener(x,b=>{const y=b;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(),Mc.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Mc.add(g),g}function Jd(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 va(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 sj(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 ij(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>sj(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function aj(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 Yd(e){return Array.isArray(e)?e.map(Jd):(e.candidates??[]).map(Jd)}async function rj(e){try{const n=await L(K("/dev-server/candidates",e));return Yd(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(K("/dev-server/detect",e));return Yd(s)}throw n}}function nd(e){return L(K("/dev-server/status",e)).then(va)}async function QI(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await L(K(`/dev-server/logs/history${i}`,n));return ij(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await nd(n);return aj(o.logs,e)}throw r}}function oj(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return L(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(va)}function lj(e){return L(K("/dev-server/stop",e),{method:"POST"}).then(va)}function cj(e){return L(K("/dev-server/restart",e),{method:"POST"}).then(va)}async function dj(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await L(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return va(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return va(r)}throw i}}function XI(e){return rs(K("/dev-server/logs/stream",e))}async function ZI(e){try{return(await L(K("/devserver",e))).sessions??[]}catch{try{const n=await nd(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 e$(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await nd(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 t$(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await oj({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 n$(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await lj(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 s$(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await cj(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 i$(e,n,s){try{const i=await L(K(`/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 dj({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function a$(e){try{return(await L(K("/devserver/detect",e))).candidates??[]}catch{try{return(await rj(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function r$(e,n){return rs(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function _r(e,n,s=25e3){const i=setInterval(()=>{qk(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function uj(e,n){return rs(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function mj(e,n,s,i){const r=uj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Mr(r,{onOpen:()=>{c(),o=_r(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 hj(e){return L(Ar("/routines",e))}function pj(e,n){return L(Ar("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Qd(e,n,s){return L(Ar(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function fj(e,n){await L(Ar(`/routines/${e}`,n),{method:"DELETE"})}function gj(e,n){return L(Ar(`/routines/${e}/trigger`,n),{method:"POST"})}function Xd(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return L(`/activity${s}`)}function xj(e){const n=K("/activity",e);return L(n,{method:"DELETE"})}function Uo(e){return L(K("/workflow-steps",e))}function Zd(e,n){return L(K("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function bj(e,n,s){return L(K(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function vj(e,n){return L(K(`/workflow-steps/${e}`,n),{method:"DELETE"})}function eu(e,n){return L(K(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function yj(e,n){return L(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function jj(){return L("/workflow-step-templates")}function kj(e,n){return L(K(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function br(e){return L(K("/scripts",e))}function wj(e,n,s){return L(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Nj(e,n){return L(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function dp(e,n,s){return(await L(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Vr={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 up(e){if(!(e instanceof Error))return Vr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Vr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Vr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Vr.NETWORK}function Sj(e,n){return L(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function Cj(e,n,s){return L(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ej(e,n){return rs(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function Mj(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Mr(Ej(e,n),{onOpen:()=>{l(),r=_r(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 _j(e,n,s,i){return L(K("/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 mp(e,n,s){return L(K("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function K(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function Aj(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 Bo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=Aj(e,s,i);return L(o,r)}function _a(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/agents${i}`)}function hp(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n))}function Rj(e,n){return L(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Tj(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function o$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function l$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function c$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function d$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function u$(e,n,s){const i=`path=${encodeURIComponent(n)}`;return L(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function m$(e,n,s,i){return L(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Pj(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ij(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function h$(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/runs${r}`)}function p$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function f$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function g$(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function x$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function $j(e){return L(K("/agents/stats",e))}function b$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function v$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return L(`/agents/org-tree${i?`?${i}`:""}`)}function y$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function tu(e,n,s){return L(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function j$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function k$(){return L("/agents/companies")}function w$(e,n){return L(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function N$(e,n){return L(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function S$(e,n){return L(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function C$(e){return L(K("/backups",e))}function E$(e){return L(K("/backups",e),{method:"POST"})}function M$(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(i)}function _$(e,n,s){return L(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function nu(){return L("/projects/across-nodes")}function lr(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function yo(){return L("/nodes")}function Dj(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function Lj(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function zj(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Oj(e){const n=await L(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function A$(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=ba();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return L(u)}function Fj(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function pp(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function su(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function Uj(e){return L(K("/executor/stats",e))}function Bj(e){return L(K("/system-stats",e))}function Hj(e){return L(K("/kill-vitest",e),{method:"POST"})}function iu(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return L(`/activity-feed${s}`)}function qj(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Vj(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function R$(){return L("/global-concurrency")}function T$(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Wj(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function fp(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Kj(e){return L(K("/missions",e))}function Gj(e,n){return L(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function gp(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n))}function Jj(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yj(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qj(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return L(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Xj(e){return L(K("/missions/health",e))}function Zj(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function ek(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function tk(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function nk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function sk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ik(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ak(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function rk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function ok(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function lk(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ck(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function dk(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function uk(e,n,s,i){return L(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function mk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function dl(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function hk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function pk(e,n,s){return L(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function fk(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function gk(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function xk(e,n){return L(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function ul(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function au(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function bk(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function ru(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function vk(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return L(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function yk(e,n){return L(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function jk(e,n){return L(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function kk(e,n){return L(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function wk(e,n){return L(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Nk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Sk(e,n,s){return L(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function Ck(e,n,s,i){return L(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Ek(e,n,s){return L(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function xp(e,n,s){return L(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Mk(e,n,s){return L(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function _k(e,n,s,i){const r=rs(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Mr(r,{onOpen:()=>{c(),o=_r(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 K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Tr(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Ak(e,n){return L(Rr(e,"/start",n),{method:"POST"})}function Rk(e,n,s,i){return L(Rr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Tk(e,n,s,i){const r=rs(Rr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Mr(r,{onOpen:()=>{c(),o=_r(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 Pk(e,n,s){return L(Rr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Ik(e,n){return L(Rr(e,"/skip",n),{method:"POST"})}function $k(e,n){return L(Tr(e,"/start",n),{method:"POST"})}function Dk(e,n,s,i){return L(Tr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Lk(e,n,s,i){const r=rs(Tr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Mr(r,{onOpen:()=>{c(),o=_r(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 zk(e,n,s){return L(Tr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Ok(e,n){return L(Tr(e,"/skip",n),{method:"POST"})}async function Fk(e,n){try{return await L(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function P$(e){return L(K("/roadmaps",e))}function I$(e,n){return L(K("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function $$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n))}function D$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function L$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function z$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function O$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function F$(e,n){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function U$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function B$(e,n,s){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function H$(e,n){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function q$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function V$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function W$(e,n,s,i){return L(K(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function K$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function G$(e,n,s,i){return L(K(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function J$(e,n,s){return L(K(`/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 Y$(e){return L(K("/todos",e))}function Q$(e,n){const s={title:e};return L(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function X$(e,n,s){const i={title:n};return L(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function Z$(e,n){return L(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function eD(e,n,s){const i={text:n};return L(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function tD(e,n,s){const i=n;return L(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function nD(e,n){return L(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function sD(e,n,s){return L(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function ya(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function sd(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(rs(`/ai-sessions${n}`),{headers:hi()});return s.ok?(await s.json()).sessions??[]:[]}async function ui(e){const n=await fetch(rs(`/ai-sessions/${encodeURIComponent(e)}`),{headers:hi()});return n.ok?n.json():null}async function Uk(e,n){const s=await L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Bk(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Hk(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function bp(e){await fetch(rs(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:hi()})}function qk(e,n){return L(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Vk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/messages/inbox${i}`)}function Wk(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/messages/outbox${i}`)}function vp(e){return L(K("/messages/unread-count",e))}function Kk(e,n){return L(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Gk(e,n){return L(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Jk(e){return L(K("/messages/read-all",e),{method:"POST"})}function Yk(e,n){return L(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(K(i,s))}function Xk(e,n){return L(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function iD(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function aD(e,n){return L(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function rD(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/performance${r}`)}function oD(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function lD(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function cD(e,n){return L(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function dD(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function uD(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function mD(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function hD(e){return L(K("/plugins",e))}async function pD(e,n){return L(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function fD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function gD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function xD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function bD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function vD(e,n,s){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function yD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Zk(e){return L(K("/plugins/ui-slots",e))}async function jD(e){return L(K("/plugins/runtimes",e))}async function kD(e){return(await L(K("/skills/discovered",e))).skills}async function wD(e,n,s){return L(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function ND(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return L(K(`/skills/catalog${r}`,s))}async function SD(e,n){return(await L(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function CD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return L(`/chat/sessions${i?`?${i}`:""}`)}async function ew(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await L(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function tw(e,n){return L(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function ED(e,n,s){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function MD(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ou(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return L(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function nw(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function sw(e,n,s,i,r,o){const l=rs(K(`/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 N=new FormData;return N.append("content",n),i.forEach(k=>N.append("attachments",k)),N})():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 N=await g.text();let k=`Request failed: ${g.status}`;try{k=JSON.parse(N).error||k}catch{}s.onError?.(k);return}if(!g.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=g.body.getReader(),f=new TextDecoder;let x="",v="",b=[];const y=(N,k=!1)=>{x+=N;const R=x.split(`
613
- `);x=R.pop()||"",k&&x.length>0&&(R.push(x),x="");for(const w of R){const M=w.endsWith("\r")?w.slice(0,-1):w;if(M.startsWith("event:"))v=M.slice(6).trim();else if(M.startsWith("data:")){const S=M.slice(5);b.push(S.startsWith(" ")?S.slice(1):S)}else if(M===""){const S=b.join(`
614
- `);d(v,S),v="",b=[]}}if(k&&v&&b.length>0){const w=b.join(`
615
- `);d(v,w),v="",b=[]}};for(;;){const{done:N,value:k}=await p.read();if(N){y(f.decode(),!0);break}y(f.decode(k,{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 _D(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return L(K(`/insights${i}`,n))}function AD(e,n){return L(K(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function RD(e="manual",n,s){return L(K("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function TD(e){return L(K("/insights/runs",e))}function PD(e,n){return L(K(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function iw(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 aw({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}=iw(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 rw(e){return e.charAt(0).toUpperCase()+e.slice(1)}function qi({status:e,showLabel:n=!1,className:s,compact:i=!1}){const r=rw(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 lu=new Map,ow=6e4;function yp(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=lu.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 x=await Zk(e);if(h||u.current)return;lu.set(m,{slots:x,expiresAt:Date.now()+ow}),s(x),c.current=!0}catch(x){if(h||u.current)return;l(x instanceof Error?x.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 Ho({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=yp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Oo,{level:"page",children:t.jsx(t.Fragment,{children:o.map(l=>t.jsx("div",{"data-plugin-slot":!0,"data-slot-id":l.slot.slotId,"data-plugin-id":l.pluginId,"data-component-path":l.slot.componentPath,"aria-label":l.slot.label},`${l.pluginId}-${l.slot.slotId}`))})})}function lw(){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(lw);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 Aa(e){return e.replace(/\\/g,"/")}function id(e){return e.replace(/[\\/]+$/g,"")}function ad(e){const n=Aa(id(e));return n?n.split("/").filter(Boolean):[]}function rd(e){const n=Aa(id(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function jp(e,n){const s=ad(e);return s.length===0?Aa(e):s.slice(-2).join("/")}function cw(e){const n=Aa(id(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function dw(e,n){return!e||e==="."?n:[...ad(e),n].join("/")}function uw(e){const n=ad(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function ID(e){const n=Aa(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 kp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function mw({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(Qt,{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=kp[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:jp(u.path)})]}),d&&t.jsx(Ln,{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 cu({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 hw({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:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:N,globalPaused:k,enginePaused:R,onToggleGlobalPause:w,onToggleEnginePause:M,view:S="board",onChangeView:z,showSkillsTab:_,showAgentsTab:I,searchQuery:F="",onSearchChange:V,projects:D=[],currentProject:E,onSelectProject:$,onViewAllProjects:B,projectId:J,isElectron:ie=!1,mobileNavEnabled:C,availableNodes:P=[],currentNode:T,onSelectNode:j,isRemote:W=!1,experimentalFeatures:q}){const ge=Pr(),be=ge==="mobile",Se=be||ge==="tablet",O=be&&C,[le,ee]=a.useState(!1),[pe,ue]=a.useState(!1),[fe,se]=a.useState(!1),[Ce,De]=a.useState(!1),[qe,et]=a.useState(!1),[Qe,Xe]=a.useState(!1),[it,Ie]=a.useState(!1),[We,re]=a.useState(!1),[ve,te]=a.useState(!1),[Ae,Fe]=a.useState(!1),[he,Me]=a.useState(!1),[Oe,at]=a.useState({}),[ye,oe]=a.useState(!1),[Te,me]=a.useState(-1),[_e,Ke]=a.useState(null),[Re,ct]=a.useState({}),[Y,de]=a.useState(!1),we=a.useRef(null),tt=a.useRef(null),Z=a.useRef(null),Ge=a.useRef(null),dt=a.useRef(null),pt=a.useRef(null),jt=a.useRef(!1),yt=a.useRef(null),ft=a.useRef(null),St=a.useRef(null),Ot=a.useRef(null),Vt=a.useRef(null),Mt=a.useRef(null),It=a.useRef(null),qt=a.useRef(null),Ft=a.useRef(!1),Xt=a.useMemo(()=>P.filter(je=>je.type==="remote"),[P]),$t=Xt.length>0,_t=a.useMemo(()=>Object.entries(Oe).sort(([je],[ae])=>je.localeCompare(ae)),[Oe]),Ct=_t.length>0,Et=_t.length+(Ct?1:0),tn=a.useMemo(()=>Object.entries(Re).sort(([je],[ae])=>je.localeCompare(ae)),[Re]),At=a.useMemo(()=>!!(q?.todoView||q?.insights||q?.roadmap||_||q?.memoryView||q?.devServerView),[q,_]),H=a.useCallback(()=>{const je=window.visualViewport;return je&&je.width>0&&je.height>0?{width:je.width,height:je.height,offsetTop:je.offsetTop,offsetLeft:je.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),xe=a.useCallback(()=>{const je=It.current;if(!je)return;const ae=je.getBoundingClientRect(),Je=qt.current,{width:ut,height:Dt,offsetTop:Wt,offsetLeft:Mn}=H(),on=16,Ut=16,G=6,Pe=Je?.offsetWidth||Math.max(ae.width,260),Ye=Math.min(Pe,Math.max(ut-on*2,160)),nt=Je?.offsetHeight||280,mt=Math.min(nt,Math.max(Dt-Ut*2,160)),Nt=ae.top-Wt,Lt=ae.bottom-Wt,Cn=ae.right-Mn,rn=Dt-Lt,kt=Nt,os=rn<mt&&kt>rn,ks=Math.min(Math.max(Cn-Ye,on),ut-on-Ye)+Mn,Is=os?Math.max(Ut+Wt,Nt-mt-G+Wt):Math.min(Lt+G+Wt,Dt+Wt-Ut-mt);Ke({top:Is,left:ks,width:Ye})},[H]),Le=a.useCallback((je,ae)=>{v?.(je,ae),Me(!1),me(-1)},[v]),A=a.useCallback(()=>{x?.(),Me(!1),me(-1)},[x]),X=a.useCallback(je=>{switch(je.key){case"ArrowDown":je.preventDefault(),Et>0&&me(ae=>ae<Et-1?ae+1:0);break;case"ArrowUp":je.preventDefault(),Et>0&&me(ae=>ae>0?ae-1:Et-1);break;case"Enter":if(je.preventDefault(),Te>=0)if(Te<_t.length){const[ae,Je]=_t[Te];Le(ae,Je)}else Ct&&Te===_t.length&&A();break;case"Home":je.preventDefault(),Et>0&&me(0);break;case"End":je.preventDefault(),Et>0&&me(Et-1);break}},[A,Le,Te,_t,Ct,Et]);a.useEffect(()=>{jt.current=qe},[qe]),a.useEffect(()=>{Ft.current=he},[he]),a.useEffect(()=>{if(!qe||!Se)return;let je=!1;return de(!0),br(J).then(ae=>{je||ct(ae)}).catch(()=>{je||ct({})}).finally(()=>{je||de(!1)}),()=>{je=!0}},[qe,Se,J]),a.useEffect(()=>{if(!he||Se)return;let je=!1;return oe(!0),br(J).then(ae=>{je||at(ae)}).catch(()=>{je||at({})}).finally(()=>{je||oe(!1)}),()=>{je=!0}},[he,Se,J]),a.useEffect(()=>{if(!he)return;const je=ae=>{Mt.current&&!Mt.current.contains(ae.target)&&Me(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[he]),a.useEffect(()=>{if(!he)return;const je=ae=>{ae.key==="Escape"&&(Me(!1),It.current?.focus())};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[he]),a.useEffect(()=>{if(he){me(-1);const je=window.setTimeout(()=>qt.current?.focus(),0);return()=>window.clearTimeout(je)}Ke(null)},[he]),a.useEffect(()=>{if(!he)return;const je=requestAnimationFrame(()=>{xe()});return()=>cancelAnimationFrame(je)},[he,ye,_t.length,Ct,xe]),a.useEffect(()=>{if(!he)return;const je=()=>xe();window.addEventListener("resize",je),window.addEventListener("scroll",je,!0);const ae=window.visualViewport;return ae&&(ae.addEventListener("resize",je),ae.addEventListener("scroll",je)),()=>{window.removeEventListener("resize",je),window.removeEventListener("scroll",je,!0),ae&&(ae.removeEventListener("resize",je),ae.removeEventListener("scroll",je))}},[he,xe]),a.useEffect(()=>{Se&&(Me(!1),me(-1))},[Se]);const ze=le||F.length>0,ot=(pe||F.length>0)&&!fe,Rt=(S==="board"||S==="list")&&!be&&V&&!fe&&F.length===0,Tt=(S==="board"||S==="list")&&!be&&V;a.useEffect(()=>{F===""&&se(!1)},[F]),a.useEffect(()=>{if(!Ce)return;const je=ae=>{tt.current&&!tt.current.contains(ae.target)&&we.current&&!we.current.contains(ae.target)&&De(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[Ce]),a.useEffect(()=>{if(!ve)return;const je=ae=>{Ge.current&&!Ge.current.contains(ae.target)&&Z.current&&!Z.current.contains(ae.target)&&te(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[ve]),a.useEffect(()=>{if(!Qe)return;const je=ae=>{yt.current&&!yt.current.contains(ae.target)&&Xe(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[Qe]),a.useEffect(()=>{const je=ae=>{if(ae.key==="Escape"){if(re(!1),te(!1),jt.current){et(!1);return}if(Ft.current){Me(!1),It.current?.focus();return}De(!1),ee(!1),Xe(!1),Ie(!1)}};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[]),a.useEffect(()=>{if(!it)return;const je=ae=>{ft.current&&!ft.current.contains(ae.target)&&Ie(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[it]),a.useEffect(()=>{if(!Ae)return;const je=ae=>{Vt.current&&!Vt.current.contains(ae.target)&&Fe(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[Ae]),a.useEffect(()=>{if(!Ae)return;const je=ae=>{ae.key==="Escape"&&Fe(!1)};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[Ae]),a.useEffect(()=>{if(!We)return;const je=ae=>{St.current&&!St.current.contains(ae.target)&&Ot.current&&!Ot.current.contains(ae.target)&&re(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[We]);const Pt=a.useCallback(()=>{ee(je=>!je)},[]),ln=a.useCallback(()=>{ue(!0),se(!1)},[]),kn=a.useCallback(()=>{ue(!1),se(!0),V&&V("")},[V]),_n=a.useCallback(()=>{De(je=>!je)},[]),Yt=a.useCallback(je=>{je&&je(),De(!1),et(!1)},[]),An=a.useCallback(()=>{ee(!1),V&&V("")},[V]);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"})]}),be&&D.length>=1&&$&&t.jsxs("div",{className:"mobile-project-switch",ref:ft,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ie(je=>!je),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(Qt,{size:14,className:`mobile-project-switch-chevron${it?" mobile-project-switch-chevron--open":""}`})}),it&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:D.map(je=>{const ae=E?.id===je.id,Je=kp[je.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ae?" mobile-project-switch-item--current":""}`,onClick:()=>{$(je),Ie(!1)},role:"option","aria-selected":ae,"data-testid":`mobile-project-switch-item-${je.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Je||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:je.name}),t.jsx("span",{className:"mobile-project-switch-path",children:jp(je.path)})]}),ae&&t.jsx(Ln,{size:14,className:"mobile-project-switch-check"})]},je.id)})})]}),!Se&&D.length>=1&&B&&t.jsx(mw,{projects:D,currentProject:E??null,onViewAll:B,onSelectProject:$}),$t&&t.jsxs("div",{className:`header-node-selector${be?" header-node-selector--mobile":""}`,ref:be?void 0:yt,children:[t.jsx(aw,{node:T??null,showDetails:!be}),!be&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Qe?" node-selector-trigger--open":""}`,onClick:()=>Xe(je=>!je),title:"Switch node","aria-label":"Switch node","aria-expanded":Qe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(vn,{size:12,className:`node-selector-chevron${Qe?" node-selector-chevron--open":""}`})}),Qe&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${W?"":" node-selector-option--active"}`,onClick:()=>{j?.(null),Xe(!1)},role:"option","aria-selected":!W,"data-testid":"node-option-local",children:[t.jsx(qi,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Xt.map(je=>t.jsxs("button",{className:`node-selector-option${T?.id===je.id?" node-selector-option--active":""}`,onClick:()=>{j?.(je),Xe(!1)},role:"option","aria-selected":T?.id===je.id,"data-testid":`node-option-${je.id}`,children:[t.jsx(qi,{status:je.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:je.name}),t.jsx("span",{className:"node-selector-option-status",children:je.status})]},je.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[O&&z&&(S==="board"||S==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Hi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(jc,{size:16})})]}),V&&be&&(O||S==="board"||S==="list")&&!ze&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Pt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(ma,{size:16})}),Rt&&t.jsx("button",{className:"btn-icon",onClick:ln,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(ma,{size:16})}),be&&O&&o&&t.jsx("button",{className:"btn-icon",onClick:je=>o(je.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ts,{size:16})}),!O&&z&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:t.jsx(Hi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:t.jsx(jc,{size:16})}),I&&t.jsx("button",{className:`view-toggle-btn${S==="agents"?" active":""}`,onClick:()=>z("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":S==="agents",children:t.jsx(Nn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="missions"?" active":""}`,onClick:()=>z("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":S==="missions",children:t.jsx(us,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="chat"?" active":""}`,onClick:()=>z("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":S==="chat",children:t.jsx(ji,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="documents"?" active":""}`,onClick:()=>z("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":S==="documents",children:t.jsx(Ui,{size:16})}),t.jsx("button",{className:`view-toggle-btn${S==="mailbox"?" active":""}`,onClick:()=>z("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":S==="mailbox",children:t.jsx(xa,{size:16})}),At&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ot,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(S)||q?.todoView&&S==="todos"?" active":""}`,onClick:()=>re(je=>!je),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":We,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(Qt,{size:12})}),We&&t.jsxs("div",{ref:St,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[q?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="insights"?" active":""}`,onClick:()=>{z("insights"),re(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Zn,{size:14}),t.jsx("span",{children:"Insights"})]}),q?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="roadmaps"?" active":""}`,onClick:()=>{z("roadmaps"),re(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(kc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),_&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="skills"?" active":""}`,onClick:()=>{z("skills"),re(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Bn,{size:14}),t.jsx("span",{children:"Skills"})]}),q?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="memory"?" active":""}`,onClick:()=>{z("memory"),re(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(fo,{size:14}),t.jsx("span",{children:"Memory"})]}),q?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="dev-server"||S==="devserver"?" active":""}`,onClick:()=>{z("devserver"),re(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(hr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),q?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${S==="todos"?" active":""}`,onClick:()=>{z("todos"),re(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(tp,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!Se&&o&&t.jsx("button",{className:"btn-icon",onClick:je=>o(je.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ts,{size:16})}),!Se&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(hr,{size:16})}),!Se&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(mr,{size:16})}),!Se&&!ie&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(cu,{size:16})}),!Se&&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(Zs,{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})]}),!Se&&t.jsxs("div",{className:"terminal-split-btn",ref:Mt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(di,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:It,className:`btn-icon terminal-split-btn__chevron${he?" btn-icon--active":""}`,onClick:()=>Me(je=>!je),title:"Scripts","aria-haspopup":"listbox","aria-expanded":he,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(Qt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${he?" rotate":""}`})}),he&&t.jsx("div",{ref:qt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:X,"data-testid":"quick-scripts-dropdown",style:_e?{position:"fixed",top:`${_e.top}px`,left:`${_e.left}px`,width:`${_e.width}px`,right:"auto"}:void 0,children:ye?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..."})]}):_t.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:A,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:_t.map(([je,ae],Je)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Te===Je?"highlighted":""}`,onClick:()=>Le(je,ae),role:"option","aria-selected":Te===Je,"data-testid":`quick-script-item-${je}`,children:[t.jsx(Sn,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:je}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ae,children:ae.length>50?`${ae.slice(0,50)}...`:ae})]})]},je))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${Ct&&Te===_t.length?"highlighted":""}`,onClick:A,"data-testid":"quick-scripts-manage",children:[t.jsx(or,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Se&&y&&t.jsx("button",{className:`btn-icon${N?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Hn,{size:16})}),!Se&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Xs,{size:16})}),!Se&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Nc,{size:16})}),!Se&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Z,className:"btn-icon",onClick:()=>te(je=>!je),title:"More actions","aria-label":"More actions","aria-expanded":ve,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(bc,{size:16})}),ve&&t.jsxs("div",{ref:Ge,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),te(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(pr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Yt(m),te(!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:Vt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${k?" btn-icon--stopped":""}`,onClick:w,title:k?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:k?t.jsx(Sn,{size:16}):t.jsx(xs,{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(je=>!je),title:"Engine options","aria-haspopup":"menu","aria-expanded":Ae,"data-testid":"engine-control-chevron-btn",children:t.jsx(Qt,{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${R?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),Fe(!1)},role:"menuitem",title:R?"Resume scheduling":"Pause triage",disabled:!!k,"data-testid":"engine-control-pause-triage-btn",children:[R?t.jsx(Sn,{size:14}):t.jsx(Us,{size:14}),t.jsx("span",{children:R?"Resume scheduling":"Pause triage"})]})})]}),!Se&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(or,{size:16})}),t.jsx(Ho,{slotId:"header-action",projectId:J}),Se&&!O&&t.jsx("button",{ref:we,className:"btn-icon compact-overflow-trigger",onClick:_n,title:"More header actions","aria-label":"More header actions","aria-expanded":Ce,"aria-haspopup":"menu",children:t.jsx(bc,{size:16})}),Se&&!O&&Ce&&t.jsxs("div",{ref:tt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[D.length>=1&&B&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(B),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Yh,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Hn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Yt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Zs,{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:()=>Yt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Xs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(pr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!ie&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(n),role:"menuitem",children:[t.jsx(cu,{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:()=>Yt(b),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:()=>et(je=>!je),role:"menuitem","aria-expanded":qe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(vn,{size:14,className:`mobile-overflow-chevron${qe?" mobile-overflow-chevron--open":""}`})})]}),qe&&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…"})]}):tn.length>0?t.jsxs(t.Fragment,{children:[tn.map(([je,ae])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(je,ae),De(!1),et(!1)},role:"menuitem","data-testid":`overflow-script-item-${je}`,children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:je})]},je)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Yt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Fs,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Yt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Fs,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(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:()=>Yt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(mr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(xa,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:je=>Yt(()=>o(je.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ts,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Nc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Yt(e),role:"menuitem",children:[t.jsx(or,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Tt&&ot&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(ma,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:je=>V(je.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:kn,"aria-label":"Close search",children:t.jsx(Gt,{size:14})})]})}),V&&be&&ze&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:dt,className:"header-search mobile-search-expanded",children:[t.jsx(ma,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:pt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:je=>V(je.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:An,"aria-label":"Close search",children:t.jsx(Gt,{size:14})})]})})]})}const pw={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:[],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},fw={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,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,experimentalFeatures:{}},gw=Object.freeze(Object.keys(pw)),xw=Object.freeze(Object.keys(fw));function $D(e){return gw.includes(e)}function DD(e){return xw.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 bw(e){return!!(e?.provider&&e?.modelId)}function Ni(...e){for(const n of e)if(bw(n))return{provider:n.provider,modelId:n.modelId};return{}}function qo(e){return Ni({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function vw(e){return Ni({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},qo(e))}function yw(e){return Ni({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},qo(e))}function jw(e){return Ni({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},qo(e))}function LD(e){return Ni({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},qo(e))}function wp(e,n){return Ni({provider:e.modelProvider,modelId:e.modelId},vw(n))}function Np(e,n){return Ni({provider:e.validatorModelProvider,modelId:e.validatorModelId},jw(n))}function Sp(e,n){return Ni({provider:e.planningModelProvider,modelId:e.planningModelId},yw(n))}const zD=["off","minimal","low","medium","high"],Oi=["triage","todo","in-progress","in-review","done","archived"],od=["low","normal","high","urgent"],vs="normal",kw=["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"],$n={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},ww={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 Nw(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 Sw(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 Cw({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 Cp=a.createContext(null);function Ew({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 po.createElement(Cp.Provider,{value:u},e,po.createElement(Cw,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Hs(){const e=a.useContext(Cp);return e||{confirm:async n=>!1}}function Mw(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 Ep({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(bs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${Mw(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Io,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Wr(e,n){return`${e??"default"}:${n}`}class _w{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=Wr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Wr(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=Wr(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(ei(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=Wr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:du(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:du(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 Ii=new _w;let Aw=0;function du(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Mp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${Aw++}`);const s=a.useSyncExternalStore(o=>Ii.subscribe(o),()=>Ii.getSnapshot(),()=>Ii.getSnapshot()),i=a.useCallback(o=>{Ii.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Ii.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Ii.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Ii.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function jo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function Rw({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Mp(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=jo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=jo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(Ep,{prInfo:h,issueInfo:g})}const Tw=a.memo(Rw);Tw.displayName="TaskCardBadge";const Pw={sm:16,md:20,lg:24};function Iw({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 uu({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 Ws({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 $w({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 mu({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 Dw({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 ml({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 hu({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 pu({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 fu({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 Oa({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 gu({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 hl({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 xu({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 pl({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 Lw({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 zw({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 bu({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 fl({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 Ow({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 vu({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 gl({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 yu({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 xl({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 ju({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 Fw={anthropic:{component:Iw,color:"var(--provider-anthropic)"},"claude-cli":{component:ju,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:ju,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:uu,color:"var(--provider-openai)"},"openai-codex":{component:uu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Ws,color:"var(--provider-gemini)"},gemini:{component:Ws,color:"var(--provider-gemini)"},"google-antigravity":{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Ws,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Ws,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Ws,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Ws,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Ws,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Ws,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:$w,color:"var(--text)"},github:{component:vu,color:"var(--text)"},"github-copilot":{component:vu,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Ow,color:"var(--provider-openrouter)"},minimax:{component:mu,color:"var(--provider-minimax)"},"minimax-cn":{component:mu,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Dw,color:"var(--provider-zai)"},kimi:{component:ml,color:"var(--provider-kimi)"},moonshot:{component:ml,color:"var(--provider-kimi)"},"kimi-coding":{component:ml,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:hu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:hu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:pu,color:"var(--text)"},grok:{component:pu,color:"var(--text)",label:"xAI"},opencode:{component:fu,color:"var(--provider-opencode)"},"opencode-go":{component:fu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Oa,color:"var(--provider-qwen)"},"qwen-ai":{component:Oa,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Oa,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Oa,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Oa,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:gu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:gu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:hl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:hl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:hl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:xu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:xu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:pl,color:"var(--provider-azure)"},"azure-openai":{component:pl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:pl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:fl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:fl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:fl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Lw,color:"var(--provider-cerebras)"},groq:{component:zw,color:"var(--provider-groq)"},vercel:{component:bu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:bu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:gl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:gl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:gl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:yu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:yu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:xl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:xl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:xl,color:"var(--provider-paperclip)",label:"Paperclip"}};function zn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=Fw[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=Pw[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(ux,{size:c})})}const Ms={data:new Map,pendingPromise:null,lastFetchTime:null},Uw=5e3;function uo(e,n){return n?`${n}::${e}`:e}function Bw(e,n){const s=Ms.data.get(uo(e,n));if(!(!s||Date.now()-s.timestamp>Uw))return s}function Hw(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 jy(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=Ms.data.get(uo(g,e));return p&&p.timestamp>d})&&Ms.lastFetchTime&&Ms.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),Ms.pendingPromise){s(!0);try{await Ms.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Ms.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,x]of Object.entries(g))Ms.data.set(uo(f,e),{result:x,timestamp:p});Ms.lastFetchTime=p}catch{}finally{Ms.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>Ms.data.get(uo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Ms.lastFetchTime,getBatchData:l}}const Ac=new Map,qw=3e4;function _p(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Vw(e,n,s,i){const r=_p(e,n,s,i),o=Ac.get(r);return o?Date.now()>o.expiresAt?(Ac.delete(r),null):o.stats:null}function Ww(e,n,s,i,r){const o=_p(e,n,s,i);Ac.set(o,{stats:r,expiresAt:Date.now()+qw})}function Kw(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 x=f?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(k=!1){if(!k){const R=Vw(e,i,x,v);if(R){b||(m(R),g(!1));return}}g(!0);try{const R=await fp(e,x,i);b||(m(R.stats),Ww(e,i,x,v,R.stats))}catch{b||m(null)}finally{b||g(!1)}}y();let N;return u&&f&&(N=setInterval(()=>{y(!0)},u)),()=>{b=!0,N&&clearInterval(N)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Gw=new Set(["failed","stuck-killed"]);function ko(e,n,s){if(e.column!=="in-progress"||e.status&&Gw.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Jw(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Yw(e){return e==="done"||e==="skipped"}function Qw(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Ap(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:Qw(u,d,n),status:d?Jw(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Yw(u.status)).length;return{total:l,completed:c,items:o}}function Xw(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 Rp(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:Xw(n)}})}function Zw(e){if(!e||e.length===0)return null;let n=0,s=0;for(const i of Rp(e))typeof i.durationMs=="number"&&(n+=i.durationMs,s+=1);return s>0?n:null}const Rc=new Map;async function eN(e,n){const s=Rc.get(e);if(s)return s;try{const i=await gp(e,n);return Rc.set(e,i.title),i.title}catch{return e}}const ku=12;function tN(e){return e.length<=ku?e:e.slice(0,ku-3)+"..."}const Tc=new Map;async function nN(e,n){const s=Tc.get(e);if(s)return s;try{const i=await hp(e,n);return Tc.set(e,i.name),i.name}catch{return e}}function sN(e){return typeof e=="string"&&od.includes(e)?e:vs}function iN(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const aN=new Set(["triage","todo"]),wu=new Set(["planning","researching","executing","finalizing","merging"]),Nu=new Set(["merging","merging-pr"]),rN={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},oN=new Set(["in-progress","in-review","done"]),lN=3e4;function vr(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function cN(e){const n=vr(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function bl(e,n){const s=vr(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function dN(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=vr(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const u=vr(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 Kr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:Zw(e.log),i=dN(e,n);return s==null&&i==null?null:(s??0)+(i??0)}function Su(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 uN(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 Cu(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 mN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function hN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function pN(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function fN(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 gN(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 xN(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 bN(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 vN(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&&xN(s.attachments,i.attachments)&&bN(s.comments,i.comments)&&hN(s.dependencies,i.dependencies)&&mN(s.steps,i.steps)&&pN(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&gN(s.workflowStepResults,i.workflowStepResults)&&Cu(s.prInfo,i.prInfo)&&Cu(s.issueInfo,i.issueInfo)}function yN({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:x,workflowStepNameLookup:v}){const[b,y]=a.useState(!1),[N,k]=a.useState(!1),[R,w]=a.useState(!1),[M,S]=a.useState(e.description||""),[z,_]=a.useState(!1),[I,F]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(A=>A.status==="done"||A.status==="skipped")),[V,D]=a.useState(null),[E,$]=a.useState(null),[B,J]=a.useState(!1),[ie,C]=a.useState(!1),[P,T]=a.useState(()=>Date.now()),j=a.useRef(null),W=a.useRef(!1),q=a.useRef(null),ge=a.useRef(null),[be,ce]=a.useState(!1),{badgeUpdates:Se,subscribeToBadge:O,unsubscribeFromBadge:le}=Mp(n),{confirm:ee}=Hs(),pe=a.useRef(null),ue=a.useRef(!1),fe=a.useCallback(A=>A instanceof Element?!!A.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{S(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!B)return;const A=X=>{ge.current&&!ge.current.contains(X.target)&&J(!1)};return document.addEventListener("click",A),()=>document.removeEventListener("click",A)},[B]),a.useEffect(()=>{if(!e.missionId){D(null);return}const A=Rc.get(e.missionId);if(A){D(A);return}let X=!1;return eN(e.missionId,n).then(ze=>{X||D(ze)}),()=>{X=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){$(null);return}const A=Tc.get(e.assignedAgentId);if(A){$(A);return}$(null);let X=!1;return nN(e.assignedAgentId,n).then(ze=>{X||$(ze)}),()=>{X=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(R&&j.current){const A=j.current;A.focus(),A.style.height="auto",A.style.height=A.scrollHeight+"px"}},[R]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){ce(!0);return}const A=q.current;if(!A)return;const X=new IntersectionObserver(([ze])=>{ce(ze?.isIntersecting??!0)},{rootMargin:"200px"});return X.observe(A),()=>X.disconnect()},[R,e.id]);const se=a.useCallback(A=>{A.dataTransfer.setData("text/plain",e.id),A.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Ce=a.useCallback(()=>{y(!1)},[]),De=a.useCallback(A=>A.dataTransfer.types.includes("Files"),[]),qe=a.useCallback(A=>{De(A)&&(A.preventDefault(),A.stopPropagation(),A.dataTransfer.dropEffect="copy",k(!0))},[De]),et=a.useCallback(A=>{De(A)&&(A.preventDefault(),A.stopPropagation(),k(!1))},[De]),Qe=a.useCallback(async A=>{if(!De(A))return;A.preventDefault(),A.stopPropagation(),k(!1);const X=Array.from(A.dataTransfer.files);for(const ze of X)try{await gr(e.id,ze,n),r(`Attached ${ze.name} to ${e.id}`,"success")}catch(ot){r(`Failed to attach ${ze.name}: ${ke(ot)}`,"error")}},[e.id,De,r]),Xe=a.useCallback(()=>{R||i(e)},[e,i,R]),it=a.useCallback(A=>{if(W.current){W.current=!1;return}fe(A.target)||Xe()},[Xe,fe]),Ie=a.useCallback(A=>{const X=A.touches[0];X&&(pe.current={x:X.clientX,y:X.clientY,time:Date.now()},ue.current=!1)},[]),We=a.useCallback(A=>{if(!pe.current)return;const X=A.touches[0];if(!X)return;const ze=Math.abs(X.clientX-pe.current.x),ot=Math.abs(X.clientY-pe.current.y);(ze>Eu||ot>Eu)&&(ue.current=!0)},[]),re=a.useCallback(A=>{if(fe(A.target)||!pe.current)return;const ze=Date.now()-pe.current.time<jN,ot=!ue.current;ze&&ot&&(W.current=!0,Xe()),pe.current=null,ue.current=!1},[Xe,fe]),ve=a.useCallback(async(A,X)=>{A.stopPropagation();try{const ze=await fr(X,n);i(ze)}catch{r(`Failed to load dependency ${X}`,"error")}},[i,r]),te=e.status==="failed",Ae=e.paused===!0,Fe=sN(e.priority),he=Fe!==vs,Me=ko(e,g,x),Oe=e.column==="triage"&&e.status==="awaiting-approval",at=e.column==="archived",ye=!o&&!s&&!te&&!Ae&&!Me&&!Oe&&(e.column==="in-progress"||wu.has(e.status)),oe=!s&&!Ae&&!R&&!at,Te=aN.has(e.column)&&!ye&&!Ae&&!s&&l,me=!!(e.prInfo||e.issueInfo),_e=!!(e.assignedAgentId&&E===null),Ke=a.useMemo(()=>{const A=[];return e.modelProvider&&A.push(e.modelProvider),e.validatorModelProvider&&!A.includes(e.validatorModelProvider)&&A.push(e.validatorModelProvider),e.planningModelProvider&&!A.includes(e.planningModelProvider)&&A.push(e.planningModelProvider),A},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Re=a.useMemo(()=>Ap(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ct=Re.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const A=e.status!=null&&Nu.has(e.status);if(!A&&e.column==="in-progress"){const ze=bl(e,Date.now()),ot=Kr(e,Date.now());if(ze==null&&ot==null)return}if(!A&&e.column==="in-review"&&Kr(e,Date.now())==null)return;T(Date.now());const X=window.setInterval(()=>{T(Date.now())},lN);return()=>window.clearInterval(X)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs]);const Y=a.useMemo(()=>{if(!oN.has(e.column))return null;if(e.status!=null&&Nu.has(e.status)){const Rt=vr(e.updatedAt);if(Rt!=null){const Tt=Math.max(0,P-Rt),Pt=Su(Tt);if(Pt)return{label:Pt,title:`Merging ${Pt}`,ariaLabel:`Merging ${Pt}`}}}if(e.column==="in-progress"){const Rt=bl(e,P)??Kr(e,P);if(Rt==null)return null;const Tt=Su(Rt);if(!Tt)return null;const Pt=bl(e,P)!=null;return{label:Tt,title:Pt?`In progress ${Tt}`:`Execution time ${Tt}`,ariaLabel:Pt?`In progress ${Tt}`:`Execution time ${Tt}`}}const A=Kr(e,P);if(A==null)return null;const X=uN(A);if(!X)return null;const ze=cN(e);if(ze==null)return{label:X,title:`Execution time ${X}`,ariaLabel:`Execution time ${X}`};const ot=new Date(ze).toLocaleString();return{label:X,title:`Execution time ${X}. Completed ${ot}`,ariaLabel:`Execution time ${X}. Completed ${ot}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,P]);a.useEffect(()=>{if(!me||!be){le(e.id);return}return O(e.id),()=>{le(e.id)}},[me,be,O,e.id,le]);const de=Se.get(`${n??"default"}:${e.id}`),we=e.column==="in-progress"||e.column==="in-review",tt=a.useMemo(()=>e.steps.map(A=>`${A.name}:${A.status}`).join("|"),[e.steps]),{stats:Z}=Kw(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:be,worktree:e.worktree,stepVersion:we?tt:void 0,pollIntervalMs:we?3e4:void 0}),Ge=a.useMemo(()=>Bw(e.id,n),[e.id,n]),dt=a.useMemo(()=>{const A=de?.prInfo,X=de?.timestamp,ze=Ge?.result?.prInfo,ot=Ge?.timestamp?new Date(Ge.timestamp).toISOString():void 0,Rt=e.prInfo,Tt=e.prInfo?.lastCheckedAt??e.updatedAt;let Pt=jo(A,X,Rt,Tt);const ln=X&&X>=Tt?X:Tt;return ze&&ot&&(!ln||ot>ln)&&(Pt=ze),Pt},[de,Ge,e.prInfo,e.updatedAt]),pt=a.useMemo(()=>{const A=de?.issueInfo,X=de?.timestamp,ze=Ge?.result?.issueInfo,ot=Ge?.timestamp?new Date(Ge.timestamp).toISOString():void 0,Rt=e.issueInfo,Tt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Pt=jo(A,X,Rt,Tt);const ln=X&&X>=Tt?X:Tt;return ze&&ot&&(!ln||ot>ln)&&(Pt=ze),Pt},[de,Ge,e.issueInfo,e.updatedAt]),jt=a.useCallback(A=>{A?.stopPropagation(),!(!Te||z)&&(w(!0),S(e.description||""))},[Te,z,e.description]),yt=a.useCallback(()=>{w(!1),S(e.description||"")},[e.description]),ft=a.useCallback(()=>M!==(e.description||""),[M,e.description]),St=a.useCallback(async()=>{if(!(!l||z)){if(!ft()){yt();return}_(!0);try{await l(e.id,{description:M.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(A){r(`Failed to update ${e.id}: ${ke(A)}`,"error")}finally{_(!1)}}},[l,e.id,M,z,ft,yt,r]),Ot=a.useCallback(A=>{A.key==="Enter"&&!A.shiftKey?(A.preventDefault(),St()):A.key==="Escape"&&(A.preventDefault(),yt())},[St,yt]),Vt=a.useCallback(()=>{setTimeout(()=>{const A=document.activeElement;A===j.current||A?.closest(".card-editing-content")||(ft()?St():yt())},0)},[ft,St,yt]),Mt=a.useCallback(A=>{Te&&(A.stopPropagation(),jt(A))},[Te,jt]),It=a.useCallback(A=>{A.stopPropagation(),jt(A)},[jt]),qt=a.useCallback(A=>{S(A.target.value);const X=A.target;X.style.height="auto",X.style.height=X.scrollHeight+"px"},[]),Ft=a.useCallback(A=>{A.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(X=>{r(`Failed to archive ${e.id}: ${ke(X)}`,"error")})},[r,c,e.id]),Xt=a.useCallback(A=>{A.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(X=>{r(`Failed to unarchive ${e.id}: ${ke(X)}`,"error")})},[r,u,e.id]),$t=a.useCallback(async A=>{if(A.stopPropagation(),!(!d||!await ee({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await d(e.id),r(`Deleted ${e.id}`,"success")}catch(ze){const ot=fN(ze);if(!ot||ot.dependentIds.length===0){r(`Failed to delete ${e.id}: ${ke(ze)}`,"error");return}const Rt=ot.dependentIds.join(", ");if(!await ee({title:"Force Delete Task",message:`${e.id} is a dependency of ${Rt}.
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(Pt){r(`Failed to delete ${e.id}: ${ke(Pt)}`,"error")}}},[r,ee,d,e.id]),_t=a.useCallback(A=>{A.stopPropagation(),h?.(e,"changes")},[e,h]),Ct=a.useCallback(A=>{A.stopPropagation(),F(X=>!X)},[]),Et=a.useCallback(A=>{A.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),tn=a.useCallback(A=>{A.stopPropagation(),J(X=>!X)},[]),At=a.useCallback((A,X)=>{A.stopPropagation(),J(!1),f&&f(e.id,X).then(()=>{r(`Moved ${e.id} to ${$n[X]}`,"success")}).catch(ze=>{r(`Failed to move ${e.id}: ${ke(ze)}`,"error")})},[r,f,e.id]),H=a.useCallback(async A=>{if(A.stopPropagation(),!(!m||ie)){C(!0);try{await m(e.id)}catch(X){r(`Failed to retry ${e.id}: ${ke(X)}`,"error")}finally{C(!1)}}},[r,ie,m,e.id]),xe=`card${b?" dragging":""}${s?" queued":""}${ye?" agent-active":""}${te?" failed":""}${Ae?" paused":""}${Me?" stuck":""}${Oe?" awaiting-approval":""}${N?" file-drop-target":""}${R?" card-editing":""}${z?" card-saving":""}`,Le=(()=>{if(e.column==="in-progress"){const A=Z?.filesChanged,X=A==null||A===0?e.modifiedFiles?.length:void 0,ze=A!=null&&A>0?A:X;return ze==null||ze===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!h,children:[t.jsx(Hn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const A=Z?.filesChanged,X=A==null||A===0?e.modifiedFiles?.length:void 0,ze=A!=null&&A>0?A:X;return ze==null||ze===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!h,children:[t.jsx(Hn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]})}if(e.column==="done"){const A=Z?.filesChanged,X=e.mergeDetails?.filesChanged,ze=A??X;if(ze!=null&&ze>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!h,children:[t.jsx(Hn,{size:12}),t.jsxs("span",{children:[ze," ",ze===1?"file":"files"," changed"]})]});const ot=e.modifiedFiles?.length;if(ot!=null&&ot>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:_t,disabled:!h,children:[t.jsx(Hn,{size:12}),t.jsxs("span",{children:[ot," ",ot===1?"file":"files"," changed"]})]})}return null})();return R?t.jsx("div",{ref:q,className:xe,"data-id":e.id,onDoubleClick:Mt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:j,className:"card-edit-desc-textarea",placeholder:"Task description",value:M,onChange:qt,onKeyDown:Ot,onBlur:Vt,disabled:z,rows:4}),z&&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:q,className:xe,"data-id":e.id,draggable:oe,onDragStart:oe?se:void 0,onDragEnd:oe?Ce:void 0,onDragOver:qe,onDragLeave:et,onDrop:Qe,onClick:it,onTouchStart:Ie,onTouchMove:We,onTouchEnd:re,onDoubleClick:Mt,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}${Oe?" awaiting-approval":""}${wu.has(e.status)?" pulsing":""}${te?" failed":""}${Me?" stuck":""}`,children:Me?"Stuck":Oe?"Awaiting Approval":e.status}),Me&&(Ae||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),me&&t.jsx(Ep,{prInfo:dt,issueInfo:pt}),he&&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:Et,title:`Mission: ${V??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(us,{size:11}),tN(V??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Te&&t.jsx("button",{className:"card-edit-btn",onClick:It,title:"Edit task","aria-label":"Edit task",children:t.jsx(ss,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:$t,title:"Delete task","aria-label":"Delete task",children:t.jsx(sn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Ft,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Xt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&f&&t.jsxs("div",{className:"card-send-back",ref:ge,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:tn,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":B,children:["Send back",t.jsx(Qt,{size:10})]}),B&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:_c["in-progress"].filter(A=>A!=="in-review").map(A=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:X=>At(X,A),children:$n[A]},A))})]}),e.column==="in-review"&&f&&t.jsxs("div",{className:"card-send-back",ref:ge,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:tn,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":B,children:["Move",t.jsx(Qt,{size:10})]}),B&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:_c["in-review"].map(A=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:X=>At(X,A),children:A==="done"?"Done (no merge)":$n[A]},A))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),te&&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:H,disabled:ie,children:[t.jsx(Ib,{size:12}),ie?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:_u(e.title,Mu)||_u(e.description,Mu)||e.id}),ct&&(()=>{const A=Re.completed/Re.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:`${A}%`,backgroundColor:rN[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Re.completed,"/",Re.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Ct,"aria-expanded":I,"aria-label":I?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Re.total," step",Re.total===1?"":"s"]}),t.jsx(Qt,{size:14,className:`card-steps-toggle-icon${I?" expanded":""}`})]}),I&&t.jsx("div",{className:"card-steps-list",children:Re.items.map(X=>{const ze=X.source==="workflow"&&X.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${X.status}${ze?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${X.status==="done"?" completed":""}`,children:X.name}),X.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${X.phase}`,title:"Workflow check",children:"workflow"})]},X.id)})})]})})(),(Le||Y)&&t.jsxs("div",{className:"card-footer-row",children:[Le,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(A=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:X=>void ve(X,A),title:`Click to view ${A}`,children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}})," ",A]},A))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Bi,{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||Ke.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Ke.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Ke.map(A=>t.jsx(zn,{provider:A,size:"sm"},A))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${_e?" card-agent-badge--loading":""}`,title:`Assigned to ${E??e.assignedAgentId}`,children:[t.jsx(Nn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:iN(E??e.assignedAgentId,15)})]})]}),t.jsx(Ho,{slotId:"task-card-badge",projectId:n})]})}const Eu=10,jN=300,Mu=140;function _u(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const wo=a.memo(yN,vN);wo.displayName="TaskCard";function kN({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(ix,{size:14}):t.jsx(Xs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(f=>t.jsx(wo,{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(wo,{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 Tp=a.memo(kN);Tp.displayName="WorktreeGroup";function Au(e){return e.toLowerCase().replace(/[-_./]/g,"")}function wN(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 NN(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 SN(e,n){const s=Au(e),i=Au(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&&wN(s,o)||s.length>=4&&NN(s,o,1))return!0;return!1}function CN(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=>SN(o,r))})}function qn({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),[x,v]=a.useState(""),[b,y]=a.useState(0),[N,k]=a.useState(null),[R,w]=a.useState(null),M=a.useRef(null),S=a.useRef(null),z=a.useRef(null),_=a.useRef(null),I=a.useRef(null),F=a.useMemo(()=>CN(e,x),[e,x]),V=a.useMemo(()=>F.reduce((ee,pe)=>((ee[pe.provider]??=[]).push(pe),ee),{}),[F]),D=a.useMemo(()=>{const ee=[];for(const pe of d){const ue=pe.indexOf("/");if(ue===-1)continue;const fe=pe.slice(0,ue),se=pe.slice(ue+1),Ce=F.find(De=>De.provider===fe&&De.id===se);Ce&&ee.push({model:Ce,fullId:pe})}return ee},[d,F]),E=a.useMemo(()=>{const ee=Object.entries(V),pe=new Set(c);return ee.sort(([ue],[fe])=>{const se=pe.has(ue),Ce=pe.has(fe);if(se&&!Ce)return-1;if(!se&&Ce)return 1;if(se&&Ce){const De=c.indexOf(ue),qe=c.indexOf(fe);if(De!==qe)return De-qe}return ue.localeCompare(fe)})},[V,c]),$=typeof h=="string"&&h.length>0,B=a.useMemo(()=>{if(!n||$&&n===h)return null;const ee=n.indexOf("/");return ee===-1?null:n.slice(0,ee)},[$,h,n]),J=a.useMemo(()=>{const ee=[];return $&&ee.push({type:"no-change",value:h,label:g}),ee.push({type:"default",value:"",label:"Use default"}),ee},[$,g,h]),ie=a.useMemo(()=>{const ee=[...J];for(const{model:pe,fullId:ue}of D)ee.push({type:"favorite",value:ue,label:pe.name,provider:pe.provider});return E.forEach(([pe,ue])=>{ee.push({type:"provider",value:`__group_${pe}`,label:pe,provider:pe}),ue.forEach(fe=>{ee.push({type:"model",value:`${fe.provider}/${fe.id}`,label:fe.name,provider:fe.provider})})}),ee},[D,E,J]),C=a.useMemo(()=>{if($&&n===h)return g;if(!n)return"Use default";const ee=n.indexOf("/");if(ee===-1)return n;const pe=n.slice(0,ee),ue=n.slice(ee+1);return e.find(se=>se.provider===pe&&se.id===ue)?.name||n},[$,g,h,n,e]),P=a.useMemo(()=>ie.findIndex(ee=>ee.value===n),[ie,n]),T=a.useCallback(()=>{const ee=window.visualViewport;return ee&&ee.height>0&&ee.width>0?{width:ee.width,height:ee.height,offsetTop:ee.offsetTop,offsetLeft:ee.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),j=a.useCallback(()=>{const{height:ee}=T(),pe=typeof window.matchMedia=="function",ue=pe?window.matchMedia("(max-width: 640px)").matches:!1,fe=pe?window.matchMedia("(max-width: 768px)").matches:!1;return ee<=0?320:ue?Math.min(ee*.6,360):fe?Math.min(ee*.7,420):320},[T]),W=a.useCallback(()=>{const ee=S.current;if(!ee)return;const pe=ee.getBoundingClientRect(),{width:ue,height:fe,offsetTop:se,offsetLeft:Ce}=T(),De=16,qe=16,et=4,Qe=j(),Xe=pe.bottom-se,it=pe.top-se,Ie=pe.left-Ce,We=fe-Xe,re=it,ve=Math.max(We-qe-et,160),te=Math.max(re-qe-et,160),Ae=We<Qe&&re>We,Fe=Math.max(Math.min(Ae?te:ve,Qe),160),he=Math.min(pe.width,ue-De*2),Me=Math.min(Math.max(Ie,De),ue-De-he)+Ce,Oe=Ae?Math.max(qe+se,it-Fe-et+se):Math.min(Xe+et+se,fe+se-qe-Fe);k({top:Oe,left:Me,width:he,maxHeight:Fe})},[T,j]);a.useEffect(()=>{w(document.body)},[]);const q=a.useRef(!1);a.useEffect(()=>{if(!p){q.current=!1;return}if(q.current||ie.length===0)return;const ee=ie.findIndex((pe,ue)=>ue>=(P>=0?P:0)&&pe.type!=="provider");y(ee>=0?ee:0),q.current=!0},[p,ie,P]),a.useEffect(()=>{p&&q.current&&(y(0),I.current&&(I.current.scrollTop=0))},[x,p]),a.useEffect(()=>{if(!p)return;W();const ee=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(ee)},[p,W]),a.useEffect(()=>{if(!p)return;const ee=()=>W();window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0);const pe=window.visualViewport;return pe&&(pe.addEventListener("resize",ee),pe.addEventListener("scroll",ee)),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0),pe&&(pe.removeEventListener("resize",ee),pe.removeEventListener("scroll",ee))}},[p,W]),a.useEffect(()=>{if(!p)return;const ee=pe=>{const ue=pe.target,fe=M.current?.contains(ue),se=z.current?.contains(ue);!fe&&!se&&(f(!1),v(""))};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[p]);const ge=a.useCallback(ee=>{switch(ee.key){case"ArrowDown":if(ee.preventDefault(),!p)f(!0);else{let pe=b;for(let ue=1;ue<=ie.length;ue++){const fe=(b+ue)%ie.length;if(ie[fe]?.type!=="provider"){pe=fe;break}}y(pe)}break;case"ArrowUp":if(ee.preventDefault(),p){let pe=b;for(let ue=1;ue<=ie.length;ue++){const fe=(b-ue+ie.length)%ie.length;if(ie[fe]?.type!=="provider"){pe=fe;break}}y(pe)}break;case"Enter":if(ee.preventDefault(),p){const pe=ie[b];pe&&pe.type!=="provider"&&pe.type!=="favorite"&&(s(pe.value),f(!1),v(""))}else f(!0);break;case"Escape":ee.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,b,ie,s]),be=a.useCallback(ee=>{s(ee),f(!1),v("")},[s]),ce=a.useCallback(()=>{v(""),_.current?.focus()},[]),Se=a.useCallback(()=>{r||f(ee=>!ee)},[r]);a.useEffect(()=>{if(p&&I.current){const ee=I.current.querySelector(`[data-index="${b}"]`);ee&&typeof ee.scrollIntoView=="function"&&ee.scrollIntoView({block:"nearest"})}},[b,p]);const O=x.length>0,le=p&&N?t.jsxs("div",{ref:z,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:ge,style:{top:`${N.top}px`,left:`${N.left}px`,width:`${N.width}px`,maxHeight:`${N.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:ee=>v(ee.target.value),onClick:ee=>ee.stopPropagation()}),O&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ce,"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:I,className:"model-combobox-list",children:[J.map((ee,pe)=>t.jsx("div",{"data-index":pe,className:`model-combobox-option ${b===pe?"model-combobox-option--highlighted":""} ${n===ee.value?"model-combobox-option--selected":""}`,onClick:()=>be(ee.value),onMouseEnter:()=>y(pe),role:"option","aria-selected":n===ee.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ee.label})},`${ee.type}-${ee.value}`)),D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),D.map(({model:ee,fullId:pe},ue)=>{const fe=ue+J.length,se=b===fe,Ce=n===pe;return t.jsxs("div",{"data-index":fe,className:`model-combobox-option model-combobox-option--favorite ${se?"model-combobox-option--highlighted":""} ${Ce?"model-combobox-option--selected":""}`,onClick:()=>be(pe),onMouseEnter:()=>y(fe),role:"option","aria-selected":Ce,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(zn,{provider:ee.provider,size:"sm"})}),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 model-combobox-option-favorite--active",onClick:De=>{De.stopPropagation(),m(pe)},title:"Remove from favorites","aria-label":`Remove ${ee.name} from favorites`,children:"★"})]},pe)}),t.jsx("div",{className:"model-combobox-divider"})]}),E.map(([ee,pe])=>{const ue=ie.findIndex(Ce=>Ce.value===`__group_${ee}`),fe=c.includes(ee),se=pe.filter(Ce=>{const De=`${Ce.provider}/${Ce.id}`;return!d.includes(De)});return se.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":ue,children:[t.jsx(zn,{provider:ee,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ee}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${fe?"model-combobox-optgroup-favorite--active":""}`,onClick:Ce=>{Ce.stopPropagation(),u(ee)},title:fe?"Remove from favorites":"Add to favorites","aria-label":fe?`Remove ${ee} from favorites`:`Add ${ee} to favorites`,children:"★"})]}),se.map(Ce=>{const De=`${Ce.provider}/${Ce.id}`,qe=ie.findIndex(it=>it.value===De),et=b===qe,Qe=n===De,Xe=d.includes(De);return t.jsxs("div",{"data-index":qe,className:`model-combobox-option ${et?"model-combobox-option--highlighted":""} ${Qe?"model-combobox-option--selected":""}`,onClick:()=>be(De),onMouseEnter:()=>y(qe),role:"option","aria-selected":Qe,children:[t.jsx("span",{className:"model-combobox-option-text",children:Ce.name}),t.jsx("span",{className:"model-combobox-option-id",children:Ce.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Xe?"model-combobox-option-favorite--active":""}`,onClick:it=>{it.stopPropagation(),m(De)},title:Xe?"Remove from favorites":"Add to favorites","aria-label":Xe?`Remove ${Ce.name} from favorites`:`Add ${Ce.name} to favorites`,children:Xe?"★":"☆"})]},De)})]},ee)}),F.length===0&&O&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:M,className:"model-combobox",onKeyDown:ge,children:t.jsxs("button",{ref:S,type:"button",id:o,className:"model-combobox-trigger",onClick:Se,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[B&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(zn,{provider:B,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:C||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),R&&le?da.createPortal(le,R):null]})}function ld(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Vn(e,n){return typeof window>"u"?null:window.localStorage.getItem(ld(e,n))}function ds(e,n,s){typeof window>"u"||window.localStorage.setItem(ld(e,s),n)}function yr(e,n){typeof window>"u"||window.localStorage.removeItem(ld(e,n))}const EN=1e4,MN=1e3;function Vo(){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 yo();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 yo();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const x=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<MN||(c.current=v,u())};return document.addEventListener("visibilitychange",x),()=>{p=!0,document.removeEventListener("visibilitychange",x)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},EN),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await Dj(p);return n(x=>[...x,f]),f},[]),m=a.useCallback(async(p,f)=>{const x=await Lj(p,f);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=a.useCallback(async p=>{await zj(p),n(f=>f.filter(x=>x.id!==p))},[]),g=a.useCallback(async p=>{const f=await Oj(p);n(x=>x.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 Fa="kb-quick-entry-text",_N=["image/png","image/jpeg","image/gif","image/webp"];function AN(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function vl(e,n){return e&&n?`${e}/${n}`:""}function yl(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 Pp({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"&&Vn(Fa,l)||""),[f,x]=a.useState(!1),[v,b]=a.useState(!1),[y,N]=a.useState(!1),k=a.useRef(null),R=a.useRef(null),w=a.useRef(!1),M=a.useRef(l),[S,z]=a.useState([]),_=a.useRef([]),[I,F]=a.useState([]),[V,D]=a.useState(!1),[E,$]=a.useState(""),[B,J]=a.useState(null),[ie,C]=a.useState([]),[P,T]=a.useState(void 0),[j,W]=a.useState(!1),[q,ge]=a.useState(!1),[be,ce]=a.useState(!1),[Se,O]=a.useState(!1),[le,ee]=a.useState(null),[pe,ue]=a.useState(void 0),[fe,se]=a.useState(void 0),[Ce,De]=a.useState(void 0),[qe,et]=a.useState(void 0),[Qe,Xe]=a.useState(void 0),[it,Ie]=a.useState(void 0),We=a.useRef(null),re=a.useRef(null),ve=a.useRef(null),te=a.useRef(null),Ae=a.useRef(null),Fe=a.useRef(null),[he,Me]=a.useState(null),[Oe,at]=a.useState(null),[ye,oe]=a.useState(null),Te=a.useRef(null),me=a.useRef(null),[_e,Ke]=a.useState(null),[Re]=a.useState(()=>typeof document<"u"?document.body:null),[ct,Y]=a.useState(!1),[de,we]=a.useState(null),[tt,Z]=a.useState(i??[]),[Ge,dt]=a.useState([]),[pt,jt]=a.useState([]),[yt,ft]=a.useState(null),[St,Ot]=a.useState(void 0),[Vt,Mt]=a.useState(!1),[It,qt]=a.useState(void 0),{nodes:Ft}=Vo(),[Xt,$t]=a.useState(!1),[_t,Ct]=a.useState(!1),Et=a.useRef(null),tn=a.useRef(null),[At,H]=a.useState(null),xe=u??Ge,Le=d??pt,A=!e;a.useEffect(()=>{if(i)Z(i),Y(!1),we(null);else{let ne=!1;return Y(!0),we(null),ms().then(Ee=>{ne||(Z(Ee.models),u||dt(Ee.favoriteProviders),d||jt(Ee.favoriteModels))}).catch(Ee=>{ne||we(ke(Ee)||"Failed to load models")}).finally(()=>{ne||Y(!1)}),Fo(l).then(Ee=>{ne||ft(Ee)}).catch(()=>{}),()=>{ne=!0}}},[i,u,d,l]);const X=vl(pe,fe),ze=vl(Ce,qe),ot=vl(Qe,it),Rt=!!(pe&&fe),Tt=!!(Ce&&qe),Pt=!!(Qe&&it),ln=Number(Rt)+Number(Tt)+Number(Pt),kn=St?yt?.modelPresets?.find(ne=>ne.id===St)?.name??"Models":ln>0?`${ln} model${ln===1?"":"s"}`:"Models",_n=a.useCallback((ne,Ee)=>{if(!ne||!Ee)return"Using default";const Ze=tt.find(vt=>vt.provider===ne&&vt.id===Ee);return Ze?`${Ze.provider}/${Ze.id}`:`${ne}/${Ee}`},[tt]);a.useEffect(()=>{p(Vn(Fa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ds(Fa,g,l)},[g,l]),a.useEffect(()=>{M.current!==l&&(M.current=l,C([]),T(void 0),J(null),W(!1),Me(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{_.current=S},[S]),a.useEffect(()=>()=>{_.current.forEach(ne=>URL.revokeObjectURL(ne.previewUrl))},[]);const Yt=a.useCallback(()=>{const ne=k.current;if(!ne)return;ne.style.height="auto";const Ee=Math.min(ne.scrollHeight,200);ne.style.height=`${Ee}px`},[]);a.useEffect(()=>{v&&Yt()},[g,v,Yt]),a.useEffect(()=>{if(!f&&g===""&&k.current){const ne=setTimeout(()=>{k.current?.focus()},0);return()=>clearTimeout(ne)}},[f,g]),a.useEffect(()=>{V||$("")},[V]),a.useEffect(()=>{if(!Xt)return;const ne=Ee=>{const Ze=Ee.target,vt=Et.current?.contains(Ze),xt=tn.current?.contains(Ze);!vt&&!xt&&$t(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[Xt]),a.useEffect(()=>{if(!Se)return;const ne=Ee=>{const Ze=Ee.target,vt=We.current?.contains(Ze),xt=re.current?.contains(Ze),jn=Ze instanceof Element&&Ze.closest?.(".model-combobox-dropdown--portal")!=null;!vt&&!xt&&!jn&&(O(!1),ee(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[Se]),a.useEffect(()=>{if(!q)return;const ne=Ee=>{const Ze=Ee.target;Ae.current?.contains(Ze)||Fe.current?.contains(Ze)||(ge(!1),at(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[q]),a.useEffect(()=>{if(!j)return;const ne=Ee=>{const Ze=Ee.target;ve.current?.contains(Ze)||te.current?.contains(Ze)||(W(!1),Me(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[j]);const An=a.useCallback(()=>{S.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),z([]),R.current&&(R.current.value=""),p(""),F([]),J(null),W(!1),Me(null),ge(!1),at(null),ue(void 0),se(void 0),De(void 0),et(void 0),Xe(void 0),Ie(void 0),Ot(void 0),Mt(!1),qt(void 0),D(!1),O(!1),oe(null),ee(null),$t(!1),Ct(!1),b(!1),N(!1),w.current=!0,k.current&&(k.current.style.height="auto"),typeof window<"u"&&yr(Fa,l)},[S,l]),je=a.useCallback(ne=>{if(!ne||ne.length===0)return;const Ee=[];for(let Ze=0;Ze<ne.length;Ze++){const vt=ne[Ze];_N.includes(vt.type)&&Ee.push({file:vt,previewUrl:URL.createObjectURL(vt)})}Ee.length>0&&z(Ze=>[...Ze,...Ee])},[]),ae=a.useCallback(ne=>{f||je(ne.clipboardData?.files)},[je,f]),Je=a.useCallback(ne=>{z(Ee=>{const Ze=Ee[ne];return Ze&&URL.revokeObjectURL(Ze.previewUrl),Ee.filter((vt,xt)=>xt!==ne)})},[]),ut=a.useCallback(async()=>{const ne=g.trim();if(!ne||f||!e)return;const Ee=g;x(!0),p("");try{const Ze=await e({description:ne,column:"triage",dependencies:I.length?I:void 0,...B?{assignedAgentId:B}:{},modelPresetId:St,modelProvider:Rt?pe:void 0,modelId:Rt?fe:void 0,validatorModelProvider:Tt?Ce:void 0,validatorModelId:Tt?qe:void 0,planningModelProvider:Pt?Qe:void 0,planningModelId:Pt?it:void 0,...Vt?{executionMode:"fast"}:{},nodeId:It});if(Ze&&S.length>0){const vt=[];for(const xt of S)try{await gr(Ze.id,xt.file,l)}catch{vt.push(xt.file.name)}vt.length>0&&n(`Failed to upload: ${vt.join(", ")}`,"error")}An()}catch(Ze){p(Ee),n(ke(Ze)||"Failed to create task","error")}finally{x(!1)}},[g,f,e,I,B,Rt,pe,fe,Tt,Ce,qe,Pt,Qe,it,S,l,n,An,Vt,It]),Dt=a.useCallback(ne=>{if(ne.key==="Enter"){if(ne.shiftKey&&v)return;ne.preventDefault(),ut()}else if(ne.key==="Escape"){if(ne.preventDefault(),le){ee(null);return}if(Se){O(!1),oe(null);return}if(V){D(!1);return}if(Xt){$t(!1);return}if(q){ge(!1),at(null);return}if(j){W(!1),Me(null);return}g.trim()&&(p(""),k.current&&(k.current.style.height="auto"),typeof window<"u"&&yr(Fa,l)),b(!1),N(!1),k.current?.blur()}},[ut,g,v,V,j,q,Se,le,Xt,l,N]),Wt=a.useCallback(()=>{w.current&&(w.current=!1)},[]),Mn=a.useCallback(()=>{c&&b(!0)},[c]),on=a.useCallback(ne=>{F(Ee=>Ee.includes(ne)?Ee.filter(Ze=>Ze!==ne):[...Ee,ne])},[]),Ut=a.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.width>0&&ne.height>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),G=a.useCallback(()=>{const ne=We.current;if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:Ze,height:vt,offsetTop:xt,offsetLeft:jn}=Ut(),en=16,cn=16,fn=4,Dn=Ze<=768,Wn=Math.min(Dn?vt*.6:vt*.5,360),Kn=Dn?Math.min(Ze-en*2,360):Math.max(Ee.width,240),Rn=Math.min(Kn,Math.max(Ze-en*2,200)),Gn=Ee.top-xt,On=Ee.bottom-xt,ps=Ee.left-jn,wn=vt-On,Fn=Gn,ls=Math.max(wn-cn-fn,160),Ns=Math.max(Fn-cn-fn,160),ts=wn<Wn&&Fn>wn,dn=Math.max(Math.min(ts?Ns:ls,Wn),160),Un=Math.min(Math.max(ps,en),Ze-en-Rn)+jn,Ls=ts?Math.max(cn+xt,Gn-dn-fn+xt):Math.min(On+fn+xt,vt+xt-cn-dn);oe({top:Ls,left:Un,width:Rn,maxHeight:dn})},[Ut]),Pe=a.useCallback(()=>{const ne=Et.current?.querySelector(".refine-button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:Ze,height:vt,offsetTop:xt,offsetLeft:jn}=Ut(),en=8,cn=12,fn=4,Dn=Math.min(200,Math.max(vt-cn*2,160)),Wn=Math.min(200,Ze-en*2),Kn=Ee.top-xt,Rn=Ee.bottom-xt,Gn=Ee.left-jn,On=vt-Rn,ps=Kn,wn=On<Dn&&ps>On,Fn=Math.min(Math.max(Gn,en),Ze-en-Wn)+jn,ls=wn?Math.max(cn+xt,Kn-Dn-fn+xt):Math.min(Rn+fn+xt,vt+xt-cn-Dn);H({top:ls,left:Fn})},[Ut]),Ye=a.useCallback(()=>{const ne=Te.current;if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:Ze,height:vt,offsetTop:xt,offsetLeft:jn}=Ut(),en=16,cn=16,fn=4,Dn=Ze<=768,Wn=Math.min(Dn?vt*.6:vt*.5,320),Kn=Dn?Math.min(Ze-en*2,360):Math.max(Ee.width,280),Rn=Math.min(Kn,Math.max(Ze-en*2,240)),Gn=Ee.top-xt,On=Ee.bottom-xt,ps=Ee.left-jn,wn=vt-On,Fn=Gn,ls=Math.max(wn-cn-fn,200),Ns=Math.max(Fn-cn-fn,200),ts=wn<Wn&&Fn>wn,dn=Math.max(Math.min(ts?Ns:ls,Wn),200),Un=Math.min(Math.max(ps,en),Ze-en-Rn)+jn,Ls=ts?Math.max(cn+xt,Gn-dn-fn+xt):Math.min(On+fn+xt,vt+xt-cn-dn);Ke({top:Ls,left:Un,width:Rn,maxHeight:dn})},[Ut]),nt=a.useCallback(()=>{const ne=ve.current?.querySelector("button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:Ze,height:vt,offsetTop:xt,offsetLeft:jn}=Ut(),en=16,cn=16,fn=4,Dn=Ze<=768,Wn=Math.min(Dn?vt*.6:vt*.5,320),Kn=Dn?Math.min(Ze-en*2,280):Math.max(Ee.width,240),Rn=Math.min(Kn,Math.max(Ze-en*2,200)),Gn=Ee.top-xt,On=Ee.bottom-xt,ps=Ee.left-jn,wn=vt-On,Fn=Gn,ls=Math.max(wn-cn-fn,160),Ns=Math.max(Fn-cn-fn,160),ts=wn<Wn&&Fn>wn,dn=Math.max(Math.min(ts?Ns:ls,Wn),160),Un=Math.min(Math.max(ps,en),Ze-en-Rn)+jn,Ls=ts?Math.max(cn+xt,Gn-dn-fn+xt):Math.min(On+fn+xt,vt+xt-cn-dn);Me({top:Ls,left:Un,width:Rn,maxHeight:dn})},[Ut]),mt=a.useCallback(()=>{const ne=Ae.current?.querySelector("button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:Ze,height:vt,offsetTop:xt,offsetLeft:jn}=Ut(),en=16,cn=16,fn=4,Dn=Ze<=768,Wn=Math.min(Dn?vt*.6:vt*.5,320),Kn=Dn?Math.min(Ze-en*2,280):Math.max(Ee.width,240),Rn=Math.min(Kn,Math.max(Ze-en*2,200)),Gn=Ee.top-xt,On=Ee.bottom-xt,ps=Ee.left-jn,wn=vt-On,Fn=Gn,ls=Math.max(wn-cn-fn,160),Ns=Math.max(Fn-cn-fn,160),ts=wn<Wn&&Fn>wn,dn=Math.max(Math.min(ts?Ns:ls,Wn),160),Un=Math.min(Math.max(ps,en),Ze-en-Rn)+jn,Ls=ts?Math.max(cn+xt,Gn-dn-fn+xt):Math.min(On+fn+xt,vt+xt-cn-dn);at({top:Ls,left:Un,width:Rn,maxHeight:dn})},[Ut]);a.useEffect(()=>{if(!Se)return;const ne=()=>G();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[Se,G]),a.useEffect(()=>{if(!Xt)return;const ne=()=>Pe();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[Xt,Pe]),a.useEffect(()=>{if(!V)return;const ne=()=>Ye();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[V,Ye]),a.useEffect(()=>{if(!j)return;const ne=()=>nt();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[j,nt]),a.useEffect(()=>{if(!q)return;const ne=()=>mt();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[q,mt]);const Nt=a.useCallback(ne=>{const Ee=yl(ne);Xe(Ee.provider),Ie(Ee.modelId)},[]),Lt=a.useCallback(ne=>{const Ee=yl(ne);ue(Ee.provider),se(Ee.modelId)},[]),Cn=a.useCallback(ne=>{const Ee=yl(ne);De(Ee.provider),et(Ee.modelId)},[]),rn=a.useCallback(async ne=>{if(m){m(ne);return}const Ee=Ge,vt=Ee.includes(ne)?Ee.filter(xt=>xt!==ne):[ne,...Ee];dt(vt);try{await mn({favoriteProviders:vt,favoriteModels:pt})}catch{dt(Ee)}},[Ge,pt,m]),kt=a.useCallback(async ne=>{if(h){h(ne);return}const Ee=pt,vt=Ee.includes(ne)?Ee.filter(xt=>xt!==ne):[ne,...Ee];jt(vt);try{await mn({favoriteProviders:Ge,favoriteModels:vt})}catch{jt(Ee)}},[pt,Ge,h]),os=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}r?.(ne),An()},[g,r,n,An]),ks=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}o?.(ne),An()},[g,o,n,An]),Is=a.useCallback(()=>{ut()},[ut]),ws=a.useCallback(async ne=>{const Ee=g.trim();if(!(!Ee||_t)){$t(!1),Ct(!0);try{const Ze=await dp(Ee,ne,l);p(Ze),n("Description refined with AI","success"),k.current&&(k.current.style.height="auto",k.current.style.height=`${Math.min(k.current.scrollHeight,200)}px`)}catch(Ze){const vt=up(Ze);n(vt,"error")}finally{Ct(!1)}}},[g,_t,n,l]),si=(ne,Ee)=>ne.length>Ee?ne.slice(0,Ee)+"…":ne,$s=a.useCallback(async()=>{if(i){Z(i),we(null),Y(!1);return}Y(!0),we(null);try{const ne=await ms();Z(ne.models),u||dt(ne.favoriteProviders),d||jt(ne.favoriteModels)}catch(ne){we(ke(ne)||"Failed to load models")}finally{Y(!1)}},[i,u,d]),Ds=a.useCallback(async()=>{if(ie.length>0&&P===l){W(!0),nt();return}ce(!0);try{const ne=await _a(void 0,l);C(ne),T(l),W(!0),nt()}catch(ne){const Ee=ke(ne);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),W(!1)}finally{ce(!1)}},[ie.length,P,l,n,nt]),ii=(B?ie.find(ne=>ne.id===B):void 0)?.name??B,ai=It?Ft.find(ne=>ne.id===It):void 0,ht=y,pn=a.useCallback(()=>{N(ne=>{const Ee=!ne;return b(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:k,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ne=>p(ne.target.value),onKeyDown:Dt,onPaste:ae,onFocus:Mn,onBlur:Wt,disabled:f||A,"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:pn,"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(Qt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ht,"aria-hidden":!ht,children:[ht&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:os,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Zs,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ks,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Do,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Et,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${_t?"refine-button--loading":""}`,onClick:()=>{$t(ne=>{const Ee=!ne;return Ee?Pe():H(null),Ee})},disabled:!g.trim()||_t,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Zn,{size:12,style:{verticalAlign:"middle"}}),_t?"Refining...":"Refine"]}),Xt&&Re&&At&&da.createPortal(t.jsxs("div",{ref:tn,className:"refine-menu refine-menu--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${At.top}px`,left:`${At.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ws("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:()=>ws("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:()=>ws("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:()=>ws("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"})]})]}),Re)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Te,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{D(ne=>{const Ee=!ne;return Ee?(O(!1),oe(null),ee(null),W(!1),Me(null),ge(!1),at(null),Ye()):Ke(null),Ee})},children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}}),I.length>0?`${I.length} deps`:"Deps"]})}),V&&Re&&_e&&(()=>{const ne=E.toLowerCase(),Ee=(ne?s.filter(Ze=>Ze.id.toLowerCase().includes(ne)||Ze.title&&Ze.title.toLowerCase().includes(ne)||Ze.description&&Ze.description.toLowerCase().includes(ne)):[...s]).sort((Ze,vt)=>{const xt=vt.createdAt.localeCompare(Ze.createdAt);if(xt!==0)return xt;const jn=parseInt(Ze.id.slice(Ze.id.lastIndexOf("-")+1),10)||0;return(parseInt(vt.id.slice(vt.id.lastIndexOf("-")+1),10)||0)-jn});return da.createPortal(t.jsxs("div",{ref:me,className:"dep-dropdown dep-dropdown--portal",onMouseDown:Ze=>Ze.preventDefault(),style:{position:"fixed",top:`${_e.top}px`,left:`${_e.left}px`,width:`${_e.width}px`,maxHeight:_e.maxHeight?`${_e.maxHeight}px`:void 0,overflowY:_e.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:E,onChange:Ze=>$(Ze.target.value),onClick:Ze=>Ze.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(Ze=>t.jsxs("div",{className:`dep-dropdown-item${I.includes(Ze.id)?" selected":""}`,onMouseDown:vt=>vt.preventDefault(),onClick:()=>on(Ze.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:Ze.id}),t.jsx("span",{className:"dep-dropdown-title",children:si(Ze.title||Ze.description||Ze.id,60)})]},Ze.id))]}),Re)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>R.current?.click(),children:[t.jsx(Xh,{size:12,style:{verticalAlign:"middle"}}),S.length>0?`Attach (${S.length})`:"Attach"]}),t.jsxs("button",{ref:We,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{D(!1),W(!1),Me(null),ge(!1),at(null),ee(null),O(!0),G()},children:[t.jsx(fo,{size:12,style:{verticalAlign:"middle"}}),kn]}),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:()=>{D(!1),W(!1),Me(null),O(!1),oe(null),ee(null),ge(ne=>{const Ee=!ne;return Ee?mt():at(null),Ee})},children:[t.jsx(pr,{size:12,style:{verticalAlign:"middle"}}),` ${ai?.name??"Node"}`,ai&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(qi,{status:ai.status,showLabel:!0})})]})}),q&&Re&&Oe&&da.createPortal(t.jsxs("div",{ref:Fe,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${Oe.top}px`,left:`${Oe.left}px`,width:`${Oe.width}px`,maxHeight:Oe.maxHeight?`${Oe.maxHeight}px`:void 0,overflowY:Oe.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${It==null?" selected":""}`,onMouseDown:ne=>ne.preventDefault(),onClick:()=>{qt(void 0),ge(!1),at(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Ft.map(ne=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${It===ne.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{qt(ne.id),ge(!1),at(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(qi,{status:ne.status})}),t.jsx("span",{className:"node-picker-item-name",children:ne.name}),t.jsx("span",{className:"node-picker-item-status",children:AN(ne.status)})]},ne.id))]}),Re),t.jsx("div",{className:"agent-trigger-wrap",ref:ve,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{j?(W(!1),Me(null)):(ge(!1),at(null),Ds())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Nn,{size:12,style:{verticalAlign:"middle"}}),ii?` ${ii}`:" Agent"]})}),j&&Re&&he&&da.createPortal(t.jsxs("div",{ref:te,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${he.top}px`,left:`${he.left}px`,width:`${he.width}px`,maxHeight:he.maxHeight?`${he.maxHeight}px`:void 0,overflowY:he.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!be&&ie.filter(ne=>ne.state!=="terminated").map(ne=>t.jsxs("div",{className:`dep-dropdown-item${B===ne.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{J(ne.id===B?null:ne.id),W(!1),Me(null)},children:[t.jsx(Nn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ne.role}),t.jsx("span",{className:"dep-dropdown-title",children:ne.name})]},ne.id)),!be&&ie.filter(ne=>ne.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),B&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ne=>ne.preventDefault(),onClick:()=>{J(null),W(!1),Me(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Re),t.jsx("button",{type:"button",className:`btn btn-sm ${Vt?"btn-primary":""}`,onClick:()=>Mt(ne=>!ne),onMouseDown:ne=>ne.preventDefault(),"aria-pressed":Vt,"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:Is,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(ep,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((ne,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Je(Ee),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},ne.previewUrl))}),Se&&Re&&ye&&da.createPortal(t.jsx("div",{ref:re,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ne=>ne.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ye.top}px`,left:`${ye.left}px`,width:`${ye.width}px`,maxHeight:ye.maxHeight?`${ye.maxHeight}px`:void 0,overflowY:ye.maxHeight?"auto":void 0},children:le===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Pt?"model-menu-item--active":""}`,onClick:()=>ee("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Zs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Pt?_n(Qe,it):"Using default"}),t.jsx(vn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Rt?"model-menu-item--active":""}`,onClick:()=>ee("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Zn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:Rt?_n(pe,fe):"Using default"}),t.jsx(vn,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Tt?"model-menu-item--active":""}`,onClick:()=>ee("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(fo,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Tt?_n(Ce,qe):"Using default"}),t.jsx(vn,{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:()=>ee(null),"data-testid":"model-submenu-back",children:[t.jsx(Qt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[le==="plan"&&"Plan Model",le==="executor"&&"Executor Model",le==="validator"&&"Reviewer Model"]}),t.jsx(qn,{models:tt,value:le==="plan"?ot:le==="executor"?X:ze,onChange:le==="plan"?Nt:le==="executor"?Lt:Cn,placeholder:"Using default",disabled:ct,id:`model-${le}-select`,label:`${le} model`,favoriteProviders:xe,onToggleFavorite:rn,favoriteModels:Le,onToggleModelFavorite:kt}),de&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:de}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:$s,children:"Retry"})]})]})}),Re)]}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ne=>{je(ne.target.files),ne.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function RN(e){return rd(e)||e}function TN(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 PN(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 x=f.worktree,v=o.get(x)||[];v.push(f),o.set(x,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(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=TN(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:RN(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 Ru=100,jl=50,Tu=25;function IN({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:x,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:N,onToggleCollapse:k,allTasks:R,availableModels:w,onPlanningMode:M,onSubtaskBreakdown:S,onOpenDetailWithTab:z,favoriteProviders:_,favoriteModels:I,onToggleFavorite:F,onToggleModelFavorite:V,isSearchActive:D,taskStuckTimeoutMs:E,onOpenMission:$,lastFetchTimeMs:B,workflowStepNameLookup:J}){const[ie,C]=a.useState(!1),[P,T]=a.useState(jl),[j,W]=a.useState(!1),[q,ge]=a.useState(!1),[be,ce]=a.useState(!1),[Se,O]=a.useState(!1),le=a.useRef(null),ee=Sw(n.length),{confirm:pe}=Hs();a.useEffect(()=>{if(!j)return;function Me(at){le.current?.contains(at.target)||W(!1)}function Oe(at){at.key==="Escape"&&W(!1)}return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Oe),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Oe)}},[j]);const ue=e==="archived",fe=ue&&N,se=!ue&&!D&&e!=="in-progress"&&n.length>Ru;a.useEffect(()=>{T(Me=>e==="in-progress"||ue||n.length<=Ru?jl:Math.min(Math.max(Me,jl),n.length))},[e,ue,n.length]);const Ce=a.useCallback(Me=>{ue||(Me.preventDefault(),Me.dataTransfer.dropEffect="move",C(!0))},[ue]),De=a.useCallback(Me=>{Me.currentTarget.contains(Me.relatedTarget)||C(!1)},[]),qe=a.useCallback(async Me=>{Me.preventDefault(),C(!1);const Oe=Me.dataTransfer.getData("text/plain");if(!Oe)return;const at=n.find(ye=>ye.id===Oe);if(!(at&&at.column===e))try{await r(Oe,e)}catch(ye){c(ke(ye),"error")}},[e,r,c,n]),et=a.useMemo(()=>e!=="in-progress"?[]:PN(n,n,i),[e,n,i]),Qe=a.useMemo(()=>se?n.slice(0,P):n,[se,n,P]),Xe=Math.max(0,n.length-Qe.length),it=a.useCallback(()=>{T(Me=>Math.min(Me+Tu,n.length))},[n.length]),Ie=a.useCallback(async()=>{if(W(!1),!(n.length===0||!await pe({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){ge(!0);try{const Oe=await Promise.allSettled(n.map(oe=>r(oe.id,"triage"))),at=Oe.filter(oe=>oe.status==="rejected").length,ye=Oe.length-at;at===0?c(`Moved ${ye} task${ye===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ye} of ${Oe.length} tasks; ${at} failed`,"error")}finally{ge(!1)}}},[n,r,c,pe]),We=a.useMemo(()=>n.filter(Me=>!Me.paused),[n]),re=We.length,ve=e==="todo"||e==="in-progress"||e==="in-review",te=q||be||Se,Ae=a.useCallback(async()=>{if(!(!o||(W(!1),re===0)||!await pe({title:"Stop All Tasks",message:`Stop all ${re} ${$n[e].toLowerCase()} task${re===1?"":"s"}?`,danger:!0}))){ce(!0);try{const Oe=await Promise.allSettled(We.map(oe=>o(oe.id))),at=Oe.filter(oe=>oe.status==="rejected").length,ye=Oe.length-at;at===0?c(`Stopped ${ye} task${ye===1?"":"s"}`,"success"):c(`Stopped ${ye} of ${Oe.length} tasks; ${at} failed`,"error")}finally{ce(!1)}}},[o,re,e,We,c,pe]),Fe=a.useCallback(async()=>{if(W(!1),!(n.length===0||!await pe({title:"Move All to Todo",message:`Move all ${n.length} ${$n[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))){O(!0);try{const Oe=await Promise.allSettled(n.map(oe=>r(oe.id,"todo"))),at=Oe.filter(oe=>oe.status==="rejected").length,ye=Oe.length-at;at===0?c(`Moved ${ye} task${ye===1?"":"s"} to Todo`,"success"):c(`Moved ${ye} of ${Oe.length} tasks to Todo; ${at} failed`,"error")}finally{O(!1)}}},[n,e,r,c,pe]),he=a.useCallback(async()=>{if(!(!y||n.length===0||!await pe({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Oe=await y();c(`Archived ${Oe.length} tasks`,"success")}catch(Oe){c(ke(Oe)||"Failed to archive tasks","error")}},[y,n.length,c,pe]);return t.jsxs("div",{className:`column${ie?" drag-over":""}${ue?" column-archived":""}${fe?" column-collapsed":""}`,"data-column":e,onDragOver:Ce,onDragLeave:De,onDrop:qe,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:$n[e]}),t.jsx("span",{className:`column-count${ee?" 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:he,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(To,{size:16})}),ue&&k&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:k,title:N?"Expand archived tasks":"Collapse archived tasks","aria-label":N?"Expand archived tasks":"Collapse archived tasks",children:N?t.jsx(Qt,{size:16}):t.jsx(mi,{size:16})}),ve&&t.jsxs("div",{className:"column-menu",ref:le,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>W(Me=>!Me),"aria-haspopup":"menu","aria-expanded":j,"aria-label":`${$n[e]} column actions`,title:"Column actions",disabled:te,children:t.jsx(fx,{size:16})}),j&&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 Ie(),disabled:n.length===0||q,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||be||!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||Se,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!fe&&t.jsx("p",{className:"column-desc",children:ww[e]}),!fe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Pp,{onCreate:u,addToast:c,tasks:R??[],availableModels:w,onPlanningMode:M,onSubtaskBreakdown:S,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:I,onToggleFavorite:F,onToggleModelFavorite:V}),e==="in-progress"?et.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):et.map(Me=>t.jsx(Tp,{label:Me.label,activeTasks:Me.activeTasks,queuedTasks:Me.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onOpenDetailWithTab:z,taskStuckTimeoutMs:E,onOpenMission:$,lastFetchTimeMs:B,workflowStepNameLookup:J},Me.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Qe.map(Me=>t.jsx(wo,{task:Me,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onRetryTask:f,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:z,taskStuckTimeoutMs:E,onOpenMission:$,onMoveTask:r,lastFetchTimeMs:B,workflowStepNameLookup:J},Me.id)),se&&Xe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:it,children:["Load ",Math.min(Tu,Xe)," more (",Xe," remaining)"]})]}),t.jsx(Ho,{slotId:"board-column-footer",projectId:s})]})]})}const Ip=a.memo(IN);Ip.displayName="Column";function $N(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 DN(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Pu=new Map;function LN(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 zN({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:x,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:N="",availableModels:k,onPlanningMode:R,onSubtaskBreakdown:w,onOpenDetailWithTab:M,favoriteProviders:S,favoriteModels:z,onToggleFavorite:_,onToggleModelFavorite:I,taskStuckTimeoutMs:F,onOpenMission:V,lastFetchTimeMs:D}){const[E,$]=a.useState(!0),B=a.useRef(!1),{fetchBatch:J}=Hw(n),ie=a.useRef(null),[C,P]=a.useState(Pu),T=N.trim()!=="",j=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),W=a.useCallback(()=>{$(be=>{const ce=!be;return!ce&&!B.current&&y&&(B.current=!0,y()),ce})},[y]),q=a.useMemo(()=>{const be=Object.fromEntries(Oi.map(O=>[O,[]]));for(const O of e)be[O.column].push(O);const ce=j.current,Se={};for(const O of Oi){const le=$N(be[O],O);Se[O]=DN(ce[O],le)?ce[O]:le}return j.current=Se,Se},[e]);a.useEffect(()=>{let be=!1;return Uo(n).then(ce=>{if(be)return;const Se=new Map(ce.map(O=>[O.id,O.name]));P(O=>LN(O,Se)?O:Se)}).catch(()=>{be||P(ce=>ce.size===0?ce:Pu)}),()=>{be=!0}},[n]);const ge=a.useMemo(()=>e.filter(be=>be.prInfo||be.issueInfo).map(be=>be.id),[e]);return a.useEffect(()=>{if(ge.length!==0)return ie.current&&clearTimeout(ie.current),ie.current=setTimeout(()=>{const be=[];for(let ce=0;ce<ge.length;ce+=50)be.push(ge.slice(ce,ce+50));be.forEach(ce=>{J(ce)})},500),()=>{ie.current&&clearTimeout(ie.current)}},[ge,J]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Oi.map(be=>t.jsx(Ip,{column:be,tasks:q[be],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onRetryTask:p,onArchiveTask:f,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:k,onOpenDetailWithTab:M,favoriteProviders:S,favoriteModels:z,onToggleFavorite:_,onToggleModelFavorite:I,isSearchActive:T,taskStuckTimeoutMs:F,onOpenMission:V,lastFetchTimeMs:D,workflowStepNameLookup:C,...be==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:R,onSubtaskBreakdown:w}:{},...be==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...be==="done"?{onArchiveAllDone:b}:{},...be==="archived"?{collapsed:E,onToggleCollapse:W}:{}},be))})})}const Ua={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Iu=new Set(["planning","researching","executing","finalizing","merging"]),Pc=["id","title","status","column","dependencies","progress"];function ON(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function FN(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function $u(e){try{const n=Vn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Pc.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Pc)}function Du(e){try{const n=Vn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Lu(e){try{const n=Vn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>Oi.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function zu(e){try{const n=Vn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function UN(e){return e.status==="executing"||e.column==="in-progress"}function Ou(e){const n=Ap(e);return n.total===0||!UN(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function BN({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:x,projectName:v,taskStuckTimeoutMs:b,searchQuery:y="",lastFetchTimeMs:N}){const[k,R]=a.useState("id"),[w,M]=a.useState("desc"),[S,z]=a.useState(null),[_,I]=a.useState(null),[F,V]=a.useState(null),E=Pr()==="mobile",[$,B]=a.useState(()=>$u(x)),[J,ie]=a.useState(()=>Du(x)),[C,P]=a.useState(()=>Lu(x));a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-list-columns",JSON.stringify([...$]),x)},[x,$]),a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-hide-done",J.toString(),x)},[J,x]),a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-list-collapsed",JSON.stringify([...C]),x)},[C,x]);const[T,j]=a.useState(!1),W=a.useRef(null),[q,ge]=a.useState(()=>zu(x));a.useEffect(()=>{B($u(x)),ie(Du(x)),P(Lu(x)),ge(zu(x))},[x]),a.useEffect(()=>{typeof window<"u"&&ds("kb-dashboard-selected-tasks",JSON.stringify([...q]),x)},[x,q]);const be=a.useCallback(Y=>{ge(de=>{const we=new Set(de);return we.has(Y)?we.delete(Y):we.add(Y),we})},[]),ce=a.useCallback(()=>{ge(new Set)},[]),Se=a.useCallback(Y=>{B(de=>{const we=new Set(de);return we.has(Y)?we.size>1&&we.delete(Y):we.add(Y),we})},[]);a.useEffect(()=>{if(!T)return;const Y=we=>{W.current&&!W.current.contains(we.target)&&j(!1)},de=we=>{we.key==="Escape"&&j(!1)};return document.addEventListener("mousedown",Y),document.addEventListener("keydown",de),()=>{document.removeEventListener("mousedown",Y),document.removeEventListener("keydown",de)}},[T]);const O={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},le=a.useCallback(Y=>{k===Y?M(de=>de==="asc"?"desc":"asc"):(R(Y),M("asc"))},[k]),ee=a.useCallback(Y=>{V(de=>de===Y?null:Y)},[]),pe=a.useCallback(Y=>{P(de=>{const we=new Set(de);return we.has(Y)?we.delete(Y):we.add(Y),we})},[]),ue=a.useCallback(()=>{V(null)},[]),fe=a.useMemo(()=>{let Y=y?e.filter(Z=>Z.id.toLowerCase().includes(y.toLowerCase())||Z.title&&Z.title.toLowerCase().includes(y.toLowerCase())||Z.description.toLowerCase().includes(y.toLowerCase())):[...e];J&&!F&&(Y=Y.filter(Z=>Z.column!=="done"&&Z.column!=="archived"));const we=[...F?Y.filter(Z=>Z.column===F):Y].sort((Z,Ge)=>{let dt=0;switch(k){case"id":dt=Z.id.localeCompare(Ge.id);break;case"title":dt=(Z.title||Z.description).localeCompare(Ge.title||Ge.description);break;case"status":dt=(Z.status||"").localeCompare(Ge.status||"");break;case"column":dt=Z.column.localeCompare(Ge.column);break}return w==="asc"?dt:-dt}),tt={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return we.forEach(Z=>tt[Z.column].push(Z)),tt},[e,y,k,w,J,F]),se=a.useMemo(()=>Object.values(fe).reduce((Y,de)=>Y+de.length,0),[fe]),Ce=a.useMemo(()=>e.filter(Y=>Y.column==="done"||Y.column==="archived").length,[e]),De=a.useMemo(()=>J?Ce:0,[J,Ce]),qe=a.useCallback(()=>{const Y=Object.values(fe).flat().filter(de=>de.column!=="archived").map(de=>de.id);ge(de=>{if(Y.every(tt=>de.has(tt))){const tt=new Set(de);return Y.forEach(Z=>tt.delete(Z)),tt}else return new Set([...de,...Y])})},[fe]),et=a.useMemo(()=>{const Y=Object.values(fe).flat().filter(de=>de.column!=="archived");return Y.length===0?!1:Y.every(de=>q.has(de.id))},[fe,q]),Qe=a.useMemo(()=>{const Y=Object.values(fe).flat().filter(we=>we.column!=="archived");if(Y.length===0)return!1;const de=Y.filter(we=>q.has(we.id)).length;return de>0&&de<Y.length},[fe,q]),[Xe,it]=a.useState("__no_change__"),[Ie,We]=a.useState("__no_change__"),[re,ve]=a.useState("__no_change__"),[te,Ae]=a.useState([]),[Fe,he]=a.useState(!1),Me=a.useMemo(()=>re&&re!=="__no_change__"?te.find(Y=>Y.id===re):void 0,[te,re]),[Oe,at]=a.useState(!1);a.useEffect(()=>{if(q.size===0)return;let Y=!1;return(async()=>{he(!0);try{const we=await yo();Y||Ae(we)}catch(we){console.error("Failed to fetch nodes for bulk edit",we),Y||Ae([])}finally{Y||he(!1)}})(),()=>{Y=!0}},[q.size]);const ye=a.useCallback(async()=>{if(q.size===0)return;const Y=Array.from(q).filter(we=>{const tt=e.find(Z=>Z.id===we);return tt&&tt.column!=="archived"});if(Y.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const de={taskIds:Y};if(Xe!=="__no_change__")if(Xe==="")de.modelProvider=null,de.modelId=null;else{const we=Xe.indexOf("/");we!==-1&&(de.modelProvider=Xe.slice(0,we),de.modelId=Xe.slice(we+1))}if(Ie!=="__no_change__")if(Ie==="")de.validatorModelProvider=null,de.validatorModelId=null;else{const we=Ie.indexOf("/");we!==-1&&(de.validatorModelProvider=Ie.slice(0,we),de.validatorModelId=Ie.slice(we+1))}if(re!=="__no_change__"&&(re===""?de.nodeId=null:de.nodeId=re),Object.keys(de).length===1){i("No changes to apply","info");return}at(!0);try{const we=await Tv(de.taskIds,de.modelProvider,de.modelId,de.validatorModelProvider,de.validatorModelId,void 0,void 0,de.nodeId,x);f&&f(we.updated),i(`Updated ${Y.length} task${Y.length===1?"":"s"}`,"success"),ce(),it("__no_change__"),We("__no_change__"),ve("__no_change__")}catch(we){i(ke(we)||"Failed to update models","error")}finally{at(!1)}},[q,e,Xe,Ie,re,x,i,ce,f]),oe=a.useCallback(Y=>{s(Y)},[s]),Te=a.useCallback((Y,de)=>{if(de.paused){Y.preventDefault();return}Y.dataTransfer.setData("text/plain",de.id),Y.dataTransfer.effectAllowed="move",z(de.id)},[]),me=a.useCallback(()=>{z(null),I(null)},[]),_e=a.useCallback((Y,de)=>{Y.preventDefault(),Y.dataTransfer.dropEffect="move",I(de)},[]),Ke=a.useCallback(()=>{I(null)},[]),Re=a.useCallback(async(Y,de)=>{Y.preventDefault(),I(null);const we=Y.dataTransfer.getData("text/plain");if(we){if(de==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(we,de)}catch(tt){i(ke(tt),"error")}}},[n,i]),ct=Y=>k!==Y?t.jsx(Hh,{size:14,className:"sort-icon"}):w==="asc"?t.jsx(zi,{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:W,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>j(Y=>!Y),"aria-expanded":T,"aria-haspopup":"menu",children:[t.jsx(lx,{size:14}),"Columns"]}),T&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Pc.map(Y=>{const de=$.has(Y),we=de&&$.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${we?" disabled":""}`,role:"menuitem",title:we?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:de,onChange:()=>Se(Y),disabled:we}),t.jsx("span",{children:O[Y]})]},Y)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>ie(Y=>!Y),"aria-pressed":J,title:J?"Show done tasks":"Hide done tasks",children:[J?t.jsx(fa,{size:14}):t.jsx(vc,{size:14}),J?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[F?`${se} of ${e.length} tasks in ${$n[F]}`:`${se} of ${e.length} tasks`,De>0&&!F&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",De," hidden)"]}),F&&t.jsx("button",{className:"btn btn-sm",onClick:ue,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),q.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[q.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:ce,children:"Clear"})]}),q.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(qn,{models:c,value:Xe,onChange:it,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(qn,{models:c,value:Ie,onChange:We,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=>ve(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"}),te.map(Y=>t.jsx("option",{value:Y.id,children:`${FN(Y.status)} ${Y.name||Y.id} (${ON(Y.status)})`},Y.id))]}),Me?t.jsx(qi,{status:Me.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ye,disabled:Oe||Xe==="__no_change__"&&Ie==="__no_change__"&&re==="__no_change__",children:Oe?"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:Oi.map(Y=>{const de=e.filter(Ge=>Ge.column===Y).length,we=Y==="done"||Y==="archived",tt=J&&we?0:de,Z=J&&we&&de>0;return t.jsxs("div",{className:`list-drop-zone${_===Y?" drag-over":""}${F===Y?" active":""}`,onClick:()=>ee(Y),onDragOver:Ge=>_e(Ge,Y),onDragLeave:Ke,onDrop:Ge=>Re(Ge,Y),"data-column":Y,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:Ua[Y]}}),t.jsx("span",{className:"drop-zone-label",children:$n[Y]}),t.jsx("span",{className:"drop-zone-count",children:Z?`${tt} of ${de}`:de})]},Y)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Pp,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:x,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),se===0?t.jsx("div",{className:"list-empty",children:y?"No tasks match your filter":"No tasks yet"}):E?t.jsx("div",{className:"list-cards",children:Oi.map(Y=>{if(F&&Y!==F||J&&(Y==="done"||Y==="archived")&&!F)return null;const de=fe[Y],we=de.length===0;if(y&&we)return null;const tt=C.has(Y);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${tt?" list-section-header--collapsed":""}`,onClick:()=>pe(Y),"aria-expanded":!tt,role:"button",tabIndex:0,onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),pe(Y))},children:[t.jsx(vn,{size:14,className:`list-section-chevron${tt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Y}`}),t.jsx("span",{className:"list-section-title",children:$n[Y]}),t.jsx("span",{className:"list-section-count",children:de.length})]}),!tt&&t.jsx(t.Fragment,{children:we?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):de.map(Z=>{const Ge=Z.status==="failed",dt=Z.paused===!0,pt=ko(Z,b,N),jt=!r&&!Ge&&!dt&&!pt&&(Z.column==="in-progress"||Iu.has(Z.status)),yt=typeof Z.status=="string"&&Z.status.trim().length>0,ft=!!(Z.dependencies&&Z.dependencies.length>0),St=Ou(Z),Ot=St.hasProgress,Vt=q.size>0;return t.jsxs("div",{className:`list-card${jt?" agent-active":""}${Vt?" list-card--selectable":""}`,onClick:()=>oe(Z),"data-id":Z.id,children:[Vt&&t.jsx("label",{className:"list-card-checkbox",onClick:Mt=>Mt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:q.has(Z.id),onChange:Mt=>{Mt.stopPropagation(),be(Z.id)},onClick:Mt=>Mt.stopPropagation(),disabled:Z.column==="archived","aria-label":`Select ${Z.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Z.id}),Z.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),pt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):yt?t.jsx("span",{className:`list-status-badge list-status-badge--${Z.column}${Ge?" failed":""}${jt?" pulsing":""}`,children:Z.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Z.title||Z.description})}),(ft||Ot)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[ft&&t.jsxs("span",{className:"list-dep-badge",title:Z.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",Z.dependencies.length]}),Ot&&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:Ua[Z.column]}})}),t.jsx("span",{className:"list-progress-label",children:St.label})]})]})]},Z.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:et,ref:Y=>{Y&&(Y.indeterminate=Qe)},onChange:qe,"aria-label":"Select all visible tasks"})}),$.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>le("id"),children:["ID ",ct("id")]}),$.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>le("title"),children:["Title ",ct("title")]}),$.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>le("status"),children:["Status ",ct("status")]}),$.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>le("column"),children:["Column ",ct("column")]}),$.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),$.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Oi.map(Y=>{if(F&&Y!==F||J&&(Y==="done"||Y==="archived")&&!F)return null;const de=fe[Y],we=de.length===0;if(y&&we)return null;const tt=C.has(Y);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${tt?" list-section-header--collapsed":""}`,onClick:()=>pe(Y),"aria-expanded":!tt,children:t.jsxs("th",{colSpan:$.size+1,className:"list-section-cell",children:[t.jsx(vn,{size:14,className:`list-section-chevron${tt?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Y}`}),t.jsx("span",{className:"list-section-title",children:$n[Y]}),t.jsx("span",{className:"list-section-count",children:de.length})]})}),!tt&&t.jsx(t.Fragment,{children:we?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:$.size+1,className:"list-empty-cell",children:"No tasks"})}):de.map(Z=>{const Ge=Z.status==="failed",dt=Z.paused===!0,pt=ko(Z,b,N),jt=!r&&!Ge&&!dt&&!pt&&(Z.column==="in-progress"||Iu.has(Z.status)),yt=S===Z.id;return t.jsxs("tr",{className:`list-row${Ge?" failed":""}${dt?" paused":""}${pt?" stuck":""}${jt?" agent-active":""}${yt?" dragging":""}`,onClick:()=>oe(Z),draggable:!dt,onDragStart:ft=>Te(ft,Z),onDragEnd:me,"data-id":Z.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:q.has(Z.id),onChange:ft=>{ft.stopPropagation(),be(Z.id)},onClick:ft=>ft.stopPropagation(),disabled:Z.column==="archived","aria-label":`Select ${Z.id}`})}),$.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:Z.id}),$.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[Z.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:Z.title||Z.description})]})}),$.has("status")&&t.jsx("td",{className:"list-cell",children:pt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Z.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Z.column}${Ge?" failed":""}${jt?" pulsing":""}`,children:Z.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),$.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Ua[Z.column]}20`,color:Ua[Z.column]},children:$n[Z.column]})}),$.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Z.dependencies&&Z.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Z.dependencies.join(", "),children:[t.jsx(ga,{size:12})," ",Z.dependencies.length]}):"-"}),$.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const ft=Ou(Z);return ft.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:`${ft.percent}%`,backgroundColor:Ua[Z.column]}})}),t.jsx("span",{className:"list-progress-label",children:ft.label})]}):"-"})()})]},Z.id)})})]},Y)})})]})]})]})}const HN={active:{label:"Active",color:"var(--success)",icon:Sn},paused:{label:"Paused",color:"var(--warning)",icon:Us},errored:{label:"Error",color:"var(--color-error)",icon:as},initializing:{label:"Initializing",color:"var(--info)",icon:rt}};function qN(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 VN(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 WN(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 KN({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=HN[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(k=>{k.stopPropagation(),i(e)},[i,e]),x=a.useCallback(k=>{k.stopPropagation(),r(e)},[r,e]),v=a.useCallback(k=>{if(k.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),b=e.status==="paused",y=e.status==="errored",N=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Hn,{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:VN(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:N?"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:qN(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||N,title:N?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Us,{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(sn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const GN=a.memo(KN,WN);function JN(){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(Hn,{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(Ts,{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(yn,{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(as,{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 YN=1e4,Fu=5;function QN(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+=Fu){const x=e.slice(f,f+Fu),v=await Promise.allSettled(x.map(async b=>{try{return await su(b)}catch{return null}}));if(x.forEach((b,y)=>{const N=v[y];p[b]=N.status==="fulfilled"?N.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 su(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()},YN),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function XN({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,x]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const V=localStorage.getItem("kb-dashboard-recent-projects");if(V)try{const D=JSON.parse(V);b(D)}catch{}},[]);const[v,b]=a.useState([]),y=a.useMemo(()=>e.map(V=>V.id),[e]),{healthMap:N,loading:k}=QN(y),R=a.useMemo(()=>e.map(V=>({project:V,health:N[V.id]||null})),[e,N]),w=a.useMemo(()=>{let V=[...R];return u!=="all"&&(V=V.filter(({project:D})=>D.status===u)),m!==null&&(V=V.filter(({project:D})=>D.nodeId===m)),V},[R,u,m]),M=a.useMemo(()=>{const V=[...w];return V.sort((D,E)=>{let $=0;switch(g){case"name":$=D.project.name.localeCompare(E.project.name);break;case"activity":{const B=D.project.lastActivityAt||D.health?.lastActivityAt||D.project.updatedAt,J=E.project.lastActivityAt||E.health?.lastActivityAt||E.project.updatedAt;$=new Date(J).getTime()-new Date(B).getTime();break}case"status":{const B={errored:0,initializing:1,paused:2,active:3};$=B[D.project.status]-B[E.project.status];break}}return f==="asc"?$:-$}),V},[w,g,f]),S=a.useMemo(()=>{const V=e.length,D=e.filter(P=>P.status==="active").length,E=e.filter(P=>P.status==="errored").length,$=new Set;e.forEach(P=>{P.nodeId&&$.add(P.nodeId)});const B=$.size||(V>0?1:0);let J=0,ie=0,C=0;return Object.values(N).forEach(P=>{P&&(J+=P.activeTaskCount,ie+=P.totalTasksCompleted,C+=P.inFlightAgentCount)}),{totalProjects:V,activeProjects:D,erroredProjects:E,totalNodes:B,totalActiveTasks:J,totalCompletedTasks:ie,totalInFlightAgents:C}},[e,N]),z=a.useMemo(()=>({all:e.length,active:e.filter(V=>V.status==="active").length,paused:e.filter(V=>V.status==="paused").length,errored:e.filter(V=>V.status==="errored").length}),[e]),_=a.useMemo(()=>{const V=new Map;return e.forEach(D=>{const E=D.nodeId,$=V.get(E);if($)$.count++;else{const J=c.find(ie=>ie.id===E)?.name??D._sourceNodeName??"Local";V.set(E,{name:J,count:1})}}),Array.from(V.entries()).map(([D,{name:E,count:$}])=>({nodeId:D??null,name:E,count:$}))},[e,c]),I=a.useCallback(V=>{const D=[V.id,...v.filter(E=>E!==V.id)].slice(0,3);b(D),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(D)),s(V)},[s,v]);return n||k&&e.length>0&&Object.keys(N).length===0?t.jsx(JN,{}):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(sr,{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(an,{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(Hi,{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(Hn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.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(Ts,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.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(yn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),S.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(as,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),S.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(pr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.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(an,{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:z.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:z.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:z.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${z.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:z.errored})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(pr,{size:14}),t.jsxs("select",{value:m??"",onChange:V=>{h(V.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),_.map(({nodeId:V,name:D,count:E})=>t.jsxs("option",{value:V??"",children:[D," (",E,")"]},V??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(go,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:V=>{const[D,E]=V.target.value.split("-");p(D),x(E)},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(Hh,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:M.map(({project:V,health:D})=>{const E=c.find(B=>B.id===V.nodeId),$=E?void 0:V._sourceNodeName;return t.jsx(GN,{project:V,health:D,node:E,nodeNameFallback:$,onSelect:I,onPause:r,onResume:o,onRemove:l},V.id)})}),M.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(go,{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 ZN=45e3,e1=3e3,t1=2e3,n1=1500,Uu="fusion:sse-client-id";let sa=null;const ki=new Map;function Bu(){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 $p(){if(!(typeof window>"u")){if(sa)return sa;try{const e=window.sessionStorage.getItem(Uu);if(e)return sa=e,e;const n=Bu();return window.sessionStorage.setItem(Uu,n),sa=n,n}catch{return sa=Bu(),sa}}}function Dp(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Lp(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function s1(e){const n=$p();if(!n)return e;const s=Dp(e);return!s||!Lp(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function cd(e,n){const s=$p();if(!s)return;const i=Dp(e);if(!i||!Lp(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),ei(`${r.pathname}${r.search}${r.hash}`)}function i1(e){if(typeof window>"u")return;const n=cd(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 Wo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Hu(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=cd(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),n1):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function a1(e){Wo(e),cd(e.url,"keepalive")&&(Hu(e),e.keepaliveTimer=window.setInterval(()=>{Hu(e)},t1))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ki.values()))if(!s.closed){if(Wo(s),i1(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,dd(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function ir(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{zp(e)},ZN)}function zp(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Wo(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&&dd(e)},e1)}}function dd(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ei(s1(e.url)));e.es=n,a1(e),n.addEventListener("open",()=>{ir(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);zp(e)}),n.addEventListener("message",()=>ir(e)),n.addEventListener("heartbeat",()=>ir(e)),Op(e),ir(e)}function Op(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=>{ir(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 r1(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Wo(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[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),dd(s),Op(s);let r=!0;return()=>{if(!r)return;r=!1;const o=ki.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&r1(o))}}const ud="kb-planning-last-description",md="kb-subtask-last-description",hd="kb-mission-last-goal";function o1(e,n){ds(ud,e,n)}function l1(e){return Vn(ud,e)||""}function ia(e){yr(ud,e)}function c1(e,n){ds(md,e,n)}function d1(e){return Vn(md,e)||""}function kl(e){yr(md,e)}function u1(e,n){ds(hd,e,n)}function m1(e){return Vn(hd,e)||""}function bi(e){yr(hd,e)}function h1(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 p1(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 f1(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 Ps({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=f1(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?h1(o):void 0,h=o.question&&m!==void 0?p1(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 qu="fusion-tab-id";function g1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Gi(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(qu);if(e)return e;const n=g1();return window.sessionStorage.setItem(qu,n),n}function Ko(e){const n=a.useMemo(()=>Gi(),[]),[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(Uk(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=Bk(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=ei(`/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(Hk(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const x1="fusion:ai-session-sync",Vu="fusion:ai-session-sync",b1=3e4,v1=6e4;function Ks(){return Date.now()}function y1(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Wu(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 j1{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=y1(),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:Ks()})}broadcastUpdate(n){const s=n.timestamp??Ks();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??Ks();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=Ks();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=Ks();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=Ks();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(x1),this.channel.onmessage=s=>{const i=Wu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Vu||!s.newValue))try{const i=JSON.parse(s.newValue),r=Wu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ks();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},b1)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=Ks();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(Vu,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:Ks()});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=Ks(),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>v1;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 Gs=new j1;function Ra(){const e=a.useSyncExternalStore(c=>Gs.subscribe(c),()=>Gs.getSnapshot(),()=>Gs.getSnapshot());a.useEffect(()=>{Gs.requestSync()},[]);const n=a.useCallback(c=>{Gs.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Gs.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Gs.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Gs.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Gs.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Gs.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function k1(e,n){return e&&n?`${e}/${n}`:""}function w1(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 N1=["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 S1({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,x]=a.useState([]),[v,b]=a.useState(null),[y,N]=a.useState(!1),k=a.useRef(!1),[R,w]=a.useState(""),[M,S]=a.useState(!0),[z,_]=a.useState(!1),[I,F]=a.useState(!1),[V,D]=a.useState(!1),E=a.useRef(null),$=a.useRef(null),B=a.useRef(null),J=a.useRef(null),[ie,C]=a.useState(o??null),P=a.useMemo(()=>Gi(),[]),{isLockedByOther:T,takeControl:j,isLoading:W}=Ko(e?ie:null),{activeTabMap:q,broadcastUpdate:ge,broadcastCompleted:be,broadcastLock:ce,broadcastUnlock:Se,broadcastHeartbeat:O}=Ra(),{confirm:le}=Hs(),[ee,pe]=a.useState(void 0),[ue,fe]=a.useState(void 0),[se,Ce]=a.useState([]),[De,qe]=a.useState(!0),[et,Qe]=a.useState(null),[Xe,it]=a.useState([]),[Ie,We]=a.useState([]),re=k1(ee,ue);a.useEffect(()=>{(async()=>{try{qe(!0);const de=await ms();Ce(de.models),it(de.favoriteProviders),We(de.favoriteModels)}catch(de){Qe(ke(de)||"Failed to load models")}finally{qe(!1)}})()},[]);const ve=a.useCallback(Y=>{it(de=>{const we=de,Z=we.includes(Y)?we.filter(Ge=>Ge!==Y):[Y,...we];return mn({favoriteProviders:Z,favoriteModels:Ie}).catch(()=>{it(we)}),Z})},[Ie]),te=a.useCallback(Y=>{We(de=>{const we=de,Z=we.includes(Y)?we.filter(Ge=>Ge!==Y):[Y,...we];return mn({favoriteProviders:Xe,favoriteModels:Z}).catch(()=>{We(we)}),Z})},[Xe]),Ae=a.useCallback((Y,de)=>{if(!Y||!de)return"Using default";const we=se.find(tt=>tt.provider===Y&&tt.id===de);return we?`${we.provider}/${we.id}`:`${Y}/${de}`},[se]),Fe=a.useCallback(Y=>{$.current?.close();const de=_k(Y,i,{onThinking:we=>{w(tt=>tt+we),ge({sessionId:Y,status:"generating",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:we=>{_(!1),F(!1),bi(i),d({type:"question",sessionId:Y,question:we}),w(""),N(!0),ge({sessionId:Y,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:we=>{_(!1),F(!1),bi(i),d({type:"summary",sessionId:Y,summary:we}),b(we),w(""),N(!0),ge({sessionId:Y,status:"complete",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:we=>{const tt=we||"Session failed while contacting the AI.";_(!1),F(!1),h(null),d({type:"error",sessionId:Y,errorMessage:tt}),w(""),N(!0),B.current=Y,ge({sessionId:Y,status:"error",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),be({sessionId:Y,status:"error"})},onComplete:()=>{_(!1),F(!1),B.current=null,be({sessionId:Y,status:"complete"})},onConnectionStateChange:we=>{_(we==="reconnecting")}});$.current=de},[be,ge,l,i,P]),he=a.useCallback(async Y=>{const de=Y??l;if(de.trim()){h(null),w(""),p([]),x([]),_(!1),d({type:"loading"});try{const{sessionId:we}=await Sk(de.trim(),i,ee&&ue?{modelProvider:ee,modelId:ue}:void 0);B.current=we,C(we),bi(i),Fe(we),p([])}catch(we){_(!1),h(ke(we)||"Failed to start interview session"),d({type:"initial"}),B.current=null,C(null)}}},[Fe,l,ee,ue,i]);a.useEffect(()=>{e&&u.type==="initial"&&E.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!k.current&&u.type==="initial"){c(r);const Y=setTimeout(()=>{k.current=!0,he(r)},0);return()=>clearTimeout(Y)}else if(e&&!r&&!k.current&&u.type==="initial"){const Y=m1(i);Y&&c(Y)}},[e,r,u.type,he]),a.useEffect(()=>{e||(k.current=!1,_(!1),F(!1),C(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let Y=!1;return ui(o).then(de=>{if(Y||!de)return;const we=ya(de.conversationHistory);if(x(we),C(de.id),p(we.map(tt=>tt.response).filter(tt=>!!(tt&&typeof tt=="object"&&!Array.isArray(tt)))),de.status==="awaiting_input"&&de.currentQuestion)try{bi(i);const tt=JSON.parse(de.currentQuestion);B.current=de.id,N(!0),d({type:"question",sessionId:de.id,question:tt})}catch{h("Failed to restore session question.")}else if(de.status==="complete"&&de.result)try{bi(i);const tt=JSON.parse(de.result);B.current=de.id,N(!0),b(tt),d({type:"summary",sessionId:de.id,summary:tt})}catch{h("Failed to restore session result.")}else de.status==="generating"?(B.current=de.id,N(!0),de.thinkingOutput&&w(de.thinkingOutput),d({type:"loading"}),Fe(de.id)):de.status==="error"&&(B.current=de.id,N(!0),h(null),d({type:"error",sessionId:de.id,errorMessage:de.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&&(Se(J.current,P),J.current=null);return}if(ie&&J.current!==ie){J.current&&Se(J.current,P),ce(ie,P),J.current=ie;return}!ie&&J.current&&(Se(J.current,P),J.current=null)},[ce,Se,e,ie,P]),a.useEffect(()=>{if(!e||!ie||J.current!==ie)return;O(P);const Y=setInterval(()=>{O(P)},3e4);return()=>{clearInterval(Y)}},[O,e,ie,P]),a.useEffect(()=>()=>{$.current?.close(),$.current=null,J.current&&(Se(J.current,P),J.current=null)},[Se,P]),a.useEffect(()=>{if(!e)return;const Y=de=>{(u.type==="question"||u.type==="summary")&&(de.preventDefault(),de.returnValue=""),$.current?.close()};return window.addEventListener("beforeunload",Y),()=>window.removeEventListener("beforeunload",Y)},[e,u]);const Me=a.useCallback(()=>{$.current?.close(),$.current=null,n()},[n]),Oe=a.useCallback(async()=>{if(l&&u1(l,i),!(y&&!await le({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if($.current?.close(),$.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await xp(u.sessionId,i,P)}catch{}c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),w(""),_(!1),F(!1),N(!1),D(!1),pe(void 0),fe(void 0),B.current=null,C(null),n()}},[l,y,u,n,i,P,le]);a.useEffect(()=>{if(!e)return;const Y=de=>{de.key==="Escape"&&Oe()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,Oe]);const at=a.useCallback(async Y=>{if(u.type!=="question")return;const{sessionId:de}=u;h(null),p(we=>[...we,Y]),x(we=>[...we,{question:u.question,response:Y}]),d({type:"loading"}),w("");try{Fe(de),await Ck(de,Y,i,P),N(!0)}catch(we){$.current?.close(),$.current=null,h(ke(we)||"Failed to submit response"),d({type:"question",sessionId:de,question:u.question})}},[u,i,P,Fe]),ye=a.useCallback(async()=>{if(u.type!=="error")return;const Y=u.sessionId;h(null),F(!0),w(""),d({type:"loading"}),Fe(Y);try{B.current=Y,C(Y),await Ek(Y,i,P)}catch(de){let we=de;if((ke(de)||"").includes("not in an error state"))try{const Z=await ui(Y);if(!Z)throw new Error("Failed to refresh interview session.");const Ge=ya(Z.conversationHistory);if(x(Ge),p(Ge.map(dt=>dt.response).filter(dt=>!!(dt&&typeof dt=="object"&&!Array.isArray(dt)))),B.current=Z.id,C(Z.id),N(!0),Z.status==="generating")w(Z.thinkingOutput??""),d({type:"loading"}),$.current?.isConnected()||Fe(Z.id);else if(Z.status==="awaiting_input"){if(!Z.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");bi(i);const dt=JSON.parse(Z.currentQuestion);d({type:"question",sessionId:Z.id,question:dt}),$.current?.isConnected()||Fe(Z.id)}else if(Z.status==="complete"){if(!Z.result)throw new Error("Interview session is complete but has no result.");bi(i);const dt=JSON.parse(Z.result);b(dt),d({type:"summary",sessionId:Z.id,summary:dt})}else Z.status==="error"&&d({type:"error",sessionId:Z.id,errorMessage:Z.error??"Retry failed. Please try again."});_(!1);return}catch(Z){we=Z}$.current?.close(),$.current=null,d({type:"error",sessionId:Y,errorMessage:ke(we)||"Retry failed. Please try again."}),_(!1)}finally{F(!1)}},[Fe,i,P,u]),oe=a.useCallback(async()=>{if(u.type==="summary"){h(null),D(!0);try{const Y=await Mk(u.sessionId,v||void 0,i);s(Y),bi(i),$.current?.close(),$.current=null,c(""),d({type:"initial"}),h(null),p([]),x([]),b(null),w(""),_(!1),F(!1),N(!1),D(!1),B.current=null,C(null),n()}catch(Y){h(ke(Y)||"Failed to create mission"),D(!1)}}},[u,v,s,n,i]),Te=()=>u.type==="question"?Math.min(g.length+1,6):6,me=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",_e=ie?q.get(ie):null,Ke=_e&&_e.tabId!==P,Re=!!(Ke&&!_e.stale),ct=T&&(!Ke||_e.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Y=>Y.target===Y.currentTarget&&Oe(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(us,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[me&&t.jsx("button",{className:"modal-send-to-background",onClick:Me,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Oe,"aria-label":"Close",children:t.jsx(Gt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),z&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Re&&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(Zn,{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:E,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(),he())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:N1.map((Y,de)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Y),children:Y.length>45?Y.slice(0,45)+"...":Y},de))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",De&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(qn,{id:"mission-interview-modal-model",label:"Planning Model",value:re,onChange:Y=>{const{provider:de,modelId:we}=w1(Y);pe(de),fe(we)},models:se,disabled:De,favoriteProviders:Xe,onToggleFavorite:ve,favoriteModels:Ie,onToggleModelFavorite:te}),et&&t.jsxs("div",{className:"form-hint form-hint-error",children:[et," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{qe(!0);const Y=await ms();Ce(Y.models),it(Y.favoriteProviders),We(Y.favoriteModels),Qe(null)}catch(Y){Qe(ke(Y)||"Failed to load models")}finally{qe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ee&&ue?"model-badge-custom":"model-badge-default"}`,children:Ae(ee,ue)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!l.trim(),children:[t.jsx(us,{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:R?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>S(!M),type:"button",children:M?"Hide thinking":"Show thinking"}),M&&R&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:R})})]})]}),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(Ps,{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 ye(),disabled:I,children:[I?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Tn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Oe,disabled:I,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(C1,{question:u.question,progress:Te(),historyEntries:f,onSubmit:at}),u.type==="summary"&&v&&t.jsx(E1,{summary:v,historyEntries:f,onSummaryChange:b,onApprove:oe,onStartOver:()=>{d({type:"initial"}),N(!1),b(null),p([]),x([]),C(null),$.current?.close(),$.current=null},isCreating:V}),T&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Lo,{size:16}),t.jsx("span",{children:ct?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),ct&&t.jsx("button",{type:"button",onClick:()=>{j()},disabled:W,className:"btn btn-primary session-lock-take-control",children:W?"Taking control...":"Take Control"})]})})]})]})}):null}function C1({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(Ps,{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(yn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Gt,{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 E1({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((k,R)=>R))),[u,d]=a.useState(()=>{const k=new Set;return e.milestones.forEach((R,w)=>{R.slices.forEach((M,S)=>k.add(`${w}-${S}`))}),k}),m=k=>{c(R=>{const w=new Set(R);return w.has(k)?w.delete(k):w.add(k),w})},h=k=>{d(R=>{const w=new Set(R);return w.has(k)?w.delete(k):w.add(k),w})},g=(k,R)=>{const w=[...e.milestones];w[k]={...w[k],...R},s({...e,milestones:w})},p=(k,R,w)=>{const M=[...e.milestones],S=[...M[k].slices];S[R]={...S[R],...w},M[k]={...M[k],slices:S},s({...e,milestones:M})},f=(k,R,w,M)=>{const S=[...e.milestones],z=[...S[k].slices],_=[...z[R].features];_[w]={..._[w],...M},z[R]={...z[R],features:_},S[k]={...S[k],slices:z},s({...e,milestones:S})},x=k=>{const R=e.milestones.filter((w,M)=>M!==k);s({...e,milestones:R})},v=(k,R)=>{const w=[...e.milestones];w[k]={...w[k],slices:w[k].slices.filter((M,S)=>S!==R)},s({...e,milestones:w})},b=(k,R,w)=>{const M=[...e.milestones],S=[...M[k].slices];S[R]={...S[R],features:S[R].features.filter((z,_)=>_!==w)},M[k]={...M[k],slices:S},s({...e,milestones:M})},y=(k,R)=>{const w=[...e.milestones],M=[...w[k].slices];M[R]={...M[R],features:[...M[R].features,{title:"New feature",description:""}]},w[k]={...w[k],slices:M},s({...e,milestones:w})},N=e.milestones.reduce((k,R)=>k+R.slices.reduce((w,M)=>w+M.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(Ps,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(yn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",N," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:k=>s({...e,missionTitle:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:k=>s({...e,missionDescription:k.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((k,R)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(R),children:[l.has(R)?t.jsx(Qt,{size:16,className:"icon-text-secondary"}):t.jsx(vn,{size:16,className:"icon-text-secondary"}),t.jsx(Bi,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:k.title,onChange:w=>g(R,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),x(R)},title:"Remove milestone",children:t.jsx(sn,{size:14,className:"icon-text-secondary"})})]}),l.has(R)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:k.description||"",onChange:w=>g(R,{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:k.verification||"",onChange:w=>g(R,{verification:w.target.value})})]}),k.slices.map((w,M)=>{const S=`${R}-${M}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(S),children:[u.has(S)?t.jsx(Qt,{size:14,className:"icon-text-secondary"}):t.jsx(vn,{size:14,className:"icon-text-secondary"}),t.jsx(wc,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:z=>p(R,M,{title:z.target.value}),onClick:z=>z.stopPropagation()}),k.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:z=>{z.stopPropagation(),v(R,M)},title:"Remove slice",children:t.jsx(sn,{size:12,className:"icon-text-secondary"})})]}),u.has(S)&&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:z=>p(R,M,{verification:z.target.value})})]}),w.features.map((z,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(gc,{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:z.title,onChange:I=>f(R,M,_,{title:I.target.value})}),z.description&&t.jsx("p",{className:"roadmap-feature-text",children:z.description}),z.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",z.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(R,M,_),title:"Remove feature",children:t.jsx(sn,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(R,M),children:[t.jsx(an,{size:12}),"Add Feature"]})]})]},M)})]})]},R))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ma,{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(yn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function M1({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([]),[x,v]=a.useState([]),[b,y]=a.useState(null),[N,k]=a.useState(""),[R,w]=a.useState(!0),[M,S]=a.useState(!1),[z,_]=a.useState(!1),I=a.useRef(null),F=a.useRef(null),V=a.useRef(null),D=a.useRef(null),[E,$]=a.useState(null),B=a.useMemo(()=>Gi(),[]);Ko(e?E:null);const{activeTabMap:J,broadcastUpdate:ie,broadcastCompleted:C,broadcastLock:P,broadcastUnlock:T,broadcastHeartbeat:j}=Ra(),W=i==="milestone"?Ak:$k,q=i==="milestone"?Rk:Dk,ge=i==="milestone"?Tk:Lk,be=i==="milestone"?Pk:zk,ce=i==="milestone"?Ik:Ok,Se=i==="milestone"?"Milestone":"Slice",O=i==="milestone"?"milestone_interview":"slice_interview",le=a.useCallback(Ie=>{F.current?.close();const We=ge(Ie,c,{onThinking:re=>{k(ve=>ve+re),ie({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:B,type:O,title:o,projectId:c??null})},onQuestion:re=>{S(!1),ee(),m({type:"question",sessionId:Ie,question:re}),k(""),ie({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:B,type:O,title:o,projectId:c??null})},onSummary:re=>{S(!1),ee(),m({type:"summary",sessionId:Ie,summary:re}),y(re),k(""),ie({sessionId:Ie,status:"complete",needsInput:!1,owningTabId:B,type:O,title:o,projectId:c??null})},onError:re=>{const ve=re||"Session failed while contacting the AI.";S(!1),g(null),m({type:"error",sessionId:Ie,errorMessage:ve}),k(""),V.current=Ie,ie({sessionId:Ie,status:"error",needsInput:!1,owningTabId:B,type:O,title:o,projectId:c??null}),C({sessionId:Ie,status:"error"})},onComplete:()=>{S(!1),V.current=null,C({sessionId:Ie,status:"complete"})},onConnectionStateChange:re=>{S(re==="reconnecting")}});F.current=We},[C,ie,ge,O,c,B,o]),ee=()=>{y(null),f([]),v([]),k("")},pe=a.useCallback(async()=>{g(null),ee(),S(!1),m({type:"loading"});try{const{sessionId:Ie}=await W(r,c);V.current=Ie,$(Ie),le(Ie)}catch(Ie){S(!1),g(ke(Ie)||`Failed to start ${Se.toLowerCase()} interview`),m({type:"initial"}),V.current=null,$(null)}},[le,c,W,r,Se]),ue=a.useCallback(async()=>{g(null),_(!0);try{await ce(r,c),s(),m({type:"applied"})}catch(Ie){g(ke(Ie)||`Failed to skip ${Se.toLowerCase()} interview`),_(!1)}},[s,c,ce,r,Se]);a.useEffect(()=>{e&&d.type==="initial"&&I.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let Ie=!1;return ui(u).then(We=>{if(Ie||!We)return;const re=ya(We.conversationHistory);if(v(re),$(We.id),f(re.map(ve=>ve.response).filter(ve=>!!(ve&&typeof ve=="object"&&!Array.isArray(ve)))),We.status==="awaiting_input"&&We.currentQuestion)try{const ve=JSON.parse(We.currentQuestion);V.current=We.id,m({type:"question",sessionId:We.id,question:ve})}catch{g("Failed to restore session question.")}else if(We.status==="complete"&&We.result)try{const ve=JSON.parse(We.result);V.current=We.id,y(ve),m({type:"summary",sessionId:We.id,summary:ve})}catch{g("Failed to restore session result.")}else We.status==="generating"?(V.current=We.id,We.thinkingOutput&&k(We.thinkingOutput),m({type:"loading"}),le(We.id)):We.status==="error"&&(V.current=We.id,g(null),m({type:"error",sessionId:We.id,errorMessage:We.error??"The session encountered an error."}))}).catch(()=>{Ie||g("Failed to resume session.")}),()=>{Ie=!0}},[le,e,u,d.type]),a.useEffect(()=>{e||(S(!1),$(null))},[e]),a.useEffect(()=>{if(!(!e||!E)){if(D.current!==E){D.current&&T(D.current,B),P(E,B),D.current=E;return}!E&&D.current&&(T(D.current,B),D.current=null)}},[P,T,e,E,B]),a.useEffect(()=>{if(!e||!E||D.current!==E)return;j(B);const Ie=setInterval(()=>{j(B)},3e4);return()=>{clearInterval(Ie)}},[j,e,E,B]),a.useEffect(()=>()=>{F.current?.close(),F.current=null,D.current&&(T(D.current,B),D.current=null)},[T,B]);const fe=a.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),se=a.useCallback(async()=>{F.current?.close(),F.current=null,ee(),m({type:"initial"}),g(null),V.current=null,$(null),n()},[n]),Ce=a.useCallback(async Ie=>{if(d.type!=="question")return;const{sessionId:We}=d;g(null),f(re=>[...re,Ie]),v(re=>[...re,{question:d.question,response:Ie}]),m({type:"loading"}),k("");try{le(We),await q(We,Ie,c,B)}catch(re){F.current?.close(),F.current=null,g(ke(re)||"Failed to submit response"),m({type:"question",sessionId:We,question:d.question})}},[le,c,q,B,d]),De=a.useCallback(async()=>{if(d.type==="summary"){g(null),_(!0);try{await be(d.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(Ie){g(ke(Ie)||"Failed to apply interview results"),_(!1)}}},[be,b,s,c,d]),qe=()=>d.type==="question"?Math.min(p.length+1,6):6,et=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Qe=E?J.get(E):null,it=!!(Qe&&Qe.tabId!==B&&!Qe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&se(),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(Zn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",Se,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[et&&t.jsx("button",{className:"modal-send-to-background",onClick:fe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:se,"aria-label":"Close",children:t.jsx(Gt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),M&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),it&&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(Zn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",Se," 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 pe(),children:[t.jsx(Zn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ue(),disabled:z,children:[z?t.jsx(rt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:se,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:N?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&N&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:N})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[x.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ps,{entries:x}),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:se,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(_1,{question:d.question,progress:qe(),historyEntries:x,onSubmit:Ce}),d.type==="summary"&&b&&t.jsx(A1,{summary:b,historyEntries:x,onSummaryChange:y,onApply:De,onCancel:se,isApplying:z}),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(yn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[Se," 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 _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(Ps,{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(yn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Gt,{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 A1({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(Ps,{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(Qt,{size:16}):t.jsx(vn,{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 Ba={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"},archived:{bg:"var(--mission-archived-bg)",text:"var(--mission-archived-text)"}},Ku={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)"}},Gu={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)"}},Gr={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)"}},Jr={inactive:{bg:"var(--autopilot-inactive-bg)",text:"var(--autopilot-inactive-text)"},watching:{bg:"var(--autopilot-watching-bg)",text:"var(--autopilot-watching-text)"},activating:{bg:"var(--autopilot-activating-bg)",text:"var(--autopilot-activating-text)"},completing:{bg:"var(--autopilot-completing-bg)",text:"var(--autopilot-completing-text)"}},Yr={pending:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},passed:{bg:"var(--assertion-passed-bg)",text:"var(--assertion-passed-text)"},failed:{bg:"var(--assertion-failed-bg)",text:"var(--assertion-failed-text)"},blocked:{bg:"var(--assertion-blocked-bg)",text:"var(--assertion-blocked-text)"}},Ju={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)"}},R1=3;function T1(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Yu({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 Qu(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const wl={title:"",description:"",status:"planning",autopilotEnabled:!1},Nl={title:"",description:"",status:"planning",dependencies:[]},Sl={title:"",description:"",status:"pending"},Cl={title:"",description:"",acceptanceCriteria:"",status:"defined"},P1=3600*1e3;function No(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 I1(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=P1,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 $1(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 D1(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 El(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 Fp=["feature_triaged","feature_completed"],Up=["slice_activated","slice_completed","milestone_completed"],Bp=["mission_started","mission_paused","mission_resumed","mission_completed"],Hp=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Xu(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Bp.includes(e);case"tasks":return Fp.includes(e);case"slices":return Up.includes(e);case"autopilot":return Hp.includes(e);default:return!0}}function L1(e){return e==="error"||e==="warning"?"mission-event__type--error":Bp.includes(e)?"mission-event__type--state":Fp.includes(e)?"mission-event__type--task":Up.includes(e)?"mission-event__type--slice":Hp.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function z1(e){return e.replace(/_/g," ")}function O1(e,n){return n?e==="watching"?`Watching since ${No(n)}`:`Last activation ${No(n)}`:null}function F1({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,x]=a.useState(null),[v,b]=a.useState(!0),[y,N]=a.useState(!1),[k,R]=a.useState(!1),[w,M]=a.useState(null),[S,z]=a.useState(wl),[_,I]=a.useState(!1),[F,V]=a.useState(new Set),[D,E]=a.useState(new Set),[$,B]=a.useState(null),[J,ie]=a.useState(Nl),[C,P]=a.useState(!1),[T,j]=a.useState(null),[W,q]=a.useState(Sl),[ge,be]=a.useState(!1),[ce,Se]=a.useState(null),[O,le]=a.useState(null),[ee,pe]=a.useState(Cl),[ue,fe]=a.useState(!1),[se,Ce]=a.useState(null),[De,qe]=a.useState(null),[et,Qe]=a.useState(""),[Xe,it]=a.useState(!1),[Ie,We]=a.useState([]),[re,ve]=a.useState(void 0),te=re??c,[Ae,Fe]=a.useState(null),[he,Me]=a.useState(null),[Oe,at]=a.useState(null);a.useEffect(()=>{h&&te&&it(!0)},[h,te]),a.useEffect(()=>{if(!h||te)return;let U=!1;return sd(r).then(Ne=>{if(U)return;const $e=Ne.filter(gt=>gt.type==="mission_interview"&&(gt.status==="awaiting_input"||gt.status==="error"));We($e)}).catch(Ne=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ne)}),()=>{U=!0}},[h,r,te]),a.useEffect(()=>{if(!h||!d)return;let U=!1;return ui(d).then(Ne=>{if(!(U||!Ne))try{const $e=JSON.parse(Ne.inputPayload||"{}");$e.targetId&&$e.targetType&&Fe({type:$e.targetType,id:$e.targetId,title:$e.targetTitle||Ne.title,resumeSessionId:d})}catch{Fe({type:"milestone",id:"",title:Ne.title,resumeSessionId:d})}}).catch(Ne=>{U||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ne),m?.())}),()=>{U=!0}},[h,d,m]);const[ye,oe]=a.useState(null),[Te,me]=a.useState(new Map),[_e,Ke]=a.useState(null),[Re,ct]=a.useState({title:"",assertion:"",status:"pending"}),[Y,de]=a.useState(!1),[we,tt]=a.useState(null),[Z,Ge]=a.useState(new Map),[dt,pt]=a.useState(new Set),[jt,yt]=a.useState(new Set),[ft,St]=a.useState(null),[Ot,Vt]=a.useState(new Map),[Mt,It]=a.useState(null),[qt,Ft]=a.useState(null),[Xt,$t]=a.useState(!0),[_t,Ct]=a.useState(new Set),[Et,tn]=a.useState(new Map),[At,H]=a.useState(null),[xe,Le]=a.useState(new Map),[A,X]=a.useState(null),[ze,ot]=a.useState(new Map),[Rt,Tt]=a.useState(new Map),[Pt,ln]=a.useState("structure"),[kn,_n]=a.useState([]),Yt=a.useRef([]),An=a.useRef([]),je=a.useRef(null),ae=a.useRef(null),Je=a.useRef("structure"),ut=a.useRef("all"),[Dt,Wt]=a.useState(!1),[Mn,on]=a.useState(0),[Ut,G]=a.useState("all"),[Pe,Ye]=a.useState(new Set),nt=a.useRef(null),mt=a.useRef(null);An.current=g,je.current=f,ae.current=Mt,Je.current=Pt,ut.current=Ut;const Nt=a.useCallback((U="auto")=>{const Ne=mt.current;if(Ne&&typeof Ne.scrollIntoView=="function"){Ne.scrollIntoView({block:"end",behavior:U});return}const $e=nt.current;$e&&($e.scrollTop=$e.scrollHeight)},[]),Lt=a.useCallback(()=>{const U=nt.current;return U?U.scrollHeight-U.scrollTop-U.clientHeight<=100:!0},[]),Cn=a.useCallback(async U=>{if(U.length===0){Tt(new Map);return}const Ne=await Xj(r);Tt($e=>{const gt=new Map($e);for(const[gn,Bt]of Object.entries(Ne))$1(Bt)&&gt.set(gn,Bt);return gt})},[r]),rn=a.useCallback(async()=>{try{b(!0);const U=await Kj(r);p(U),Cn(U)}catch(U){i(ke(U)||"Failed to load missions","error")}finally{b(!1)}},[i,r,Cn]),kt=a.useCallback(async U=>{try{N(!0);const Ne=await gp(U,r);if(x(Ne),Ne.milestones.length>0){const $e=Ne.milestones[0].id;It($e),$t(!0),V(new Set([$e])),dl($e,r).then(gt=>{me(gn=>{const Bt=new Map(gn);return Bt.set($e,gt),Bt})}).catch(()=>{}),ul($e,r).then(gt=>{Vt(gn=>{const Bt=new Map(gn);return Bt.set($e,gt),Bt})}).catch(()=>{}),Ne.milestones[0].slices.length>0&&E(new Set([Ne.milestones[0].slices[0].id]))}else It(null),Ft(null)}catch(Ne){i(ke(Ne)||"Failed to load mission details","error")}finally{N(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Mt){Ft(null);return}let U=!1;return Ft(null),au(Mt,r).then(Ne=>{if(!U){if(!El(Ne)){Ft(null);return}Ft(Ne),Vt($e=>{const gt=new Map($e);return gt.set(Mt,Ne.rollup),gt})}}).catch(()=>{U||Ft(null)}),()=>{U=!0}},[h,Mt,r]),a.useEffect(()=>{$t(!0)},[Mt]);const os=a.useCallback(U=>{!U||U!==ae.current||au(U,r).then(Ne=>{ae.current!==U||!El(Ne)||(Ft(Ne),Vt($e=>{const gt=new Map($e);return gt.set(U,Ne.rollup),gt}))}).catch(()=>{})},[r]),ks=a.useCallback(async(U,Ne)=>{const $e=Ne?.append??!1,gt=$e?Yt.current.length:0;$e||(Wt(!0),Ye(new Set));try{const gn=await Qj(U,{limit:50,offset:gt,eventType:void 0},r),Bt=gn.events.filter(nn=>Xu(nn.eventType,Ut));_n(nn=>{if(!$e)return Bt;const He=new Set(nn.map(bt=>bt.id)),Ve=[...nn];for(const bt of Bt)He.has(bt.id)||Ve.push(bt);return Ve}),on(gn.total),$e||requestAnimationFrame(()=>{Nt("auto")})}catch(gn){i(ke(gn)||"Failed to load mission activity","error")}finally{$e||Wt(!1)}},[i,Ut,r,Nt]);a.useEffect(()=>{Yt.current=kn},[kn]),a.useEffect(()=>{h&&(rn(),x(null),It(null),Ft(null),_n([]),on(0),ln("structure"),G("all"),Ye(new Set))},[h,rn]);const Is=a.useRef(null);a.useEffect(()=>{h&&u&&Is.current!==u&&g.length>0&&(Is.current=u,kt(u))},[h,u,g,kt]),a.useEffect(()=>{h||(Is.current=null)},[h]),a.useEffect(()=>{!h||!f||Pt!=="activity"||ks(f.id)},[Pt,h,ks,f,Ut]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const U=new URLSearchParams;r&&U.set("projectId",r);const Ne=`/api/events${U.size>0?`?${U.toString()}`:""}`,$e=()=>{Cn(An.current)},gt=Yn=>{$e();const En=Yn;if(En.data)try{const Kt=JSON.parse(En.data);Kt?.id&&p(Ti=>Ti.map(Es=>Es.id===Kt.id?{...Es,...Kt}:Es))}catch{}je.current&&kt(je.current.id)},gn=Yn=>{$e(),je.current&&kt(je.current.id)},Bt=()=>{$e(),je.current&&kt(je.current.id)},nn=Yn=>{$e(),je.current&&kt(je.current.id)},He=Yn=>{const En=Yn;if(En.data)try{const Kt=JSON.parse(En.data);Kt&&Kt.featureId&&(Pn(Kt.featureId),ri(Kt.featureId),Kt.milestoneId&&os(Kt.milestoneId))}catch{}},Ve=Yn=>{const En=Yn;if(En.data)try{const Kt=JSON.parse(En.data);Kt&&Kt.featureId&&(Pn(Kt.featureId),ri(Kt.featureId),Kt.milestoneId&&os(Kt.milestoneId),je.current&&kt(je.current.id))}catch{}},bt=Yn=>{const En=Yn;if(En.data)try{const Kt=JSON.parse(En.data);Kt&&Kt.milestoneId&&(Un(Kt.milestoneId),os(Kt.milestoneId))}catch{}},xn=Yn=>{const En=Yn;if(En.data)try{const Kt=JSON.parse(En.data);Kt&&Kt.milestoneId&&(dn(Kt.milestoneId),Un(Kt.milestoneId),os(Kt.milestoneId))}catch{}};return qs(Ne,{events:{"mission:updated":gt,"slice:updated":gn,"feature:updated":Bt,"milestone:updated":nn,"mission:event":Yn=>{$e();const En=je.current;if(!En||Je.current!=="activity")return;const Kt=Lt(),Ti=Yn;if(Ti.data)try{const Es=JSON.parse(Ti.data);if(!D1(Es)||Es.missionId!==En.id||!Xu(Es.eventType,ut.current))return;_n(li=>{const al=li.filter(rl=>rl.id!==Es.id);return[Es,...al].slice(0,100)}),on(li=>li+1),Kt&&requestAnimationFrame(()=>{const li=nt.current;li&&(li.scrollTop=0)})}catch{}},"validator-run:started":He,"validator-run:completed":Ve,"milestone:validation:updated":bt,"assertion:created":xn,"assertion:updated":xn,"assertion:deleted":xn,"assertion:linked":xn,"assertion:unlinked":xn,"fix-feature:created":Yn=>{const En=Yn;if(En.data)try{const Kt=JSON.parse(En.data);if(Kt&&Kt.sourceFeatureId){Pn(Kt.sourceFeatureId);const Ti=Kt?.feature?.sliceId,Es=je.current;if(Ti&&Es){const li=Es.milestones.find(al=>al.slices.some(rl=>rl.id===Ti));li&&os(li.id)}je.current&&kt(je.current.id)}}catch{}}}})},[h,Lt,kt,Cn,r,os]);const ws=a.useCallback(()=>{R(!0),M(null),z(wl)},[]),si=a.useCallback(U=>{M(U.id),R(!1),z({title:U.title,description:U.description||"",status:U.status,autopilotEnabled:U.autopilotEnabled??!1})},[]),$s=a.useCallback(()=>{M(null),R(!1),z(wl)},[]),Ds=a.useCallback(async()=>{if(!S.title.trim()){i("Mission title is required","error");return}try{if(I(!0),k)await Gj({title:S.title.trim(),description:S.description.trim()||void 0,autopilotEnabled:S.autopilotEnabled},r),i("Mission created","success");else if(w){const U={title:S.title.trim(),description:S.description.trim()||void 0,status:S.status,autopilotEnabled:S.autopilotEnabled};S.autopilotEnabled&&(U.autoAdvance=!0),await Jj(w,U,r),i("Mission updated","success"),f?.id===w&&await kt(w)}await rn(),$s()}catch(U){i(ke(U)||"Failed to save mission","error")}finally{I(!1)}},[S,k,w,i,rn,kt,f,$s,r]),Yi=a.useCallback(async U=>{try{await Yj(U,r),i("Mission deleted","success"),f?.id===U&&x(null),await rn(),oe(null)}catch(Ne){i(ke(Ne)||"Failed to delete mission","error")}},[i,rn,f,r]),ii=a.useCallback(()=>{P(!0),B(null),ie(Nl)},[]),ai=a.useCallback(U=>{B(U.id),P(!1),ie({title:U.title,description:U.description||"",status:U.status,dependencies:U.dependencies})},[]),ht=a.useCallback(()=>{B(null),P(!1),ie(Nl)},[]),pn=a.useCallback(async()=>{if(!J.title.trim()){i("Milestone title is required","error");return}try{I(!0),C&&f?(await Zj(f.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),i("Milestone created","success")):$&&(await ek($,{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),ht()}catch(U){i(ke(U)||"Failed to save milestone","error")}finally{I(!1)}},[J,C,$,f,i,kt,ht,S.title,r]),ne=a.useCallback(async U=>{try{await tk(U,r),i("Milestone deleted","success"),await kt(f.id),oe(null)}catch(Ne){i(ke(Ne)||"Failed to delete milestone","error")}},[i,kt,f,r]),Ee=a.useCallback(U=>{It(U),$t(!0),V(Ne=>{const $e=new Set(Ne);return!$e.has(U)?($e.add(U),dl(U,r).then(gn=>{me(Bt=>{const nn=new Map(Bt);return nn.set(U,gn),nn})}).catch(()=>{}),ul(U,r).then(gn=>{Vt(Bt=>{const nn=new Map(Bt);return nn.set(U,gn),nn})}).catch(()=>{})):$e.delete(U),$e})},[r]),Ze=a.useCallback(U=>{Se(U),be(!0),j(null),q(Sl)},[]),vt=a.useCallback(U=>{j(U.id),be(!1),q({title:U.title,description:U.description||"",status:U.status})},[]),xt=a.useCallback(()=>{j(null),be(!1),Se(null),q(Sl)},[]),jn=a.useCallback(async()=>{if(!W.title.trim()){i("Slice title is required","error");return}try{I(!0),ge&&ce?(await nk(ce,{title:W.title.trim(),description:W.description.trim()||void 0},r),i("Slice created","success")):T&&(await sk(T,{title:W.title.trim(),description:W.description.trim()||void 0,status:W.status},r),i("Slice updated","success")),await kt(f.id),xt()}catch(U){i(ke(U)||"Failed to save slice","error")}finally{I(!1)}},[W,ge,T,ce,f,i,kt,xt,r]),en=a.useCallback(async U=>{try{await ik(U,r),i("Slice deleted","success"),await kt(f.id),oe(null)}catch(Ne){i(ke(Ne)||"Failed to delete slice","error")}},[i,kt,f,r]),cn=a.useCallback(async U=>{try{await ak(U,r),i("Slice activated","success"),await kt(f.id)}catch(Ne){i(ke(Ne)||"Failed to activate slice","error")}},[i,kt,f,r]),fn=a.useCallback(U=>{E(Ne=>{const $e=new Set(Ne);return $e.has(U)?$e.delete(U):$e.add(U),$e})},[]),Dn=a.useCallback(U=>{Ce(U),fe(!0),le(null),pe(Cl)},[]),Wn=a.useCallback(U=>{le(U.id),fe(!1),pe({title:U.title,description:U.description||"",acceptanceCriteria:U.acceptanceCriteria||"",status:U.status})},[]),Kn=a.useCallback(()=>{le(null),fe(!1),Ce(null),pe(Cl)},[]),Rn=a.useCallback(async()=>{if(!ee.title.trim()){i("Feature title is required","error");return}try{I(!0),ue&&se?(await rk(se,{title:ee.title.trim(),description:ee.description.trim()||void 0,acceptanceCriteria:ee.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):O&&(await ok(O,{title:ee.title.trim(),description:ee.description.trim()||void 0,acceptanceCriteria:ee.acceptanceCriteria.trim()||void 0,status:ee.status},r),i("Feature updated","success")),await kt(f.id),Kn()}catch(U){i(ke(U)||"Failed to save feature","error")}finally{I(!1)}},[ee,ue,O,se,f,i,kt,Kn,r]),Gn=a.useCallback(async U=>{try{await lk(U,r),i("Feature deleted","success"),await kt(f.id),oe(null)}catch(Ne){i(ke(Ne)||"Failed to delete feature","error")}},[i,kt,f,r]),On=a.useCallback(async()=>{if(!De||!et.trim()){i("Task ID is required","error");return}try{await ck(De,et.trim(),r),i("Feature linked to task","success"),await kt(f.id),qe(null),Qe("")}catch(U){i(ke(U)||"Failed to link feature to task","error")}},[De,et,i,kt,f,r]),ps=a.useCallback(async U=>{try{await dk(U,r),i("Feature unlinked from task","success"),await kt(f.id)}catch(Ne){i(ke(Ne)||"Failed to unlink feature","error")}},[i,kt,f,r]),wn=a.useCallback(async U=>{try{I(!0),await uk(U,void 0,void 0,r),i("Feature triaged — task created","success"),await kt(f.id)}catch(Ne){i(ke(Ne)||"Failed to triage feature","error")}finally{I(!1)}},[i,kt,f,r]),Fn=a.useCallback(async U=>{at(U);try{const Ne=await Fk(U,r);Me({featureId:U,enrichedDescription:Ne.description})}catch{await wn(U)}finally{at(null)}},[wn,r]),ls=a.useCallback(async()=>{he&&(Me(null),await wn(he.featureId))},[wn,he]),Ns=a.useCallback(()=>{Me(null)},[]),ts=a.useCallback(async U=>{try{I(!0);const Ne=await mk(U,r);i(`Triaged ${Ne.count} feature${Ne.count!==1?"s":""}`,"success"),await kt(f.id)}catch(Ne){i(ke(Ne)||"Failed to triage slice features","error")}finally{I(!1)}},[i,kt,f,r]),dn=a.useCallback(async U=>{try{const Ne=await dl(U,r);me($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch{}},[r]),Un=a.useCallback(async U=>{try{const Ne=await ul(U,r);Vt($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch{}},[r]),Ls=a.useCallback(async U=>{if(!Re.title.trim()||!Re.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await hk(U,{title:Re.title.trim(),assertion:Re.assertion.trim(),status:Re.status},r),i("Assertion created","success"),await dn(U),await Un(U),de(!1),ct({title:"",assertion:"",status:"pending"})}catch(Ne){i(ke(Ne)||"Failed to create assertion","error")}finally{I(!1)}},[Re,i,dn,Un,r]),Zo=a.useCallback(U=>{Ke(U.id),ct({title:U.title,assertion:U.assertion,status:U.status})},[]),Ei=a.useCallback(()=>{Ke(null),de(!1),ct({title:"",assertion:"",status:"pending"})},[]),Lr=a.useCallback(async(U,Ne)=>{if(!Re.title.trim()||!Re.assertion.trim()){i("Title and assertion text are required","error");return}try{I(!0),await pk(U,{title:Re.title.trim(),assertion:Re.assertion.trim(),status:Re.status},r),i("Assertion updated","success"),await dn(Ne),await Un(Ne),Ei()}catch($e){i(ke($e)||"Failed to update assertion","error")}finally{I(!1)}},[Re,i,dn,Un,Ei,r]),zs=a.useCallback(async U=>{try{const Ne=await xk(U,r);Ge($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch{}},[r]),zr=a.useCallback(async U=>{const Ne=we!==U;tt($e=>$e===U?null:U),Ne&&await zs(U)},[we,zs]),Or=a.useCallback(U=>{tt(U),zs(U),requestAnimationFrame(()=>{const Ne=document.querySelector(`[data-mission-assertion-id="${U}"]`);Ne instanceof HTMLElement&&typeof Ne.scrollIntoView=="function"&&Ne.scrollIntoView({behavior:"smooth",block:"center"})})},[zs]),Fr=a.useCallback(async(U,Ne)=>{try{pt($e=>new Set($e).add(Ne)),await fk(U,Ne,r),i("Feature linked to assertion","success"),await zs(Ne),St(null)}catch($e){i(ke($e)||"Failed to link feature","error")}finally{pt($e=>{const gt=new Set($e);return gt.delete(Ne),gt})}},[i,zs,r]),Jn=a.useCallback(async(U,Ne)=>{const $e=`${U}-${Ne}`;try{yt(gt=>new Set(gt).add($e)),await gk(U,Ne,r),i("Feature unlinked from assertion","success"),await zs(Ne)}catch(gt){i(ke(gt)||"Failed to unlink feature","error")}finally{yt(gt=>{const gn=new Set(gt);return gn.delete($e),gn})}},[i,zs,r]),Ia=a.useCallback(async U=>{try{Ct($e=>new Set($e).add(U)),await bk(U,r),i("Validation triggered","success");const Ne=await ru(U,r);tn($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch(Ne){i(ke(Ne)||"Failed to trigger validation","error")}finally{Ct(Ne=>{const $e=new Set(Ne);return $e.delete(U),$e})}},[i,r]),Pn=a.useCallback(async U=>{try{const Ne=await ru(U,r);tn($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch{}},[r]),ri=a.useCallback(async U=>{try{const Ne=await vk(U,{limit:10},r);Le($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch{}},[r]),Mi=a.useCallback(U=>{const Ne=je.current;if(Ne){for(const $e of Ne.milestones)for(const gt of $e.slices)if(gt.features.find(Bt=>Bt.id===U)){V(Bt=>{const nn=new Set(Bt);return nn.add($e.id),nn}),E(Bt=>{const nn=new Set(Bt);return nn.add(gt.id),nn}),H(U),It($e.id),Pn(U),ri(U),requestAnimationFrame(()=>{const Bt=document.querySelector(`[data-mission-feature-id="${U}"]`);Bt instanceof HTMLElement&&typeof Bt.scrollIntoView=="function"&&Bt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Pn,ri]),$a=a.useCallback(async U=>{try{const Ne=await yk(U,r);ot($e=>{const gt=new Map($e);return gt.set(U,Ne),gt})}catch{}},[r]),Qi=a.useCallback(async U=>{At===U?H(null):(H(U),await Pn(U),await ri(U))},[At,Pn,ri]),el=a.useCallback(async U=>{A===U?X(null):(X(U),await $a(U))},[A,$a]),Da=a.useCallback(async U=>{try{await jk(U,r),i("Mission resumed","success"),await kt(U),rn()}catch(Ne){i(ke(Ne)||"Failed to resume mission","error")}},[i,kt,rn,r]),Q=a.useCallback(async U=>{try{const $e=(await kk(U,r)).pausedTaskIds?.length??0;i(`Mission stopped (${$e} task${$e!==1?"s":""} paused)`,"success"),await kt(U),rn()}catch(Ne){i(ke(Ne)||"Failed to stop mission","error")}},[i,kt,rn,r]),Be=a.useCallback(async U=>{try{await wk(U,r),i("Mission started — first slice activated","success"),await kt(U),rn()}catch(Ne){i(ke(Ne)||"Failed to start mission","error")}},[i,kt,rn,r]),lt=a.useCallback(async(U,Ne)=>{try{await Nk(U,{enabled:Ne},r),i(Ne?"Autopilot enabled":"Autopilot disabled","success"),await kt(U),rn()}catch($e){i(ke($e)||"Failed to update autopilot","error")}},[i,kt,rn,r]),zt=a.useCallback(U=>{ln("structure"),It(null),Ft(null),_n([]),on(0),G("all"),Ye(new Set),kt(U.id)},[kt]),Vs=a.useCallback(()=>{x(null),It(null),Ft(null),ln("structure"),_n([]),on(0),G("all"),Ye(new Set),rn()},[rn]),fs=kn.length<Mn,xi=f?.autopilotState??"inactive",La=xi==="watching"||xi==="activating",Ur=O1(xi,f?.lastAutopilotActivityAt),Xi=a.useMemo(()=>!qt||!Mt||!El(qt)?null:qt.rollup.milestoneId===Mt?qt:null,[Mt,qt]),tl=a.useMemo(()=>{const U=new Map;for(const Ne of Xi?.validationTelemetry.validationRounds??[]){const $e=U.get(Ne.featureId);(!$e||Ne.startedAt>$e.startedAt)&&U.set(Ne.featureId,Ne)}return U},[Xi]),nl=a.useCallback(()=>{!f||Dt||!fs||ks(f.id,{append:!0})},[Dt,fs,ks,f]),sl=a.useCallback(U=>{Ye(Ne=>{const $e=new Set(Ne);return $e.has(U)?$e.delete(U):$e.add(U),$e})},[]),_i=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Ds())},[Ds]),Zi=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),pn())},[pn]),Ai=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),jn())},[jn]),ea=a.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Rn())},[Rn]),Pd=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const U=Ne=>{Ne.key==="Escape"&&s()};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[h,s]),!h)return null;const il=t.jsxs("div",{ref:Pd,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:Vs,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Po,{size:18})}):null,t.jsx(us,{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(Gt,{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:[La&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(Ba[f.status]||Ba.planning).bg,color:(Ba[f.status]||Ba.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:U=>lt(f.id,U.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(Bn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Jr[xi]||Jr.inactive).bg,color:(Jr[xi]||Jr.inactive).text},"data-testid":"autopilot-state-badge",children:[La&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),xi]})]}),Ur&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Ur})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Q(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(xs,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Da(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Sn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Be(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>si(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(sn,{size:14})})]})]}),w===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:U=>z({...S,title:U.target.value}),onKeyDown:_i,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:U=>z({...S,description:U.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:U=>z({...S,status:U.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:S.autopilotEnabled,onChange:U=>z({...S,autopilotEnabled:U.target.checked})}),t.jsx(Bn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ds,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$s,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Pt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>ln("structure"),role:"tab","aria-selected":Pt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Pt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>ln("activity"),role:"tab","aria-selected":Pt==="activity","data-testid":"mission-tab-activity",children:["Activity (",Mn,")"]})]}),Pt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(U=>{const Ne=Xi?.rollup.milestoneId===U.id?Xi:null,$e=Ne?.rollup??Ot.get(U.id),gt=Ne?.validationTelemetry.validationRounds??[],gn=Ne?.fixFeatures??[],Bt=Ju[$e?.state??"not_started"]??Ju.not_started,nn=$e&&($e.state==="blocked"||$e.state==="failed")?Ne?.validationTelemetry.validationRounds.find(He=>He.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Ee(U.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:F.has(U.id)?t.jsx(Qt,{size:16}):t.jsx(vn,{size:16})}),t.jsx(Bi,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:U.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ku[U.status].bg,color:Ku[U.status].text},children:U.status}),t.jsxs("span",{className:"mission-milestone__count",children:[U.slices.length," slices"]}),t.jsx(Yu,{state:T1(U.interviewState)}),$e&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bt.bg,color:Bt.text},title:"Validation state",children:Qu($e.state)}),$e.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${$e.passedAssertions??0} of ${$e.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${($e.passedAssertions??0)/$e.totalAssertions*100}%`,backgroundColor:($e.passedAssertions??0)===$e.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),U.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fe({type:"milestone",id:U.id,title:U.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:He=>He.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ze(U.id),title:"Add slice",children:t.jsx(an,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ai(U),title:"Edit milestone",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"milestone",id:U.id}),title:"Delete milestone",children:t.jsx(sn,{size:14})})]})]}),F.has(U.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(C||$===U.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:He=>ie({...J,title:He.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:He=>ie({...J,description:He.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:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),$?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),Ne&&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:[Ne.validationTelemetry.totalRuns," rounds",Ne.validationTelemetry.lastValidatorStatus?` · Last ${Ne.validationTelemetry.lastValidatorStatus}`:""]})]}),nn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",nn]}),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:()=>$t(He=>!He),title:Xt?"Hide validation rounds":"Show validation rounds",children:[Xt?t.jsx(Qt,{size:12}):t.jsx(vn,{size:12}),"Validation rounds (",gt.length,")"]}),Xt&&t.jsx("div",{className:"mission-validation-rounds__list",children:gt.map(He=>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--${He.validatorStatus}`,children:He.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:He.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",He.implementationAttempt," · reviewer #",He.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),He.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.failedAssertionIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Or(Ve),title:`Jump to assertion ${Ve}`,children:Ve},`${He.roundId}-${Ve}`))}):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:"}),He.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:He.generatedFixFeatureIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Mi(Ve),title:`Jump to fix feature ${Ve}`,children:Ve},`${He.roundId}-${Ve}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),He.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:He.blockedReason})]},He.roundId))})]}),gn.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:gn.map(He=>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:()=>Mi(He.id),title:`Jump to feature ${He.id}`,children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Gr[He.status].bg,color:Gr[He.status].text},children:He.status}),He.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${He.loopState}`,children:He.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:()=>Mi(He.sourceFeatureId),title:`Jump to source feature ${He.sourceFeatureId}`,children:He.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:He.runId})]}),He.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:He.failedAssertionIds.map(Ve=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Or(Ve),title:`Jump to assertion ${Ve}`,children:Ve},`${He.id}-${Ve}`))})]})]},He.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[U.slices.map(He=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>fn(He.id),children:[t.jsx("button",{className:"mission-slice__expand",children:D.has(He.id)?t.jsx(Qt,{size:16}):t.jsx(vn,{size:16})}),t.jsx(wc,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:He.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Gu[He.status].bg,color:Gu[He.status].text},children:He.status}),t.jsxs("span",{className:"mission-slice__count",children:[He.features?.length||0," features"]}),t.jsx(Yu,{state:He.planState??"not_started"}),He.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fe({type:"slice",id:He.id,title:He.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ui,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:Ve=>Ve.stopPropagation(),children:[He.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>cn(He.id),title:"Activate slice",children:t.jsx(Sn,{size:14})}),He.status==="active"&&He.features?.some(Ve=>Ve.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ts(He.id),title:"Triage all features",disabled:_,children:_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Dn(He.id),title:"Add feature",children:t.jsx(an,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt(He),title:"Edit slice",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"slice",id:He.id}),title:"Delete slice",children:t.jsx(sn,{size:14})})]})]}),D.has(He.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ge&&ce===U.id&&!T&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:W.title,onChange:Ve=>q({...W,title:Ve.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:Ve=>q({...W,description:Ve.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:jn,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xt,children:"Cancel"})]})]}),T===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:W.title,onChange:Ve=>q({...W,title:Ve.target.value}),onKeyDown:Ai,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:Ve=>q({...W,description:Ve.target.value}),rows:2}),t.jsxs("select",{value:W.status,onChange:Ve=>q({...W,status:Ve.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:jn,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:xt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[He.features?.map(Ve=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":Ve.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Qi(Ve.id),title:At===Ve.id?"Collapse details":"Expand to show run history",children:At===Ve.id?t.jsx(Qt,{size:14}):t.jsx(vn,{size:14})}),t.jsx(gc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:Ve.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Gr[Ve.status].bg,color:Gr[Ve.status].text},children:Ve.status}),Ve.loopState&&Ve.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${Ve.loopState}`,title:`Loop state: ${Ve.loopState}`,children:[Ve.loopState==="implementing"&&"⏳",Ve.loopState==="validating"&&"🔄",Ve.loopState==="needs_fix"&&"🔧",Ve.loopState==="passed"&&"✅",Ve.loopState==="blocked"&&"🚫"]}),Ve.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Mi(Ve.generatedFromFeatureId),title:`Generated from feature: ${Ve.generatedFromFeatureId}`,children:"🔗 Fix"}),(Ve.loopState==="validating"||Ve.loopState==="needs_fix")&&(()=>{const bt=Et.get(Ve.id),xn=tl.get(Ve.id),Cs=bt?.implementationAttemptCount??xn?.implementationAttempt??Ve.implementationAttemptCount??0,Ri=bt?.retryBudgetRemaining??Math.max(0,R1-Cs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Cs," · ",Ri," ",Ri===1?"retry":"retries"," left"]})})(),Ve.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Ia(Ve.id),title:"Validate feature",disabled:_t.has(Ve.id),children:_t.has(Ve.id)?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Zn,{size:14})}),Ve.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(Ve.taskId),title:"Click to view task",children:Ve.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[Ve.status==="defined"&&!Ve.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Fn(Ve.id),title:"Triage — create task",disabled:_||Oe===Ve.id,children:Oe===Ve.id?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Bn,{size:14})}),Ve.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ps(Ve.id),title:"Unlink task",children:t.jsx(Ld,{size:14})}):Ve.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(Ve.id),title:"Link to task",children:t.jsx(ga,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Wn(Ve),title:"Edit feature",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"feature",id:Ve.id}),title:"Delete feature",children:t.jsx(sn,{size:14})})]})]}),Ve.description&&t.jsx("p",{className:"mission-feature__description",children:Ve.description}),Ve.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",Ve.acceptanceCriteria]}),he?.featureId===Ve.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:he.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:ls,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:Ns,disabled:_,children:"Cancel"})]})]}),O===Ve.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ee.title,onChange:bt=>pe({...ee,title:bt.target.value}),onKeyDown:ea,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:bt=>pe({...ee,description:bt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ee.acceptanceCriteria,onChange:bt=>pe({...ee,acceptanceCriteria:bt.target.value}),rows:2}),t.jsxs("select",{value:ee.status,onChange:bt=>pe({...ee,status:bt.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:Rn,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Kn,children:"Cancel"})]})]}),At===Ve.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(Ve.id)??[]).map(bt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>el(bt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${bt.status}`,title:bt.status,children:bt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(bt.startedAt).toLocaleString()}),bt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(bt.completedAt).getTime()-new Date(bt.startedAt).getTime())/1e3),"s"]}),bt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:bt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:A===bt.id?"Hide details":"Show details",children:A===bt.id?t.jsx(Qt,{size:12}):t.jsx(vn,{size:12})})]}),A===bt.id&&ze.get(bt.id)&&t.jsxs("div",{className:"mission-run__details",children:[bt.summary&&t.jsx("p",{className:"mission-run__summary",children:bt.summary}),bt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",bt.blockedReason]}),ze.get(bt.id)?.failures&&ze.get(bt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),ze.get(bt.id).failures.map(xn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:xn.message}),xn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",xn.expected]}),xn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",xn.actual]})]},xn.id))]}),(!ze.get(bt.id)?.failures||ze.get(bt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},bt.id)),(!xe.get(Ve.id)||xe.get(Ve.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},Ve.id)),ue&&se===He.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ee.title,onChange:Ve=>pe({...ee,title:Ve.target.value}),onKeyDown:ea,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ee.description,onChange:Ve=>pe({...ee,description:Ve.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ee.acceptanceCriteria,onChange:Ve=>pe({...ee,acceptanceCriteria:Ve.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Rn,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Kn,children:"Cancel"})]})]}),!ue&&(!He.features||He.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(gc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},He.id)),U.slices.length===0&&!ge&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(wc,{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"}),$e&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Bt.bg,color:Bt.text},children:Qu($e.state)}),$e&&$e.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${$e.passedAssertions??0} of ${$e.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${($e.passedAssertions??0)/$e.totalAssertions*100}%`,backgroundColor:($e.passedAssertions??0)===$e.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{de(!0),Ke(null),ct({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(an,{size:14})})]}),Y&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Re.title,onChange:He=>ct({...Re,title:He.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Re.assertion,onChange:He=>ct({...Re,assertion:He.target.value}),rows:2}),t.jsxs("select",{value:Re.status,onChange:He=>ct({...Re,status:He.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:()=>Ls(U.id),disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ei,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(Te.get(U.id))?Te.get(U.id):[]).map(He=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":He.id,children:[t.jsx("div",{className:"mission-assertion__header",children:_e===He.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Re.title,onChange:Ve=>ct({...Re,title:Ve.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Re.assertion,onChange:Ve=>ct({...Re,assertion:Ve.target.value}),rows:2}),t.jsxs("select",{value:Re.status,onChange:Ve=>ct({...Re,status:Ve.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(He.id,U.id),disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ei,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Yr[He.status]??Yr.pending).bg,color:(Yr[He.status]??Yr.pending).text},children:He.status}),t.jsx("span",{className:"mission-assertion__title",children:He.title}),(()=>{const bt=Z.get(He.id)?.length??0;return bt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${bt} linked feature${bt!==1?"s":""}`,children:["(",bt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>zr(He.id),title:"Toggle details",children:we===He.id?t.jsx(Qt,{size:14}):t.jsx(vn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Zo(He),title:"Edit assertion",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"assertion",id:He.id}),title:"Delete assertion",children:t.jsx(sn,{size:14})})]})}),we===He.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:He.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()=>{we!==He.id&&await zr(He.id),St(ft===He.id?null:He.id)},title:"Link a feature",children:[t.jsx(ga,{size:12}),"Link Feature"]})]}),ft===He.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const Ve=new Set((Z.get(He.id)??[]).map(xn=>xn.id)),bt=[];return f?.milestones.forEach(xn=>xn.slices.forEach(Cs=>bt.push(...Cs.features.filter(Ri=>!Ve.has(Ri.id))))),bt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):bt.map(xn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Fr(xn.id,He.id),disabled:dt.has(He.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:xn.title}),dt.has(He.id)&&t.jsx(rt,{size:12,className:"spinner"})]},xn.id))})()})}),(()=>{const Ve=Z.get(He.id)??[];return Ve.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):Ve.map(bt=>{const xn=`${bt.id}-${He.id}`,Cs=jt.has(xn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:bt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Jn(bt.id,He.id),disabled:Cs,title:"Unlink feature",children:Cs?t.jsx(rt,{size:12,className:"spinner"}):t.jsx(Ld,{size:12})})]},bt.id)})})()]})]})]},He.id)),(!Te.get(U.id)||Te.get(U.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."})})]})]})]})]})]},U.id)}),f&&!C&&$===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ii,children:[t.jsx(an,{size:16}),"Add Milestone"]}),C&&$===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:U=>ie({...J,title:U.target.value}),onKeyDown:Zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:U=>ie({...J,description:U.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:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ht,children:"Cancel"})]})]}),f.milestones.length===0&&!C&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Bi,{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:Ut,onChange:U=>G(U.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:[kn.length," of ",Mn]})]}),!Dt&&fs&&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:nl,"data-testid":"mission-activity-load-more",children:"Load more"})}),Dt?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..."})]}):kn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ts,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:nt,className:"mission-events","data-testid":"mission-activity-events",children:[kn.map(U=>{const Ne=!!(U.metadata&&Object.keys(U.metadata).length>0),$e=Pe.has(U.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${L1(U.eventType)}`,children:z1(U.eventType)}),t.jsx("span",{className:"mission-event__time",children:No(U.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:U.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(U.timestamp).toLocaleString()}),Ne&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>sl(U.id),"data-testid":`mission-event-metadata-${U.id}`,children:[$e?"Hide":"Show"," metadata"]}),$e&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(U.metadata,null,2)})]})]},U.id)}),t.jsx("div",{ref:mt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[k&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:U=>z({...S,title:U.target.value}),onKeyDown:_i,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:U=>z({...S,description:U.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ds,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$s,children:"Cancel"})]})]}),g.map(U=>{const Ne=U,$e=f,gt=$e&&$e.id===Ne.id,gn=Ba[Ne.status]||{bg:"",text:""},Bt=Ne.summary,nn=Rt.get(Ne.id),He=I1(nn),Ve=!!(Bt&&(Bt.totalMilestones>0||Bt.totalFeatures>0)),bt=nn?.totalTasks??0,xn=nn?.tasksCompleted??0,Cs=nn?.tasksFailed??0,Ri=nn?.estimatedCompletionPercent??Bt?.progressPercent??0,Yn=Ve||bt>0||Cs>0||!!nn?.lastActivityAt,En=Ne.status==="active"&&(nn?.currentMilestoneId||nn?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${gt?"mission-list__item--selected":""}`,onClick:()=>zt(U),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(us,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ne.title}),U.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Bn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${He}`,"data-testid":`mission-health-badge-${Ne.id}`,"aria-label":`Mission health: ${He}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:gn.bg,color:gn.text},children:Ne.status})]}),Ne.description&&t.jsx("p",{className:"mission-list__item-description",children:Ne.description}),En&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",En]}),Yn&&t.jsxs("div",{className:"mission-list__item-summary",children:[Ve&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Bt.completedMilestones,"/",Bt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Bt.completedFeatures,"/",Bt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ne.id}`,children:[xn,"/",bt," tasks"]}),Cs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Kt=>{Kt.stopPropagation(),zt(U)},"data-testid":`mission-failed-${Ne.id}`,title:"View mission failures",children:[Cs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ne.id}`,children:["Activity ",No(nn?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${He}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Ri}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Kt=>Kt.stopPropagation(),children:[Ne.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Q(Ne.id),title:"Stop mission",children:t.jsx(xs,{size:14})}),Ne.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Da(Ne.id),title:"Resume mission",children:t.jsx(Sn,{size:14})}),Ne.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Be(Ne.id),title:"Start mission",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>si(U),title:"Edit mission",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>oe({type:"mission",id:Ne.id}),title:"Delete mission",children:t.jsx(sn,{size:14})})]})]},Ne.id)}),w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:U=>z({...S,title:U.target.value}),onKeyDown:_i,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:U=>z({...S,description:U.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:U=>z({...S,status:U.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:S.autopilotEnabled,onChange:U=>z({...S,autopilotEnabled:U.target.checked})}),t.jsx(Bn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ds,disabled:_,children:[_?t.jsx(rt,{size:14,className:"spinner"}):t.jsx(Ln,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$s,children:"Cancel"})]})]}),g.length===0&&!k&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(us,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!k&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[Ie.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(as,{size:16}),t.jsx("span",{children:Ie.length===1?`Resume "${Ie[0].title}"?`:`${Ie.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:Ie.map(U=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{ve(U.id),it(!0),We([])},children:[U.status==="error"?t.jsx(Tn,{size:14}):t.jsx(Zn,{size:14}),U.status==="error"?"Retry":"Resume"]},U.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>it(!0),children:[t.jsx(Zn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:ws,children:[t.jsx(an,{size:16}),"New Mission"]})]})]})]})}),ye&&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 ",ye.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()=>{ye.type==="mission"?await Yi(ye.id):ye.type==="milestone"?await ne(ye.id):ye.type==="slice"?await en(ye.id):ye.type==="feature"&&await Gn(ye.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>oe(null),children:"Cancel"})]})]})}),De&&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:et,onChange:U=>Qe(U.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(U=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Qe(U.id),children:[U.id,": ",U.title||"Untitled"]},U.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:On,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{qe(null),Qe("")},children:"Cancel"})]})]})})]}),Ss=t.jsx(S1,{isOpen:Xe,onClose:()=>it(!1),onMissionCreated:()=>{rn(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:te}),oi=Ae?t.jsx(M1,{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:[il,Ss,oi]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:U=>U.target===U.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:il}),Ss,oi]})}const Qr=2e3;function Zu({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,x]=a.useState(!1),[v,b]=a.useState(null),y=u.trim()!==""&&g.trim().length>0&&g.length<=Qr,N=a.useCallback(async()=>{if(!(!y||f)){x(!0),b(null);try{const R=m==="agent"?"user-to-agent":"system";await Kk({toId:u.trim(),toType:m,content:g.trim(),type:R,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(R){const w=ke(R)||"Failed to send message";b(w),l?.(w,"error")}finally{x(!1)}}},[y,f,u,m,g,n,i,r,l]),k=a.useCallback(R=>{d(R),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(Gt,{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:R=>k(R.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(R=>t.jsx("option",{value:R.id,children:R.name||R.id},R.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Nn,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:R=>p(R.target.value),maxLength:Qr,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>Qr?"over-limit":"",children:[g.length,"/",Qr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(as,{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:N,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(Li,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function aa(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 U1(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 B1(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 em(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function H1(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 q1({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),[x,v]=a.useState([]),[b,y]=a.useState(!1),[N,k]=a.useState(null),[R,w]=a.useState(null),[M,S]=a.useState(null),[z,_]=a.useState("inbox"),[I,F]=a.useState(null),[V,D]=a.useState([]),E=a.useMemo(()=>new Map(V.map(se=>[se.id,se.name??""])),[V]),$=a.useCallback((se,Ce)=>U1(se,Ce,E),[E]),J=Pr()==="mobile",ie=!J,C=a.useCallback(async()=>{g(!0);try{const se=await Vk({limit:50},e);l(se),m(se.unreadCount),s?.(se.unreadCount)}catch{}finally{g(!1)}},[e,s]),P=a.useCallback(async()=>{g(!0);try{const se=await Wk({limit:50},e);u(se)}catch{}finally{g(!1)}},[e]),T=a.useCallback(async se=>{g(!0);try{const Ce=await Xk(se,e);F(Ce)}catch{}finally{g(!1)}},[e]),j=a.useCallback(async()=>{try{const se=await _a(void 0,e);D(se)}catch{}},[e]),W=a.useCallback(async()=>{try{const se=await vp(e);m(se.unreadCount),s?.(se.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?C():i==="outbox"?P():i==="agents"&&j()},[i,C,P,j]),a.useEffect(()=>{M&&T(M)},[M,T]),a.useEffect(()=>{W()},[W]),a.useEffect(()=>{j()},[j]),a.useEffect(()=>{if(typeof EventSource>"u")return;const se=e?`?projectId=${encodeURIComponent(e)}`:"",Ce=()=>{W(),i==="inbox"?C():i==="outbox"&&P(),M&&T(M)};return qs(`/api/events${se}`,{events:{"message:sent":Ce,"message:received":Ce,"message:read":Ce,"message:deleted":Ce}})},[e,i,M,W,C,P,T]);const q=a.useCallback(async se=>{if(f(se),!se.read)try{const Ce=await Gk(se.id,e);Ce&&l(qe=>qe&&{...qe,messages:qe.messages.map(et=>et.id===Ce.id?Ce:et),unreadCount:Math.max(0,qe.unreadCount-1)});const De=Math.max(0,d-1);m(De),s?.(De)}catch{}try{const Ce=await Qk(se.fromId,se.fromType,e);v(Ce)}catch{v([se])}},[e,d,s]),ge=a.useCallback(()=>{f(null),v([])},[]),be=a.useCallback(async()=>{try{const se=await Jk(e);m(0),s?.(0),l(Ce=>Ce&&{...Ce,messages:Ce.messages.map(De=>({...De,read:!0})),unreadCount:0}),n?.(`Marked ${se.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ce=a.useCallback(async se=>{try{await Yk(se,e),f(null),v([]),i==="inbox"?C():i==="outbox"?P():M&&T(M),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,M,C,P,T,n]),Se=a.useCallback(se=>{k({id:se.fromId,type:se.fromType}),w({messageId:se.id,preview:em(se.content,120)}),y(!0)},[]),O=a.useCallback(()=>{y(!1),k(null),w(null),n?.("Message sent","success"),i==="outbox"?P():i==="agents"&&M&&T(M),W()},[i,P,M,T,n,W]),le=a.useCallback(()=>{k(i==="agents"&&M?{id:M,type:"agent"}:null),w(null),y(!0)},[i,M]),ee=a.useCallback(()=>{y(!1),k(null),w(null)},[]),pe=()=>!p||b?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:ge,"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:B1(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:aa(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>Se(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:()=>ce(p.id),"data-testid":"mailbox-delete",children:[t.jsx(sn,{size:14}),t.jsx("span",{children:"Delete"})]})]})]}),t.jsxs("div",{className:"mailbox-message-participants",children:[t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"From:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?t.jsx(Nn,{size:14}):t.jsx(ta,{size:14}),$(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(Nn,{size:14}):t.jsx(ta,{size:14}),$(p.toId,p.toType)]})]})]}),x.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),x.map(se=>{const Ce=se.metadata?.replyTo?.messageId,De=Ce?x.find(qe=>qe.id===Ce):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${se.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:$(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:aa(se.createdAt)})]}),Ce&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${se.id}`,children:["↪ Replying to ",De?em(De.content,60):`message ${Ce}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:se.content})]},se.id)})]}),x.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})]})]}),ue=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Ml,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(sr,{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:H1(o.messages).map(se=>t.jsxs("div",{className:`mailbox-conversation-group ${se.unreadCount>0?"unread":""}`,onClick:()=>q(se.latestMessage),"data-testid":`mailbox-conversation-${se.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.fromType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ta,{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:$(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:aa(se.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.latestMessage.content.slice(0,80),se.latestMessage.content.length>80?"…":""]})]}),se.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${se.key}`,children:se.unreadCount>9?"9+":se.unreadCount})]},se.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Ml,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Li,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(se=>t.jsxs("div",{className:"mailbox-item",onClick:()=>q(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.toType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ta,{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: ",$(se.toId,se.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:aa(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:V.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Nn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:M??"",onChange:se=>{S(se.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),V.map(se=>t.jsx("option",{value:se.id,children:se.name||se.id},se.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:le,"data-testid":"mailbox-compose-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Compose"})]})]}),M&&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 ${z==="inbox"?"active":""}`,onClick:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(sr,{size:12}),t.jsx("span",{children:"Inbox"}),I&&I.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:I.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Li,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!M&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Nn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),M&&h&&!I&&t.jsx(Ml,{}),M&&I&&z==="inbox"&&I.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(sr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),M&&I&&z==="outbox"&&I.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Li,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),M&&I&&z==="inbox"&&I.inbox.map(se=>t.jsxs("div",{className:`mailbox-item ${se.read?"":"unread"}`,onClick:()=>q(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.fromType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ta,{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:$(se.fromId,se.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:aa(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id)),M&&I&&z==="outbox"&&I.outbox.map(se=>t.jsxs("div",{className:"mailbox-item",onClick:()=>q(se),"data-testid":`mailbox-item-${se.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:se.toType==="agent"?t.jsx(Nn,{size:16}):t.jsx(ta,{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: ",$(se.toId,se.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:aa(se.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[se.content.slice(0,80),se.content.length>80?"…":""]})]})]},se.id))]})]})})]}),fe=()=>b?t.jsx(Zu,{recipient:N,replyContext:R,agents:V,projectId:e,onSend:O,onCancel:ee,addToast:n}):p?pe():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(xa,{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(xa,{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:le,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:be,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(qg,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?C():i==="outbox"?P():M&&T(M)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Tn,{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(sr,{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(Li,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Nn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:ie?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:ue()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:fe()})]}):t.jsxs(t.Fragment,{children:[pe(),b&&t.jsx(Zu,{recipient:N,replyContext:R,agents:V,projectId:e,onSend:O,onCancel:ee,addToast:n}),!p&&!b&&ue()]})})]})}function Ml(){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 ti(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 V1(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const W1=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,K1=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,G1={};function tm(e,n){return(G1.jsx?K1:W1).test(e)}const J1=/[ \t\n\f\r]/g;function Y1(e){return typeof e=="object"?e.type==="text"?nm(e.value):!1:nm(e)}function nm(e){return e.replace(J1,"")===""}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 qp(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 Ic(e){return e.toLowerCase()}class hs{constructor(n,s){this.attribute=s,this.property=n}}hs.prototype.attribute="";hs.prototype.booleanish=!1;hs.prototype.boolean=!1;hs.prototype.commaOrSpaceSeparated=!1;hs.prototype.commaSeparated=!1;hs.prototype.defined=!1;hs.prototype.mustUseProperty=!1;hs.prototype.number=!1;hs.prototype.overloadedBoolean=!1;hs.prototype.property="";hs.prototype.spaceSeparated=!1;hs.prototype.space=void 0;let Q1=0;const Ht=Ji(),In=Ji(),$c=Ji(),st=Ji(),bn=Ji(),pa=Ji(),gs=Ji();function Ji(){return 2**++Q1}const Dc=Object.freeze(Object.defineProperty({__proto__:null,boolean:Ht,booleanish:In,commaOrSpaceSeparated:gs,commaSeparated:pa,number:st,overloadedBoolean:$c,spaceSeparated:bn},Symbol.toStringTag,{value:"Module"})),_l=Object.keys(Dc);class pd extends hs{constructor(n,s,i,r){let o=-1;if(super(n,s),sm(this,"space",r),typeof i=="number")for(;++o<_l.length;){const l=_l[o];sm(this,_l[o],(i&Dc[l])===Dc[l])}}}pd.prototype.defined=!0;function sm(e,n,s){s&&(e[n]=s)}function Ta(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new pd(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Ic(i)]=i,s[Ic(o.attribute)]=i}return new Ir(n,s,e.space)}const Vp=Ta({properties:{ariaActiveDescendant:null,ariaAtomic:In,ariaAutoComplete:null,ariaBusy:In,ariaChecked:In,ariaColCount:st,ariaColIndex:st,ariaColSpan:st,ariaControls:bn,ariaCurrent:null,ariaDescribedBy:bn,ariaDetails:null,ariaDisabled:In,ariaDropEffect:bn,ariaErrorMessage:null,ariaExpanded:In,ariaFlowTo:bn,ariaGrabbed:In,ariaHasPopup:null,ariaHidden:In,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:bn,ariaLevel:st,ariaLive:null,ariaModal:In,ariaMultiLine:In,ariaMultiSelectable:In,ariaOrientation:null,ariaOwns:bn,ariaPlaceholder:null,ariaPosInSet:st,ariaPressed:In,ariaReadOnly:In,ariaRelevant:null,ariaRequired:In,ariaRoleDescription:bn,ariaRowCount:st,ariaRowIndex:st,ariaRowSpan:st,ariaSelected:In,ariaSetSize:st,ariaSort:null,ariaValueMax:st,ariaValueMin:st,ariaValueNow:st,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Wp(e,n){return n in e?e[n]:n}function Kp(e,n){return Wp(e,n.toLowerCase())}const X1=Ta({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:pa,acceptCharset:bn,accessKey:bn,action:null,allow:null,allowFullScreen:Ht,allowPaymentRequest:Ht,allowUserMedia:Ht,alt:null,as:null,async:Ht,autoCapitalize:null,autoComplete:bn,autoFocus:Ht,autoPlay:Ht,blocking:bn,capture:null,charSet:null,checked:Ht,cite:null,className:bn,cols:st,colSpan:null,content:null,contentEditable:In,controls:Ht,controlsList:bn,coords:st|pa,crossOrigin:null,data:null,dateTime:null,decoding:null,default:Ht,defer:Ht,dir:null,dirName:null,disabled:Ht,download:$c,draggable:In,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:Ht,formTarget:null,headers:bn,height:st,hidden:$c,high:st,href:null,hrefLang:null,htmlFor:bn,httpEquiv:bn,id:null,imageSizes:null,imageSrcSet:null,inert:Ht,inputMode:null,integrity:null,is:null,isMap:Ht,itemId:null,itemProp:bn,itemRef:bn,itemScope:Ht,itemType:bn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:Ht,low:st,manifest:null,max:null,maxLength:st,media:null,method:null,min:null,minLength:st,multiple:Ht,muted:Ht,name:null,nonce:null,noModule:Ht,noValidate:Ht,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:Ht,optimum:st,pattern:null,ping:bn,placeholder:null,playsInline:Ht,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:Ht,referrerPolicy:null,rel:bn,required:Ht,reversed:Ht,rows:st,rowSpan:st,sandbox:bn,scope:null,scoped:Ht,seamless:Ht,selected:Ht,shadowRootClonable:Ht,shadowRootDelegatesFocus:Ht,shadowRootMode:null,shape:null,size:st,sizes:null,slot:null,span:st,spellCheck:In,src:null,srcDoc:null,srcLang:null,srcSet:null,start:st,step:null,style:null,tabIndex:st,target:null,title:null,translate:null,type:null,typeMustMatch:Ht,useMap:null,value:In,width:st,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:bn,axis:null,background:null,bgColor:null,border:st,borderColor:null,bottomMargin:st,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:Ht,declare:Ht,event:null,face:null,frame:null,frameBorder:null,hSpace:st,leftMargin:st,link:null,longDesc:null,lowSrc:null,marginHeight:st,marginWidth:st,noResize:Ht,noHref:Ht,noShade:Ht,noWrap:Ht,object:null,profile:null,prompt:null,rev:null,rightMargin:st,rules:null,scheme:null,scrolling:In,standby:null,summary:null,text:null,topMargin:st,valueType:null,version:null,vAlign:null,vLink:null,vSpace:st,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:Ht,disableRemotePlayback:Ht,prefix:null,property:null,results:st,security:null,unselectable:null},space:"html",transform:Kp}),Z1=Ta({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:gs,accentHeight:st,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:st,amplitude:st,arabicForm:null,ascent:st,attributeName:null,attributeType:null,azimuth:st,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:st,by:null,calcMode:null,capHeight:st,className:bn,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:st,diffuseConstant:st,direction:null,display:null,dur:null,divisor:st,dominantBaseline:null,download:Ht,dx:null,dy:null,edgeMode:null,editable:null,elevation:st,enableBackground:null,end:null,event:null,exponent:st,externalResourcesRequired:null,fill:null,fillOpacity:st,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:pa,g2:pa,glyphName:pa,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:st,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:st,horizOriginX:st,horizOriginY:st,id:null,ideographic:st,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:st,k:st,k1:st,k2:st,k3:st,k4:st,kernelMatrix:gs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:st,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:st,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:st,overlineThickness:st,paintOrder:null,panose1:null,path:null,pathLength:st,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:bn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:st,pointsAtY:st,pointsAtZ:st,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:gs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:gs,rev:gs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:gs,requiredFeatures:gs,requiredFonts:gs,requiredFormats:gs,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:st,specularExponent:st,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:st,strikethroughThickness:st,string:null,stroke:null,strokeDashArray:gs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:st,strokeOpacity:st,strokeWidth:null,style:null,surfaceScale:st,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:gs,tabIndex:st,tableValues:null,target:null,targetX:st,targetY:st,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:gs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:st,underlineThickness:st,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:st,values:null,vAlphabetic:st,vMathematical:st,vectorEffect:null,vHanging:st,vIdeographic:st,version:null,vertAdvY:st,vertOriginX:st,vertOriginY:st,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:st,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Wp}),Gp=Ta({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()}}),Jp=Ta({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Kp}),Yp=Ta({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),e0={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"},t0=/[A-Z]/g,im=/-[a-z]/g,n0=/^data[-\w.:]+$/i;function s0(e,n){const s=Ic(n);let i=n,r=hs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&n0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(im,a0);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!im.test(o)){let l=o.replace(t0,i0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=pd}return new r(i,n)}function i0(e){return"-"+e.toLowerCase()}function a0(e){return e.charAt(1).toUpperCase()}const r0=qp([Vp,X1,Gp,Jp,Yp],"html"),fd=qp([Vp,Z1,Gp,Jp,Yp],"svg");function o0(e){return e.join(" ").trim()}var ra={},Al,am;function l0(){if(am)return Al;am=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,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,N=1;function k(D){var E=D.match(n);E&&(y+=E.length);var $=D.lastIndexOf(u);N=~$?D.length-$:N+D.length}function R(){var D={line:y,column:N};return function(E){return E.position=new w(D),z(),E}}function w(D){this.start=D,this.end={line:y,column:N},this.source=b.source}w.prototype.content=v;function M(D){var E=new Error(b.source+":"+y+":"+N+": "+D);if(E.reason=D,E.filename=b.source,E.line=y,E.column=N,E.source=v,!b.silent)throw E}function S(D){var E=D.exec(v);if(E){var $=E[0];return k($),v=v.slice($.length),E}}function z(){S(s)}function _(D){var E;for(D=D||[];E=I();)E!==!1&&D.push(E);return D}function I(){var D=R();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var E=2;h!=v.charAt(E)&&(m!=v.charAt(E)||d!=v.charAt(E+1));)++E;if(E+=2,h===v.charAt(E-1))return M("End of comment missing");var $=v.slice(2,E-2);return N+=2,k($),v=v.slice(E),N+=2,D({type:g,comment:$})}}function F(){var D=R(),E=S(i);if(E){if(I(),!S(r))return M("property missing ':'");var $=S(o),B=D({type:p,property:x(E[0].replace(e,h)),value:$?x($[0].replace(e,h)):h});return S(l),B}}function V(){var D=[];_(D);for(var E;E=F();)E!==!1&&(D.push(E),_(D));return D}return z(),V()}function x(v){return v?v.replace(c,h):h}return Al=f,Al}var rm;function c0(){if(rm)return ra;rm=1;var e=ra&&ra.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(ra,"__esModule",{value:!0}),ra.default=s;const n=e(l0());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 ra}var Ha={},om;function d0(){if(om)return Ha;om=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.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 Ha.camelCase=u,Ha}var qa,lm;function u0(){if(lm)return qa;lm=1;var e=qa&&qa.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(c0()),s=d0();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,qa=i,qa}var m0=u0();const h0=Uh(m0),Qp=Xp("end"),gd=Xp("start");function Xp(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 p0(e){const n=gd(e),s=Qp(e);if(n&&s)return{start:n,end:s}}function cr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?cm(e.position):"start"in e||"end"in e?cm(e):"line"in e||"column"in e?Lc(e):""}function Lc(e){return dm(e&&e.line)+":"+dm(e&&e.column)}function cm(e){return Lc(e&&e.start)+"-"+Lc(e&&e.end)}function dm(e){return e&&typeof e=="number"?e:1}class es 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=cr(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}}es.prototype.file="";es.prototype.name="";es.prototype.reason="";es.prototype.message="";es.prototype.stack="";es.prototype.column=void 0;es.prototype.line=void 0;es.prototype.ancestors=void 0;es.prototype.cause=void 0;es.prototype.fatal=void 0;es.prototype.place=void 0;es.prototype.ruleId=void 0;es.prototype.source=void 0;const xd={}.hasOwnProperty,f0=new Map,g0=/[A-Z]/g,x0=new Set(["table","tbody","thead","tfoot","tr"]),b0=new Set(["td","th"]),Zp="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function v0(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=E0(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=C0(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"?fd:r0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=ef(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function ef(e,n,s){if(n.type==="element")return y0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return j0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return w0(e,n,s);if(n.type==="mdxjsEsm")return k0(e,n);if(n.type==="root")return N0(e,n,s);if(n.type==="text")return S0(e,n)}function y0(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=fd,e.schema=r),e.ancestors.push(n);const o=nf(e,n.tagName,!1),l=M0(e,n);let c=vd(e,n);return x0.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!Y1(u):!0})),tf(e,l,o,n),bd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function j0(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 k0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);jr(e,n.position)}function w0(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=fd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:nf(e,n.name,!0),l=_0(e,n),c=vd(e,n);return tf(e,l,o,n),bd(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function N0(e,n,s){const i={};return bd(i,vd(e,n)),e.create(n,e.Fragment,i,s)}function S0(e,n){return n.value}function tf(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function bd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function C0(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 E0(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=gd(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 M0(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&xd.call(n.properties,r)){const o=A0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&b0.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 _0(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 vd(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:f0;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=ef(e,o,l);c!==void 0&&s.push(c)}return s}function A0(e,n,s){const i=s0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?V1(s):o0(s)),i.property==="style"){let r=typeof s=="object"?s:R0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=T0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?e0[i.property]||i.property:i.attribute,s]}}function R0(e,n){try{return h0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new es("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=Zp+"#cannot-parse-style-attribute",r}}function nf(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=tm(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=tm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return xd.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 es("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=Zp+"#cannot-handle-mdx-estrees-without-createevaluater",s}function T0(e){const n={};let s;for(s in e)xd.call(e,s)&&(n[P0(s)]=e[s]);return n}function P0(e){let n=e.replace(g0,I0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function I0(e){return"-"+e.toLowerCase()}const Rl={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"]},$0={};function yd(e,n){const s=$0,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return sf(e,i,r)}function sf(e,n,s){if(D0(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 um(e.children,n,s)}return Array.isArray(e)?um(e,n,s):""}function um(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=sf(e[r],n,s);return i.join("")}function D0(e){return!!(e&&typeof e=="object")}const mm=document.createElement("i");function jd(e){const n="&"+e+";";mm.innerHTML=n;const s=mm.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ys(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 As(e,n){return e.length>0?(ys(e,e.length,0,n),e):n}const hm={}.hasOwnProperty;function af(e){const n={};let s=-1;for(;++s<e.length;)L0(n,e[s]);return n}function L0(e,n){let s;for(s in n){const r=(hm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){hm.call(r,l)||(r[l]=[]);const c=o[l];z0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function z0(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);ys(e,0,0,i)}function rf(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 Bs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const is=Ci(/[A-Za-z]/),Xn=Ci(/[\dA-Za-z]/),O0=Ci(/[#-'*+\--9=?A-Z^-~]/);function So(e){return e!==null&&(e<32||e===127)}const zc=Ci(/\d/),F0=Ci(/[\dA-Fa-f]/),U0=Ci(/[!-/:-@[-`{-~]/);function wt(e){return e!==null&&e<-2}function hn(e){return e!==null&&(e<0||e===32)}function Jt(e){return e===-2||e===-1||e===32}const Go=Ci(/\p{P}|\p{S}/u),Vi=Ci(/\s/);function Ci(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Pa(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Xn(e.charCodeAt(s+1))&&Xn(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 Zt(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return Jt(u)?(e.enter(s),c(u)):n(u)}function c(u){return Jt(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const B0={tokenize:H0};function H0(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"),Zt(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 wt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const q0={tokenize:V0},pm={tokenize:W0};function V0(e){const n=this,s=[];let i=0,r,o,l;return c;function c(N){if(i<s.length){const k=s[i];return n.containerState=k[1],e.attempt(k[0].continuation,u,d)(N)}return d(N)}function u(N){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const k=n.events.length;let R=k,w;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){w=n.events[R][1].end;break}b(i);let M=k;for(;M<n.events.length;)n.events[M][1].end={...w},M++;return ys(n.events,R+1,0,n.events.slice(k)),n.events.length=M,d(N)}return c(N)}function d(N){if(i===s.length){if(!r)return g(N);if(r.currentConstruct&&r.currentConstruct.concrete)return f(N);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(pm,m,h)(N)}function m(N){return r&&y(),b(i),g(N)}function h(N){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(N)}function g(N){return n.containerState={},e.attempt(pm,p,f)(N)}function p(N){return i++,s.push([n.currentConstruct,n.containerState]),g(N)}function f(N){if(N===null){r&&y(),b(0),e.consume(N);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(N)}function x(N){if(N===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(N);return}return wt(N)?(e.consume(N),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(N),x)}function v(N,k){const R=n.sliceStream(N);if(k&&R.push(null),N.previous=o,o&&(o.next=N),o=N,r.defineSkip(N.start),r.write(R),n.parser.lazy[N.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 M=n.events.length;let S=M,z,_;for(;S--;)if(n.events[S][0]==="exit"&&n.events[S][1].type==="chunkFlow"){if(z){_=n.events[S][1].end;break}z=!0}for(b(i),w=M;w<n.events.length;)n.events[w][1].end={..._},w++;ys(n.events,S+1,0,n.events.slice(M)),n.events.length=w}}function b(N){let k=s.length;for(;k-- >N;){const R=s[k];n.containerState=R[1],R[0].exit.call(n,e)}s.length=N}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function W0(e,n,s){return Zt(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ja(e){if(e===null||hn(e)||Vi(e))return 1;if(Go(e))return 2}function Jo(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 Oc={name:"attention",resolveAll:K0,tokenize:G0};function K0(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};fm(h,-u),fm(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=As(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=As(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=As(d,Jo(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=As(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=As(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ys(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 G0(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=ja(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=ja(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 fm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const J0={name:"autolink",tokenize:Y0};function Y0(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 is(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||Xn(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||Xn(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||So(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):O0(p)?(e.consume(p),d):s(p)}function m(p){return Xn(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||Xn(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const $r={partial:!0,tokenize:Q0};function Q0(e,n,s){return i;function i(o){return Jt(o)?Zt(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||wt(o)?n(o):s(o)}}const of={continuation:{tokenize:Z0},exit:eS,name:"blockQuote",tokenize:X0};function X0(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 Jt(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function Z0(e,n,s){const i=this;return r;function r(l){return Jt(l)?Zt(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(of,n,s)(l)}}function eS(e){e.exit("blockQuote")}const lf={name:"characterEscape",tokenize:tS};function tS(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 U0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const cf={name:"characterReference",tokenize:nS};function nS(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=Xn,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=F0,m):(e.enter("characterReferenceValue"),o=7,l=zc,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===Xn&&!jd(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 gm={partial:!0,tokenize:iS},xm={concrete:!0,name:"codeFenced",tokenize:sS};function sS(e,n,s){const i=this,r={partial:!0,tokenize:R};let o=0,l=0,c;return u;function u(w){return d(w)}function d(w){const M=i.events[i.events.length-1];return o=M&&M[1].type==="linePrefix"?M[2].sliceSerialize(M[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"),Jt(w)?Zt(e,h,"whitespace")(w):h(w))}function h(w){return w===null||wt(w)?(e.exit("codeFencedFence"),i.interrupt?n(w):e.check(gm,x,k)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||wt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):Jt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Zt(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),g)}function p(w){return w===null||wt(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||wt(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),f)}function x(w){return e.attempt(r,k,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return o>0&&Jt(w)?Zt(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||wt(w)?e.check(gm,x,k)(w):(e.enter("codeFlowValue"),N(w))}function N(w){return w===null||wt(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),N)}function k(w){return e.exit("codeFenced"),n(w)}function R(w,M,S){let z=0;return _;function _(E){return w.enter("lineEnding"),w.consume(E),w.exit("lineEnding"),I}function I(E){return w.enter("codeFencedFence"),Jt(E)?Zt(w,F,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):F(E)}function F(E){return E===c?(w.enter("codeFencedFenceSequence"),V(E)):S(E)}function V(E){return E===c?(z++,w.consume(E),V):z>=l?(w.exit("codeFencedFenceSequence"),Jt(E)?Zt(w,D,"whitespace")(E):D(E)):S(E)}function D(E){return E===null||wt(E)?(w.exit("codeFencedFence"),M(E)):S(E)}}}function iS(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 Tl={name:"codeIndented",tokenize:rS},aS={partial:!0,tokenize:oS};function rS(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Zt(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):wt(d)?e.attempt(aS,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||wt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function oS(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):wt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Zt(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):wt(l)?r(l):s(l)}}const lS={name:"codeText",previous:dS,resolve:cS,tokenize:uS};function cS(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 dS(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function uS(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)):wt(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||wt(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 mS{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&&Va(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),Va(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Va(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);Va(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Va(this.left,s.reverse())}}}function Va(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 df(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new mS(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,hS(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 ys(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function hS(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,x=0;const v=[x];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&&(x=g+1,v.push(x),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 b=c.slice(v[g],v[g+1]),y=o.pop();u.push([y,y+b.length-1]),e.splice(y,2,b)}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 pS={resolve:gS,tokenize:xS},fS={partial:!0,tokenize:bS};function gS(e){return df(e),e}function xS(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):wt(c)?e.check(fS,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 bS(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Zt(e,o,"linePrefix")}function o(l){if(l===null||wt(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 uf(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(b),e.exit(o),g):b===null||b===32||b===41||So(b)?s(b):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function g(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),g(b)):b===null||b===60||wt(b)?s(b):(e.consume(b),b===92?f:p)}function f(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||hn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(b)):m<d&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||So(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function mf(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):wt(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||wt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!Jt(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function hf(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):wt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Zt(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||wt(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 dr(e,n){let s;return i;function i(r){return wt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):Jt(r)?Zt(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const vS={name:"definition",tokenize:jS},yS={partial:!0,tokenize:kS};function jS(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return mf.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Bs(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 hn(p)?dr(e,d)(p):d(p)}function d(p){return uf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(yS,h,h)(p)}function h(p){return Jt(p)?Zt(e,g,"whitespace")(p):g(p)}function g(p){return p===null||wt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function kS(e,n,s){return i;function i(c){return hn(c)?dr(e,r)(c):s(c)}function r(c){return hf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return Jt(c)?Zt(e,l,"whitespace")(c):l(c)}function l(c){return c===null||wt(c)?n(c):s(c)}}const wS={name:"hardBreakEscape",tokenize:NS};function NS(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return wt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const SS={name:"headingAtx",resolve:CS,tokenize:ES};function CS(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"},ys(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function ES(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||hn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||wt(m)?(e.exit("atxHeading"),n(m)):Jt(m)?Zt(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||hn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const MS=["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"],bm=["pre","script","style","textarea"],_S={concrete:!0,name:"htmlFlow",resolveTo:TS,tokenize:PS},AS={partial:!0,tokenize:$S},RS={partial:!0,tokenize:IS};function TS(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 PS(e,n,s){const i=this;let r,o,l,c,u;return d;function d(j){return m(j)}function m(j){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(j),h}function h(j){return j===33?(e.consume(j),g):j===47?(e.consume(j),o=!0,x):j===63?(e.consume(j),r=3,i.interrupt?n:C):is(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function g(j){return j===45?(e.consume(j),r=2,p):j===91?(e.consume(j),r=5,c=0,f):is(j)?(e.consume(j),r=4,i.interrupt?n:C):s(j)}function p(j){return j===45?(e.consume(j),i.interrupt?n:C):s(j)}function f(j){const W="CDATA[";return j===W.charCodeAt(c++)?(e.consume(j),c===W.length?i.interrupt?n:F:f):s(j)}function x(j){return is(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function v(j){if(j===null||j===47||j===62||hn(j)){const W=j===47,q=l.toLowerCase();return!W&&!o&&bm.includes(q)?(r=1,i.interrupt?n(j):F(j)):MS.includes(l.toLowerCase())?(r=6,W?(e.consume(j),b):i.interrupt?n(j):F(j)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(j):o?y(j):N(j))}return j===45||Xn(j)?(e.consume(j),l+=String.fromCharCode(j),v):s(j)}function b(j){return j===62?(e.consume(j),i.interrupt?n:F):s(j)}function y(j){return Jt(j)?(e.consume(j),y):_(j)}function N(j){return j===47?(e.consume(j),_):j===58||j===95||is(j)?(e.consume(j),k):Jt(j)?(e.consume(j),N):_(j)}function k(j){return j===45||j===46||j===58||j===95||Xn(j)?(e.consume(j),k):R(j)}function R(j){return j===61?(e.consume(j),w):Jt(j)?(e.consume(j),R):N(j)}function w(j){return j===null||j===60||j===61||j===62||j===96?s(j):j===34||j===39?(e.consume(j),u=j,M):Jt(j)?(e.consume(j),w):S(j)}function M(j){return j===u?(e.consume(j),u=null,z):j===null||wt(j)?s(j):(e.consume(j),M)}function S(j){return j===null||j===34||j===39||j===47||j===60||j===61||j===62||j===96||hn(j)?R(j):(e.consume(j),S)}function z(j){return j===47||j===62||Jt(j)?N(j):s(j)}function _(j){return j===62?(e.consume(j),I):s(j)}function I(j){return j===null||wt(j)?F(j):Jt(j)?(e.consume(j),I):s(j)}function F(j){return j===45&&r===2?(e.consume(j),$):j===60&&r===1?(e.consume(j),B):j===62&&r===4?(e.consume(j),P):j===63&&r===3?(e.consume(j),C):j===93&&r===5?(e.consume(j),ie):wt(j)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(AS,T,V)(j)):j===null||wt(j)?(e.exit("htmlFlowData"),V(j)):(e.consume(j),F)}function V(j){return e.check(RS,D,T)(j)}function D(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),E}function E(j){return j===null||wt(j)?V(j):(e.enter("htmlFlowData"),F(j))}function $(j){return j===45?(e.consume(j),C):F(j)}function B(j){return j===47?(e.consume(j),l="",J):F(j)}function J(j){if(j===62){const W=l.toLowerCase();return bm.includes(W)?(e.consume(j),P):F(j)}return is(j)&&l.length<8?(e.consume(j),l+=String.fromCharCode(j),J):F(j)}function ie(j){return j===93?(e.consume(j),C):F(j)}function C(j){return j===62?(e.consume(j),P):j===45&&r===2?(e.consume(j),C):F(j)}function P(j){return j===null||wt(j)?(e.exit("htmlFlowData"),T(j)):(e.consume(j),P)}function T(j){return e.exit("htmlFlow"),n(j)}}function IS(e,n,s){const i=this;return r;function r(l){return wt(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 $S(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt($r,n,s)}}const DS={name:"htmlText",tokenize:LS};function LS(e,n,s){const i=this;let r,o,l;return c;function c(C){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(C),u}function u(C){return C===33?(e.consume(C),d):C===47?(e.consume(C),R):C===63?(e.consume(C),N):is(C)?(e.consume(C),S):s(C)}function d(C){return C===45?(e.consume(C),m):C===91?(e.consume(C),o=0,f):is(C)?(e.consume(C),y):s(C)}function m(C){return C===45?(e.consume(C),p):s(C)}function h(C){return C===null?s(C):C===45?(e.consume(C),g):wt(C)?(l=h,B(C)):(e.consume(C),h)}function g(C){return C===45?(e.consume(C),p):h(C)}function p(C){return C===62?$(C):C===45?g(C):h(C)}function f(C){const P="CDATA[";return C===P.charCodeAt(o++)?(e.consume(C),o===P.length?x:f):s(C)}function x(C){return C===null?s(C):C===93?(e.consume(C),v):wt(C)?(l=x,B(C)):(e.consume(C),x)}function v(C){return C===93?(e.consume(C),b):x(C)}function b(C){return C===62?$(C):C===93?(e.consume(C),b):x(C)}function y(C){return C===null||C===62?$(C):wt(C)?(l=y,B(C)):(e.consume(C),y)}function N(C){return C===null?s(C):C===63?(e.consume(C),k):wt(C)?(l=N,B(C)):(e.consume(C),N)}function k(C){return C===62?$(C):N(C)}function R(C){return is(C)?(e.consume(C),w):s(C)}function w(C){return C===45||Xn(C)?(e.consume(C),w):M(C)}function M(C){return wt(C)?(l=M,B(C)):Jt(C)?(e.consume(C),M):$(C)}function S(C){return C===45||Xn(C)?(e.consume(C),S):C===47||C===62||hn(C)?z(C):s(C)}function z(C){return C===47?(e.consume(C),$):C===58||C===95||is(C)?(e.consume(C),_):wt(C)?(l=z,B(C)):Jt(C)?(e.consume(C),z):$(C)}function _(C){return C===45||C===46||C===58||C===95||Xn(C)?(e.consume(C),_):I(C)}function I(C){return C===61?(e.consume(C),F):wt(C)?(l=I,B(C)):Jt(C)?(e.consume(C),I):z(C)}function F(C){return C===null||C===60||C===61||C===62||C===96?s(C):C===34||C===39?(e.consume(C),r=C,V):wt(C)?(l=F,B(C)):Jt(C)?(e.consume(C),F):(e.consume(C),D)}function V(C){return C===r?(e.consume(C),r=void 0,E):C===null?s(C):wt(C)?(l=V,B(C)):(e.consume(C),V)}function D(C){return C===null||C===34||C===39||C===60||C===61||C===96?s(C):C===47||C===62||hn(C)?z(C):(e.consume(C),D)}function E(C){return C===47||C===62||hn(C)?z(C):s(C)}function $(C){return C===62?(e.consume(C),e.exit("htmlTextData"),e.exit("htmlText"),n):s(C)}function B(C){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),J}function J(C){return Jt(C)?Zt(e,ie,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):ie(C)}function ie(C){return e.enter("htmlTextData"),l(C)}}const kd={name:"labelEnd",resolveAll:US,resolveTo:BS,tokenize:HS},zS={tokenize:qS},OS={tokenize:VS},FS={tokenize:WS};function US(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&&ys(e,0,e.length,s),e}function BS(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=As(c,e.slice(o+1,o+i+3)),c=As(c,[["enter",m,n]]),c=As(c,Jo(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=As(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=As(c,e.slice(l+1)),c=As(c,[["exit",u,n]]),ys(e,o,e.length,c),e}function HS(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(Bs(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(zS,m,l?m:h)(g):g===91?e.attempt(OS,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(FS,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function qS(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 hn(h)?dr(e,o)(h):o(h)}function o(h){return h===41?m(h):uf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return hn(h)?dr(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?hf(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return hn(h)?dr(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 VS(e,n,s){const i=this;return r;function r(c){return mf.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Bs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function WS(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 KS={name:"labelStartImage",resolveAll:kd.resolveAll,tokenize:GS};function GS(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 JS={name:"labelStartLink",resolveAll:kd.resolveAll,tokenize:YS};function YS(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 Pl={name:"lineEnding",tokenize:QS};function QS(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Zt(e,n,"linePrefix")}}const mo={name:"thematicBreak",tokenize:XS};function XS(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||wt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),Jt(d)?Zt(e,c,"whitespace")(d):c(d))}}const cs={continuation:{tokenize:nC},exit:iC,name:"list",tokenize:tC},ZS={partial:!0,tokenize:aC},eC={partial:!0,tokenize:sC};function tC(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:zc(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(mo,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 zc(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(ZS,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return Jt(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 nC(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,Zt(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!Jt(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(eC,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Zt(e,e.attempt(cs,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function sC(e,n,s){const i=this;return Zt(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 iC(e){e.exit(this.containerState.type)}function aC(e,n,s){const i=this;return Zt(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!Jt(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const vm={name:"setextUnderline",resolveTo:rC,tokenize:oC};function rC(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 oC(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"),Jt(d)?Zt(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||wt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const lC={tokenize:cC};function cC(e){const n=this,s=e.attempt($r,i,e.attempt(this.parser.constructs.flowInitial,r,Zt(e,e.attempt(this.parser.constructs.flow,r,e.attempt(pS,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 dC={resolveAll:ff()},uC=pf("string"),mC=pf("text");function pf(e){return{resolveAll:ff(e==="text"?hC: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 ff(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 hC(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 pC={42:cs,43:cs,45:cs,48:cs,49:cs,50:cs,51:cs,52:cs,53:cs,54:cs,55:cs,56:cs,57:cs,62:of},fC={91:vS},gC={[-2]:Tl,[-1]:Tl,32:Tl},xC={35:SS,42:mo,45:[vm,mo],60:_S,61:vm,95:mo,96:xm,126:xm},bC={38:cf,92:lf},vC={[-5]:Pl,[-4]:Pl,[-3]:Pl,33:KS,38:cf,42:Oc,60:[J0,DS],91:JS,92:[wS,lf],93:kd,95:Oc,96:lS},yC={null:[Oc,dC]},jC={null:[42,95]},kC={null:[]},wC=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:jC,contentInitial:fC,disable:kC,document:pC,flow:xC,flowInitial:gC,insideSpan:yC,string:bC,text:vC},Symbol.toStringTag,{value:"Module"}));function NC(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:M(R),check:M(w),consume:y,enter:N,exit:k,interrupt:M(w,{interrupt:!0})},d={code:null,containerState:{},defineSkip:x,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(I){return l=As(l,I),v(),l[l.length-1]!==null?[]:(S(n,0),d.events=Jo(o,d.events,d),d.events)}function g(I,F){return CC(p(I),F)}function p(I){return SC(l,I)}function f(){const{_bufferIndex:I,_index:F,line:V,column:D,offset:E}=i;return{_bufferIndex:I,_index:F,line:V,column:D,offset:E}}function x(I){r[I.line]=I.column,_()}function v(){let I;for(;i._index<l.length;){const F=l[i._index];if(typeof F=="string")for(I=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===I&&i._bufferIndex<F.length;)b(F.charCodeAt(i._bufferIndex));else b(F)}}function b(I){m=m(I)}function y(I){wt(I)?(i.line++,i.column=1,i.offset+=I===-3?2:1,_()):I!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=I}function N(I,F){const V=F||{};return V.type=I,V.start=f(),d.events.push(["enter",V,d]),c.push(V),V}function k(I){const F=c.pop();return F.end=f(),d.events.push(["exit",F,d]),F}function R(I,F){S(I,F.from)}function w(I,F){F.restore()}function M(I,F){return V;function V(D,E,$){let B,J,ie,C;return Array.isArray(D)?T(D):"tokenize"in D?T([D]):P(D);function P(ge){return be;function be(ce){const Se=ce!==null&&ge[ce],O=ce!==null&&ge.null,le=[...Array.isArray(Se)?Se:Se?[Se]:[],...Array.isArray(O)?O:O?[O]:[]];return T(le)(ce)}}function T(ge){return B=ge,J=0,ge.length===0?$:j(ge[J])}function j(ge){return be;function be(ce){return C=z(),ie=ge,ge.partial||(d.currentConstruct=ge),ge.name&&d.parser.constructs.disable.null.includes(ge.name)?q():ge.tokenize.call(F?Object.assign(Object.create(d),F):d,u,W,q)(ce)}}function W(ge){return I(ie,C),E}function q(ge){return C.restore(),++J<B.length?j(B[J]):$}}}function S(I,F){I.resolveAll&&!o.includes(I)&&o.push(I),I.resolve&&ys(d.events,F,d.events.length-F,I.resolve(d.events.slice(F),d)),I.resolveTo&&(d.events=I.resolveTo(d.events,d))}function z(){const I=f(),F=d.previous,V=d.currentConstruct,D=d.events.length,E=Array.from(c);return{from:D,restore:$};function $(){i=I,d.previous=F,d.currentConstruct=V,d.events.length=D,c=E,_()}}function _(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function SC(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 CC(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 EC(e){const i={constructs:af([wC,...(e||{}).extensions||[]]),content:r(B0),defined:[],document:r(q0),flow:r(lC),lazy:{},string:r(uC),text:r(mC)};return i;function r(o){return l;function l(c){return NC(i,o,c)}}}function MC(e){for(;!df(e););return e}const ym=/[\0\t\n\r]/g;function _C(){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(ym.lastIndex=h,d=ym.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 AC=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function RC(e){return e.replace(AC,TC)}function TC(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return rf(s.slice(o?2:1),o?16:10)}return jd(s)||e}const gf={}.hasOwnProperty;function PC(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),IC(s)(MC(EC(s).document().write(_C()(e,n,!0))))}function IC(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(qe),autolinkProtocol:z,autolinkEmail:z,atxHeading:o(fe),blockQuote:o(O),characterEscape:z,characterReference:z,codeFenced:o(le),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(le,l),codeText:o(ee,l),codeTextData:z,data:z,codeFlowValue:z,definition:o(pe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(ue),hardBreakEscape:o(se),hardBreakTrailing:o(se),htmlFlow:o(Ce,l),htmlFlowData:z,htmlText:o(Ce,l),htmlTextData:z,image:o(De),label:l,link:o(qe),listItem:o(Qe),listItemValue:g,listOrdered:o(et,h),listUnordered:o(et),paragraph:o(Xe),reference:j,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(fe),strong:o(it),thematicBreak:o(We)},exit:{atxHeading:u(),atxHeadingSequence:R,autolink:u(),autolinkEmail:Se,autolinkProtocol:ce,blockQuote:u(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:q,characterReferenceMarkerNumeric:q,characterReferenceValue:ge,characterReference:be,codeFenced:u(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:f,codeFlowValue:_,codeIndented:u(b),codeText:u(E),codeTextData:_,data:_,definition:u(),definitionDestinationString:k,definitionLabelString:y,definitionTitleString:N,emphasis:u(),hardBreakEscape:u(F),hardBreakTrailing:u(F),htmlFlow:u(V),htmlFlowData:_,htmlText:u(D),htmlTextData:_,image:u(B),label:ie,labelText:J,lineEnding:I,link:u($),listItem:u(),listOrdered:u(),listUnordered:u(),paragraph:u(),referenceString:W,resourceDestinationString:C,resourceTitleString:P,resource:T,setextHeading:u(S),setextHeadingLineSequence:M,setextHeadingText:w,strong:u(),thematicBreak:u()}};xf(n,(e||{}).mdastExtensions||[]);const s={};return i;function i(re){let ve={type:"root",children:[]};const te={stack:[ve],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 he=Ae.pop();Fe=r(re,he,Fe)}for(Fe=-1;++Fe<re.length;){const he=n[re[Fe][0]];gf.call(he,re[Fe][1].type)&&he[re[Fe][1].type].call(Object.assign({sliceSerialize:re[Fe][2].sliceSerialize},te),re[Fe][1])}if(te.tokenStack.length>0){const he=te.tokenStack[te.tokenStack.length-1];(he[1]||jm).call(te,void 0,he[0])}for(ve.position={start:vi(re.length>0?re[0][1].start:{line:1,column:1,offset:0}),end:vi(re.length>0?re[re.length-2][1].end:{line:1,column:1,offset:0})},Fe=-1;++Fe<n.transforms.length;)ve=n.transforms[Fe](ve)||ve;return ve}function r(re,ve,te){let Ae=ve-1,Fe=-1,he=!1,Me,Oe,at,ye;for(;++Ae<=te;){const oe=re[Ae];switch(oe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{oe[0]==="enter"?Fe++:Fe--,ye=void 0;break}case"lineEndingBlank":{oe[0]==="enter"&&(Me&&!ye&&!Fe&&!at&&(at=Ae),ye=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ye=void 0}if(!Fe&&oe[0]==="enter"&&oe[1].type==="listItemPrefix"||Fe===-1&&oe[0]==="exit"&&(oe[1].type==="listUnordered"||oe[1].type==="listOrdered")){if(Me){let Te=Ae;for(Oe=void 0;Te--;){const me=re[Te];if(me[1].type==="lineEnding"||me[1].type==="lineEndingBlank"){if(me[0]==="exit")continue;Oe&&(re[Oe][1].type="lineEndingBlank",he=!0),me[1].type="lineEnding",Oe=Te}else if(!(me[1].type==="linePrefix"||me[1].type==="blockQuotePrefix"||me[1].type==="blockQuotePrefixWhitespace"||me[1].type==="blockQuoteMarker"||me[1].type==="listItemIndent"))break}at&&(!Oe||at<Oe)&&(Me._spread=!0),Me.end=Object.assign({},Oe?re[Oe][1].start:oe[1].end),re.splice(Oe||Ae,0,["exit",Me,oe[2]]),Ae++,te++}if(oe[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},oe[1].start),end:void 0};Me=Te,re.splice(Ae,0,["enter",Te,oe[2]]),Ae++,te++,at=void 0,ye=!0}}}return re[ve][1]._spread=he,te}function o(re,ve){return te;function te(Ae){c.call(this,re(Ae),Ae),ve&&ve.call(this,Ae)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(re,ve,te){this.stack[this.stack.length-1].children.push(re),this.stack.push(re),this.tokenStack.push([ve,te||void 0]),re.position={start:vi(ve.start),end:void 0}}function u(re){return ve;function ve(te){re&&re.call(this,te),d.call(this,te)}}function d(re,ve){const te=this.stack.pop(),Ae=this.tokenStack.pop();if(Ae)Ae[0].type!==re.type&&(ve?ve.call(this,re,Ae[0]):(Ae[1]||jm).call(this,re,Ae[0]));else throw new Error("Cannot close `"+re.type+"` ("+cr({start:re.start,end:re.end})+"): it’s not open");te.position.end=vi(re.end)}function m(){return yd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function g(re){if(this.data.expectingFirstListItemValue){const ve=this.stack[this.stack.length-2];ve.start=Number.parseInt(this.sliceSerialize(re),10),this.data.expectingFirstListItemValue=void 0}}function p(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.lang=re}function f(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.meta=re}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.value=re.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.value=re.replace(/(\r?\n|\r)$/g,"")}function y(re){const ve=this.resume(),te=this.stack[this.stack.length-1];te.label=ve,te.identifier=Bs(this.sliceSerialize(re)).toLowerCase()}function N(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.title=re}function k(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.url=re}function R(re){const ve=this.stack[this.stack.length-1];if(!ve.depth){const te=this.sliceSerialize(re).length;ve.depth=te}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function M(re){const ve=this.stack[this.stack.length-1];ve.depth=this.sliceSerialize(re).codePointAt(0)===61?1:2}function S(){this.data.setextHeadingSlurpLineEnding=void 0}function z(re){const te=this.stack[this.stack.length-1].children;let Ae=te[te.length-1];(!Ae||Ae.type!=="text")&&(Ae=Ie(),Ae.position={start:vi(re.start),end:void 0},te.push(Ae)),this.stack.push(Ae)}function _(re){const ve=this.stack.pop();ve.value+=this.sliceSerialize(re),ve.position.end=vi(re.end)}function I(re){const ve=this.stack[this.stack.length-1];if(this.data.atHardBreak){const te=ve.children[ve.children.length-1];te.position.end=vi(re.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(ve.type)&&(z.call(this,re),_.call(this,re))}function F(){this.data.atHardBreak=!0}function V(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.value=re}function D(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.value=re}function E(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.value=re}function $(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const ve=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=ve,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function B(){const re=this.stack[this.stack.length-1];if(this.data.inReference){const ve=this.data.referenceType||"shortcut";re.type+="Reference",re.referenceType=ve,delete re.url,delete re.title}else delete re.identifier,delete re.label;this.data.referenceType=void 0}function J(re){const ve=this.sliceSerialize(re),te=this.stack[this.stack.length-2];te.label=RC(ve),te.identifier=Bs(ve).toLowerCase()}function ie(){const re=this.stack[this.stack.length-1],ve=this.resume(),te=this.stack[this.stack.length-1];if(this.data.inReference=!0,te.type==="link"){const Ae=re.children;te.children=Ae}else te.alt=ve}function C(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.url=re}function P(){const re=this.resume(),ve=this.stack[this.stack.length-1];ve.title=re}function T(){this.data.inReference=void 0}function j(){this.data.referenceType="collapsed"}function W(re){const ve=this.resume(),te=this.stack[this.stack.length-1];te.label=ve,te.identifier=Bs(this.sliceSerialize(re)).toLowerCase(),this.data.referenceType="full"}function q(re){this.data.characterReferenceType=re.type}function ge(re){const ve=this.sliceSerialize(re),te=this.data.characterReferenceType;let Ae;te?(Ae=rf(ve,te==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Ae=jd(ve);const Fe=this.stack[this.stack.length-1];Fe.value+=Ae}function be(re){const ve=this.stack.pop();ve.position.end=vi(re.end)}function ce(re){_.call(this,re);const ve=this.stack[this.stack.length-1];ve.url=this.sliceSerialize(re)}function Se(re){_.call(this,re);const ve=this.stack[this.stack.length-1];ve.url="mailto:"+this.sliceSerialize(re)}function O(){return{type:"blockquote",children:[]}}function le(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function pe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ue(){return{type:"emphasis",children:[]}}function fe(){return{type:"heading",depth:0,children:[]}}function se(){return{type:"break"}}function Ce(){return{type:"html",value:""}}function De(){return{type:"image",title:null,url:"",alt:null}}function qe(){return{type:"link",title:null,url:"",children:[]}}function et(re){return{type:"list",ordered:re.type==="listOrdered",start:null,spread:re._spread,children:[]}}function Qe(re){return{type:"listItem",spread:re._spread,checked:null,children:[]}}function Xe(){return{type:"paragraph",children:[]}}function it(){return{type:"strong",children:[]}}function Ie(){return{type:"text",value:""}}function We(){return{type:"thematicBreak"}}}function vi(e){return{line:e.line,column:e.column,offset:e.offset}}function xf(e,n){let s=-1;for(;++s<n.length;){const i=n[s];Array.isArray(i)?xf(e,i):$C(e,i)}}function $C(e,n){let s;for(s in n)if(gf.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 jm(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+cr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+cr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+cr({start:n.start,end:n.end})+") is still open")}function DC(e){const n=this;n.parser=s;function s(i){return PC(i,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function LC(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 zC(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
622
- `}]}function OC(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 FC(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function UC(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function BC(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",i=String(n.identifier).toUpperCase(),r=Pa(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 HC(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 qC(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function bf(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 VC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return bf(e,n);const r={src:Pa(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 WC(e,n){const s={src:Pa(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 KC(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 GC(e,n){const s=String(n.identifier).toUpperCase(),i=e.definitionById.get(s);if(!i)return bf(e,n);const r={href:Pa(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 JC(e,n){const s={href:Pa(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 YC(e,n,s){const i=e.all(n),r=s?QC(s):vf(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 QC(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=vf(s[i])}return n}function vf(e){const n=e.spread;return n??e.children.length>1}function XC(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 ZC(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function e2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function t2(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function n2(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=gd(n.children[1]),u=Qp(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 s2(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 i2(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const km=9,wm=32;function a2(e){const n=String(e),s=/\r?\n|\r/g;let i=s.exec(n),r=0;const o=[];for(;i;)o.push(Nm(n.slice(r,i.index),r>0,!0),i[0]),r=i.index+i[0].length,i=s.exec(n);return o.push(Nm(n.slice(r),r>0,!1)),o.join("")}function Nm(e,n,s){let i=0,r=e.length;if(n){let o=e.codePointAt(i);for(;o===km||o===wm;)i++,o=e.codePointAt(i)}if(s){let o=e.codePointAt(r-1);for(;o===km||o===wm;)r--,o=e.codePointAt(r-1)}return r>i?e.slice(i,r):""}function r2(e,n){const s={type:"text",value:a2(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function o2(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const l2={blockquote:LC,break:zC,code:OC,delete:FC,emphasis:UC,footnoteReference:BC,heading:HC,html:qC,imageReference:VC,image:WC,inlineCode:KC,linkReference:GC,link:JC,listItem:YC,list:XC,paragraph:ZC,root:e2,strong:t2,table:n2,tableCell:i2,tableRow:s2,text:r2,thematicBreak:o2,toml:Xr,yaml:Xr,definition:Xr,footnoteDefinition:Xr};function Xr(){}const yf=-1,Yo=0,ur=1,Co=2,wd=3,Nd=4,Sd=5,Cd=6,jf=7,kf=8,Sm=typeof self=="object"?self:globalThis,c2=(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 Yo:case yf:return s(l,r);case ur:{const c=s([],r);for(const u of l)c.push(i(u));return c}case Co:{const c=s({},r);for(const[u,d]of l)c[i(u)]=i(d);return c}case wd:return s(new Date(l),r);case Nd:{const{source:c,flags:u}=l;return s(new RegExp(c,u),r)}case Sd:{const c=s(new Map,r);for(const[u,d]of l)c.set(i(u),i(d));return c}case Cd:{const c=s(new Set,r);for(const u of l)c.add(i(u));return c}case jf:{const{name:c,message:u}=l;return s(new Sm[c](u),r)}case kf: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 Sm[o](l),r)};return i},Cm=e=>c2(new Map,e)(0),oa="",{toString:d2}={},{keys:u2}=Object,Wa=e=>{const n=typeof e;if(n!=="object"||!e)return[Yo,n];const s=d2.call(e).slice(8,-1);switch(s){case"Array":return[ur,oa];case"Object":return[Co,oa];case"Date":return[wd,oa];case"RegExp":return[Nd,oa];case"Map":return[Sd,oa];case"Set":return[Cd,oa];case"DataView":return[ur,s]}return s.includes("Array")?[ur,s]:s.includes("Error")?[jf,s]:[Co,s]},Zr=([e,n])=>e===Yo&&(n==="function"||n==="symbol"),m2=(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]=Wa(l);switch(c){case Yo:{let m=l;switch(u){case"bigint":c=kf,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+u);m=null;break;case"undefined":return r([yf],l)}return r([c,m],l)}case ur:{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 Co:{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 u2(l))(e||!Zr(Wa(l[g])))&&m.push([o(g),o(l[g])]);return h}case wd:return r([c,l.toISOString()],l);case Nd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case Sd:{const m=[],h=r([c,m],l);for(const[g,p]of l)(e||!(Zr(Wa(g))||Zr(Wa(p))))&&m.push([o(g),o(p)]);return h}case Cd:{const m=[],h=r([c,m],l);for(const g of l)(e||!Zr(Wa(g)))&&m.push(o(g));return h}}const{message:d}=l;return r([c,{name:u,message:d}],l)};return o},Em=(e,{json:n,lossy:s}={})=>{const i=[];return m2(!(n||s),!!n,new Map,i)(e),i},Eo=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?Cm(Em(e,n)):structuredClone(e):(e,n)=>Cm(Em(e,n));function h2(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 p2(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function f2(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||h2,i=e.options.footnoteBackLabel||p2,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=Pa(h.toLowerCase());let p=0;const f=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){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 b={type:"element",tagName:"li",properties:{id:n+"fn-"+g},children:e.wrap(m,!0)};e.patch(d,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...Eo(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 Qo=(function(e){if(e==null)return v2;if(typeof e=="function")return Xo(e);if(typeof e=="object")return Array.isArray(e)?g2(e):x2(e);if(typeof e=="string")return b2(e);throw new Error("Expected function, string, or object as test")});function g2(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Qo(e[s]);return Xo(i);function i(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function x2(e){const n=e;return Xo(s);function s(i){const r=i;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function b2(e){return Xo(n);function n(s){return s&&s.type===e}}function Xo(e){return n;function n(s,i,r){return!!(y2(s)&&e.call(this,s,typeof i=="number"?i:void 0,r||void 0))}}function v2(){return!0}function y2(e){return e!==null&&typeof e=="object"&&"type"in e}const wf=[],j2=!0,Fc=!1,k2="skip";function Nf(e,n,s,i){let r;typeof n=="function"&&typeof s!="function"?(i=s,s=n):r=n;const o=Qo(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=wf,f,x,v;if((!n||o(u,d,m[m.length-1]||void 0))&&(p=w2(s(u,m)),p[0]===Fc))return p;if("children"in u&&u.children){const b=u;if(b.children&&p[0]!==k2)for(x=(i?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(f=c(y,x,v)(),f[0]===Fc)return f;x=typeof f[1]=="number"?f[1]:x+l}}return p}}}function w2(e){return Array.isArray(e)?e:typeof e=="number"?[j2,e]:e==null?wf:[e]}function Ed(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),Nf(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 Uc={}.hasOwnProperty,N2={};function S2(e,n){const s=n||N2,i=new Map,r=new Map,o=new Map,l={...l2,...s.handlers},c={all:d,applyData:E2,definitionById:i,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:u,options:s,patch:C2,wrap:_2};return Ed(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(Uc.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:x,...v}=m,b=Eo(v);return b.children=c.all(m),b}return Eo(m)}return(c.options.unknownHandler||M2)(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=Mm(f.value)),!Array.isArray(f)&&f.type==="element")){const x=f.children[0];x&&x.type==="text"&&(x.value=Mm(x.value))}Array.isArray(f)?h.push(...f):h.push(f)}}}return h}}function C2(e,n){e.position&&(n.position=p0(e))}function E2(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,Eo(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function M2(e,n){const s=n.data||{},i="value"in n&&!(Uc.call(s,"hProperties")||Uc.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 _2(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 Mm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function _m(e,n){const s=S2(e,n),i=s.one(e,void 0),r=f2(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 A2(e,n){return e&&"run"in e?async function(s,i){const r=_m(s,{file:i,...n});await e.run(r,i)}:function(s,i){return _m(s,{file:i,...e||n})}}function Am(e){if(e)throw e}var Il,Rm;function R2(){if(Rm)return Il;Rm=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 Il=function u(){var d,m,h,g,p,f,x=arguments[0],v=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(d=arguments[v],d!=null)for(m in d)h=c(x,m),g=c(d,m),x!==g&&(y&&g&&(o(g)||(p=r(g)))?(p?(p=!1,f=h&&r(h)?h:[]):f=h&&o(h)?h:{},l(x,{name:m,newValue:u(y,f,g)})):typeof g<"u"&&l(x,{name:m,newValue:g}));return x},Il}var T2=R2();const $l=Uh(T2);function Bc(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 P2(){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?I2(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 I2(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 Js={basename:$2,dirname:D2,extname:L2,join:z2,sep:"/"};function $2(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 D2(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 L2(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 z2(...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?".":O2(s)}function O2(e){Dr(e);const n=e.codePointAt(0)===47;let s=F2(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function F2(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 U2={cwd:B2};function B2(){return"/"}function Hc(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function H2(e){if(typeof e=="string")e=new URL(e);else if(!Hc(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 q2(e)}function q2(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 Dl=["history","path","basename","stem","extname","dirname"];class Sf{constructor(n){let s;n?Hc(n)?s={path:n}:typeof n=="string"||V2(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":U2.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let i=-1;for(;++i<Dl.length;){const o=Dl[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)Dl.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Js.basename(this.path):void 0}set basename(n){zl(n,"basename"),Ll(n,"basename"),this.path=Js.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Js.dirname(this.path):void 0}set dirname(n){Tm(this.basename,"dirname"),this.path=Js.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Js.extname(this.path):void 0}set extname(n){if(Ll(n,"extname"),Tm(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=Js.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Hc(n)&&(n=H2(n)),zl(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Js.basename(this.path,this.extname):void 0}set stem(n){zl(n,"stem"),Ll(n,"stem"),this.path=Js.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 es(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 Ll(e,n){if(e&&e.includes(Js.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Js.sep+"`")}function zl(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Tm(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function V2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const W2=(function(e){const i=this.constructor.prototype,r=i[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,i),o}),K2={}.hasOwnProperty;class Md extends W2{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=P2()}copy(){const n=new Md;let s=-1;for(;++s<this.attachers.length;){const i=this.attachers[s];n.use(...i)}return n.data($l(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Ul("data",this.frozen),this.namespace[n]=s,this):K2.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Ul("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=eo(n),i=this.parser||this.Parser;return Ol("parse",i),i(String(s),s)}process(n,s){const i=this;return this.freeze(),Ol("process",this.parser||this.Parser),Fl("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=eo(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);Y2(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(),Ol("processSync",this.parser||this.Parser),Fl("processSync",this.compiler||this.Compiler),this.process(n,r),Im("processSync","process",s),i;function r(o,l){s=!0,Am(o),i=l}}run(n,s,i){Pm(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=eo(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),Im("runSync","run",i),r;function o(l,c){Am(l),r=c,i=!0}}stringify(n,s){this.freeze();const i=eo(s),r=this.compiler||this.Compiler;return Fl("stringify",r),Pm(n),r(n,i)}use(n,...s){const i=this.attachers,r=this.namespace;if(Ul("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=$l(!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 x=i[g][1];Bc(x)&&Bc(p)&&(p=$l(!0,x,p)),i[g]=[d,p,...f]}}}}const G2=new Md().freeze();function Ol(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function Fl(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Ul(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 Pm(e){if(!Bc(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Im(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function eo(e){return J2(e)?e:new Sf(e)}function J2(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function Y2(e){return typeof e=="string"||Q2(e)}function Q2(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const X2="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",$m=[],Dm={allowDangerousHtml:!0},Z2=/^(https?|ircs?|mailto|xmpp)$/i,eE=[{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=tE(e),s=nE(e);return sE(n.runSync(n.parse(s),s),e)}function tE(e){const n=e.rehypePlugins||$m,s=e.remarkPlugins||$m,i=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Dm}:Dm;return G2().use(DC).use(s).use(A2,i).use(n)}function nE(e){const n=e.children||"",s=new Sf;return typeof n=="string"&&(s.value=n),s}function sE(e,n){const s=n.allowedElements,i=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,u=n.urlTransform||iE;for(const m of eE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+X2+m.id,void 0);return Ed(e,d),v0(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 Rl)if(Object.hasOwn(Rl,p)&&Object.hasOwn(m.properties,p)){const f=m.properties[p],x=Rl[p];(x===null||x.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 iE(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||Z2.test(e.slice(0,n))?e:""}function Lm(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 aE(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function rE(e,n,s){const r=Qo((s||{}).ignore||[]),o=oE(n);let l=-1;for(;++l<o.length;)Nf(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 b=!1,y=[];g.lastIndex=0;let N=g.exec(d.value);for(;N;){const k=N.index,R={index:N.index,input:N.input,stack:[...m,d]};let w=p(...N,R);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?g.lastIndex=k+1:(f!==k&&y.push({type:"text",value:d.value.slice(f,k)}),Array.isArray(w)?y.push(...w):w&&y.push(w),f=k+N[0].length,b=!0),!g.global)break;N=g.exec(d.value)}return b?(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 oE(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([lE(r[0]),cE(r[1])])}return n}function lE(e){return typeof e=="string"?new RegExp(aE(e),"g"):e}function cE(e){return typeof e=="function"?e:function(){return e}}const Bl="phrasing",Hl=["autolink","link","image","label"];function dE(){return{transforms:[xE],enter:{literalAutolink:mE,literalAutolinkEmail:ql,literalAutolinkHttp:ql,literalAutolinkWww:ql},exit:{literalAutolink:gE,literalAutolinkEmail:fE,literalAutolinkHttp:hE,literalAutolinkWww:pE}}}function uE(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Bl,notInConstruct:Hl},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Bl,notInConstruct:Hl},{character:":",before:"[ps]",after:"\\/",inConstruct:Bl,notInConstruct:Hl}]}}function mE(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function ql(e){this.config.enter.autolinkProtocol.call(this,e)}function hE(e){this.config.exit.autolinkProtocol.call(this,e)}function pE(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 fE(e){this.config.exit.autolinkEmail.call(this,e)}function gE(e){this.exit(e)}function xE(e){rE(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,bE],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,vE]],{ignore:["link","linkReference"]})}function bE(e,n,s,i,r){let o="";if(!Cf(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!yE(s)))return!1;const l=jE(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 vE(e,n,s,i){return!Cf(i,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function yE(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 jE(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=Lm(e,"(");let o=Lm(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 Cf(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||Vi(s)||Go(s))&&(!n||s!==47)}Ef.peek=AE;function kE(){this.buffer()}function wE(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function NE(){this.buffer()}function SE(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function CE(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Bs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function EE(e){this.exit(e)}function ME(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=Bs(this.sliceSerialize(e)).toLowerCase(),s.label=n}function _E(e){this.exit(e)}function AE(){return"["}function Ef(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 RE(){return{enter:{gfmFootnoteCallString:kE,gfmFootnoteCall:wE,gfmFootnoteDefinitionLabelString:NE,gfmFootnoteDefinition:SE},exit:{gfmFootnoteCallString:CE,gfmFootnoteCall:EE,gfmFootnoteDefinitionLabelString:ME,gfmFootnoteDefinition:_E}}}function TE(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Ef},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?Mf:PE))),d(),u}}function PE(e,n,s){return n===0?e:Mf(e,n,s)}function Mf(e,n,s){return(s?"":" ")+e}const IE=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];_f.peek=OE;function $E(){return{canContainEols:["delete"],enter:{strikethrough:LE},exit:{strikethrough:zE}}}function DE(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:IE}],handlers:{delete:_f}}}function LE(e){this.enter({type:"delete",children:[]},e)}function zE(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 OE(){return"~"}function FE(e){return e.length}function UE(e,n){const s=n||{},i=(s.align||[]).concat(),r=s.stringLength||FE,o=[],l=[],c=[],u=[];let d=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>d&&(d=e[m].length);++b<e[m].length;){const y=BE(e[m][b]);if(s.alignDelimiters!==!1){const N=r(y);v[b]=N,(u[b]===void 0||N>u[b])&&(u[b]=N)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof i=="object"&&"length"in i)for(;++h<d;)o[h]=zm(i[h]);else{const x=zm(i);for(;++h<d;)o[h]=x}h=-1;const g=[],p=[];for(;++h<d;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,u[h]-v.length-b.length);const N=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>u[h]&&(u[h]=y),p[h]=y),g[h]=N}l.splice(1,0,g),c.splice(1,0,p),m=-1;const f=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<d;){const y=x[h]||"";let N="",k="";if(s.alignDelimiters!==!1){const R=u[h]-(v[h]||0),w=o[h];w===114?N=" ".repeat(R):w===99?R%2?(N=" ".repeat(R/2+.5),k=" ".repeat(R/2-.5)):(N=" ".repeat(R/2),k=N):k=" ".repeat(R)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(N),b.push(y),s.alignDelimiters!==!1&&b.push(k),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==d-1)&&b.push("|")}f.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return f.join(`
633
- `)}function BE(e){return e==null?"":String(e)}function zm(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 HE(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()),qE);return r(),l}function qE(e,n,s){return">"+(s?"":" ")+e}function VE(e,n){return Om(e,n.inConstruct,!0)&&!Om(e,n.notInConstruct,!1)}function Om(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 Fm(e,n,s,i){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
634
- `&&VE(s.stack,s.unsafe[r]))return/[ \t]/.test(i.before)?"":" ";return`\\
635
- `}function WE(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 KE(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 GE(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 JE(e,n,s,i){const r=GE(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(KE(e,s)){const h=s.enter("codeIndented"),g=s.indentLines(o,YE);return h(),g}const c=s.createTracker(i),u=r.repeat(Math.max(WE(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 YE(e,n,s){return(s?"":" ")+e}function _d(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 QE(e,n,s,i){const r=_d(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 XE(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 Mo(e,n,s){const i=ja(e),r=ja(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}}Af.peek=ZE;function Af(e,n,s,i){const r=XE(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=Mo(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=Mo(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 ZE(e,n,s){return s.options.emphasis||"*"}function eM(e,n){let s=!1;return Ed(e,function(i){if("value"in i&&/\r?\n|\r/.test(i.value)||i.type==="break")return s=!0,Fc}),!!((!e.depth||e.depth<3)&&yd(e)&&(n.options.setext||s))}function tM(e,n,s,i){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(i);if(eM(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}Rf.peek=nM;function Rf(e){return e.value||""}function nM(){return"<"}Tf.peek=sM;function Tf(e,n,s,i){const r=_d(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 sM(){return"!"}Pf.peek=iM;function Pf(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 iM(){return"!"}If.peek=aM;function If(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 aM(){return"`"}function $f(e,n){const s=yd(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))}Df.peek=rM;function Df(e,n,s,i){const r=_d(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if($f(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 rM(e,n,s){return $f(e,s)?"<":"["}Lf.peek=oM;function Lf(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 oM(){return"["}function Ad(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 lM(e){const n=Ad(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 cM(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 zf(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 dM(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?cM(s):Ad(s);const c=e.ordered?l==="."?")":".":lM(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),zf(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 uM(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 mM(e,n,s,i){const r=uM(s);let o=s.bulletCurrent||Ad(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 hM(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const pM=Qo(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function fM(e,n,s,i){return(e.children.some(function(l){return pM(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function gM(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Of.peek=xM;function Of(e,n,s,i){const r=gM(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=Mo(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=Mo(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 xM(e,n,s){return s.options.strong||"*"}function bM(e,n,s,i){return s.safe(e.value,i)}function vM(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 yM(e,n,s){const i=(zf(s)+(s.options.ruleSpaces?" ":"")).repeat(vM(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Ff={blockquote:HE,break:Fm,code:JE,definition:QE,emphasis:Af,hardBreak:Fm,heading:tM,html:Rf,image:Tf,imageReference:Pf,inlineCode:If,link:Df,linkReference:Lf,list:dM,listItem:mM,paragraph:hM,root:fM,strong:Of,text:bM,thematicBreak:yM};function jM(){return{enter:{table:kM,tableData:Um,tableHeader:Um,tableRow:NM},exit:{codeText:SM,table:wM,tableData:Vl,tableHeader:Vl,tableRow:Vl}}}function kM(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 wM(e){this.exit(e),this.data.inTable=void 0}function NM(e){this.enter({type:"tableRow",children:[]},e)}function Vl(e){this.exit(e)}function Um(e){this.enter({type:"tableCell",children:[]},e)}function SM(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,CM));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function CM(e,n){return n==="|"?n:e}function EM(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,x,v){return d(m(p,x,v),p.align)}function c(p,f,x,v){const b=h(p,x,v),y=d([b]);return y.slice(0,y.indexOf(`
646
- `))}function u(p,f,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),N=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),N}function d(p,f){return UE(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,x){const v=p.children;let b=-1;const y=[],N=f.enter("table");for(;++b<v.length;)y[b]=h(v[b],f,x);return N(),y}function h(p,f,x){const v=p.children;let b=-1;const y=[],N=f.enter("tableRow");for(;++b<v.length;)y[b]=u(v[b],p,f,x);return N(),y}function g(p,f,x){let v=Ff.inlineCode(p,f,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function MM(){return{exit:{taskListCheckValueChecked:Bm,taskListCheckValueUnchecked:Bm,paragraph:AM}}}function _M(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:RM}}}function Bm(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function AM(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 RM(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=Ff.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 TM(){return[dE(),RE(),$E(),jM(),MM()]}function PM(e){return{extensions:[uE(),TE(e),DE(),EM(e),_M()]}}const IM={tokenize:FM,partial:!0},Uf={tokenize:UM,partial:!0},Bf={tokenize:BM,partial:!0},Hf={tokenize:HM,partial:!0},$M={tokenize:qM,partial:!0},qf={name:"wwwAutolink",tokenize:zM,previous:Wf},Vf={name:"protocolAutolink",tokenize:OM,previous:Kf},gi={name:"emailAutolink",tokenize:LM,previous:Gf},ni={};function DM(){return{text:ni}}let $i=48;for(;$i<123;)ni[$i]=gi,$i++,$i===58?$i=65:$i===91&&($i=97);ni[43]=gi;ni[45]=gi;ni[46]=gi;ni[95]=gi;ni[72]=[gi,Vf];ni[104]=[gi,Vf];ni[87]=[gi,qf];ni[119]=[gi,qf];function LM(e,n,s){const i=this;let r,o;return l;function l(h){return!qc(h)||!Gf.call(i,i.previous)||Rd(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return qc(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check($M,m,d)(h):h===45||h===95||Xn(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&&is(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function zM(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Wf.call(i,i.previous)||Rd(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(IM,e.attempt(Uf,e.attempt(Bf,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function OM(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Kf.call(i,i.previous)&&!Rd(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(is(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||So(h)||hn(h)||Vi(h)||Go(h)?s(h):e.attempt(Uf,e.attempt(Bf,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function FM(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 UM(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Hf,u,c)(d):d===null||hn(d)||Vi(d)||d!==45&&Go(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 BM(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(Hf,n,o)(l):l===null||hn(l)||Vi(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function HM(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||hn(c)||Vi(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||hn(c)||Vi(c)?n(c):i(c)}function o(c){return is(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):is(c)?(e.consume(c),l):s(c)}}function qM(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return Xn(o)?s(o):n(o)}}function Wf(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||hn(e)}function Kf(e){return!is(e)}function Gf(e){return!(e===47||qc(e))}function qc(e){return e===43||e===45||e===46||e===95||Xn(e)}function Rd(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 VM={tokenize:ZM,partial:!0};function WM(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:YM,continuation:{tokenize:QM},exit:XM}},text:{91:{name:"gfmFootnoteCall",tokenize:JM},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:KM,resolveTo:GM}}}}function KM(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=Bs(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 GM(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 JM(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||hn(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Bs(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return hn(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 YM(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||hn(f))return s(f);if(f===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=Bs(i.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return hn(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),Zt(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function QM(e,n,s){return e.check($r,n,e.attempt(VM,n,s))}function XM(e){e.exit("gfmFootnoteDefinition")}function ZM(e,n,s){const i=this;return Zt(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 e_(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&&ys(g,g.length,0,Jo(p,l.slice(d+1,u),c)),ys(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),ys(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 x=ja(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"),b=ja(f);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(f)}}}class t_{constructor(){this.map=[]}add(n,s,i){n_(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 n_(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 s_(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 i_(){return{flow:{null:{name:"table",tokenize:a_,resolveAll:r_}}}}function a_(e,n,s){const i=this;let r=0,o=0,l;return c;function c(_){let I=i.events.length-1;for(;I>-1;){const D=i.events[I][1].type;if(D==="lineEnding"||D==="linePrefix")I--;else break}const F=I>-1?i.events[I][1].type:null,V=F==="tableHead"||F==="tableRow"?w:u;return V===w&&i.parser.lazy[i.now().line]?s(_):V(_)}function u(_){return e.enter("tableHead"),e.enter("tableRow"),d(_)}function d(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):wt(_)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):Jt(_)?Zt(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||hn(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?g:h)}function g(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,Jt(_)?Zt(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):f(_))}function f(_){return _===45||_===58?v(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),x):R(_)}function x(_){return Jt(_)?Zt(e,v,"whitespace")(_):v(_)}function v(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),b):_===45?(o+=1,b(_)):_===null||wt(_)?k(_):R(_)}function b(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):R(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),N):(e.exit("tableDelimiterFiller"),N(_))}function N(_){return Jt(_)?Zt(e,k,"whitespace")(_):k(_)}function k(_){return _===124?f(_):_===null||wt(_)?!l||r!==o?R(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):R(_)}function R(_){return s(_)}function w(_){return e.enter("tableRow"),M(_)}function M(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),M):_===null||wt(_)?(e.exit("tableRow"),n(_)):Jt(_)?Zt(e,M,"whitespace")(_):(e.enter("data"),S(_))}function S(_){return _===null||_===124||hn(_)?(e.exit("data"),M(_)):(e.consume(_),_===92?z:S)}function z(_){return _===92||_===124?(e.consume(_),S):S(_)}}function r_(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 t_;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Hm(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=to(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=to(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=to(g,n,o,r,s,h)):l[1]!==0&&(h=to(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Hm(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=s_(n.events,s))}return e}function to(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ua(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=ua(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=ua(n.events,s[2]),m=ua(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,x=s[3]-s[2]-1;e.add(f,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},ua(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Hm(e,n,s,i,r){const o=[],l=ua(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 ua(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const o_={name:"tasklistCheck",tokenize:c_};function l_(){return{text:{91:o_}}}function c_(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 hn(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 wt(u)?n(u):Jt(u)?e.check({tokenize:d_},n,s)(u):s(u)}}function d_(e,n,s){return Zt(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function u_(e){return af([DM(),WM(),e_(e),i_(),l_()])}const m_={};function fi(e){const n=this,s=e||m_,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(u_(s)),o.push(TM()),l.push(PM(s))}const qm=500,Vm=100;function Wl(e){return e.length>qm?e.slice(-qm):e}function Jf(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),x=a.useRef(0),v=a.useRef(e),b=a.useRef(s),y=a.useRef(n),N=a.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.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 M=x.current,S=++N.current;f.current=!1;const z=e,_=s;async function I(){if(!z)return;l(!0),g(!1);try{const V=await Hd(z,_,{limit:Vm});if(f.current||x.current!==M||N.current!==S)return;r(Wl(V.entries)),u(V.hasMore),m(V.total)}catch{if(f.current||x.current!==M||N.current!==S)return;r([]),u(!1),m(null)}finally{!f.current&&x.current===M&&N.current===S&&l(!1)}const F=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=qs(`/api/tasks/${z}/logs/stream${F}`,{events:{"agent:log":V=>{if(!(f.current||x.current!==M))try{const D=JSON.parse(V.data);r(E=>Wl([...E,D])),m(E=>E!==null?E+1:null)}catch{}}}})}return I(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=a.useCallback(async()=>{if(!e||h)return;const M=x.current,S=i.length,z=e;g(!0);try{const _=await Hd(z,s,{limit:Vm,offset:S});if(f.current||x.current!==M)return;r(I=>{const F=[..._.entries,...I];return Wl(F)}),u(_.hasMore),m(_.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),w=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:w,loadMore:R,hasMore:c,total:d,loadingMore:h}}function h_(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 Wm={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})},Yf=50,p_={triage:"Plan"};function Km(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Yf}function Vc(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function f_(e){const n=new Map;return e.map(s=>{const i=Vc(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function g_(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function x_(e,n){return e.agent?g_(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function b_(e,n){const s=[];for(let i=0;i<e.length;i+=1){const r=e[i],o=n[i]??`${Vc(r)}|fallback`,l=i>0?e[i-1]:void 0,c=x_(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]??`${Vc(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 v_({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,x]=a.useState(!0),[v,b]=a.useState(!1),[y,N]=a.useState(!1),[k,R]=a.useState(!0),w=a.useMemo(()=>f_(e),[e]),M=a.useMemo(()=>b_(e,w),[e,w]);a.useLayoutEffect(()=>{const E=d.current;if(!E)return;const $=e.length,B=m.current,J=h.current||E.scrollHeight,ie=w[0]??null,C=w[w.length-1]??null,P=g.current!==ie,T=p.current!==C;if($>B)if(B===0)E.scrollTop=E.scrollHeight;else{const j=J-(E.scrollTop+E.clientHeight)<=Yf,W=T&&!P,q=P&&!T;if(W&&j&&(E.scrollTop=E.scrollHeight),q){const ge=E.scrollHeight-J;ge>0&&(E.scrollTop+=ge)}}m.current=$,h.current=E.scrollHeight,g.current=ie,p.current=C,R(Km(E))},[e,w]);const S=a.useCallback(()=>{const E=d.current;E&&R(Km(E))},[]),z=a.useCallback(()=>{const E=d.current;E&&(E.scrollTop=E.scrollHeight,R(!0))},[]),_=a.useCallback(E=>{E.key==="Escape"&&v&&b(!1)},[v]);a.useEffect(()=>{if(v)return document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}},[v,_]);const I=s?.provider&&s?.modelId,F=i?.provider&&i?.modelId,V=r?.provider&&r?.modelId,D=a.useMemo(()=>{const E=[];return I&&E.push({role:"Executor",provider:s.provider,modelId:s.modelId}),F&&E.push({role:"Reviewer",provider:i.provider,modelId:i.modelId}),V&&E.push({role:"Planning",provider:r.provider,modelId:r.modelId}),E},[I,s,F,i,V,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:[D.map(E=>t.jsx(zn,{provider:E.provider,size:"sm"},`${E.role}-${E.provider}-${E.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>N(E=>!E),"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(Qt,{size:14}):t.jsx(vn,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(E=>!E),"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:()=>b(E=>!E),"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(zo,{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:"}),I?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(zn,{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(zn,{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:"}),V?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(zn,{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:S,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"})}),M.map(E=>{const $=E.kind==="single"?E.entry:E.entries[0],B=E.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:h_($.timestamp)}):null,J=E.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",p_[$.agent]??$.agent,"]"]}),B]}):null;if(E.kind==="single"){const{entry:C}=E;if(C.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[J,"⚡ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},E.key);if(C.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[J,"✓ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},E.key);if(C.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[J,"✗ ",C.text,C.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",C.detail]})]},E.key)}const ie=E.kind==="single"?$.text:E.entries.map(C=>C.text).join("");return E.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:Wm,children:ie})}):ie]},E.key):t.jsxs("div",{className:"agent-log-text",children:[J,f?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:Wm,children:ie})}):ie]},E.key)}),!k&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:z,"data-testid":"agent-log-return-to-live",children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ka(e){return e??void 0}function no(e){return{provider:ka(e.modelProvider),modelId:ka(e.modelId)}}function so(e){return{provider:ka(e.validatorModelProvider),modelId:ka(e.validatorModelId)}}function io(e){return{provider:ka(e.planningModelProvider),modelId:ka(e.planningModelId)}}function y_(e,n){return wp(e,n)}function j_(e,n){return Np(e,n)}function k_(e,n){return Sp(e,n)}function Kl(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 Gl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Jl(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function w_(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 N_({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,x]=a.useState(()=>no(e)),[v,b]=a.useState(()=>no(e)),[y,N]=a.useState(()=>so(e)),[k,R]=a.useState(()=>so(e)),[w,M]=a.useState(()=>io(e)),[S,z]=a.useState(()=>io(e)),[_,I]=a.useState(()=>e.thinkingLevel??null),[F,V]=a.useState(()=>e.thinkingLevel??null),[D,E]=a.useState(null),$=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),ms().then(ue=>{o(ue.models),c(ue.favoriteProviders),d(ue.favoriteModels)}).catch(ue=>{p(ue.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const B=a.useCallback(async ue=>{const fe=l,Ce=fe.includes(ue)?fe.filter(De=>De!==ue):[ue,...fe];c(Ce);try{await mn({favoriteProviders:Ce,favoriteModels:u})}catch{c(fe),n("Failed to update favorites","error")}},[l,u,n]),J=a.useCallback(async ue=>{const fe=u,Ce=fe.includes(ue)?fe.filter(De=>De!==ue):[ue,...fe];d(Ce);try{await mn({favoriteProviders:l,favoriteModels:Ce})}catch{d(fe),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{$.current=e.id;const ue=no(e),fe=so(e),se=io(e);x(ue),b(ue),N(fe),R(fe),M(se),z(se);const Ce=e.thinkingLevel??null;I(Ce),V(Ce),E(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const ie=a.useMemo(()=>Gl(f),[f]),C=a.useMemo(()=>Gl(y),[y]),P=a.useMemo(()=>Gl(w),[w]),T=a.useMemo(()=>y_(e,i),[e,i]),j=a.useMemo(()=>j_(e,i),[e,i]),W=a.useMemo(()=>k_(e,i),[e,i]),q=D!==null,ge=a.useCallback(async(ue,fe)=>{const se=e.id,Ce=v,De=k,qe=S;E(ue);try{const et=s?ue==="executor"?{modelProvider:fe.provider??null,modelId:fe.modelId??null}:ue==="validator"?{validatorModelProvider:fe.provider??null,validatorModelId:fe.modelId??null}:{planningModelProvider:fe.provider??null,planningModelId:fe.modelId??null}:{modelProvider:(ue==="executor"?fe:v).provider??null,modelId:(ue==="executor"?fe:v).modelId??null,validatorModelProvider:(ue==="validator"?fe:k).provider??null,validatorModelId:(ue==="validator"?fe:k).modelId??null,planningModelProvider:(ue==="planning"?fe:S).provider??null,planningModelId:(ue==="planning"?fe:S).modelId??null},Qe=await Qs(se,et);if($.current!==se)return;const Xe=no(Qe),it=so(Qe),Ie=io(Qe);b(Xe),x(Xe),R(it),N(it),z(Ie),M(Ie),s?.(Qe),n(w_(ue,{executor:Xe,validator:it,planning:Ie}[ue]),"success")}catch(et){if($.current!==se)return;ue==="executor"?x(Ce):ue==="validator"?N(De):M(qe),n(ke(et)||"Failed to save model settings","error")}finally{$.current===se&&E(null)}},[e.id,v,k,S,n,s]),be=a.useCallback(ue=>{const fe=Kl(ue);x(fe),!Jl(fe,v)&&ge("executor",fe)},[v,ge]),ce=a.useCallback(ue=>{const fe=Kl(ue);N(fe),!Jl(fe,k)&&ge("validator",fe)},[k,ge]),Se=a.useCallback(ue=>{const fe=Kl(ue);M(fe),!Jl(fe,S)&&ge("planning",fe)},[S,ge]),O=a.useCallback(async ue=>{const fe=e.id,se=F,Ce=ue===""?null:ue;I(Ce),E("thinking");try{const De=await Qs(fe,{thinkingLevel:Ce});if($.current!==fe)return;const qe=De.thinkingLevel??null;V(qe),I(qe),s?.(De);const et=i?.defaultThinkingLevel??"off";n(qe===null?`Thinking level set to default (${et})`:`Thinking level set to ${qe}`,"success")}catch(De){if($.current!==fe)return;I(se),n(ke(De)||"Failed to save thinking level","error")}finally{$.current===fe&&E(null)}},[e.id,F,i,n,s]),le=!v.provider&&!v.modelId,ee=!k.provider&&!k.modelId,pe=!S.provider&&!S.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),ms().then(ue=>{o(ue.models),c(ue.favoriteProviders),d(ue.favoriteModels)}).catch(ue=>p(ue.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:le?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",T.provider&&T.modelId?` (${T.provider}/${T.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(zn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(qn,{id:"executorModel",label:"Executor Model",value:ie,onChange:be,models:r,disabled:q,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:B,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:ee?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",j.provider&&j.modelId?` (${j.provider}/${j.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[k.provider&&t.jsx(zn,{provider:k.provider,size:"sm"}),k.provider,"/",k.modelId]})}),t.jsx(qn,{id:"validatorModel",label:"Reviewer Model",value:C,onChange:ce,models:r,disabled:q,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:B,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:pe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",W.provider&&W.modelId?` (${W.provider}/${W.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(zn,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(qn,{id:"planningModel",label:"Planning Model",value:P,onChange:Se,models:r,disabled:q,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:B,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:_??"",onChange:ue=>O(ue.target.value),disabled:q,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:le&&ee&&pe&&F===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const S_={open:t.jsx(Io,{size:16}),closed:t.jsx(Sr,{size:16}),merged:t.jsx(Jh,{size:16})};function C_({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(""),[x,v]=a.useState(!1),[b,y]=a.useState(!1),[N,k]=a.useState(null),R=a.useCallback(async()=>{if(h.trim()){v(!0);try{const z=await vy(e,{title:h.trim(),body:p.trim()||void 0},n);l(z),m(!1),g(""),f(""),u(`Created PR #${z.number}`,"success")}catch(z){u(ke(z)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),w=a.useCallback(async()=>{if(s){y(!0);try{const z=await yy(e,n);k(z),c(z.prInfo),u("PR status refreshed","success")}catch(z){u(ke(z)||"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(bs,{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(bs,{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(bs,{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:z=>g(z.target.value),disabled:x,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:z=>f(z.target.value),disabled:x,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(bs,{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(an,{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 M=S_[s.status]??t.jsx(Io,{size:16}),S=N?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(bs,{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:M}),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:b,title:"Refresh PR status",children:t.jsx(Tn,{size:14,style:{verticalAlign:"middle",opacity:b?.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:S.length>0?`Waiting for: ${S.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(bx,{size:14}),"View on GitHub"]})]})]})]})}const Gm=2e3;function E_(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function M_(e){return e==="agent"||e==="system"}function __({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),x=a.useMemo(()=>[...e.comments||[]].sort((M,S)=>new Date(S.createdAt).getTime()-new Date(M.createdAt).getTime()),[e.comments]),v=o.length>Gm;async function b(){const M=o.trim();if(M){g(!0);try{const S=await Xv(e.id,M,r);l(""),n?.(S),s("Comment added","success")}catch(S){s(ke(S)||"Failed to add comment","error")}finally{g(!1)}}}async function y(M){const S=d.trim();if(S){g(!0);try{const z=await Kv(e.id,M,S,r);u(null),m(""),n?.(z),s("Comment updated","success")}catch(z){s(ke(z)||"Failed to update comment","error")}finally{g(!1)}}}async function N(M){f(M);try{const S=await Gv(e.id,M,r);n?.(S),s("Comment deleted","success")}catch(S){s(ke(S)||"Failed to delete comment","error")}finally{f(null)}}function k(M){M.key==="Enter"&&(M.ctrlKey||M.metaKey)&&(M.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(M=>{const S=M.author===i,z=c===M.id,_=M_(M.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:M.author}),t.jsx("span",{className:"detail-log-timestamp",children:E_(M)})]}),S&&!z?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(M.id),m(M.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void N(M.id),disabled:p===M.id,children:p===M.id?"Deleting…":"Delete"})]}):null]}),z?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:I=>m(I.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(M.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:M.text})]},M.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:M=>l(M.target.value),onKeyDown:k,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," / ",Gm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function A_(e){return e?e.slice(0,7):"Unknown"}function R_({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:A_(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 Qf(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(po.Fragment,{children:`${s}
649
- `},i)})}function T_(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function P_({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);ti(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)},[]),x=a.useCallback(()=>{d(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(a.useEffect(()=>{if(!e)return;const y=N=>{if(N.key==="Escape"){l();return}N.key==="ArrowUp"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),f()),N.key==="ArrowDown"&&(N.metaKey||N.ctrlKey)&&(N.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,f,x]),!e)return null;const v=u!==null?s[u]:null,b=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(Fs,{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(Po,{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:x,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(vn,{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(xo,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Tn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Gt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(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,N)=>t.jsxs("button",{className:`changes-diff-file-item ${u===N?"selected":""}`,onClick:()=>d(N),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:T_(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:Qf(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(Fs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Xf(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Yl(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(Fs,{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:Xf("unknown")}),t.jsx("span",{className:"changes-file-path",title:i,children:t.jsx("bdo",{dir:"ltr",children:i})})]})},i))})]})}function I_({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,x]=a.useState(new Set),[v,b]=a.useState(null),[y,N]=a.useState(!0),[k,R]=a.useState(!1),w=i==="done",M=w&&!!r?.commitSha,S=i==="in-progress"||i==="in-review"||M,z=a.useCallback(async()=>{if(!S){h(!1);return}try{h(!0),p(null);const D=await fp(e,void 0,s),E=D.files.map($=>({path:$.path,status:$.status,additions:$.additions,deletions:$.deletions,patch:$.patch}));c(E),d(D.stats),E.length>0&&(x(new Set([E[0].path])),b(0))}catch(D){p(ke(D)||"Failed to load diff")}finally{h(!1)}},[e,s,S]);a.useEffect(()=>{z()},[z]);const _=D=>{x(E=>{const $=new Set(E);if($.has(D))$.delete(D);else{$.add(D);const B=l.findIndex(J=>J.path===D);B!==-1&&b(B)}return $})},I=D=>{if(D<0||D>=l.length)return;const E=l[D].path;x(new Set([E])),b(D)},F=v!==null&&v>0,V=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(as,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!w&&!n)return o&&o.length>0?Yl(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Fs,{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&&!M){if(o&&o.length>0)return Yl(o,!0,r);const D=r?.filesChanged,E=r?.insertions,$=r?.deletions,B=D!=null||E!=null||$!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Fs,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:B?`Merge summary: ${D??0} file${(D??0)===1?"":"s"} changed, +${E??0} additions, -${$??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Yl(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Fs,{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(Fs,{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&&I(v-1),disabled:!F,title:"Previous file","aria-label":"Previous file",children:t.jsx(Po,{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:()=>V&&I(v+1),disabled:!V,title:"Next file","aria-label":"Next file",children:t.jsx(vn,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>N(D=>!D),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(xo,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:z,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>R(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(zo,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(D=>{const E=f.has(D.path);return t.jsxs("div",{className:`changes-file-item ${E?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_(D.path),children:[t.jsx("span",{className:"changes-file-toggle",children:E?t.jsx(Qt,{size:14}):t.jsx(vn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${D.status}`,title:D.status,children:Xf(D.status)}),t.jsx("span",{className:"changes-file-path",title:D.path,children:t.jsx("bdo",{dir:"ltr",children:D.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${D.additions} -${D.deletions}`,children:["+",D.additions," -",D.deletions]})]}),E&&D.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:Qf(D.patch)})})})]},D.path)})}),t.jsx(P_,{isOpen:k,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>R(!1),onRefresh:z})]})}function Jm(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function $_(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function OD(e,n){const s=$_(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 D_(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Ym=["image/png","image/jpeg","image/gif","image/webp"];function L_(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 Zf({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:x,validatorModel:v,onValidatorModelChange:b,planningModel:y,onPlanningModelChange:N,thinkingLevel:k,onThinkingLevelChange:R,presetMode:w,onPresetModeChange:M,selectedPresetId:S,onSelectedPresetIdChange:z,selectedWorkflowSteps:_,onWorkflowStepsChange:I,onDefaultOnApplied:F,pendingImages:V,onImagesChange:D,tasks:E,projectId:$,disabled:B=!1,addToast:J,isActive:ie=!0,onAutoSaveDescription:C,onPlanningMode:P,onSubtaskBreakdown:T,onClose:j,renderBelowPrimary:W,renderBelowModelConfiguration:q,hideDependencies:ge,autoExpandMoreOptionsOnSelection:be=!0,reviewLevel:ce,onReviewLevelChange:Se,executionMode:O,onExecutionModeChange:le}){const ee=(ge?!1:o.length>0)||V.length>0||_.length>0||w!=="default"||(g??vs)!==vs||f!==""||v!==""||(y||"")!==""||(k||"")!==""||ce!==void 0||O==="fast"||(c||"")!=="",[pe,ue]=a.useState(!1),[fe,se]=a.useState(be?ee:!1),[Ce,De]=a.useState(""),[qe,et]=a.useState([]),[Qe,Xe]=a.useState([]),[it,Ie]=a.useState([]),[We,re]=a.useState(!1),[ve,te]=a.useState(null),[Ae,Fe]=a.useState([]),[he,Me]=a.useState("idle"),[Oe,at]=a.useState(!1),[ye,oe]=a.useState(!1),[Te,me]=a.useState(!1),_e=a.useRef(null),Ke=a.useRef(null),Re=a.useRef(null),ct=a.useRef(null),Y=a.useRef(null),de=a.useRef(null),we=a.useRef(null),tt=a.useRef(!1),Z=a.useRef(ee),Ge=a.useRef(n.trim()),dt=a.useRef(n.trim());a.useEffect(()=>{ie&&(re(!0),ms().then(A=>{et(A.models),Xe(A.favoriteProviders),Ie(A.favoriteModels)}).catch(()=>{}).finally(()=>re(!1)),Fo($).then(A=>te(A)).catch(()=>te(null)),Uo($).then(A=>Fe(A.filter(X=>X.enabled))).catch(()=>Fe([])))},[ie,$]);const pt=ve?.modelPresets||[],jt=pt.find(A=>A.id===S),yt=(ge?!1:o.length>0)||V.length>0||_.length>0||w!=="default"||(g??vs)!==vs||f!==""||v!==""||(y||"")!==""||(k||"")!==""||ce!==void 0||O==="fast"||(c||"")!=="";a.useEffect(()=>{if(e!=="create"||!ie||!ve?.autoSelectModelPreset)return;const A=(ve.defaultPresetBySize,void 0);if(A){const X=Jm(A);z(A.id),M("preset"),x(X.executorValue),b(X.validatorValue)}},[ie,ve,pt,e]);const ft=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!ie||ft.current||Ae.length===0)return;const A=Ae.filter(ze=>ze.defaultOn);if(A.length===0)return;ft.current=!0;const X=A.map(ze=>ze.id);I(X),F?.(X)},[e,ie,Ae]),a.useEffect(()=>{ie||(ft.current=!1)},[ie]),a.useEffect(()=>{if(!be){Z.current=yt;return}yt&&!Z.current&&se(!0),Z.current=yt},[yt,be]),a.useEffect(()=>{fe||(ue(!1),De(""))},[fe]),a.useEffect(()=>{e!=="edit"||!ie||ct.current&&(ct.current.focus(),ct.current.select())},[e,ie]),a.useEffect(()=>{if(!pe)return;const A=X=>{Ke.current&&!Ke.current.contains(X.target)&&ue(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[pe]),a.useEffect(()=>{(e!=="edit"||B)&&me(!1)},[e,B]),a.useEffect(()=>{if(e!=="edit"){Me("idle");return}const A=n.trim();Ge.current=A,dt.current=A,Me("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!C||!ie)return;const A=n.trim(),X=Ge.current;if(A===X||A===dt.current){de.current&&(clearTimeout(de.current),de.current=null),tt.current||Me("idle");return}return de.current&&clearTimeout(de.current),de.current=setTimeout(async()=>{if(!tt.current){tt.current=!0,Me("saving");try{await C(A),dt.current=A,Me("saved"),we.current&&clearTimeout(we.current),we.current=setTimeout(()=>{Me("idle"),we.current=null},2e3)}catch{Me("idle")}finally{tt.current=!1,de.current=null}}},1500),()=>{de.current&&(clearTimeout(de.current),de.current=null)}},[e,n,C,ie]),a.useEffect(()=>()=>{de.current&&clearTimeout(de.current),we.current&&clearTimeout(we.current)},[]),a.useEffect(()=>{if(!Oe)return;const A=X=>{_e.current&&!_e.current.contains(X.target)&&at(!1)};return document.addEventListener("mousedown",A),()=>document.removeEventListener("mousedown",A)},[Oe]);const St=a.useCallback(A=>{const X=A.clipboardData?.items;if(X)for(let ze=0;ze<X.length;ze++){const ot=X[ze];if(ot.type.startsWith("image/")){const Rt=ot.getAsFile();if(Rt&&Ym.includes(Rt.type)){A.preventDefault(),D([...V,{file:Rt,previewUrl:URL.createObjectURL(Rt)}]);return}}}},[V,D]),Ot=a.useCallback(A=>{A.preventDefault();const X=A.dataTransfer.files;for(let ze=0;ze<X.length;ze++){const ot=X[ze];if(Ym.includes(ot.type)){D([...V,{file:ot,previewUrl:URL.createObjectURL(ot)}]);return}}},[V,D]),Vt=a.useCallback(A=>{const X=V[A];X&&URL.revokeObjectURL(X.previewUrl),D(V.filter((ze,ot)=>ot!==A))},[V,D]),Mt=a.useCallback(A=>{l(o.includes(A)?o.filter(X=>X!==A):[...o,A])},[o,l]),It=(A,X)=>A.length>X?A.slice(0,X)+"…":A,qt=a.useCallback(A=>{s(A.target.value);const X=A.target;X.style.height="auto",X.style.height=X.scrollHeight+"px"},[s]),Ft=a.useCallback(()=>{me(A=>!A)},[]),Xt=a.useCallback(A=>{!Te||A.key!=="Escape"||(A.preventDefault(),A.stopPropagation(),me(!1))},[Te]),$t=a.useCallback(async A=>{const X=n.trim();if(!(!X||ye)){oe(!0);try{const ze=await dp(X,A,$);s(ze),at(!1),J("Description refined with AI","success"),Re.current&&(Re.current.style.height="auto",Re.current.style.height=Re.current.scrollHeight+"px")}catch(ze){const ot=up(ze);J(ot,"error")}finally{oe(!1)}}},[n,ye,J,s,$]),_t=a.useCallback(async A=>{const X=Qe,ot=X.includes(A)?X.filter(Rt=>Rt!==A):[A,...X];Xe(ot);try{await mn({favoriteProviders:ot,favoriteModels:it})}catch{Xe(X)}},[Qe,it]),Ct=a.useCallback(async A=>{const X=it,ot=X.includes(A)?X.filter(Rt=>Rt!==A):[A,...X];Ie(ot);try{await mn({favoriteProviders:Qe,favoriteModels:ot})}catch{Ie(X)}},[it,Qe]),Et=a.useCallback(A=>{if(A<=0)return;const X=[..._];[X[A-1],X[A]]=[X[A],X[A-1]],I(X)},[_,I]),tn=a.useCallback(A=>{if(A>=_.length-1)return;const X=[..._];[X[A],X[A+1]]=[X[A+1],X[A]],I(X)},[_,I]),At=a.useCallback(A=>{I(_.filter(X=>X!==A))},[_,I]),H=new Map;for(const A of Ae)H.set(A.id,{name:A.name,description:A.description});const xe=E.filter(A=>!o.includes(A.id)).sort((A,X)=>{const ze=X.createdAt.localeCompare(A.createdAt);if(ze!==0)return ze;const ot=parseInt(A.id.slice(A.id.lastIndexOf("-")+1),10)||0;return(parseInt(X.id.slice(X.id.lastIndexOf("-")+1),10)||0)-ot}),Le=Ce?xe.filter(A=>A.id.toLowerCase().includes(Ce.toLowerCase())||A.title&&A.title.toLowerCase().includes(Ce.toLowerCase())||A.description&&A.description.toLowerCase().includes(Ce.toLowerCase())):xe;return t.jsxs("div",{className:"task-form",onDrop:Ot,onDragOver:A=>A.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:ct,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:A=>r(A.target.value),disabled:B})]}),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${he==="idle"?"":" is-visible"}`,"aria-live":"polite",children:he==="saving"?"Saving...":he==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Te?" description--fullscreen":""}`,ref:_e,onKeyDown:Xt,children:[Te&&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:Ft,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Er,{size:14})})]}),t.jsx("textarea",{ref:Re,autoFocus:e==="create",id:"task-form-description",value:n,onChange:qt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:B||ye}),(()=>{const A=!!n.trim()&&!B;return t.jsxs(t.Fragment,{children:[!Te&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${A?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Ft,"aria-label":"Expand description",title:"Expand description",children:t.jsx(zo,{size:14})}),A&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ye?"refine-button--loading":""}`,onClick:()=>at(X=>!X),disabled:ye,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Zn,{size:12,style:{verticalAlign:"middle"}}),ye?"Refining...":"Refine"]})]})})(),Oe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:A=>A.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>$t("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:()=>$t("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:()=>$t("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:()=>$t("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"&&(P||T)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[P&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const A=n.trim();if(!A){J("Enter a description first","error");return}j?.(),P(A)},disabled:B||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),T&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const A=n.trim();if(!A){J("Enter a description first","error");return}j?.(),T(A)},disabled:B||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),W,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>se(A=>!A),"aria-expanded":fe,"aria-controls":"task-form-more-options",disabled:B,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),fe?t.jsx(mi,{size:14}):t.jsx(Qt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${fe?"":" collapsed"}`,"aria-hidden":!fe,hidden:!fe,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),V.length>0&&t.jsx("div",{className:"inline-create-previews",children:V.map((A,X)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:A.previewUrl,alt:A.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Vt(X),disabled:B,title:"Remove image",children:"×"})]},A.previewUrl))}),t.jsx("input",{ref:Y,type:"file",accept:"image/*",onChange:A=>{const X=A.target.files?.[0];X&&(D([...V,{file:X,previewUrl:URL.createObjectURL(X)}]),A.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Y.current?.click(),disabled:B,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:A=>u(A.target.value||void 0),disabled:B||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(d??[]).map(A=>t.jsxs("option",{value:A.id,children:[A.name," (",D_(A.status),")"]},A.id))]}),(()=>{const A=(d??[]).find(X=>X.id===c);return A?t.jsx("div",{className:"task-form-node-status",children:t.jsx(qi,{status:A.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!ge&&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:Ke,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ue(A=>!A),disabled:B,children:o.length>0?`${o.length} selected`:"Add dependencies"}),pe&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ce,onChange:A=>De(A.target.value),onClick:A=>A.stopPropagation()}),Le.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Le.map(A=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(A.id)?" selected":""}`,onClick:()=>Mt(A.id),onMouseDown:X=>X.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:A.id}),t.jsx("span",{className:"dep-dropdown-title",children:It(A.title||A.description||A.id,30)})]},A.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(A=>t.jsxs("span",{className:"dep-chip",children:[A,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Mt(A),disabled:B,children:"×"})]},A))})]})}),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??vs,onChange:A=>p(A.target.value),disabled:B,children:od.map(A=>t.jsx("option",{value:A,children:A[0].toUpperCase()+A.slice(1)},A))})]}),le&&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:A=>le(A.target.value),disabled:B,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),We?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):qe.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"?S:w,onChange:A=>{const X=A.target.value;if(X==="default"){M("default"),z(""),x(""),b("");return}if(X==="custom"){M("custom"),z("");return}const ze=pt.find(Rt=>Rt.id===X),ot=Jm(ze);M("preset"),z(X),x(ot.executorValue),b(ot.validatorValue)},disabled:B,children:[t.jsx("option",{value:"default",children:"Use default"}),pt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,pt.map(A=>t.jsx("option",{value:A.id,children:A.name},A.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),w==="preset"&&jt?t.jsxs("small",{children:["Using preset: ",jt.name]}):null,w==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>M("custom"),disabled:B,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(qn,{id:"executor-model",label:"Executor Model",value:f,onChange:A=>{M("custom"),z(""),x(A)},models:qe,disabled:B||w==="preset",favoriteProviders:Qe,onToggleFavorite:_t,favoriteModels:it,onToggleModelFavorite:Ct})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(qn,{id:"validator-model",label:"Reviewer Model",value:v,onChange:A=>{M("custom"),z(""),b(A)},models:qe,disabled:B||w==="preset",favoriteProviders:Qe,onToggleFavorite:_t,favoriteModels:it,onToggleModelFavorite:Ct})]}),N&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(qn,{id:"planning-model",label:"Planning Model",value:y||"",onChange:A=>{M("custom"),z(""),N(A)},models:qe,disabled:B||w==="preset",favoriteProviders:Qe,onToggleFavorite:_t,favoriteModels:it,onToggleModelFavorite:Ct})]}),R&&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:k||"",onChange:A=>R(A.target.value),disabled:B||w==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ve?.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"})]})]}),Se&&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:ce??"",onChange:A=>Se(A.target.value===""?void 0:parseInt(A.target.value,10)),disabled:B,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"})]})]})]})]}),q,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(A=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${A.id}`,children:[t.jsx("input",{type:"checkbox",checked:_.includes(A.id),onChange:X=>{I(X.target.checked?[..._,A.id]:_.filter(ze=>ze!==A.id))},disabled:B}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[A.name,L_(A.phase||"pre-merge",A.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:A.description})]})]},A.id))})]}),_.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:"}),_.map((A,X)=>{const ze=H.get(A);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${A}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:X+1}),t.jsx("span",{className:"workflow-step-order-name",children:ze?.name||A}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Et(X),disabled:B||X===0,"data-testid":`workflow-step-move-up-${A}`,title:"Move up",children:t.jsx(mi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>tn(X),disabled:B||X===_.length-1,"data-testid":`workflow-step-move-down-${A}`,title:"Move down",children:t.jsx(Qt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>At(A),disabled:B,"data-testid":`workflow-step-remove-${A}`,title:"Remove",children:t.jsx(Gt,{size:14})})]})]},A)})]})]})]})]})}const Qm={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 z_(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function O_(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 F_(e){return e?new Date(e).toLocaleString():null}function U_(e){const n=e.split(`
650
- `);return n.length<=1?e:`${n.length} lines`}function ao(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 B_({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 H_({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,x]=a.useState([]),[v,b]=a.useState(!1),y=n.some(j=>j.status==="pending"),{entries:N}=Jf(e,!!l&&y,o);a.useEffect(()=>{let j=!1;return Uo(o).then(W=>{j||x(W.filter(q=>q.enabled))}).catch(()=>{j||x([])}),()=>{j=!0}},[o]);const k=i??[],R=a.useMemo(()=>f.map(j=>({id:j.id,name:j.name,description:j.description,phase:j.phase||"pre-merge"})),[f]),w=a.useMemo(()=>new Map(R.map(j=>[j.id,j])),[R]),M=j=>{d(W=>({...W,[j]:!W[j]}))},S=j=>{h(W=>{const q=W[j]??"markdown";return{...W,[j]:q==="markdown"?"plain":"markdown"}})},z=j=>{p(j)},_=()=>{p(null)};a.useEffect(()=>{if(!g)return;const j=W=>{W.key==="Escape"&&_()};return document.addEventListener("keydown",j),()=>{document.removeEventListener("keydown",j)}},[g]);const I=a.useCallback((j,W)=>{if(c){if(W){if(k.includes(j)){c(k);return}c([...k,j]);return}c(k.filter(q=>q!==j))}},[c,k]),F=a.useCallback(j=>{if(!c||j<=0)return;const W=[...k];[W[j-1],W[j]]=[W[j],W[j-1]],c(W)},[c,k]),V=a.useCallback(j=>{if(!c||j>=k.length-1)return;const W=[...k];[W[j],W[j+1]]=[W[j+1],W[j]],c(W)},[c,k]),D=a.useCallback(j=>{c&&c(k.filter(W=>W!==j))},[c,k]),E=n.length>0,$=k.length>0;a.useEffect(()=>{r||b(!1)},[r]);const B=a.useMemo(()=>k.map(j=>{const W=w.get(j);return{id:j,name:W?.name||j,description:W?.description||"Step definition not found.",phase:W?.phase||"pre-merge"}}),[k,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:R.map(j=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${j.id}`,children:[t.jsx("input",{type:"checkbox",checked:k.includes(j.id),onChange:W=>I(j.id,W.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,ao(j.phase,j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.id))})]}),k.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),k.map((j,W)=>{const q=w.get(j);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${j}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:W+1}),t.jsx("span",{className:"workflow-step-order-name",children:q?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>F(W),disabled:W===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(mi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>V(W),disabled:W===k.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(Qt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>D(j),"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(Gt,{size:14})})]})]},j)})]})]}),ie=()=>{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(!E)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 j=n.filter(ce=>ce.status==="passed").length,W=n.filter(ce=>ce.status==="failed").length,q=n.filter(ce=>ce.status==="skipped").length,ge=n.filter(ce=>ce.status==="pending").length,be=[`${n.length} step${n.length!==1?"s":""}`];return j>0&&be.push(`${j} passed`),W>0&&be.push(`${W} failed`),q>0&&be.push(`${q} skipped`),ge>0&&be.push(`${ge} 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:be.join(" · ")}),n.map((ce,Se)=>{const O=ce.phase||"pre-merge",le=u[ce.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ce.status}`,"data-testid":`workflow-result-item-${ce.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ce.workflowStepName,ao(O,ce.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ce.status}`,"data-testid":`workflow-result-badge-${ce.workflowStepId}`,children:z_(ce.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ce.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",F_(ce.startedAt)]}),ce.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:O_(ce.startedAt,ce.completedAt)})]}),ce.status==="pending"&&ce.startedAt?t.jsx(B_,{entries:N,startedAt:ce.startedAt,stepId:ce.workflowStepId}):ce.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:()=>M(ce.workflowStepId),"data-testid":`workflow-result-toggle-${ce.workflowStepId}`,children:le?"Hide output":"Show output"}),!le&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ce.workflowStepId}`,children:U_(ce.output)}),le&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(ce.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ce.workflowStepId}`,title:(m[ce.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ce.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>z(ce.workflowStepId),"data-testid":`workflow-result-expand-${ce.workflowStepId}`,title:"Expand output",children:t.jsx(zo,{size:12})})]})]}),le&&t.jsx("div",{className:`workflow-result-output${(m[ce.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ce.workflowStepId}`,children:(m[ce.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:Qm,children:ce.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ce.output})})]}):null]},`${ce.workflowStepId}-${Se}`)})]})},C=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(j=>!j),"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(Ln,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(ss,{size:14}),"Edit"]})}):null,P=!s&&!E&&$,T=r&&E;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[P?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:[B.length," step",B.length===1?"":"s"]})]}),C]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:B.map(j=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${j.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[j.name,ao(j.phase,j.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:j.description})]},j.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:[T&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),C]}),ie(),J()]}),g&&(()=>{const j=n.find(ge=>ge.workflowStepId===g);if(!j)return null;const W=m[j.workflowStepId]??"markdown",q=j.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ge=>{ge.target===ge.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:j.workflowStepName}),ao(q,j.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>S(j.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:W==="markdown"?"Switch to plain text":"Switch to markdown",children:W==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Gt,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${W==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:W==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],components:Qm,children:j.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:j.output})})})]})})})()]})}function q_(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const V_=new Set(["planning","researching","executing","finalizing","merging"]);function W_(e){return e!==void 0&&e!=="online"}function K_({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),yo().then(_=>{o(_)}).catch(_=>{d(ke(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=a.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),v=a.useMemo(()=>[...r].sort((_,I)=>_.name.localeCompare(I.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,N=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",k=y?x.get(y):void 0,R=k?`${k.name} (${k.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||V_.has(e.status),M=w||g||l,S=a.useCallback(async _=>{if(_===m)return;const I=e.id,F=m;h(_),p(!0);try{const V=await Qs(I,{nodeId:_||null});if(f.current!==I)return;h(V.nodeId??""),i?.(V),s(_?"Node override updated":"Node override cleared","success")}catch(V){if(f.current!==I)return;h(F),s(ke(V)||"Failed to update node override","error")}finally{f.current===I&&p(!1)}},[s,i,m,e.id]),z=a.useCallback(()=>{S("")},[S]);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:[k?t.jsx(qi,{status:k.status,compact:!0}):null,R,W_(k?.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:N})]}),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:q_(b?.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:M,onChange:_=>{S(_.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(_=>t.jsxs("option",{value:_.id,title:`Status: ${_.status}`,children:[_.name," (",_.type,") — ",_.status]},_.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: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:w||g,onClick:z,children:"Clear override"})]}):null]})]})}const G_=/^[a-zA-Z0-9_-]{1,64}$/,J_=200;function Xm(e){return e?new Date(e).toLocaleString():""}function Y_(e,n=J_){return e.length<=n?e:e.substring(0,n)+"…"}function Q_({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),[x,v]=a.useState(""),[b,y]=a.useState(null),[N,k]=a.useState([]),[R,w]=a.useState(!1),[M,S]=a.useState(!1),[z,_]=a.useState(""),[I,F]=a.useState(""),[V,D]=a.useState(!1),[E,$]=a.useState(null),[B,J]=a.useState(null),[ie,C]=a.useState(!1),P=a.useCallback(async()=>{try{const O=await Jv(e,i);l(O)}catch(O){n(ke(O)||"Failed to load documents","error")}finally{u(!1)}},[e,i,n]);a.useEffect(()=>{P()},[P]);async function T(O){d===O.key?(m(null),g(""),f(null),v(""),y(null),k([]),C(!1)):(m(O.key),g(O.content),f(null),v(""),y(null),k([]),C(!1))}async function j(O){if(b===O)y(null),k([]);else{y(O),w(!0);try{const le=await Yv(e,O,i);k(le)}catch(le){n(ke(le)||"Failed to load revisions","error")}finally{w(!1)}}}function W(){d&&(f(d),v(h))}function q(){f(null),v("")}async function ge(){if(!(!p||!x.trim())){D(!0);try{await qd(e,p,x,{},i),f(null),v(""),await P();const O=o.find(le=>le.key===p);O&&g(O.content),n("Document saved","success")}catch(O){n(ke(O)||"Failed to save document","error")}finally{D(!1)}}}async function be(){const O=z.trim(),le=I.trim();if(!O){n("Document key is required","error");return}if(!G_.test(O)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!le){n("Content is required","error");return}D(!0);try{await qd(e,O,le,{},i),S(!1),_(""),F(""),await P(),n("Document created","success")}catch(ee){n(ke(ee)||"Failed to create document","error")}finally{D(!1)}}async function ce(O){$(O);try{await Qv(e,O,i),J(null),$(null),d===O&&(m(null),g("")),b===O&&(y(null),k([])),await P(),n("Document deleted","success")}catch(le){n(ke(le)||"Failed to delete document","error")}finally{$(null)}}function Se(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"}),M&&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:z,onChange:O=>_(O.target.value),placeholder:"e.g., plan, notes, research",disabled:V}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:I,onChange:O=>F(O.target.value),rows:6,placeholder:"Enter document content…",disabled:V})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{S(!1),_(""),F("")},disabled:V,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void be(),disabled:V||!z.trim()||!I.trim(),children:V?"Creating…":"Create"})]})]}),o.length===0&&!M?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(Ui,{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:Xm(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:()=>C(le=>!le),"aria-label":ie?"Switch to plain text":"Switch to markdown","aria-pressed":ie,title:ie?"Switch to plain text":"Switch to markdown",children:ie?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:ie?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})}),b===O.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),R?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):N.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:N.filter(le=>le.revision<O.revision).sort((le,ee)=>ee.revision-le.revision).map(le=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Se(le),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",le.revision]}),t.jsx("span",{className:"revision-author",children:le.author}),t.jsx("span",{className:"revision-timestamp",children:Xm(le.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:Y_(le.content,100)})]},le.id))})]})]}),p===O.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:le=>v(le.target.value),rows:10,disabled:V}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:q,disabled:V,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ge(),disabled:V||!x.trim(),children:V?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void T(O),children:d===O.key?t.jsxs(t.Fragment,{children:[t.jsx(mi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(Qt,{size:14})," Expand"]})}),d===O.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void j(O.key),children:[t.jsx(mr,{size:14})," History"]}),r&&p!==O.key&&t.jsx("button",{className:"btn btn-sm",onClick:W,children:"Edit"}),r&&(B===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 ce(O.key),disabled:E===O.key,children:E===O.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:E===O.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(O.key),children:t.jsx(sn,{size:14})}))]})]})]},O.key))}),r&&!M&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>S(!0),children:[t.jsx(an,{size:14})," New Document"]})]})}function ro(e){return e.toLocaleString()}function Ql(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Ka(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 X_(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 Z_({tokenUsage:e,loading:n,task:s}){const i=Rp(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=X_(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:Ka(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:Ka(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:Ka(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} (${Ka(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} (${Ka(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 ${Ql(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:ro(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:ro(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:ro(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:ro(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:Ql(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:Ql(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const eA=new Set(["planning","researching","executing","finalizing","merging"]);function tA(e,n){return wp(e,n)}function nA(e,n){return Np(e,n)}function sA(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 iA(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=sA(n);return i||Sp(e,s)}function aA(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 rA(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 oA(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function lA(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 Zm(e,n){return e.length>n?e.slice(0,n)+"…":e}function eh(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function Xl(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Zl(e){return e.trim()}function cA(e){const n=e.trim();return n.length>0?n:void 0}function Ga(e){return typeof e=="string"&&od.includes(e)?e:vs}function Ja(e){return e==="fast"?"fast":"standard"}const ec=200,dA=new Set(["triage","todo"]);function uA({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,x]=a.useState(p),[v,b]=a.useState(()=>"prompt"in e?e:null),[y,N]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){b(e),N(!1);return}let Q=!1;return N(!0),b(null),fr(e.id,n).then(Be=>{Q||(b(Be),N(!1))}).catch(()=>{Q||N(!1)}),()=>{Q=!0}},[e.id,n]);const k=v?{...v,...e,prompt:v.prompt,log:v.log}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt;a.useEffect(()=>{x(p)},[p]),a.useEffect(()=>{z(!1)},[e.id]);const[w,M]=a.useState("activity"),[S,z]=a.useState(!1),[_,I]=a.useState(e.attachments||[]),[F,V]=a.useState(!1),[D,E]=a.useState(e.dependencies||[]),[$,B]=a.useState(!1),[J,ie]=a.useState(""),[C,P]=a.useState(null),[T,j]=a.useState([]),[W,q]=a.useState(!1),[ge,be]=a.useState(!1),[ce,Se]=a.useState(!1),[O,le]=a.useState(!1),[ee,pe]=a.useState(!1),[ue,fe]=a.useState(k.prompt||""),[se,Ce]=a.useState(""),[De,qe]=a.useState(!1),[et,Qe]=a.useState(""),[Xe,it]=a.useState(!1),[Ie,We]=a.useState(!1),[re,ve]=a.useState(e.title||""),[te,Ae]=a.useState(e.description||""),[Fe,he]=a.useState(e.dependencies||[]),[Me,Oe]=a.useState(""),[at,ye]=a.useState(""),[oe,Te]=a.useState(""),[me,_e]=a.useState(""),[Ke,Re]=a.useState("default"),[ct,Y]=a.useState(void 0),[de,we]=a.useState(vs),[tt,Z]=a.useState(e.nodeId),[Ge,dt]=a.useState(Ja(e.executionMode)),[pt,jt]=a.useState(""),[yt,ft]=a.useState(e.enabledWorkflowSteps||[]),[St,Ot]=a.useState(e.sourceIssue?.provider??""),[Vt,Mt]=a.useState(e.sourceIssue?.repository??""),[It,qt]=a.useState(e.sourceIssue?.externalIssueId??""),[Ft,Xt]=a.useState(e.sourceIssue?.url??""),[$t,_t]=a.useState([]),[Ct,Et]=a.useState(!1),tn=a.useRef(!1),[At,H]=a.useState(!1),[xe,Le]=a.useState(!1),[A,X]=a.useState(!1),ze=a.useRef(null),ot=a.useRef(null),Rt=a.useRef(null),Tt=a.useRef(null);ti(Tt,!0,"fusion:task-detail-modal-size");const{getSlotsForId:Pt}=yp(n),ln=Pt("task-detail-tab");a.useEffect(()=>(tn.current=!0,()=>{tn.current=!1}),[]);const[kn,_n]=a.useState(void 0),[Yt,An]=a.useState([]),[je,ae]=a.useState(!1),[Je,ut]=a.useState(e.enabledWorkflowSteps||[]),Dt=e.column==="in-progress"||eA.has(e.status);a.useEffect(()=>{ve(e.title||""),Ae(e.description||""),Ot(e.sourceIssue?.provider??""),Mt(e.sourceIssue?.repository??""),qt(e.sourceIssue?.externalIssueId??""),Xt(e.sourceIssue?.url??""),dt(Ja(e.executionMode)),X(!1),We(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),a.useEffect(()=>{ut(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{let Q=!1;return Fo(n).then(Be=>{Q||_n(Be)}).catch(()=>{}),()=>{Q=!0}},[n]),a.useEffect(()=>{if(f!=="workflow")return;let Q=!1;return ae(!0),yj(e.id,n).then(Be=>{Q||An(Be)}).catch(Be=>{Q||h(`Failed to load workflow results: ${ke(Be)}`,"error")}).finally(()=>{Q||ae(!1)}),()=>{Q=!0}},[f,e.id,n,h]),a.useEffect(()=>{if(f!=="workflow")return;const Q=n?`?projectId=${encodeURIComponent(n)}`:"",Be=lt=>{try{const zt=JSON.parse(lt.data);zt.id===e.id&&Array.isArray(zt.workflowStepResults)&&An(zt.workflowStepResults)}catch{}};return qs(`/api/events${Q}`,{events:{"task:updated":Be}})},[f,e.id,n]),a.useEffect(()=>{$||ie("")},[$]),a.useEffect(()=>{if(!e.assignedAgentId){P(null);return}const Q=T.find(lt=>lt.id===e.assignedAgentId);if(Q){P(Q);return}let Be=!1;return hp(e.assignedAgentId,n).then(lt=>{Be||P(lt)}).catch(()=>{Be||P(null)}),()=>{Be=!0}},[e.assignedAgentId,n,T]),a.useEffect(()=>{q(!1)},[e.id]),a.useEffect(()=>{if(!(At||xe))return;const Be=lt=>{const zt=lt.target,Vs=ze.current?.contains(zt),fs=Rt.current?.contains(zt);!Vs&&At&&H(!1),!fs&&xe&&Le(!1)};return document.addEventListener("mousedown",Be),()=>document.removeEventListener("mousedown",Be)},[At,xe]),a.useEffect(()=>{if(!(At||xe))return;const Be=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),At&&H(!1),xe&&Le(!1))};return document.addEventListener("keydown",Be),()=>document.removeEventListener("keydown",Be)},[At,xe]),a.useEffect(()=>{pe(!1),fe(k.prompt||""),Ce("")},[e.id,k.prompt]);const Wt=dA.has(e.column)&&!Ct,Mn=a.useCallback(()=>{if(!Wt)return;We(!0),ve(e.title||""),Ae(e.description||""),he(e.dependencies||[]);const Q=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Be=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Oe(Q),ye(Be),Te(lt),_e(e.thinkingLevel??""),Z(e.nodeId),Re(Q||Be||lt?"custom":"default"),jt(""),ft(e.enabledWorkflowSteps||[]),dt(Ja(e.executionMode)),Ot(e.sourceIssue?.provider??""),Mt(e.sourceIssue?.repository??""),qt(e.sourceIssue?.externalIssueId??""),Xt(e.sourceIssue?.url??""),_t([]),Y(e.reviewLevel),we(Ga(e.priority))},[Wt,e]),on=a.useCallback(()=>{We(!1),ve(e.title||""),Ae(e.description||""),he(e.dependencies||[]),Z(e.nodeId),Ot(e.sourceIssue?.provider??""),Mt(e.sourceIssue?.repository??""),qt(e.sourceIssue?.externalIssueId??""),Xt(e.sourceIssue?.url??""),we(Ga(e.priority)),dt(Ja(e.executionMode)),$t.forEach(Q=>URL.revokeObjectURL(Q.previewUrl)),_t([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,$t]),Ut=a.useCallback(async()=>{Et(!0);try{const Q={},Be=re.trim(),lt=te.trim();Be&&Be!==(e.title??"")&&(Q.title=Be),lt&&lt!==(e.description??"")&&(Q.description=lt),eh(Fe,e.dependencies??[])||(Q.dependencies=Fe),eh(yt,e.enabledWorkflowSteps??[])||(Q.enabledWorkflowSteps=yt);const zt=Xl(Me),Vs=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Me!==Vs&&(Q.modelProvider=zt?.provider??null,Q.modelId=zt?.modelId??null);const fs=Xl(at),xi=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";at!==xi&&(Q.validatorModelProvider=fs?.provider??null,Q.validatorModelId=fs?.modelId??null);const La=Xl(oe),Ur=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";oe!==Ur&&(Q.planningModelProvider=La?.provider??null,Q.planningModelId=La?.modelId??null);const Xi=e.thinkingLevel??"";me!==Xi&&(Q.thinkingLevel=me!==""?me:null),(e.nodeId??void 0)!==tt&&(Q.nodeId=tt??null);const tl=e.reviewLevel;ct!==tl&&(Q.reviewLevel=ct);const nl=Ga(e.priority);de!==nl&&(Q.priority=de);const sl=Ja(e.executionMode);Ge!==sl&&(Q.executionMode=Ge==="fast"?"fast":null);const _i=Zl(St),Zi=Zl(Vt),Ai=Zl(It),ea=cA(Ft);if(_i.length===0&&Zi.length===0&&Ai.length===0&&!ea)e.sourceIssue&&(Q.sourceIssue=null);else{if(!_i||!Zi||!Ai){h("Source issue provider, repository, and issue identifier are required","error"),Et(!1);return}const Ss=Number.parseInt(Ai,10),oi=e.sourceIssue?.issueNumber??Ss;if(!Number.isFinite(oi)||oi<=0){h("Source issue identifier must be numeric for new metadata","error"),Et(!1);return}const U={provider:_i,repository:Zi,externalIssueId:Ai,issueNumber:oi,...ea?{url:ea}:{}},Ne=e.sourceIssue;(!Ne||Ne.provider!==U.provider||Ne.repository!==U.repository||Ne.externalIssueId!==U.externalIssueId||Ne.issueNumber!==U.issueNumber||(Ne.url??void 0)!==U.url)&&(Q.sourceIssue=U)}if(Object.keys(Q).length>0){const Ss=await Qs(e.id,Q,n);m?.(Ss)}if($t.length>0){const Ss=[];for(const oi of $t)try{const U=await gr(e.id,oi.file,n);I(Ne=>[...Ne,U])}catch{Ss.push(oi.file.name)}Ss.length>0&&h(`Failed to upload: ${Ss.join(", ")}`,"error")}$t.forEach(Ss=>URL.revokeObjectURL(Ss.previewUrl)),_t([]),h(`Updated ${e.id}`,"success"),We(!1)}catch(Q){h(`Failed to update ${e.id}: ${ke(Q)}`,"error")}finally{tn.current&&Et(!1)}},[e,re,te,Fe,Me,at,oe,me,tt,ct,de,Ge,yt,St,Vt,It,Ft,$t,h,n,m]),G=a.useCallback(async Q=>{try{await Qs(e.id,{description:Q},n),h("Description saved","success")}catch(Be){h(`Failed to save: ${ke(Be)}`,"error")}},[e.id,h,n]),Pe=a.useCallback(Q=>{Ie&&(Q.key==="Escape"?(Q.preventDefault(),on()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),Ut()))},[Ie,on,Ut]);a.useEffect(()=>{if(Ie)return document.addEventListener("keydown",Pe),()=>document.removeEventListener("keydown",Pe)},[Ie,Pe]);const Ye=a.useRef(null),{nodes:nt}=Vo(),{confirm:mt}=Hs(),{entries:Nt,loading:Lt,loadMore:Cn,hasMore:rn,total:kt,loadingMore:os}=Jf(e.id,f==="logs"&&w==="agent-log",n);a.useEffect(()=>{const Q=Be=>{Be.key==="Escape"&&!Ie&&i()};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[i,Ie]);const ks=Si(i),Is=a.useCallback(async Q=>{try{await o(e.id,Q),i(),h(`Moved to ${$n[Q]}`,"success")}catch(Be){h(ke(Be),"error")}},[e.id,o,i,h]),ws=a.useCallback(async()=>{if(await mt({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await l(e.id),i(),h(`Deleted ${e.id}`,"info")}catch(Be){const lt=lA(Be);if(!lt||lt.dependentIds.length===0){h(ke(Be),"error");return}const zt=lt.dependentIds.join(", ");if(!await mt({title:"Force Delete Task",message:`${e.id} is a dependency of ${zt}.
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(fs){h(ke(fs),"error")}}},[e.id,l,i,h,mt]),si=a.useCallback(async()=>{await mt({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(i(),h(`Merging ${e.id}...`,"info"),c(e.id).then(Be=>{const lt=Be.merged?`Merged ${e.id} (branch: ${Be.branch})`:`Closed ${e.id} (${Be.error||"no branch to merge"})`;h(lt,"success")}).catch(Be=>{h(ke(Be),"error")}))},[e.id,c,i,h,mt]),$s=a.useCallback(()=>{u&&(i(),u(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Q=>{h(ke(Q),"error")}))},[e.id,u,i,h]),Ds=a.useCallback(async()=>{if(!(!d||!await mt({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Be=await d(e.id);i(),h(`Duplicated ${e.id} → ${Be.id}`,"success")}catch(Be){h(ke(Be),"error")}},[e.id,d,i,h,mt]),Yi=a.useCallback(async()=>{try{e.paused?(await zv(e.id,n),h(`Unpaused ${e.id}`,"success")):(await rp(e.id,n),h(`Paused ${e.id}`,"success")),i()}catch(Q){h(ke(Q),"error")}},[e.id,e.paused,i,h]),ii=a.useCallback(async()=>{try{await Bv(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),i()}catch(Q){h(ke(Q),"error")}},[e.id,i,h]),ai=a.useCallback(async()=>{if(await mt({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Hv(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),i()}catch(Be){h(ke(Be),"error")}},[e.id,i,h,mt]),ht=a.useCallback(async()=>{if(await mt({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await ey(e.id,n),i(),h(`Replanning ${e.id}...`,"info")}catch(Be){h(ke(Be),"error")}},[e.id,n,i,h,mt]),pn=a.useCallback(()=>{qe(!0),Qe("")},[]),ne=a.useCallback(()=>{H(!1),Le(!1)},[]),Ee=a.useCallback(Q=>{ne(),Is(Q)},[ne]),Ze=a.useCallback(Q=>{ne(),Q()},[ne]),vt=a.useCallback(()=>{ne(),si()},[ne,si]),xt=a.useCallback(()=>{qe(!1),Qe(""),it(!1)},[]),jn=a.useCallback(async()=>{if(!et.trim()){h("Please enter feedback describing what needs refinement","error");return}if(et.length>2e3){h("Feedback must be 2000 characters or less","error");return}it(!0);try{const Q=await ty(e.id,et.trim(),n);h(`Refinement task created: ${Q.id}`,"success"),i()}catch(Q){h(ke(Q),"error")}finally{it(!1)}},[e.id,et,h,i]),en=a.useCallback(async Q=>{V(!0);try{const Be=await gr(e.id,Q,n);I(lt=>[...lt,Be]),h("Screenshot attached","success")}catch(Be){h(ke(Be),"error")}finally{V(!1)}},[e.id,h]),cn=a.useCallback(async Q=>{const Be=Q.target.files?.[0];Be&&(await en(Be),Ye.current&&(Ye.current.value=""))},[en]);a.useEffect(()=>{const Q=Be=>{const lt=Be.clipboardData?.items;if(lt)for(let zt=0;zt<lt.length;zt++){const Vs=lt[zt];if(Vs.type.startsWith("image/")){const fs=Vs.getAsFile();if(fs){Be.preventDefault(),en(fs);return}}}};return document.addEventListener("paste",Q),()=>document.removeEventListener("paste",Q)},[en]);const fn=a.useCallback(Q=>{Q.preventDefault()},[]),Dn=a.useCallback(Q=>{Q.preventDefault();const Be=Q.dataTransfer.files;for(let lt=0;lt<Be.length;lt++){const zt=Be[lt];if(zt.type.startsWith("image/")){en(zt);return}}},[en]),Wn=a.useCallback(async Q=>{try{await Wv(e.id,Q,n),I(Be=>Be.filter(lt=>lt.filename!==Q)),h("Attachment deleted","info")}catch(Be){h(ke(Be),"error")}},[e.id,h]),Kn=a.useCallback(async Q=>{const Be=Je;ut(Q);try{const lt=await Qs(e.id,{enabledWorkflowSteps:Q},n);h("Workflow steps updated","success"),m?.(lt)}catch(lt){ut(Be),h(`Failed to update workflow steps: ${ke(lt)}`,"error")}},[e.id,n,Je,m,h]),Rn=a.useCallback(async()=>{be(!0);try{const Q=await _a(void 0,n);j(Q),q(!0)}catch(Q){h(`Failed to load agents: ${ke(Q)}`,"error"),q(!1)}finally{be(!1)}},[n,h]),Gn=a.useCallback(async Q=>{try{const Be=await tu(e.id,Q,n),lt=T.find(zt=>zt.id===Q)??null;P(lt||(zt=>zt?.id===Q?zt:null)),q(!1),m?.(Be),h("Assigned agent updated","success")}catch(Be){h(`Failed to assign agent: ${ke(Be)}`,"error")}},[e.id,n,T,m,h]),On=a.useCallback(async()=>{try{const Q=await tu(e.id,null,n);P(null),q(!1),m?.(Q),h("Agent unassigned","success")}catch(Q){h(`Failed to unassign agent: ${ke(Q)}`,"error")}},[e.id,n,m,h]),ps=a.useCallback(async Q=>{const Be=[...D,Q];E(Be);try{await Qs(e.id,{dependencies:Be},n)}catch(lt){E(D),h(ke(lt),"error")}},[e.id,D,h]),wn=a.useCallback(async(Q,Be)=>{Q.stopPropagation();const lt=D.filter(zt=>zt!==Be);E(lt);try{await Qs(e.id,{dependencies:lt},n)}catch(zt){E(D),h(ke(zt),"error")}},[e.id,D,h]),Fn=a.useCallback(async Q=>{try{const Be=await fr(Q,n);r(Be)}catch{h(`Failed to load dependency ${Q}`,"error")}},[r,h]),ls=a.useCallback(async Q=>{Se(!0);try{await Qs(k.id,{prompt:Q},n),h("Spec updated","success"),v&&(v.prompt=Q)}catch(Be){throw h(ke(Be),"error"),Be}finally{Se(!1)}},[k,v,h]),Ns=a.useCallback(async Q=>{le(!0);try{await Zv(e.id,Q,n),h("AI revision requested. Task moved to planning.","success"),i()}catch(Be){const lt=ke(Be);lt.includes("done")||lt.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(lt,"error")}finally{le(!1)}},[e.id,h,i]),ts=a.useCallback(()=>{pe(!0),fe(k.prompt||""),Ce("")},[k.prompt]),dn=a.useCallback(()=>{pe(!1),fe(k.prompt||""),Ce("")},[k.prompt]),Un=a.useCallback(async()=>{if(ue===(k.prompt||"")){dn();return}pe(!1);try{await ls(ue)}catch(Q){throw pe(!0),Q}},[ue,k.prompt,ls,dn]),Ls=a.useCallback(async()=>{se.trim()&&await Ns(se.trim())},[se,Ns]),Zo=a.useCallback(Q=>{Q.key==="Escape"?(Q.preventDefault(),dn()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),Un())},[dn,Un]),Ei=s.filter(Q=>Q.id!==e.id&&!D.includes(Q.id)).sort((Q,Be)=>{const lt=Be.createdAt.localeCompare(Q.createdAt);if(lt!==0)return lt;const zt=parseInt(Q.id.slice(Q.id.lastIndexOf("-")+1),10)||0;return(parseInt(Be.id.slice(Be.id.lastIndexOf("-")+1),10)||0)-zt}),Lr=C?.name??e.assignedAgentId??null,zs=a.useMemo(()=>{const Q=[];return k.modelProvider&&Q.push(k.modelProvider),k.validatorModelProvider&&!Q.includes(k.validatorModelProvider)&&Q.push(k.validatorModelProvider),k.planningModelProvider&&!Q.includes(k.planningModelProvider)&&Q.push(k.planningModelProvider),Q},[k.modelProvider,k.validatorModelProvider,k.planningModelProvider]),zr=_c[e.column]||[],Or=["todo","in-progress"],Fr=e.column==="in-review"?Or:zr,Jn=Fr[0],Ia=Fr.slice(1),Pn=Ia.length>0,ri=a.useCallback(()=>{H(!1),ot.current?.focus()},[]),Mi=a.useCallback(Q=>{if(!Pn){Jn&&Ee(Jn);return}const Be=Q.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Q.target instanceof Element&&Q.target.closest(".detail-move-btn__arrow")||Be&&Q.clientX>0&&Q.clientX>=Be.getBoundingClientRect().left)){H(zt=>!zt),Le(!1);return}Jn&&Ee(Jn)},[Pn,Jn,Ee]),$a=a.useCallback(Q=>{!Pn||!(Q.key==="ArrowDown"||Q.altKey&&Q.key==="ArrowDown")||(Q.preventDefault(),H(!0),Le(!1))},[Pn]),Qi=a.useCallback(Q=>{Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),ri())},[ri]);a.useEffect(()=>{if(!At)return;ze.current?.querySelector(".detail-move-menu-item")?.focus()},[At]);const el={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},Da=e.status?el[e.status]:void 0;return t.jsx("div",{className:"modal-overlay open",...ks,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg task-detail-modal",ref:Tt,onDragOver:fn,onDrop:Dn,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:$n[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Ie&&Wt&&t.jsx("button",{className:"modal-edit-btn",onClick:Mn,title:"Edit task","aria-label":"Edit task",children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${f==="logs"&&w==="agent-log"&&!Ie?" detail-body--agent-log":""}`,children:[Ie?t.jsx("div",{className:"modal-edit-form",children:t.jsx(Zf,{mode:"edit",title:re,onTitleChange:ve,description:te,onDescriptionChange:Ae,dependencies:Fe,onDependenciesChange:he,executorModel:Me,onExecutorModelChange:Oe,validatorModel:at,onValidatorModelChange:ye,planningModel:oe,onPlanningModelChange:Te,thinkingLevel:me,onThinkingLevelChange:_e,presetMode:Ke,onPresetModeChange:Re,selectedPresetId:pt,onSelectedPresetIdChange:jt,selectedWorkflowSteps:yt,onWorkflowStepsChange:ft,pendingImages:$t,onImagesChange:_t,tasks:s.filter(Q=>Q.id!==e.id),projectId:n,disabled:Ct,addToast:h,isActive:Ie,onAutoSaveDescription:G,reviewLevel:ct,onReviewLevelChange:Y,priority:de,onPriorityChange:we,nodeId:tt,onNodeIdChange:Z,nodeOptions:nt,nodeOverrideDisabled:Dt,nodeOverrideDisabledReason:Dt?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Ge,onExecutionModeChange:dt,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:St,onChange:Q=>Ot(Q.target.value),disabled:Ct,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Vt,onChange:Q=>Mt(Q.target.value),disabled:Ct,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:It,onChange:Q=>qt(Q.target.value),disabled:Ct,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Ft,onChange:Q=>Xt(Q.target.value),disabled:Ct,"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,Be=!S&&Q.length>ec;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Be?Q.slice(0,ec)+"…":Q}),Q.length>ec&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>z(!S),children:S?"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--${Ga(e.priority)}`,children:["Priority: ",Ga(e.priority)]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Ie&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${f==="definition"?" detail-tab-active":""}`,onClick:()=>x("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${f==="logs"?" detail-tab-active":""}`,onClick:()=>x("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:()=>x("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${f==="comments"?" detail-tab-active":""}`,onClick:()=>x("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${f==="documents"?" detail-tab-active":""}`,onClick:()=>x("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${f==="model"?" detail-tab-active":""}`,onClick:()=>x("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${f==="workflow"?" detail-tab-active":""}`,onClick:()=>x("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${f==="stats"?" detail-tab-active":""}`,onClick:()=>x("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${f==="routing"?" detail-tab-active":""}`,onClick:()=>x("routing"),children:"Routing"}),ln.map((Q,Be)=>{const lt=`plugin-${Be}`;return t.jsx("button",{className:`detail-tab${f===lt?" detail-tab-active":""}`,onClick:()=>x(lt),children:Q.slot.label},`plugin-tab-${Q.pluginId}`)})]}),f==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(H_,{taskId:e.id,results:Yt,loading:je,enabledWorkflowSteps:Je,canEdit:Wt,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Kn})}):f==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(N_,{task:e,addToast:h,onTaskUpdated:m,settings:kn})}):f==="logs"?t.jsxs("div",{className:`detail-section${w==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${w==="activity"?" log-subview-btn-active":""}`,onClick:()=>M("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${w==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>M("agent-log"),children:"Agent Log"})]}),w==="agent-log"?t.jsx(v_,{entries:Nt,loading:Lt,executorModel:tA(e,kn),validatorModel:nA(e,kn),planningModel:iA(e,Nt,kn),hasMore:rn,onLoadMore:Cn,loadingMore:os,totalCount:kt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),k.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",k.log.length," activity entries."]}):null,k.log&&k.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...k.log].reverse().map((Q,Be)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:rA(Q.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Q.action})]}),Q.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Q.outcome})]},Be))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):f==="changes"?t.jsx(I_,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):f==="comments"?t.jsx(__,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):f==="documents"?t.jsx(Q_,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Wt}):typeof f=="string"&&f.startsWith("plugin-")?t.jsx("div",{className:"detail-section",children:t.jsx(Ho,{slotId:"task-detail-tab",projectId:n})}):f==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(Z_,{tokenUsage:k.tokenUsage,loading:y,task:k})}):f==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(K_,{task:e,settings:kn,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(R_,{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":A,"aria-label":A?"Collapse source issue details":"Expand source issue details",onClick:()=>X(Q=>!Q),children:t.jsx(vn,{size:16,className:A?"detail-source-chevron--expanded":void 0})})]}),A&&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:[zs.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:zs.map(Q=>t.jsx(zn,{provider:Q,size:"sm"},Q))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Nn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Lr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Nn,{size:14}),Lr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void On(),title:"Unassign agent",children:t.jsx(Gt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{W?q(!1):Rn()},children:"Assign Agent"}),W&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ge&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ge&&T.filter(Q=>Q.state!=="terminated").map(Q=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Q.id?" selected":""}`,onClick:()=>void Gn(Q.id),children:[t.jsx(Nn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Q.name}),t.jsx("span",{className:"agent-picker-role",children:Q.role})]},Q.id)),!ge&&T.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"}),k.steps&&k.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:k.steps.map((Q,Be)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Q.status}`,"data-tooltip":`${Q.name} (${Q.status})`,style:{backgroundColor:aA(Q.status)}},Be))}),t.jsxs("span",{className:"step-progress-label",children:[k.steps.filter(Q=>Q.status==="done").length,"/",k.steps.length," step",k.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ee&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:ts,children:"Edit"})}),ee?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:ue,onChange:Q=>fe(Q.target.value),onKeyDown:Zo,disabled:ce,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:dn,disabled:ce,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Un(),disabled:ue===(k.prompt||"")||ce,children:ce?"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:se,onChange:Q=>Ce(Q.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:O,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[se.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ls(),disabled:!se.trim()||O,children:O?"Requesting…":"Request AI Revision"})]})]})]}):y?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):k.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(pi,{remarkPlugins:[fi],children:k.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),_.length>0?t.jsx("div",{className:"detail-attachments-grid",children:_.map(Q=>{const Be=ei(`/api/tasks/${e.id}/attachments/${Q.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Be,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Be,alt:Q.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Q.originalName," (",oA(Q.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Wn(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:Ye,type:"file",accept:"image/*",onChange:cn}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ye.current?.click(),disabled:F,children:F?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),D.length>0?t.jsx("ul",{className:"detail-dep-list",children:D.map(Q=>{const Be=s.find(zt=>zt.id===Q),lt=Be?.title||Be?.description||Q;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Fn(Q),onKeyDown:zt=>{(zt.key==="Enter"||zt.key===" ")&&(zt.preventDefault(),Fn(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:Zm(lt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:zt=>wn(zt,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:()=>{$&&ie(""),B(Q=>!Q)},children:"Add Dependency"}),$&&(()=>{const Q=J.toLowerCase(),Be=Q?Ei.filter(lt=>lt.id.toLowerCase().includes(Q)||lt.title&&lt.title.toLowerCase().includes(Q)||lt.description&&lt.description.toLowerCase().includes(Q)):Ei;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:J,onChange:lt=>ie(lt.target.value),onClick:lt=>lt.stopPropagation()}),Be.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Be.map(lt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ps(lt.id),B(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:lt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Zm(lt.title||lt.description||lt.id,30)})]},lt.id))]})})()]})]}),e.column==="in-review"&&t.jsx(C_,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:kn?.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:Ie?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:on,disabled:Ct,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ut,disabled:Ct,children:Ct?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&k.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ii,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:ai,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ws,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Rt,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Le(Q=>!Q),H(!1)},"aria-haspopup":"menu","aria-expanded":xe,children:["Actions",t.jsx(Qt,{size:12})]}),xe&&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:()=>Ze(ws),children:"Delete"}),d&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(Ds),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(pn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(ht),children:"Respecify"}),R&&u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze($s),children:"Retry"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ze(Yi),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:ze,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:ot,className:"btn btn-primary btn-sm detail-move-btn",onClick:Mi,onKeyDown:$a,disabled:!Jn,"aria-label":Jn?`Move to ${$n[Jn]}`:void 0,"aria-haspopup":Pn?"menu":void 0,"aria-expanded":Pn?At:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Jn?$n[Jn]:""]}),Pn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Qt,{size:12})})]}),At&&Pn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Qi,children:Ia.map(Q=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ee(Q),onKeyDown:Qi,children:Q==="in-progress"?"Back to In Progress":`Move to ${$n[Q]}`},Q))})]}),Da?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Da}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:vt,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:ot,className:"btn btn-primary btn-sm detail-move-btn",onClick:Mi,onKeyDown:$a,disabled:!Jn,"aria-label":Jn?`Move to ${$n[Jn]}`:void 0,"aria-haspopup":Pn?"menu":void 0,"aria-expanded":Pn?At:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Jn?$n[Jn]:""]}),Pn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(Qt,{size:12})})]}),At&&Pn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Qi,children:Ia.map(Q=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ee(Q),onKeyDown:Qi,children:["Move to ",$n[Q]]},Q))})]})})]})}),De&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:xt,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick: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:xt,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:et,onChange:Q=>Qe(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:[et.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:jn,disabled:!et.trim()||Xe,children:Xe?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:xt,disabled:Xe,children:"Cancel"})})]})})]})})}const mA=640;function hA({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"),[x,v]=a.useState([]),[b,y]=a.useState(null),[N,k]=a.useState([]),[R,w]=a.useState(null),[M,S]=a.useState(null),[z,_]=a.useState(!1),[I,F]=a.useState([]),[V,D]=a.useState(!1),[E,$]=a.useState(""),B=a.useRef(!1),J=a.useRef(null);ti(J,e,"fusion:github-modal-size");const ie=Si(n),[C,P]=a.useState(!1),[T,j]=a.useState("list"),W=a.useRef(null),q=new Set;for(const he of i){const Me=he.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Me&&q.add(Me[1]);const Oe=he.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Oe&&q.add(Oe[1])}a.useEffect(()=>{if(e)return l(""),u(""),m(""),v([]),y(null),k([]),w(null),f("issues"),S(null),_(!1),F([]),D(!0),$(""),W.current=null,B.current=!0,hy().then(he=>{if(B.current)if(F(he),D(!1),he.length===1){const Me=he[0];l(Me.owner),u(Me.repo),$(Me.name)}else he.length>1&&(l(""),u(""),$(""))}).catch(()=>{B.current&&D(!1)}),()=>{B.current=!1}},[e]);const ge=a.useCallback(he=>{if($(he),he==="")l(""),u("");else{const Me=I.find(Oe=>Oe.name===he);Me&&(l(Me.owner),u(Me.repo))}},[I]),be=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}g(!0),S(null),v([]),y(null);try{const he=d.split(",").map(Oe=>Oe.trim()).filter(Boolean),Me=await cy(o.trim(),c.trim(),30,he.length>0?he:void 0);v(Me),Me.length===0&&S("No open issues found")}catch(he){S(ke(he)||"Failed to fetch issues")}finally{g(!1)}},[o,c,d]),ce=a.useCallback(async()=>{if(!o.trim()||!c.trim()){S("Repository must be selected");return}g(!0),S(null),k([]),w(null);try{const he=await uy(o.trim(),c.trim(),30);k(he),he.length===0&&S("No open pull requests found")}catch(he){S(ke(he)||"Failed to fetch pull requests")}finally{g(!1)}},[o,c]);a.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||z)return;const he={owner:o.trim(),repo:c.trim(),labels:d.trim(),tab:p};W.current?.owner===he.owner&&W.current?.repo===he.repo&&W.current?.labels===he.labels&&W.current?.tab===he.tab||(W.current=he,p==="issues"?be():ce())},[o,c,d,p,e,h,z,be,ce]),a.useEffect(()=>{if(!e)return;const he=Me=>{Me.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),a.useEffect(()=>{if(!e)return;const he=()=>{P(window.innerWidth<=mA)};return he(),window.addEventListener("resize",he),()=>window.removeEventListener("resize",he)},[e]);const Se=a.useCallback(he=>{y(he),C&&j("preview")},[C]),O=a.useCallback(he=>{w(he),C&&j("preview")},[C]),le=a.useCallback(()=>{j("list")},[]),ee=a.useCallback(async()=>{if(p==="issues"){if(b===null)return;_(!0),S(null);try{const he=await dy(o.trim(),c.trim(),b,r);s(he),y(null),C&&T==="preview"&&j("list")}catch(he){const Me=ke(he);Me?.includes("already imported")?S(Me):S(Me||"Failed to import issue")}finally{_(!1)}}else{if(R===null)return;_(!0),S(null);try{const he=await my(o.trim(),c.trim(),R,r);s(he),w(null),C&&T==="preview"&&j("list")}catch(he){const Me=ke(he);Me?.includes("already imported")?S(Me):S(Me||"Failed to import pull request")}finally{_(!1)}}},[p,b,R,o,c,s,C,T]),pe=x.find(he=>he.number===b),ue=N.find(he=>he.number===R);if(!e)return null;const fe=I.length>0,se=I.length===1,Ce=x.filter(he=>q.has(he.html_url)).length,De=N.filter(he=>q.has(he.html_url)).length,qe=M==="No open issues found",et=M==="No open pull requests found",Qe=p==="issues"?qe:et,Xe=!!M&&!qe&&x.length===0&&!h,it=!!M&&!et&&N.length===0&&!h,Ie=p==="issues"?Xe:it,We=h||x.length>0||qe||Xe,re=h||N.length>0||et||it,ve=p==="issues"?We:re,te=!!M&&x.length>0&&!qe,Ae=!!M&&N.length>0&&!et,Fe=p==="issues"?te:Ae;return t.jsx("div",{className:"modal-overlay open",...ie,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||z,children:[t.jsx(Io,{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||z,children:[t.jsx(bs,{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:V?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…"})]}):fe?se?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:I[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[I[0].owner,"/",I[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:E,onChange:he=>ge(he.target.value),disabled:h||z,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),I.map(he=>t.jsxs("option",{value:he.name,children:[he.name," (",he.owner,"/",he.repo,")"]},he.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:he=>m(he.target.value),onKeyDown:he=>he.key==="Enter"&&be(),disabled:h||z||!fe,"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"?be:ce,disabled:h||z||!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(Tn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!V&&!fe&&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:M}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${C?"mobile":""} ${T==="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"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[Ce," imported"]})]}),p==="pulls"&&N.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[N.length," pull request",N.length===1?"":"s"]}),t.jsxs("span",{children:[De," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!ve&&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."})]})]}),Ie&&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:M})]})}),Qe&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(he=>{const Me=q.has(he.html_url);return t.jsxs("div",{className:`issue-item ${b===he.number?"selected":""} ${Me?"imported":""}`,onClick:()=>!Me&&Se(he.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===he.number,onChange:()=>Se(he.number),disabled:Me,"aria-label":`Select issue #${he.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",he.number]}),t.jsx("span",{className:"issue-title",children:he.title})]}),he.labels.length>0&&t.jsx("span",{className:"issue-labels",children:he.labels.map(Oe=>t.jsx("span",{className:"label-chip",children:Oe.name},Oe.name))})]}),Me&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},he.number)})}),p==="pulls"&&N.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:N.map(he=>{const Me=q.has(he.html_url);return t.jsxs("div",{className:`issue-item ${R===he.number?"selected":""} ${Me?"imported":""}`,onClick:()=>!Me&&O(he.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:R===he.number,onChange:()=>O(he.number),disabled:Me,"aria-label":`Select pull request #${he.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",he.number]}),t.jsx("span",{className:"issue-title",children:he.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[he.headBranch," → ",he.baseBranch]})]}),Me&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},he.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${C?"mobile":""} ${T==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[C&&t.jsxs("button",{className:"github-import-back-button",onClick:le,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ma,{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"&&pe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",pe.number]}),t.jsx("div",{className:"preview-title",children:pe.title}),t.jsx("div",{className:"preview-body",children:pe.body?pe.body.slice(0,200)+(pe.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&ue?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",ue.number]}),t.jsx("div",{className:"preview-title",children:ue.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",ue.headBranch," → ",ue.baseBranch]}),t.jsx("div",{className:"preview-body",children:ue.body?ue.body.slice(0,200)+(ue.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:z,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:(p==="issues"?b===null:R===null)||z,children:z?t.jsx(rt,{size:14,className:"spin"}):"Import"})]})]})})}const pA=["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 fA(e,n){return e&&n?`${e}/${n}`:""}function gA(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 xA({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,x]=a.useState([]),[v,b]=a.useState([]),[y,N]=a.useState(null),k=a.useRef(!1),R=a.useRef(!1),[w,M]=a.useState(""),[S,z]=a.useState(!0),[_,I]=a.useState(!1),[F,V]=a.useState(!1),[D,E]=a.useState(null),[$,B]=a.useState(0),J=a.useRef(null),ie=a.useRef(null),C=a.useRef(null),P=a.useRef(null),[T,j]=a.useState(c??null),W=a.useMemo(()=>Gi(),[]),{isLockedByOther:q,takeControl:ge,isLoading:be}=Ko(e?T:null),{activeTabMap:ce,broadcastUpdate:Se,broadcastCompleted:O,broadcastLock:le,broadcastUnlock:ee,broadcastHeartbeat:pe}=Ra(),[ue,fe]=a.useState(void 0),[se,Ce]=a.useState(void 0),[De,qe]=a.useState([]),[et,Qe]=a.useState(!1),[Xe,it]=a.useState(null),[Ie,We]=a.useState([]),[re,ve]=a.useState([]),te=a.useRef(null),[Ae,Fe]=a.useState([]),[he,Me]=a.useState(!1),[Oe,at]=a.useState(c??null),[ye,oe]=a.useState(!!c),[Te,me]=a.useState(null),_e=a.useRef(!1),Ke=a.useRef(null);ti(ie,e,"fusion:planning-modal-size"),a.useEffect(()=>{const H=Ke.current;if(!H)return;H.scrollHeight-H.scrollTop-H.clientHeight<32&&(H.scrollTop=H.scrollHeight)},[w]),a.useEffect(()=>{if(m.type!=="loading"){E(null),B(0);return}const H=Date.now();E(H),B(0);const xe=setInterval(()=>{B(Math.max(0,Math.floor((Date.now()-H)/1e3)))},1e3);return()=>clearInterval(xe)},[m.type]);const Re=a.useCallback(()=>{d(""),h({type:"initial"}),p(null),x([]),b([]),N(null),M(""),I(!1),V(!1),fe(void 0),Ce(void 0),P.current=null,j(null)},[]),ct=fA(ue,se),Y=a.useCallback((H,xe)=>{if(!H||!xe)return"Using default";const Le=De.find(A=>A.provider===H&&A.id===xe);return Le?`${Le.provider}/${Le.id}`:`${H}/${xe}`},[De]),de=a.useCallback(async()=>{Qe(!0),it(null);try{const H=await ms();qe(H.models),We(H.favoriteProviders),ve(H.favoriteModels)}catch(H){it(ke(H)||"Failed to load models")}finally{Qe(!1)}},[]),we=a.useCallback(H=>{We(xe=>{const Le=xe,X=Le.includes(H)?Le.filter(ze=>ze!==H):[H,...Le];return mn({favoriteProviders:X,favoriteModels:re}).catch(()=>{We(Le)}),X})},[re]),tt=a.useCallback(H=>{ve(xe=>{const Le=xe,X=Le.includes(H)?Le.filter(ze=>ze!==H):[H,...Le];return mn({favoriteProviders:Ie,favoriteModels:X}).catch(()=>{ve(Le)}),X})},[Ie]),Z=a.useCallback(H=>{C.current?.close();const xe=mj(H,l,{onThinking:Le=>{M(A=>A+Le),Se({sessionId:H,status:"generating",needsInput:!1,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onQuestion:Le=>{I(!1),V(!1),ia(l),h({type:"question",session:{sessionId:H,currentQuestion:Le,summary:null}}),M(""),Se({sessionId:H,status:"awaiting_input",needsInput:!0,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onSummary:Le=>{I(!1),V(!1),ia(l),h({type:"summary",session:{sessionId:H,currentQuestion:null,summary:Le},summary:Le}),N(Le),M(""),Se({sessionId:H,status:"complete",needsInput:!1,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null})},onError:Le=>{const A=Le||"Session failed while contacting the AI.";I(!0),(async()=>{try{const X=await ui(H);if(X&&(X.status==="generating"||X.status==="awaiting_input")){Z(H);return}}catch{}I(!1),V(!1),p(null),h(X=>X.type==="question"||X.type==="summary"||X.type==="error"?{type:"error",session:X.session,errorMessage:A}:{type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:A}),M(""),P.current=H,Se({sessionId:H,status:"error",needsInput:!1,owningTabId:W,type:"planning",title:u.trim()||"Planning session",projectId:l??null}),O({sessionId:H,status:"error"})})()},onComplete:()=>{I(!1),V(!1),P.current=null,O({sessionId:H,status:"complete"})},onConnectionStateChange:Le=>{I(Le==="reconnecting")}});C.current=xe},[O,Se,u,l,W]),Ge=a.useCallback(async H=>{const xe=H??u;if(xe.trim()){p(null),M(""),b([]),x([]),I(!1),h({type:"loading"});try{const Le=ue&&se?{planningModelProvider:ue,planningModelId:se}:void 0,{sessionId:A}=await Jy(xe.trim(),l,Le);P.current=A,j(A),at(A),Z(A),x([])}catch(Le){I(!1),p(ke(Le)||"Failed to start planning session"),h({type:"initial"}),P.current=null,j(null)}}},[Z,u,se,ue,l]);a.useEffect(()=>{e&&m.type==="initial"&&J.current?.focus()},[e,m.type]),a.useEffect(()=>{e&&de()},[e,de]),a.useEffect(()=>{if(e&&o&&!k.current&&m.type==="initial"){d(o);const H=setTimeout(()=>{k.current=!0,Ge(o)},0);return()=>clearTimeout(H)}else if(e&&!o&&!k.current&&!R.current&&m.type==="initial"){R.current=!0;const H=l1(l);H&&d(H)}},[e,o,m.type,Ge,l]);const dt=a.useCallback(async H=>{C.current?.close(),C.current=null,p(null),M(""),x([]),b([]),N(null),V(!1),h({type:"loading"});try{const xe=await ui(H);if(!xe){at(null),oe(!1),h({type:"initial"});return}P.current=H,j(H);const Le=ya(xe.conversationHistory);if(b(Le),x(Le.map(A=>A.response).filter(A=>!!(A&&typeof A=="object"&&!Array.isArray(A)))),xe.status==="awaiting_input"&&xe.currentQuestion){ia(l);const A=JSON.parse(xe.currentQuestion);h({type:"question",session:{sessionId:H,currentQuestion:A,summary:null}}),xe.thinkingOutput&&M(xe.thinkingOutput),Z(H)}else if(xe.status==="complete"&&xe.result){ia(l);const A=JSON.parse(xe.result);h({type:"summary",session:{sessionId:H,currentQuestion:null,summary:A},summary:A}),N(A)}else xe.status==="generating"?(h({type:"loading"}),xe.thinkingOutput&&M(xe.thinkingOutput),Z(H)):xe.status==="error"&&h({type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:xe.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Z,l]);a.useEffect(()=>{!e||!c||P.current!==c&&(at(c),oe(!0),dt(c))},[e,c,dt]),a.useEffect(()=>{e&&Oe&&(c&&c===Oe||C.current?.isConnected()||dt(Oe))},[e]);const pt=a.useCallback(async()=>{Me(!0);try{const xe=(await sd(l)).filter(Le=>Le.type==="planning").sort((Le,A)=>Date.parse(A.updatedAt)-Date.parse(Le.updatedAt));Fe(xe)}catch{}finally{Me(!1)}},[l]);a.useEffect(()=>{e&&pt()},[e,pt]),a.useEffect(()=>{if(!e)return;const H=l?`?projectId=${encodeURIComponent(l)}`:"",xe=A=>{try{const X=JSON.parse(A.data);if(X.type!=="planning")return;Fe(ze=>{const ot=ze.findIndex(Tt=>Tt.id===X.id);return(ot>=0?[...ze.slice(0,ot),X,...ze.slice(ot+1)]:[X,...ze]).sort((Tt,Pt)=>Date.parse(Pt.updatedAt)-Date.parse(Tt.updatedAt))})}catch{}},Le=A=>{try{const X=JSON.parse(A.data);Fe(ze=>ze.filter(ot=>ot.id!==X))}catch{}};return qs(`/api/events${H}`,{events:{"ai_session:updated":xe,"ai_session:deleted":Le},onReconnect:()=>{pt()}})},[e,l,pt]);const jt=a.useCallback(H=>{if(Oe===H){oe(!0);return}at(H),oe(!0),dt(H)},[dt,Oe]),yt=a.useCallback(()=>{C.current?.close(),C.current=null,Re(),at(null),oe(!0)},[Re]),ft=a.useCallback(()=>{oe(!1)},[]),St=a.useCallback(async H=>{const xe=A=>A==="generating"||A==="awaiting_input",Le=Ae.find(A=>A.id===H);if(Le&&xe(Le.status))try{await cp(H,l,W)}catch{}try{await bp(H)}catch{}O({sessionId:H,status:"complete",timestamp:Date.now()}),Fe(A=>A.filter(X=>X.id!==H)),Oe===H&&(C.current?.close(),C.current=null,Re(),at(null),oe(!1)),me(null)},[O,Ae,l,Re,Oe,W]);a.useEffect(()=>{e||(k.current=!1,R.current=!1,I(!1),V(!1),j(null))},[e]),a.useEffect(()=>{if(!e){te.current&&(ee(te.current,W),te.current=null);return}if(T&&te.current!==T){te.current&&ee(te.current,W),le(T,W),te.current=T;return}!T&&te.current&&(ee(te.current,W),te.current=null)},[le,ee,e,T,W]),a.useEffect(()=>{if(!e||!T||te.current!==T)return;pe(W);const H=setInterval(()=>{pe(W)},3e4);return()=>{clearInterval(H)}},[pe,e,T,W]),a.useEffect(()=>()=>{C.current?.close(),C.current=null,te.current&&(ee(te.current,W),te.current=null)},[ee,W]),a.useEffect(()=>{if(!e)return;const H=()=>{C.current?.close(),C.current=null};return window.addEventListener("beforeunload",H),()=>window.removeEventListener("beforeunload",H)},[e]);const Ot=a.useCallback(()=>{u&&m.type==="initial"&&o1(u,l),C.current?.close(),C.current=null,I(!1),V(!1),n()},[u,n,l,m.type]);a.useEffect(()=>{if(!e)return;const H=xe=>{xe.key==="Escape"&&Ot()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,Ot]);const Vt=a.useCallback(async H=>{if(m.type!=="question")return;const{session:xe}=m,Le=xe.sessionId,A=xe.currentQuestion;if(!A){p("No active question in session");return}p(null),x(X=>[...X,H]),b(X=>[...X,{question:A,response:H}]),h({type:"loading"}),M("");try{await Yy(Le,H,l,W)}catch(X){p(ke(X)||"Failed to submit response"),h({type:"question",session:xe})}},[l,W,m]),Mt=a.useCallback(async()=>{const H=P.current;if(H){try{await Xy(H,l,W)}catch{}C.current?.close(),C.current=null,I(!1),V(!1),h({type:"error",session:{sessionId:H,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),M("")}},[l,W]),It=a.useCallback(async()=>{if(m.type!=="error")return;const H=m.session;p(null),V(!0),M(""),h({type:"loading"}),Z(H.sessionId);try{P.current=H.sessionId,j(H.sessionId),await Qy(H.sessionId,l,W)}catch(xe){let Le=xe;if((ke(xe)||"").includes("not in an error state"))try{const X=await ui(H.sessionId);if(!X)throw new Error("Failed to refresh planning session.");if(P.current=X.id,j(X.id),X.status==="generating")M(X.thinkingOutput??""),h({type:"loading"});else if(X.status==="awaiting_input"){if(!X.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const ze=JSON.parse(X.currentQuestion);ia(l),h({type:"question",session:{sessionId:X.id,currentQuestion:ze,summary:null}}),C.current?.isConnected()||Z(X.id)}else if(X.status==="complete"){if(!X.result)throw new Error("Planning session is complete but has no result.");const ze=JSON.parse(X.result);ia(l),h({type:"summary",session:{sessionId:X.id,currentQuestion:null,summary:ze},summary:ze}),N(ze)}else X.status==="error"&&h({type:"error",session:{sessionId:X.id,currentQuestion:null,summary:null},errorMessage:X.error||"Retry failed. Please try again."});I(!1);return}catch(X){Le=X}C.current?.close(),C.current=null,h({type:"error",session:H,errorMessage:ke(Le)||"Retry failed. Please try again."}),I(!1)}finally{V(!1)}},[Z,l,W,m]),qt=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const H=m.session.sessionId,xe=await Zy(H,y??void 0,l);s(xe),at(null),Fe(Le=>Le.filter(A=>A.id!==H)),O({sessionId:H,status:"complete",timestamp:Date.now()}),Ot()}catch(H){p(ke(H)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[O,y,m,l,s,Ot]),Ft=a.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const H=await ej(m.session.sessionId,y??void 0,l);j(H.sessionId),h({type:"breakdown",sessionId:H.sessionId,subtasks:H.subtasks,dirty:!1})}catch(H){p(ke(H)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),Xt=a.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const H=m.sessionId,xe=await tj(H,m.subtasks,l);i(xe.tasks),Fe(Le=>Le.filter(A=>A.id!==H)),O({sessionId:H,status:"complete",timestamp:Date.now()}),d(""),h({type:"initial"}),p(null),x([]),b([]),N(null),M(""),fe(void 0),Ce(void 0),P.current=null,j(null),at(null),n()}catch(H){p(ke(H)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[O,m,i,n,l]),$t=a.useCallback(()=>{if(m.type==="question"&&f.length>0){const H=f.slice(0,-1);x(H),h({type:"question",session:m.session})}},[m,f]),_t=()=>m.type==="question"?Math.min(f.length+1,3):3,Ct=T?ce.get(T):null,Et=Ct&&Ct.tabId!==W,tn=!!(Et&&!Ct.stale),At=q&&(!Et||Ct.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:H=>{_e.current=H.target===H.currentTarget},onClick:H=>{H.target===H.currentTarget&&_e.current&&Ot(),_e.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:ie,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[ye&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:ft,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Po,{size:18})}),t.jsx(Zs,{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:Ot,"aria-label":"Close",children:t.jsx(Gt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${ye?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(kA,{sessions:Ae,loading:he,selectedSessionId:Oe,pendingDeleteId:Te,onSelectSession:jt,onNewSession:yt,onRequestDelete:me,onConfirmDelete:H=>void St(H),onCancelDelete:()=>me(null)}),t.jsxs("div",{className:"planning-detail",children:[g&&t.jsx("div",{className:"form-error planning-error",children:g}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),tn&&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(Zn,{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:H=>d(H.target.value),onKeyDown:H=>{H.key==="Enter"&&!H.shiftKey&&u.trim()&&(H.preventDefault(),Ge())}})]}),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:pA.map((H,xe)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>d(H),children:H.length>40?H.slice(0,40)+"...":H},xe))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",et&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(qn,{id:"planning-modal-model",label:"Planning Model",value:ct,onChange:H=>{const{provider:xe,modelId:Le}=gA(H);fe(xe),Ce(Le)},models:De,disabled:et,favoriteProviders:Ie,onToggleFavorite:we,favoriteModels:re,onToggleModelFavorite:tt}),Xe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Xe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{de()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ue&&se?"model-badge-custom":"model-badge-default"}`,children:Y(ue,se)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Ge(),disabled:!u.trim(),children:[t.jsx(Zs,{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..."}),D&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",$,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>z(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void Mt(),children:[t.jsx(tx,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),S&&w&&t.jsx("div",{className:"planning-thinking-output",ref:Ke,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(Ps,{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 It(),disabled:F,children:[F?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Tn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ot,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(bA,{question:m.session.currentQuestion,progress:_t(),historyEntries:v,onSubmit:Vt,onBack:f.length>0?$t:void 0})}),m.type==="summary"&&y&&t.jsx(vA,{summary:y,historyEntries:v,onSummaryChange:N,tasks:r,onCreateTask:qt,onBreakIntoTasks:Ft,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(jA,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:H=>h({...m,subtasks:H,dirty:!0}),onCreateTasks:Xt,onBack:()=>{const xe={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:xe,summary:y})}})]}),q&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Lo,{size:16}),t.jsx("span",{children:At?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),At&&t.jsx("button",{type:"button",onClick:()=>{ge()},disabled:be,className:"btn btn-primary session-lock-take-control",children:be?"Taking control...":"Take Control"})]})})]})]})}):null}function bA({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(Ps,{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(x=>x!==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(yn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Gt,{size:18}),"No"]})]})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Ma,{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 vA({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(x=>x!==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(Ps,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(yn,{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(Ma,{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(Do,{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(yn,{size:16,className:"icon-mr-8"}),"Create Task"]})})]})]})]})}function th(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 yA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function jA({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(M=>!M.title.trim())?!0:th(e),[e]),f=a.useCallback((M,S)=>{i(e.map(z=>z.id===M?{...z,...S}:z))},[e,i]),x=a.useCallback(()=>{i([...e,yA(e.length+1)])},[e,i]),v=a.useCallback(M=>{i(e.filter(S=>S.id!==M).map(S=>({...S,dependsOn:S.dependsOn.filter(z=>z!==M)})))},[e,i]),b=a.useCallback((M,S)=>{if(S<0||S>=e.length)return;const z=[...e],[_]=z.splice(M,1);z.splice(S,0,_),i(z)},[e,i]),y=a.useCallback(M=>S=>{c(M),S.dataTransfer.setData("text/plain",M),S.dataTransfer.effectAllowed="move"},[]),N=a.useCallback(()=>{c(null),d(null),h(null)},[]),k=a.useCallback(M=>S=>{if(S.preventDefault(),M===l)return;const z=S.currentTarget.getBoundingClientRect(),_=z.top+z.height/2,I=S.clientY<_?"before":"after";d(M),h(I)},[l]),R=a.useCallback(M=>S=>{S.preventDefault();const z=S.dataTransfer.getData("text/plain");if(!z||z===M){N();return}const _=e.findIndex(E=>E.id===z),I=e.findIndex(E=>E.id===M);if(_===-1||I===-1){N();return}const F=[...e],[V]=F.splice(_,1);let D=I;m==="after"&&_<I&&D--,m==="after"&&D++,F.splice(D,0,V),i(F),N()},[e,m,i,N]),w=a.useCallback(M=>{const S=M.currentTarget.getBoundingClientRect(),z=M.clientX,_=M.clientY;(z<S.left||z>S.right||_<S.top||_>S.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(Do,{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((M,S)=>{const z=l===M.id,_=u===M.id,I=["task-detail-section","subtask-item",z?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:I,"data-testid":`subtask-item-${S}`,draggable:!s,onDragStart:y(M.id),onDragEnd:N,onDragOver:k(M.id),onDrop:R(M.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(Zc,{size:16}),t.jsx("strong",{children:M.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(S,S-1),disabled:s||S===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(zi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(S,S+1),disabled:s||S===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(M.id),disabled:s,children:[t.jsx(sn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:F=>{g.current[S]=F},value:M.title,onChange:F=>f(M.id,{title:F.target.value}),onKeyDown:F=>{F.key==="Enter"&&(F.preventDefault(),S<e.length-1&&g.current[S+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:M.description,onChange:F=>f(M.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:M.suggestedSize,onChange:F=>f(M.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,S).filter(F=>F.id!==M.id).map(F=>{const V=M.dependsOn.includes(F.id);return t.jsxs("label",{className:`planning-dep-chip ${V?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:V,onChange:()=>{const D=V?M.dependsOn.filter(E=>E!==F.id):[...M.dependsOn,F.id];f(M.id,{dependsOn:D})},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)}),S===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),S>0&&e.slice(0,S).filter(F=>F.id!==M.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},M.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(an,{size:16,className:"icon-mr-6"})," Add subtask"]}),th(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(Ma,{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 kA({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(pb,{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(wA,{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(NA,{status:d.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:SA(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(sn,{size:14})})]},d.id)})]})]})}function wA({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(xc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(yn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(as,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(wi,{size:14,className:"planning-sidebar-status-icon"})}}function NA({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 SA(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 CA(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function nh(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 EA({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(""),[x,v]=a.useState(!0),[b,y]=a.useState(!1),[N,k]=a.useState(!1),[R,w]=a.useState(s),[M,S]=a.useState(null),[z,_]=a.useState(!1),[I,F]=a.useState(null),[V,D]=a.useState(null),[E,$]=a.useState(null),B=a.useRef(null),J=a.useRef([]),ie=a.useRef(!1),C=a.useRef(null),P=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,T=a.useMemo(()=>Gi(),[]),{isLockedByOther:j,takeControl:W,isLoading:q}=Ko(e?P:null),{activeTabMap:ge,broadcastUpdate:be,broadcastCompleted:ce,broadcastLock:Se,broadcastUnlock:O,broadcastHeartbeat:le}=Ra(),ee=a.useMemo(()=>d.length===0||d.some(oe=>!oe.title.trim())?!0:nh(d),[d]),pe=c.type==="generating"||c.type==="editing"||c.type==="error",ue=P?ge.get(P):null,{confirm:fe}=Hs(),se=ue&&ue.tabId!==T,Ce=!!(se&&!ue.stale),De=j&&(!se||ue.stale),qe=a.useCallback(()=>{R&&c1(R,o),B.current?.close(),B.current=null,u({type:"initial"}),m([]),g([]),f(""),v(!0),y(!1),k(!1),S(null),_(!1),ie.current=!1},[R,o]),et=a.useCallback(()=>{B.current?.close(),B.current=null,n()},[n]),Qe=a.useCallback(async()=>{if(!((z||c.type==="editing"||c.type==="creating")&&!await fe({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(P)try{await mp(P,o,T)}catch{}qe(),n()}},[z,n,qe,P,T,c.type,o,fe]),Xe=a.useCallback(oe=>{B.current?.close(),B.current=Mj(oe,o,{onThinking:Te=>{f(me=>me+Te),be({sessionId:oe,status:"generating",needsInput:!1,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onSubtasks:Te=>{y(!1),k(!1),kl(o),m(Te),u({type:"editing",sessionId:oe}),_(!1),be({sessionId:oe,status:"awaiting_input",needsInput:!0,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null})},onError:Te=>{const me=Te||"Session failed while contacting the AI.";y(!1),k(!1),S(null),u({type:"error",sessionId:oe,errorMessage:me}),be({sessionId:oe,status:"error",needsInput:!1,owningTabId:T,type:"subtask",title:R.trim()||"Subtask breakdown",projectId:o??null}),ce({sessionId:oe,status:"error"})},onComplete:()=>{ce({sessionId:oe,status:"complete"})},onConnectionStateChange:Te=>{y(Te==="reconnecting")}})},[ce,be,R,o,T]),it=a.useCallback(async()=>{if(R.trim()){S(null),g([]),f(""),y(!1);try{const{sessionId:oe}=await Sj(R.trim(),o);u({type:"generating",sessionId:oe}),Xe(oe)}catch(oe){S(ke(oe)||"Failed to start subtask breakdown"),u({type:"initial"})}}},[Xe,R,o]);a.useEffect(()=>{if(!e){qe();return}if(e&&s&&!ie.current)w(s),ie.current=!0,it();else if(e&&!s&&!ie.current){const oe=d1(o);oe&&w(oe)}},[e,s,it,qe]),a.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const oe=await ui(l);if(!oe)return;const Te=ya(oe.conversationHistory);if(g(Te),oe.status==="generating"||oe.status==="awaiting_input")f(oe.thinkingOutput??""),u({type:"generating",sessionId:l}),Xe(l);else if(oe.status==="complete"&&oe.result){kl(o);const me=JSON.parse(oe.result);m(me),u({type:"editing",sessionId:l})}else oe.status==="error"&&(S(null),u({type:"error",sessionId:l,errorMessage:oe.error??"Session encountered an error"}))}catch(oe){S(ke(oe)||"Failed to resume session")}})()},[Xe,e,l,c.type,o]),a.useEffect(()=>{if(!e){C.current&&(O(C.current,T),C.current=null);return}if(P&&C.current!==P){C.current&&O(C.current,T),Se(P,T),C.current=P;return}!P&&C.current&&(O(C.current,T),C.current=null)},[Se,O,e,P,T]),a.useEffect(()=>{if(!e||!P||C.current!==P)return;le(T);const oe=setInterval(()=>{le(T)},3e4);return()=>{clearInterval(oe)}},[le,e,P,T]),a.useEffect(()=>()=>{B.current?.close(),C.current&&(O(C.current,T),C.current=null)},[O,T]),a.useEffect(()=>{if(!e)return;const oe=Te=>{Te.key==="Escape"&&(Te.preventDefault(),Qe())};return document.addEventListener("keydown",oe),()=>document.removeEventListener("keydown",oe)},[e,Qe]);const Ie=a.useCallback((oe,Te)=>{m(me=>me.map(_e=>_e.id===oe?{..._e,...Te}:_e)),_(!0)},[]),We=a.useCallback(()=>{m(oe=>[...oe,CA(oe.length+1)]),_(!0)},[]),re=a.useCallback(oe=>{m(Te=>Te.filter(me=>me.id!==oe).map(me=>({...me,dependsOn:me.dependsOn.filter(_e=>_e!==oe)}))),_(!0)},[]),ve=a.useCallback(oe=>Te=>{F(oe),Te.dataTransfer.setData("text/plain",oe),Te.dataTransfer.effectAllowed="move"},[]),te=a.useCallback(()=>{F(null),D(null),$(null)},[]),Ae=a.useCallback(oe=>Te=>{if(Te.preventDefault(),oe===I)return;const me=Te.currentTarget.getBoundingClientRect(),_e=me.top+me.height/2,Ke=Te.clientY<_e?"before":"after";D(oe),$(Ke)},[I]),Fe=a.useCallback(oe=>Te=>{Te.preventDefault();const me=Te.dataTransfer.getData("text/plain");if(!me||me===oe){F(null),D(null),$(null);return}m(_e=>{const Ke=_e.findIndex(we=>we.id===me),Re=_e.findIndex(we=>we.id===oe);if(Ke===-1||Re===-1)return _e;const ct=[..._e],[Y]=ct.splice(Ke,1);let de=Re;return E==="after"&&Ke<Re&&de--,E==="after"&&de++,ct.splice(de,0,Y),ct}),_(!0),F(null),D(null),$(null)},[E]),he=a.useCallback(oe=>{const Te=oe.currentTarget.getBoundingClientRect(),me=oe.clientX,_e=oe.clientY;(me<Te.left||me>Te.right||_e<Te.top||_e>Te.bottom)&&(D(null),$(null))},[]),Me=a.useCallback((oe,Te)=>{Te<0||Te>=d.length||(m(me=>{const _e=[...me],[Ke]=_e.splice(oe,1);return _e.splice(Te,0,Ke),_e}),_(!0))},[d.length]),Oe=a.useCallback(oe=>{J.current[oe+1]?.focus()},[]),at=a.useCallback(async()=>{if(!(!P||ee)){S(null),u({type:"creating",sessionId:P});try{const oe=await _j(P,d,r,o);i(oe.tasks),qe(),n()}catch(oe){S(ke(oe)||"Failed to create tasks"),u({type:"editing",sessionId:P})}}},[ee,n,i,r,o,qe,P,d]),ye=a.useCallback(async()=>{if(c.type!=="error")return;const oe=c.sessionId;S(null),k(!0),f(""),u({type:"generating",sessionId:oe}),Xe(oe);try{await Cj(oe,o,T)}catch(Te){let me=Te;if((ke(Te)||"").includes("not in an error state"))try{const Ke=await ui(oe);if(!Ke)throw new Error("Failed to refresh subtask session.");if(g(ya(Ke.conversationHistory)),Ke.status==="generating"||Ke.status==="awaiting_input")f(Ke.thinkingOutput??""),u({type:"generating",sessionId:Ke.id}),B.current?.isConnected()||Xe(Ke.id);else if(Ke.status==="complete"){if(!Ke.result)throw new Error("Subtask session is complete but has no result.");kl(o);const Re=JSON.parse(Ke.result);m(Re),u({type:"editing",sessionId:Ke.id}),_(!1)}else Ke.status==="error"&&u({type:"error",sessionId:Ke.id,errorMessage:Ke.error??"Retry failed. Please try again."});y(!1);return}catch(Ke){me=Ke}B.current?.close(),B.current=null,u({type:"error",sessionId:oe,errorMessage:ke(me)||"Retry failed. Please try again."}),y(!1)}finally{k(!1)}},[Xe,o,T,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:oe=>oe.target===oe.currentTarget&&void Qe(),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(Do,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[pe&&t.jsx("button",{className:"modal-send-to-background",onClick:et,title:"Send to background","aria-label":"Send to background",children:t.jsx(Er,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Qe(),"aria-label":"Close",children:t.jsx(Gt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[M&&t.jsx("div",{className:"form-error planning-error",children:M}),b&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ce&&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:R})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Ps,{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(!x),type:"button",children:x?"Hide thinking":"Show thinking"}),x&&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(Ps,{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 ye(),disabled:N,children:[N?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Tn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:N?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Qe(),disabled:N,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(Ps,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(yn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[d.map((oe,Te)=>{const me=I===oe.id,_e=V===oe.id,Ke=["task-detail-section","subtask-item",me?"subtask-item-dragging":"",_e?"subtask-item-drop-target":"",_e&&E==="before"?"subtask-item-drop-before":"",_e&&E==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Ke,"data-testid":`subtask-item-${Te}`,draggable:c.type!=="creating",onDragStart:ve(oe.id),onDragEnd:te,onDragOver:Ae(oe.id),onDrop:Fe(oe.id),onDragLeave:he,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(Zc,{size:16}),t.jsx("strong",{children:oe.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Me(Te,Te-1),disabled:c.type==="creating"||Te===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(zi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Me(Te,Te+1),disabled:c.type==="creating"||Te===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(oe.id),disabled:c.type==="creating",children:[t.jsx(sn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:Re=>{J.current[Te]=Re},value:oe.title,onChange:Re=>Ie(oe.id,{title:Re.target.value}),onKeyDown:Re=>{Re.key==="Enter"&&(Re.preventDefault(),Oe(Te))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:oe.description,onChange:Re=>Ie(oe.id,{description:Re.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:oe.suggestedSize,onChange:Re=>Ie(oe.id,{suggestedSize:Re.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,Te).filter(Re=>Re.id!==oe.id).map(Re=>{const ct=oe.dependsOn.includes(Re.id);return t.jsxs("label",{className:`planning-dep-chip ${ct?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:ct,onChange:()=>{const Y=ct?oe.dependsOn.filter(de=>de!==Re.id):[...oe.dependsOn,Re.id];Ie(oe.id,{dependsOn:Y})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:Re.id}),t.jsx("span",{className:"planning-dep-title",children:Re.title||"Untitled"})]},Re.id)}),Te===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Te>0&&d.slice(0,Te).filter(Re=>Re.id!==oe.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},oe.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:We,disabled:c.type==="creating",children:[t.jsx(an,{size:16,className:"icon-mr-6"})," Add subtask"]}),nh(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 Qe(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void at(),disabled:c.type==="creating"||ee,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"})})]})]}),j&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Lo,{size:16}),t.jsx("span",{children:De?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),De&&t.jsx("button",{type:"button",onClick:()=>{W()},disabled:q,className:"btn btn-primary session-lock-take-control",children:q?"Taking control...":"Take Control"})]})})]})]})}):null}const MA=5,_A=1e3,AA=45e3;function oo(){return{scrollback:null,connected:null,data:[]}}function RA(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),x=a.useRef(new Set),v=a.useRef(new Set),b=a.useRef(new Set),y=a.useRef(oo()),N=a.useCallback(D=>{p.current.add(D);const E=y.current;return E.data.length>0&&(E.data.forEach($=>D($)),E.data=[]),()=>p.current.delete(D)},[]),k=a.useCallback(D=>(f.current.add(D),()=>f.current.delete(D)),[]),R=a.useCallback(D=>{x.current.add(D);const E=y.current;return E.connected&&(D(E.connected),E.connected=null),()=>x.current.delete(D)},[]),w=a.useCallback(D=>{v.current.add(D);const E=y.current;return E.scrollback&&(D(E.scrollback),E.scrollback=null),()=>v.current.delete(D)},[]),M=a.useCallback(D=>(b.current.add(D),()=>b.current.delete(D)),[]),S=a.useCallback(D=>{const E=u.current;E?.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"input",data:D}))},[]),z=a.useCallback((D,E)=>{const $=u.current;$?.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"resize",cols:D,rows: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=oo()},[]),I=a.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),u.current&&(g.current=!0,u.current.close(),u.current=null),y.current=oo()},[]),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 D=r.current;let $=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&($+=`&projectId=${encodeURIComponent(n)}`);const B=new WebSocket(ei($));u.current=B,B.onopen=()=>{if(r.current!==D){B.close();return}y.current=oo(),i("connected"),d.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===D&&B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"ping"}))},AA)},B.onmessage=J=>{if(r.current===D)try{const ie=JSON.parse(J.data),C=y.current;switch(ie.type){case"data":ie.data&&(p.current.size===0&&C.data.push(ie.data),p.current.forEach(P=>P(ie.data)));break;case"scrollback":ie.data&&(C.scrollback=ie.data,v.current.forEach(P=>P(ie.data)));break;case"connected":ie.shell&&ie.cwd&&(C.connected={shell:ie.shell,cwd:ie.cwd},x.current.forEach(P=>P({shell:ie.shell,cwd:ie.cwd})));break;case"exit":ie.exitCode!==void 0&&f.current.forEach(P=>P(ie.exitCode));break;case"ping":B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},B.onclose=J=>{if(r.current!==D)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&&b.current.forEach(P=>P());return}if(d.current++,d.current>MA){i("disconnected");return}const ie=_A*Math.pow(2,d.current-1);i("reconnecting");const C=r.current;m.current=setTimeout(()=>{r.current===C&&(g.current||F())},Math.min(ie,16e3))},B.onerror=()=>{}},[e,n]),V=a.useCallback(()=>{d.current=0,I(),F()},[I,F]);return a.useEffect(()=>(c&&(_(),d.current=0,i("disconnected")),e?F():i("disconnected"),I),[e,n,c,F,I,_]),{connectionStatus:s,sendInput:S,resize:z,onData:N,onExit:k,onConnect:R,onScrollback:w,reconnect:V,onSessionInvalid:M}}const eg="kb-terminal-tabs",TA=15e3,PA=15e3;function sh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function ih(e){if(typeof window>"u")return[];try{const n=Vn(eg,e);if(n)return JSON.parse(n)}catch{}return[]}function tc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function ah(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 IA(e){const[n,s]=a.useState(()=>ih(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(ih(e)),r(!1),l(!0),u(null)},[e]),a.useEffect(()=>{try{ds(eg,JSON.stringify(n),e)}catch{}},[e,n]),a.useEffect(()=>{let R=!1;const w=h.current;return(async()=>{if(!R)try{const S=await ah(ky(e),TA,"listTerminalSessions");if(R||w!==h.current)return;const z=new Set(S.map(_=>_.id));l(!0),s(_=>{if(R||w!==h.current)return _;const F=_.map(E=>({...E,_verified:z.has(E.sessionId)})).filter(E=>E._verified);if(F.length===0)return[];const V=F.map(({_verified:E,...$})=>$);return V.find(E=>E.isActive)?V:V.map((E,$)=>({...E,isActive:$===0}))}),r(!0)}catch(S){if(R||w!==h.current)return;const z=tc(S);z||console.warn("Failed to validate terminal sessions with server:",S),l(!z),r(!0)}})(),()=>{R=!0}},[e]),a.useEffect(()=>{if(n.length===0&&i&&o){const R=h.current,w=setTimeout(()=>{ah(Hr(void 0,void 0,void 0,e),PA,"createTerminalSession").then(M=>{if(R!==h.current)return;const S={id:sh(),sessionId:M.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(z=>z.length>0?z:[...z.map(I=>({...I,isActive:!1})),S]),u(null)}).catch(M=>{if(R!==h.current)return;tc(M)||console.error(M);const S=M instanceof Error?M.message:typeof M=="string"?M:"Failed to create terminal session";u(S)})},0);return()=>clearTimeout(w)}},[i,o,n.length,d]);const g=a.useCallback(async()=>{const R=await Hr(void 0,void 0,void 0,e),w={id:sh(),sessionId:R.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(M=>[...M.map(z=>({...z,isActive:!1})),w]),w},[n.length]),p=a.useCallback(async()=>g(),[g]),f=a.useCallback(R=>{s(w=>{const M=w.find(I=>I.id===R);if(!M)return w;Vd(M.sessionId,e).catch(I=>{console.warn(`Failed to kill terminal session ${M.sessionId}:`,I)});const S=w.findIndex(I=>I.id===R),z=M.isActive,_=w.filter(I=>I.id!==R);if(_.length===0)return[];if(z){const I=Math.min(S,_.length-1);return _.map((F,V)=>({...F,isActive:V===I}))}return _})},[]),x=a.useCallback(R=>{s(w=>{let M=!1;const S=w.map(z=>z.id===R?(M=!0,{...z,isActive:!0}):{...z,isActive:!1});return M?S:w})},[]),v=a.useCallback((R,w)=>{s(M=>M.map(S=>S.id===R?{...S,title:w}:S))},[]),b=a.useCallback(async()=>{s(M=>{const S=M.find(z=>z.isActive);return S&&Vd(S.sessionId,e).catch(z=>{console.warn(`Failed to kill old session ${S.sessionId}:`,z)}),M});const R=n.find(M=>M.isActive);if(!R)return;const w=await Hr(void 0,void 0,void 0,e);s(M=>M.map(S=>S.id===R.id?{...S,sessionId:w.sessionId}:S))},[n]),y=a.useCallback(async()=>{const R=n.find(w=>w.isActive);if(R)try{const w=await Hr(void 0,void 0,void 0,e);s(M=>M.map(S=>S.id===R.id?{...S,sessionId:w.sessionId}:S)),u(null)}catch(w){tc(w)||console.error(w);const M=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";u(M)}},[n]),N=n.find(R=>R.isActive)??null,k=a.useCallback(()=>{u(null),h.current+=1,m(R=>R+1)},[]);return{tabs:n,activeTab:N,isReady:i,bootstrapError:c,createTab:p,closeTab:f,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:k,replaceActiveTabSession:y}}const $A=1e4,DA=[500,1500,3e3],tg="kb-terminal-font-size",ar=14,LA=8,zA=32;function OA(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 FA(e){return`\x1B${e}`}const UA=[{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 rr(e){return Math.min(zA,Math.max(LA,e))}function BA(){if(typeof window>"u")return ar;try{const e=window.localStorage.getItem(tg);if(!e)return ar;const n=Number.parseInt(e,10);return Number.isFinite(n)?rr(n):ar}catch{return ar}}function HA(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 qA(e){return new Promise(n=>setTimeout(n,e))}async function VA(e,n=DA){let s;for(let i=0;i<=n.length;i+=1)try{return await e()}catch(r){if(!HA(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 qA(o)}throw s??new Error("Dynamic import failed")}function rh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function WA(){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=KA()-e.offsetTop-e.height;return i>=30&&i>80?i:0}let nc=null;function KA(){return nc===null&&(nc=window.innerHeight),nc}function GA({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,x]=a.useState(0),[v,b]=a.useState(null),[y,N]=a.useState(()=>BA()),[k,R]=a.useState(!1),[w,M]=a.useState(null),S=a.useRef(null),z=a.useRef(null),_=a.useRef(!1);ti(z,e,"fusion:terminal-modal-size");const I=a.useRef(null),F=a.useRef(null),V=a.useRef(!1),D=a.useRef(!1),E=a.useRef(null),$=a.useRef(()=>{}),B=a.useRef(null),J=a.useRef(0),ie=a.useRef(y),C=a.useRef(null),P=a.useRef(i);J.current=f,ie.current=y;const T=a.useCallback(me=>{if(me&&D.current!==me)return;const _e=F.current,Ke=I.current,Re=E.current;if(!(!_e||!Ke)&&!(me&&D.current!==me))try{_e.fit(),Re&&Re(Ke.cols,Ke.rows)}catch{}},[]);a.useEffect(()=>{e&&p(me=>me+1)},[e]),a.useEffect(()=>{if(!e||!rh())return;const me=window.visualViewport;if(!me)return;const _e=()=>{const Ke=WA();x(Ke),b(me.height),Ke>0&&z.current?.scrollIntoView&&z.current.scrollIntoView({block:"end",behavior:"smooth"}),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const Re=typeof D.current=="string"?D.current:void 0;C.current=requestAnimationFrame(()=>{C.current=null,T(Re)})};return _e(),me.addEventListener("resize",_e),me.addEventListener("scroll",_e),()=>{me.removeEventListener("resize",_e),me.removeEventListener("scroll",_e),C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),x(0),b(null)}},[T,e]),a.useEffect(()=>{if(!e)return;const me=z.current;if(!me||typeof ResizeObserver>"u")return;let _e=null;const Ke=new ResizeObserver(()=>{_e!==null&&cancelAnimationFrame(_e),_e=requestAnimationFrame(()=>{_e=null;const Re=typeof D.current=="string"?D.current:void 0;T(Re)})});return Ke.observe(me),()=>{Ke.disconnect(),_e!==null&&cancelAnimationFrame(_e)}},[T,e]);const{tabs:j,activeTab:W,isReady:q,bootstrapError:ge,createTab:be,closeTab:ce,setActiveTab:Se,updateTabTitle:O,restartActiveTab:le,retryBootstrap:ee,replaceActiveTabSession:pe}=IA(i),{connectionStatus:ue,sendInput:fe,resize:se,onData:Ce,onConnect:De,onExit:qe,onScrollback:et,reconnect:Qe,onSessionInvalid:Xe}=RA(W?.sessionId??null,i);E.current=se,$.current=fe,a.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(tg,String(y))}catch{}},[y]);const it=a.useCallback(()=>{const me=I.current;if(me)try{F.current?.fit(),se(me.cols,me.rows)}catch{}},[se]);a.useEffect(()=>{if(!e||!q)return;const me=W?.sessionId;if(!me)return;const _e=P.current!==i;if(_e&&(P.current=i),D.current===me&&I.current&&!_e)return;I.current&&(D.current!==me||_e)&&(I.current.dispose(),I.current=null,F.current=null,D.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null));let Ke=!0,Re;return(async()=>{const Y=VA(()=>Promise.all([un(()=>import("./vendor-xterm-DzcZoU0P.js").then(Z=>Z.x),__vite__mapDeps([0,1,2])),un(()=>import("./addon-fit-C7jRorKK.js").then(Z=>Z.a),__vite__mapDeps([3,1])),un(()=>import("./addon-web-links-CkJwd4cQ.js").then(Z=>Z.a),__vite__mapDeps([4,1]))])),de=new Promise((Z,Ge)=>{Re=setTimeout(()=>{Ge(new Error("xterm initialization timed out"))},$A)});let we,tt;try{const[{Terminal:Z},{FitAddon:Ge},{WebLinksAddon:dt}]=await Promise.race([Y,de]);if(!Ke||!S.current||I.current)return;we=new Z({cursorBlink:!0,cursorStyle:"block",fontSize:ie.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}),tt=new Ge,we.loadAddon(tt);const pt=new dt;if(we.loadAddon(pt),!rh())try{const{WebglAddon:ft}=await un(async()=>{const{WebglAddon:Ot}=await import("./addon-webgl-BjvOw43o.js").then(Vt=>Vt.a);return{WebglAddon:Ot}},__vite__mapDeps([5,1])),St=new ft;St.onContextLoss(()=>{St.dispose()}),we.loadAddon(St)}catch{}we.open(S.current),Re&&clearTimeout(Re);const jt=S.current?.querySelector(".xterm-helper-textarea");if(jt&&jt.focus(),S.current)try{S.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{tt.fit();const ft=S.current?.querySelector(".xterm-helper-textarea");ft&&ft.focus()},50),I.current=we,F.current=tt,D.current=me,J.current>0&&(C.current!==null&&(cancelAnimationFrame(C.current),C.current=null),C.current=requestAnimationFrame(()=>{C.current=null,T(me)})),we.onData(ft=>{D.current===me&&$.current(ft)});const yt=()=>{if(D.current===me&&F.current&&I.current)try{F.current.fit();const{cols:ft,rows:St}=I.current;E.current?.(ft,St)}catch{}};window.addEventListener("resize",yt),B.current&&window.removeEventListener("resize",B.current),B.current=yt,d(!0),h(null)}catch(Z){if(Re&&clearTimeout(Re),!Ke)return;const Ge=Z instanceof Error?Z.message:"xterm initialization failed";h(Ge)}})(),()=>{Ke=!1,Re&&clearTimeout(Re)}},[T,e,q,W?.sessionId,i]),a.useEffect(()=>{e||(I.current&&(I.current.dispose(),I.current=null),F.current=null,D.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null),V.current=!1,o(null),c(null),R(!1),M(null))},[e]),a.useEffect(()=>{if(!u||!I.current||!W)return;const me=W.sessionId,_e=de=>{D.current===me&&I.current?.write(de)},Ke=Ce(de=>{_e(de)}),Re=et(de=>{_e(de)}),ct=De(de=>{O(W.id,rd(de.shell)||de.shell)}),Y=qe(de=>{D.current===me&&(c(de),I.current?.write(`\r
653
- \x1B[33m[Process exited with code ${de}]\x1B[0m\r
654
- `))});return()=>{Ke(),Re(),ct(),Y()}},[u,W?.sessionId,W?.id,W,ue,Ce,et,De,qe,O]),a.useEffect(()=>{ue==="connected"&&s&&V.current!==s&&W&&(V.current=s,setTimeout(()=>{fe(s+`
655
- `)},500))},[ue,s,fe,W,g]),a.useEffect(()=>{if(!u||!I.current)return;I.current.options.fontSize=y,C.current!==null&&(cancelAnimationFrame(C.current),C.current=null);const me=requestAnimationFrame(()=>{C.current=null,it()});return C.current=me,()=>{C.current===me&&(cancelAnimationFrame(me),C.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const me=_e=>{if(!(!_e.ctrlKey&&!_e.metaKey)){if(_e.code==="Equal"||_e.code==="NumpadAdd"){_e.preventDefault(),N(Ke=>rr(Ke+1));return}if(_e.code==="Minus"||_e.code==="NumpadSubtract"){_e.preventDefault(),N(Ke=>rr(Ke-1));return}if(_e.code==="Digit0"||_e.code==="Numpad0"){_e.preventDefault(),N(ar);return}}};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[e,it]),a.useEffect(()=>{if(!e)return;const me=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,n]),a.useEffect(()=>{ue==="connected"&&I.current&&setTimeout(()=>{if(!I.current||!S.current)return;const me=S.current.querySelector(".xterm-helper-textarea");me&&me.focus();try{S.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[ue]);const Ie=a.useCallback(()=>{if(!S.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;I.current?.focus();const _e=S.current.querySelector(".xterm-helper-textarea");if(!_e)return;_e.autocapitalize="off",_e.autocomplete="off",_e.autocorrect="off",_e.spellcheck=!1,_e.setAttribute("inputmode","text");try{_e.focus({preventScroll:!0})}catch{_e.focus()}const Ke=_e.value.length;_e.setSelectionRange(Ke,Ke)},[]);a.useEffect(()=>Xe(()=>{I.current?.clear(),c(null),V.current=!1,I.current&&(I.current.dispose(),I.current=null),F.current=null,D.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),d(!1),h(null),pe().catch(_e=>{console.error("Failed to replace invalid terminal session:",_e)})}),[Xe,pe]);const We=a.useCallback(me=>{me.target===me.currentTarget&&(_.current=!0)},[]),re=a.useCallback(me=>{_.current&&me.target===me.currentTarget&&n(),_.current=!1},[n]),ve=a.useCallback(()=>{I.current?.clear()},[]),te=a.useCallback(async()=>{I.current?.clear(),c(null),V.current=!1;try{await le()}catch(me){o(ke(me)||"Failed to restart terminal session")}},[le]),Ae=a.useCallback(()=>{I.current&&(I.current.dispose(),I.current=null),F.current=null,D.current=!1,B.current&&(window.removeEventListener("resize",B.current),B.current=null),h(null),d(!1)},[]),Fe=a.useCallback(()=>{window.location.reload()},[]),he=a.useCallback(()=>{N(me=>rr(me+1))},[]),Me=a.useCallback(()=>{N(me=>rr(me-1))},[]),Oe=a.useCallback(me=>{M(_e=>_e===me?null:me)},[]),at=a.useCallback(me=>{if(w==="ctrl"){fe(OA(me)),M(null);return}if(w==="alt"){fe(FA(me)),M(null);return}fe(me)},[fe,w]),ye=a.useCallback(me=>{fe(me),M(null)},[fe]);if(!e)return null;const oe=()=>{switch(ue){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}},Te=!q||!W&&!ge;return t.jsx("div",{className:"modal-overlay open",onMouseDown:We,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:z,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:[j.map(me=>t.jsxs("div",{className:`terminal-tab ${me.isActive?"terminal-tab--active":""}`,onClick:()=>Se(me.id),title:me.title,role:"tab","aria-selected":me.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:me.title}),j.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:_e=>{_e.stopPropagation(),ce(me.id)},title:"Close tab",children:"×"})]},me.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:be,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(di,{size:16}),oe()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[ue==="disconnected"&&W&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Qe,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Tn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:te,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Tn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:ve,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(sn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>R(me=>!me),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Zx,{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(Gt,{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:[Te&&!ge&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ge&&!W&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",ge]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ee,"data-testid":"terminal-retry-btn",children:[t.jsx(Tn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Tn,{size:14}),"Refresh page"]})]})]})}),m&&W&&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(Tn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Tn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:S,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Ie,onTouchStart:Ie},W?.sessionId)]}),k&&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:()=>Oe("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:()=>Oe("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ye("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ye(" "),children:"Tab"})]}),UA.map(me=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>at(me.key),title:me.description,children:me.label},me.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${ue}`,children:[ue==="connected"&&"Connected",ue==="connecting"&&"Connecting...",ue==="reconnecting"&&"Reconnecting...",ue==="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:Me,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(bb,{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:he,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(an,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Ya={name:"",command:""};function oh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function JA(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function YA({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(Ya),[x,v]=a.useState(!1),[b,y]=a.useState(null),[N,k]=a.useState(null),R=Si(n),w=a.useCallback(async()=>{try{u(!0);const $=await br(i);l($)}catch($){s(ke($)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&w()},[e,w]);const M=a.useCallback(()=>{m(!0),g(null),f(Ya),k(null)},[]),S=a.useCallback(($,B)=>{g($),m(!1),f({name:$,command:B}),k(null)},[]),z=a.useCallback(()=>{g(null),m(!1),f(Ya),k(null)},[]),_=a.useCallback($=>{f(B=>({...B,name:$})),$&&!oh($)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),I=a.useCallback(async()=>{const $=p.name.trim(),B=p.command.trim();if(!$){s("Script name is required","error");return}if(!oh($)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!B){s("Script command is required","error");return}v(!0);try{await wj($,B,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Ya),k(null),await w()}catch(J){const ie=ke(J);ie?.includes("already exists")?s("A script with this name already exists","error"):s(ie||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,i]),F=a.useCallback(async $=>{try{await Nj($,i),s("Script deleted","success"),y(null),h===$&&(g(null),f(Ya)),await w()}catch(B){s(ke(B)||"Failed to delete script","error")}},[h,s,w,i]),V=a.useCallback(($,B)=>{r&&r($,B)},[r]);if(!e)return null;const D=d||h!==null,E=Object.entries(o).map(([$,B])=>({name:$,command:B}));return t.jsx("div",{className:"modal-overlay open",...R,"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..."]}):D?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:$=>_($.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:N?"var(--color-error)":void 0}}),N&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:N}),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:$=>f(B=>({...B,command:$.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"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:z,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:I,disabled:x||!!N,"data-testid":"script-save-btn",children:x?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:E.length===0?"No scripts defined":`${E.length} script${E.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:M,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(an,{size:14}),"Add Script"]})]}),E.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:E.map($=>t.jsx("div",{className:"script-card","data-testid":`script-${$.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:$.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:$.command,children:JA($.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:()=>V($.name,$.command),title:"Run script","aria-label":`Run ${$.name}`,"data-testid":`run-script-${$.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Sn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>S($.name,$.command),title:"Edit","aria-label":`Edit ${$.name}`,"data-testid":`edit-script-${$.name}`,children:t.jsx(an,{size:14,style:{transform:"rotate(45deg)"}})}),b===$.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>F($.name),title:"Confirm delete","aria-label":`Confirm delete ${$.name}`,"data-testid":`confirm-delete-script-${$.name}`,style:{color:"var(--color-error)"},children:t.jsx(sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${$.name}`,children:t.jsx(Gt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y($.name),title:"Delete","aria-label":`Delete ${$.name}`,"data-testid":`delete-script-${$.name}`,children:t.jsx(sn,{size:14})})]})]})},$.name))})]})})]})})}function QA(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(x=>x+1)},[]),f=a.useCallback(x=>{l(x),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){u(!0),m(null);try{const b=await Fy(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(ke(b)||"Failed to load files"),r([]))}finally{x||u(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function XA(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,x]=a.useState(null),v=a.useCallback(N=>{o(N),x(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),x(null);return}let N=!1;async function k(){h(!0),x(null);try{const R=await Uy(e,n,i);N||(o(R.content),c(R.content),d(R.mtime))}catch(R){N||(x(ke(R)||"Failed to load file"),o(""),c(""),d(null))}finally{N||h(!1)}}return k(),()=>{N=!0}},[e,n,s,i]);const b=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const N=await By(e,n,r,i);c(r),d(N.mtime)}catch(N){throw x(ke(N)||"Failed to save file"),N}finally{p(!1)}}},[e,n,r,b,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:b,mtime:u}}const ZA=1e4;function eR(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function tR(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function nR(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 Oy(e);if(d)return;s(eR(g.project)),r(g.tasks.map(tR)),u(null)}catch(g){d||u(ke(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},ZA);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function sR(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function iR(e){return e?new Date(e).toLocaleDateString():""}function lh(e,n){return dw(e,n)}const Qa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},sc={type:null,entry:null,entryFullPath:""},aR=200,rR=500,ch=10;function oR({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,x=g?.offsetLeft??0,v=g?.offsetTop??0,b=8;let y=e-x,N=n-v;y+h.width>p-b&&(y=p-b-h.width),N+h.height>f-b&&(N=f-b-h.height),y<b&&(y=b),N<b&&(N=b),c({x:y+x,y:N+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:Fi,disabled:!1},{id:"move",label:"Move",icon:jb,disabled:!1},{id:"rename",label:"Rename",icon:ss,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:To,disabled:!1}]:[{id:"download",label:"Download",icon:hx,disabled:!1}],{id:"divider",label:"",icon:Fi,disabled:!0},{id:"delete",label:"Delete",icon:sn,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 lR({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 cR({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(Qa),[g,p]=a.useState(sc),[f,x]=a.useState(!1),[v,b]=a.useState(null),[y,N]=a.useState(!1),[k,R]=a.useState(null),w=a.useRef(null),M=a.useRef(null),S=a.useRef(null),z=a.useRef(!1),_=a.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),I=a.useCallback(()=>{_(),S.current=null,N(!1),R(null)},[_]);a.useEffect(()=>()=>{_()},[_]);const F=a.useCallback((P,T,j,W)=>{h({visible:!0,x:P,y:T,entry:j,entryFullPath:W})},[]),V=a.useCallback((P,T,j)=>{if(P.touches.length!==1)return;const W=P.touches[0];W&&(I(),S.current={x:W.clientX,y:W.clientY},M.current=window.setTimeout(()=>{N(!0),R(j)},aR),w.current=window.setTimeout(()=>{const q=S.current;q&&(z.current=!0,N(!1),R(null),_(),F(q.x,q.y,T,j))},rR))},[I,_,F]),D=a.useCallback(P=>{const T=S.current,j=P.touches[0];!T||!j||(Math.abs(j.clientX-T.x)>ch||Math.abs(j.clientY-T.y)>ch)&&I()},[I]),E=a.useCallback(()=>{I()},[I]);a.useEffect(()=>{if(!m.visible)return;const P=document.querySelector(".file-browser-list"),T=()=>{z.current=!1,I(),h(Qa)};return P?.addEventListener("scroll",T),()=>P?.removeEventListener("scroll",T)},[I,m.visible]),a.useEffect(()=>{if(!m.visible)return;const P=T=>{T.key==="Escape"&&(z.current=!1,h(Qa))};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[m.visible]);const $=a.useCallback((P,T)=>{P.preventDefault(),P.stopPropagation(),I(),z.current=!1,F(P.clientX,P.clientY,T,lh(n,T.name))},[I,n,F]),B=a.useCallback(P=>{if(!m.entry)return;z.current=!1;const T=m.entry,j=m.entryFullPath;if(h(Qa),P==="download"){if(!c)return;const W=lp(c,j,d);window.open(ei(W),"_blank");return}if(P==="download-zip"){if(!c)return;const W=Gy(c,j,d);window.open(ei(W),"_blank");return}p({type:P,entry:T,entryFullPath:j}),b(null)},[m,c,d]),J=a.useCallback(async P=>{if(!(!g.type||!g.entry||!c)){x(!0),b(null);try{switch(g.type){case"copy":await qy(c,g.entryFullPath,P,d);break;case"move":await Vy(c,g.entryFullPath,P,d);break;case"rename":await Ky(c,g.entryFullPath,P,d);break;case"delete":await Wy(c,g.entryFullPath,d);break}p(sc),u?.()}catch(T){b(ke(T)||"Operation failed")}finally{x(!1)}}},[g,c,u,d]),ie=a.useCallback(()=>{p(sc),b(null)},[]),C=a.useCallback((P,T)=>{if(z.current){z.current=!1;return}m.visible||(P.type==="directory"?i(T):s(T))},[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(uw(n))},children:[t.jsx(vn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Aa(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(P=>{const T=lh(n,P.name),j=y&&k===T;return t.jsxs("div",{className:`file-node file-node--${P.type} ${j?"file-node--long-pressing":""}`,onClick:()=>C(P,T),onContextMenu:W=>$(W,P),onTouchStart:W=>V(W,P,T),onTouchMove:D,onTouchEnd:E,onTouchCancel:E,children:[t.jsx("div",{className:"file-node-icon",children:P.type==="directory"?t.jsx(Hn,{size:16}):t.jsx(Gh,{size:16})}),t.jsx("div",{className:"file-node-name",children:P.name}),P.type==="file"&&P.size!==void 0&&t.jsx("div",{className:"file-node-size",children:sR(P.size)}),P.mtime&&t.jsx("div",{className:"file-node-time",children:iR(P.mtime)})]},P.name)})}),m.visible&&m.entry&&t.jsx(oR,{x:m.x,y:m.y,entry:m.entry,onAction:B,onClose:()=>{z.current=!1,h(Qa)}}),g.type&&g.entry&&t.jsx(lR,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:J,onCancel:ie,loading:f,error:v})]})}function dR(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function uR({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=dR(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(Kh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(fa,{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(xo,{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(xo,{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 mR(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function hR({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($d,{size:14}):t.jsx(yc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(Qt,{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($d,{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(yc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:mR(c.title)})]},c.id))]})]})]})}const pR=768,ng=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),fR=new Set([...ng,".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 dh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return fR.has(n)}function gR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ng.has(n)}function xR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=nR(i),l=a.useRef(null);ti(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,x]=a.useState("list"),{entries:v,currentPath:b,setPath:y,loading:N,error:k,refresh:R}=QA(u,!0,i),{content:w,setContent:M,originalContent:S,loading:z,saving:_,error:I,save:F,hasChanges:V,mtime:D}=XA(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const j=()=>{p(window.innerWidth<=pR)};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[]),a.useEffect(()=>{m||x("list")},[m]),a.useEffect(()=>{const j=W=>{W.key==="Escape"&&n(),(W.metaKey||W.ctrlKey)&&W.key==="s"&&(W.preventDefault(),V&&!_&&F())};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[n,V,_,F]);const E=a.useCallback(j=>{h(j),g&&x("editor")},[g]),$=a.useCallback(()=>{x("list")},[]),B=a.useCallback(()=>{M(S)},[S,M]),J=a.useCallback(j=>{d(j),h(null),x("list"),s?.(j)},[s]),C=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(j=>j.id===u)?.id??u,[u,o])}`,P=a.useMemo(()=>!m||!gR(m)?null:lp(u,m,i),[m,u,i]),T=j=>{const W=new Blob([j]).size;return W<1024?`${W} B`:`${(W/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(Hn,{size:18}),t.jsx("span",{children:C}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(hR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:J}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Gt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${g?"mobile":""} ${f==="list"?"active":""}`,children:t.jsx(cR,{entries:v,currentPath:b,onSelectFile:E,onNavigate:y,loading:N,error:k,onRetry:R,workspace:u,onRefresh:R,projectId:i})}),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:$,"aria-label":"Back to file list",children:[t.jsx(Ma,{size:16}),t.jsx("span",{children:"Back"})]}),m,dh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Tx,{size:12}),"Binary file — read only"]}),D&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(D).toLocaleString()]}),z&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!P&&V&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:B,disabled:_,children:[t.jsx(Tb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void F(),disabled:_,children:[t.jsx(ep,{size:14}),_?"Saving...":"Save"]})]})})]}),I&&!P&&t.jsx("div",{className:"file-browser-error-banner",children:I}),P?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:P,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(uR,{content:w,onChange:M,filePath:m,readOnly:dh(m)})}),!P&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:T(w)}),V&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Hn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function bR(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 ny();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 vR(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 yR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const sg="kb-usage-hidden-windows";function uh(e){const n=Vn(sg,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 jR(e,n){ds(sg,JSON.stringify(e),n)}function ig(e,n,s){return s[e]?.includes(n)??!1}function kR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=yR(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 b=Math.floor(v/36e5),y=Math.floor(b/24),N=b%24;y>0&&N>0?d=`resets in ${y}d ${N}h`:y>0?d=`resets in ${y}d`:b>0?d=`resets in ${b}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",x=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(fa,{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:vR(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(ed,{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(ev,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function wR(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 NR({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(zn,{provider:wR(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=ig(e.name,c.label,s);return t.jsx(kR,{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 SR(){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 CR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=bR({autoRefresh:e}),[d,m]=a.useState(!1),[h,g]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,f]=a.useState("used"),[x,v]=a.useState(()=>uh(s)),b=a.useRef(null),y=a.useRef(e),N=a.useRef(!1);a.useEffect(()=>{e||(N.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(N.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const E=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const E=Vn("kb-usage-view-mode",s);if(E==="used"||E==="remaining"){f(E);return}f("used")},[s]);const k=a.useCallback(E=>{f(E),ds("kb-usage-view-mode",E,s)},[s]);a.useEffect(()=>{v(uh(s))},[s]),a.useEffect(()=>{jR(x,s)},[x,s]);const R=a.useCallback((E,$)=>{v(B=>{if(ig(E,$,B)){const J=(B[E]??[]).filter(ie=>ie!==$);if(J.length===0){const{[E]:ie,...C}=B;return C}return{...B,[E]:J}}return{...B,[E]:[...B[E]??[],$]}})},[]),w=a.useCallback(E=>{v($=>{if(!$[E])return $;const{[E]:B,...J}=$;return J})},[]),M=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const E=$=>{$.key==="Escape"&&n()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,n]);const S=a.useCallback(E=>{E.target===E.currentTarget&&n()},[n]);if(!e)return null;const z=!!(i&&h),F=z?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,V=z?Math.max(window.innerWidth-(i?.right??0),0):void 0,D=t.jsxs("div",{className:`usage-modal${z?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:z?{position:"fixed",top:F,right:V}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ts,{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:()=>k("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:()=>k("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(Gt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:b,children:(o||!N.current&&!l)&&r.length===0?t.jsx(SR,{}):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:M,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(E=>t.jsx(NR,{provider:E,viewMode:p,hiddenWindows:x,onToggleWindow:R,onShowAllHidden:w},E.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:M,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Tn,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return z?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),D]}):t.jsx("div",{className:"modal-overlay open",onClick:S,"data-testid":"usage-modal-overlay",children:D})}function ag(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 _o(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 ER={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},rg={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},MR={cron:qh,webhook:np,api:Vh,manual:Bn},_R={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},AR={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function RR({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(yn,{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:ag(n)})]})}function TR({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"} ${_o(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(yn,{size:12}):t.jsx(Sr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:_o(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:rg[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:ag(r)}),s?t.jsx(mi,{size:12}):t.jsx(Qt,{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 PR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Hs(),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=ER[e.trigger.type],g=MR[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}),rg[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($o,{size:10}):t.jsx(Hn,{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(Sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(Us,{size:14}):t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(ss,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(sn,{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(Bi,{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:_R[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:AR[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:_o(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:_o(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(RR,{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(Qt,{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,x)=>t.jsx(TR,{result:f,index:x},`${f.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function IR({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(ab,{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(Zn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function ic(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function $R(e){return e==="command"?{id:ic(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:ic(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:ic(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function DR({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??""),[x,v]=a.useState(e.taskTitle??""),[b,y]=a.useState(e.taskDescription??""),[N,k]=a.useState(e.taskColumn??"triage"),[R,w]=a.useState(e.timeoutMs),[M,S]=a.useState(e.continueOnFailure??!1),[z,_]=a.useState({}),[I,F]=a.useState([]),[V,D]=a.useState(!1),[E,$]=a.useState(null);a.useEffect(()=>{let P=!1;return D(!0),$(null),ms().then(T=>{P||F(T.models)}).catch(T=>{P||$(T instanceof Error?T.message:"Failed to load models")}).finally(()=>{P||D(!1)}),()=>{P=!0}},[]);const B=a.useCallback(()=>{const P={};return i.trim()||(P.name="Step name is required"),o==="command"&&!c.trim()&&(P.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(P.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(P.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(P.modelProvider="Both model provider and model ID must be set together"),R!==void 0&&R<1e3&&(P.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(P),Object.keys(P).length===0},[i,o,c,d,b,h,p,R]),J=h&&p?`${h}/${p}`:"",ie=a.useCallback(P=>{if(!P)g(""),f("");else{const T=P.indexOf("/");T!==-1&&(g(P.slice(0,T)),f(P.slice(T+1)))}},[]),C=a.useCallback(()=>{if(!B())return;const P={...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"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?N: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:R||void 0,continueOnFailure:M};o!=="ai-prompt"&&delete P.prompt,o!=="create-task"&&(delete P.taskTitle,delete P.taskDescription,delete P.taskColumn),n(P)},[B,n,e,i,o,c,d,x,b,N,h,p,R,M]);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:P=>r(P.target.value),"aria-invalid":!!z.name}),z.name&&t.jsx("small",{className:"field-error",children:z.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:P=>l(P.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:P=>u(P.target.value),rows:2,"aria-invalid":!!z.command}),z.command&&t.jsx("small",{className:"field-error",children:z.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:P=>m(P.target.value),rows:3,"aria-invalid":!!z.prompt}),z.prompt&&t.jsx("small",{className:"field-error",children:z.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(qn,{id:`step-model-${e.id}`,label:"Model",models:I,value:J,onChange:ie,placeholder:"Use default",disabled:V}),E&&t.jsx("small",{className:"field-error",children:E}),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:x,onChange:P=>v(P.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:b,onChange:P=>y(P.target.value),rows:4,"aria-invalid":!!z.taskDescription}),z.taskDescription&&t.jsx("small",{className:"field-error",children:z.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:N,onChange:P=>k(P.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(qn,{id:`step-task-model-${e.id}`,label:"Model",models:I,value:J,onChange:ie,placeholder:"Use default",disabled:V}),E&&t.jsx("small",{className:"field-error",children:E}),z.modelProvider&&t.jsx("small",{className:"field-error",children:z.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:R??"",onChange:P=>w(P.target.value?Number(P.target.value):void 0),"aria-invalid":!!z.timeoutMs}),z.timeoutMs&&t.jsx("small",{className:"field-error",children:z.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:M,onChange:P=>S(P.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:C,children:"Save Step"})]})]})}function LR({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=$R(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(DR,{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(Zc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(IR,{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(Qt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(ss,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(sn,{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(an,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(an,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(an,{size:14}),"Add Create Task Step"]})]})]})}const og={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},zR={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function OR(e){const n=e.trim();for(const[s,i]of Object.entries(og))if(i===n)return s;return"custom"}function FR(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function UR(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 BR(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 HR=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],qR=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function mh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function hh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?BR(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,x]=a.useState(c.cronExpression),[v,b]=a.useState(()=>c.triggerType!=="cron"?"custom":OR(c.cronExpression)),[y,N]=a.useState(c.webhookPath),[k,R]=a.useState(c.webhookSecret),[w,M]=a.useState(c.endpoint),[S,z]=a.useState(e?.executionPolicy??"queue"),[_,I]=a.useState(e?.catchUpPolicy??"run_one"),[F,V]=a.useState(e?.enabled??!0),D=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,E=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[$,B]=a.useState(e?.steps&&e.steps.length>0&&!D&&!E?"advanced":"simple"),[J,ie]=a.useState(()=>D?"ai-prompt":E?"create-task":"command"),[C,P]=a.useState(e?.command??""),[T,j]=a.useState(e?.steps??[]),[W,q]=a.useState(!1),[ge,be]=a.useState(e?.timeoutMs??3e5),[ce,Se]=a.useState(D?e.steps?.[0]?.prompt??"":""),[O,le]=a.useState(E?e.steps?.[0]?.taskTitle??"":""),[ee,pe]=a.useState(E?e.steps?.[0]?.taskDescription??"":""),[ue,fe]=a.useState(E?e.steps?.[0]?.taskColumn??"triage":"triage"),[se,Ce]=a.useState(D||E?e.steps?.[0]?.modelProvider??"":""),[De,qe]=a.useState(D||E?e.steps?.[0]?.modelId??"":""),[et,Qe]=a.useState([]),[Xe,it]=a.useState(!1),[Ie,We]=a.useState(null),[re,ve]=a.useState(i??"global"),[te,Ae]=a.useState({}),[Fe,he]=a.useState(!1),Me=a.useRef(!0);a.useEffect(()=>()=>{Me.current=!1},[]),a.useEffect(()=>{i&&ve(i)},[i]),a.useEffect(()=>{let Z=!1;return it(!0),We(null),ms().then(Ge=>{Z||Qe(Ge.models)}).catch(Ge=>{Z||We(Ge instanceof Error?Ge.message:"Failed to load models")}).finally(()=>{Z||it(!1)}),()=>{Z=!0}},[]);const Oe=se&&De?`${se}/${De}`:"",at=a.useCallback(Z=>{if(!Z){Ce(""),qe("");return}const Ge=Z.indexOf("/");Ge!==-1&&(Ce(Z.slice(0,Ge)),qe(Z.slice(Ge+1)))},[]),ye=a.useCallback(()=>{const Z={};if(u.trim()||(Z.name="Name is required"),re==="project"&&!r&&(Z.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?FR(f)||(Z.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Z.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(Z.webhookPath="Webhook path is required"),g==="api"&&!w.trim()&&(Z.endpoint="API endpoint is required"),$==="simple")J==="command"&&!C.trim()&&(Z.command="Command is required"),J==="ai-prompt"&&!ce.trim()&&(Z.prompt="Prompt is required"),J==="create-task"&&!ee.trim()&&(Z.taskDescription="Task description is required"),(se.trim()&&!De.trim()||!se.trim()&&De.trim())&&(Z.model="Both model provider and model ID must be set, or both must be empty");else{T.length===0&&(Z.steps="At least one step is required"),W&&(Z.stepsEditing="Please save or cancel all step edits before saving the routine");const Ge=[];T.forEach((dt,pt)=>{dt.name?.trim()||Ge.push(`Step ${pt+1}: Name is required`),dt.type==="command"&&!dt.command?.trim()&&Ge.push(`Step ${pt+1}: Command is required`),dt.type==="ai-prompt"&&!dt.prompt?.trim()&&Ge.push(`Step ${pt+1}: Prompt is required`),dt.type==="create-task"&&!dt.taskDescription?.trim()&&Ge.push(`Step ${pt+1}: Task description is required`)}),Ge.length>0&&(Z.steps=Ge.join("; "))}return ge<1e3&&(Z.timeoutMs="Timeout must be at least 1 second (1000ms)"),Ae(Z),Object.keys(Z).length===0},[u,g,f,v,y,w,re,r,$,J,C,ce,ee,se,De,T,W,ge]),oe=a.useCallback(async Z=>{if(Z.preventDefault(),!!ye()){he(!0);try{let Ge=e?.scope??re??(r?"project":"global");Ge==="project"&&!r&&(Ge="global");const dt=UR(g,f,y,k,w);let pt,jt;$==="simple"?J==="command"?pt=C.trim()||void 0:J==="ai-prompt"?jt=[{id:mh(),type:"ai-prompt",name:u.trim(),prompt:ce.trim(),modelProvider:se.trim()||void 0,modelId:De.trim()||void 0}]:jt=[{id:mh(),type:"create-task",name:u.trim(),taskTitle:O.trim()||void 0,taskDescription:ee.trim(),taskColumn:ue,modelProvider:se.trim()||void 0,modelId:De.trim()||void 0}]:jt=T;const yt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:dt,command:pt,steps:jt,timeoutMs:ge,executionPolicy:S,catchUpPolicy:_,enabled:F,scope:Ge};await n(yt)}finally{Me.current&&he(!1)}}},[ye,n,u,m,g,f,y,k,w,$,J,C,ce,se,De,O,ee,ue,T,ge,S,_,F,re,r,e?.scope,e?.agentId]),Te="routine-name-error",me="routine-cron-error",_e="routine-webhook-error",Ke="routine-endpoint-error",Re="routine-command-error",ct="routine-prompt-error",Y="routine-task-description-error",de="routine-model-error",we="routine-timeout-error",tt=a.useCallback(Z=>{b(Z),Z!=="custom"&&x(og[Z])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:oe,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:Z=>d(Z.target.value),"aria-invalid":!!te.name,"aria-describedby":te.name?Te:void 0}),te.name&&t.jsx("small",{id:Te,className:"field-error",children:te.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:Z=>h(Z.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:()=>{ve("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($o,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${re==="project"?" active":""}`,onClick:()=>{ve("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(Hn,{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."}),te.scope&&t.jsx("small",{className:"field-error",children:te.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(np,{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(Vh,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(Bn,{size:14}),"Manual"]})]})]}),g==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:Z=>tt(Z.target.value),children:Object.entries(zR).map(([Z,Ge])=>t.jsx("option",{value:Z,children:Ge},Z))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:Z=>x(Z.target.value),disabled:v!=="custom","aria-invalid":!!te.cronExpression,"aria-describedby":te.cronExpression?me:void 0}),te.cronExpression?t.jsx("small",{id:me,className:"field-error",children:te.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:Z=>N(Z.target.value),"aria-invalid":!!te.webhookPath,"aria-describedby":te.webhookPath?_e:void 0}),te.webhookPath?t.jsx("small",{id:_e,className:"field-error",children:te.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:k,onChange:Z=>R(Z.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:Z=>M(Z.target.value),"aria-invalid":!!te.endpoint,"aria-describedby":te.endpoint?Ke:void 0}),te.endpoint?t.jsx("small",{id:Ke,className:"field-error",children:te.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${$==="simple"?" active":""}`,onClick:()=>B("simple"),role:"radio","aria-checked":$==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${$==="advanced"?" active":""}`,onClick:()=>B("advanced"),role:"radio","aria-checked":$==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:$==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),$==="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:()=>ie("command"),role:"radio","aria-checked":J==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="ai-prompt"?" active":""}`,onClick:()=>ie("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:()=>ie("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:C,onChange:Z=>P(Z.target.value),"aria-invalid":!!te.command,"aria-describedby":te.command?Re:void 0}),te.command?t.jsx("small",{id:Re,className:"field-error",children:te.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:ce,onChange:Z=>Se(Z.target.value),rows:3,"aria-invalid":!!te.prompt,"aria-describedby":te.prompt?ct:void 0}),te.prompt?t.jsx("small",{id:ct,className:"field-error",children:te.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(qn,{id:"routine-model",label:"Model",models:et,value:Oe,onChange:at,placeholder:"Use default",disabled:Xe}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),te.model&&t.jsx("small",{id:de,className:"field-error",children:te.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:Z=>le(Z.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:ee,onChange:Z=>pe(Z.target.value),rows:4,"aria-invalid":!!te.taskDescription,"aria-describedby":te.taskDescription?Y:void 0}),te.taskDescription?t.jsx("small",{id:Y,className:"field-error",children:te.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:ue,onChange:Z=>fe(Z.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(qn,{id:"routine-task-model",label:"Executor Model",models:et,value:Oe,onChange:at,placeholder:"Use default",disabled:Xe}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),te.model&&t.jsx("small",{id:de,className:"field-error",children:te.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(LR,{steps:T,onChange:j,onEditingChange:q}),te.steps&&t.jsx("small",{className:"field-error",children:te.steps}),te.stepsEditing&&t.jsx("small",{className:"field-error",children:te.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:ge,onChange:Z=>be(Number(Z.target.value)),"aria-invalid":!!te.timeoutMs,"aria-describedby":te.timeoutMs?we:void 0}),te.timeoutMs?t.jsx("small",{id:we,className:"field-error",children:te.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:S,onChange:Z=>z(Z.target.value),children:HR.map(Z=>t.jsx("option",{value:Z.value,children:Z.label},Z.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:Z=>I(Z.target.value),children:qR.map(Z=>t.jsx("option",{value:Z.value,children:Z.label},Z.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:Z=>V(Z.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 VR=3e4;function WR({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({}),x=a.useRef(null);ti(x,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),b=a.useCallback(async()=>{try{const D=await hj(v);l(D),f(E=>{const $={...E};for(const B of D){const J=$[B.id];if(!J||!B.lastRunResult)continue;const ie=B.lastRunResult;ie.success===J.success&&(ie.output||"")===J.output&&(ie.error||"")===(J.error||"")&&delete $[B.id]}return $})}catch(D){n(ke(D)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const D=setInterval(()=>{b()},VR);return()=>clearInterval(D)},[b]),a.useEffect(()=>{const D=E=>{E.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[e,c]);const y=Si(e),N=a.useCallback(async D=>{try{await pj(D,v),n("Routine created","success"),u("list"),await b()}catch(E){n(ke(E)||"Failed to create routine","error")}},[n,b,v]),k=a.useCallback(D=>{m(D),u("edit")},[]),R=a.useCallback(async D=>{if(d)try{await Qd(d.id,D,v),n("Routine updated","success"),u("list"),m(void 0),await b()}catch(E){n(ke(E)||"Failed to update routine","error")}},[d,n,b,v]),w=a.useCallback(async D=>{try{await fj(D.id,v),n(`Deleted "${D.name}"`,"success"),await b()}catch(E){n(ke(E)||"Failed to delete routine","error")}},[n,b,v]),M=a.useCallback(async D=>{g(D.id);try{const{result:E}=await gj(D.id,v);f($=>({...$,[D.id]:{output:E.output||"",error:E.error,success:E.success}})),E.success?n(`"${D.name}" completed successfully`,"success"):n(`"${D.name}" failed: ${E.error||"Unknown error"}`,"error"),await b()}catch(E){n(ke(E)||"Failed to run routine","error")}finally{g(null)}},[n,b,v]),S=a.useCallback(async D=>{try{await Qd(D.id,{enabled:!D.enabled},v),n(`"${D.name}" ${D.enabled?"disabled":"enabled"}`,"success"),await b()}catch(E){n(ke(E)||"Failed to toggle routine","error")}},[n,b,v]),z=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const _=a.useCallback(D=>{r(D),u("list"),m(void 0),f({})},[]),I=()=>c==="create"?t.jsx(hh,{onSubmit:N,onCancel:z,scope:i,projectId:s}):c==="edit"&&d?t.jsx(hh,{routine:d,onSubmit:R,onCancel:z,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Bn,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),children:[t.jsx(an,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(D=>t.jsx(PR,{routine:D,onEdit:k,onDelete:w,onRun:M,onToggle:S,running:h===D.id,lastRunOutput:p[D.id]??null},D.id))}),F=()=>I(),V=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,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(Bn,{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(Gt,{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:()=>_("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx($o,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>_("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(Hn,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Bn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:V&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(an,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:F()})]})})}const KR=3e4,Wc=new Map,ac=new Map;function ph(e){return e??"default"}function fh(e){const n=Wc.get(e);return n?Date.now()>=n.expiresAt?(Wc.delete(e),null):n:null}function GR(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 JR(e){const n=ac.get(e);if(n)return n;const s=xr().then(({providers:i,ghCli:r})=>{const l={...GR(i,r),ghCli:r,expiresAt:Date.now()+KR};return Wc.set(e,l),l}).finally(()=>{ac.delete(e)});return ac.set(e,s),s}function lg(e){const n=ph(e),s=fh(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=ph(e),p=fh(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 JR(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 cg({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(Gt,{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 YR({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Hs(),[d,m]=a.useState(""),[h,g]=a.useState([]),[p,f]=a.useState([]),[x,v]=a.useState(!1),[b,y]=a.useState(""),[N,k]=a.useState(""),[R,w]=a.useState(""),[M,S]=a.useState(""),[z,_]=a.useState(""),[I,F]=a.useState("default"),[V,D]=a.useState(!1),[E,$]=a.useState([]),[B,J]=a.useState(!1),[ie,C]=a.useState(void 0),[P,T]=a.useState(vs),[j,W]=a.useState(void 0),[q,ge]=a.useState(null),[be,ce]=a.useState([]),[Se,O]=a.useState(!1),[le,ee]=a.useState(!1),pe=a.useRef(null),[ue,fe]=a.useState(!1),[se,Ce]=a.useState(""),De=a.useRef(null),{hasAiProvider:qe,hasGithub:et,loading:Qe}=lg(s),{nodes:Xe}=Vo(),it=a.useCallback(ye=>{J(!0),$(ye)},[]),Ie=a.useCallback(()=>{J(!1)},[]),We=a.useCallback(async()=>{if(be.length>0){O(!0);return}ee(!0);try{const ye=await _a(void 0,s);ce(ye),O(!0)}catch(ye){const oe=ke(ye);o(oe?`Failed to load agents: ${oe}`:"Failed to load agents","error"),O(!1)}finally{ee(!1)}},[be.length,s,o]);a.useEffect(()=>{if(!Se)return;const ye=oe=>{pe.current&&!pe.current.contains(oe.target)&&O(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[Se]),a.useEffect(()=>{if(!ue)return;const ye=oe=>{De.current&&!De.current.contains(oe.target)&&(fe(!1),Ce(""))};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[ue]);const re=i.filter(ye=>!h.includes(ye.id)).sort((ye,oe)=>{const Te=oe.createdAt.localeCompare(ye.createdAt);if(Te!==0)return Te;const me=parseInt(ye.id.slice(ye.id.lastIndexOf("-")+1),10)||0;return(parseInt(oe.id.slice(oe.id.lastIndexOf("-")+1),10)||0)-me}),ve=se?re.filter(ye=>ye.id.toLowerCase().includes(se.toLowerCase())||ye.title&&ye.title.toLowerCase().includes(se.toLowerCase())||ye.description&&ye.description.toLowerCase().includes(se.toLowerCase())):re,te=(ye,oe)=>ye.length>oe?ye.slice(0,oe)+"…":ye;a.useEffect(()=>{const ye=d.trim()!==""||h.length>0||p.length>0||b!==""||N!==""||R!==""||M!==""||E.length>0||q!==null||ie!==void 0||P!==vs||j!==void 0;D(ye)},[d,h,p,b,N,R,M,E,q,ie,P,j]);const Ae=a.useCallback(async()=>{V&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ye=>URL.revokeObjectURL(ye.previewUrl)),f([]),m(""),g([]),y(""),k(""),w(""),S(""),_(""),F("default"),$([]),J(!1),ge(null),O(!1),C(void 0),T(vs),W(void 0),D(!1),n())},[V,n,p,u]),Fe=a.useCallback(async()=>{const ye=d.trim();if(!(!ye||x)){v(!0);try{const oe=b.indexOf("/"),Te=N.indexOf("/"),me=R.indexOf("/"),_e=await r({title:void 0,description:ye,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:B?E.length>0?E:[]:void 0,...q?{assignedAgentId:q}:{},modelPresetId:I==="preset"&&z||void 0,modelProvider:b&&oe!==-1?b.slice(0,oe):void 0,modelId:b&&oe!==-1?b.slice(oe+1):void 0,validatorModelProvider:N&&Te!==-1?N.slice(0,Te):void 0,validatorModelId:N&&Te!==-1?N.slice(Te+1):void 0,planningModelProvider:R&&me!==-1?R.slice(0,me):void 0,planningModelId:R&&me!==-1?R.slice(me+1):void 0,thinkingLevel:M!==""?M:void 0,reviewLevel:ie,priority:P,nodeId:j});if(p.length>0){const Ke=[];for(const Re of p)try{await gr(_e.id,Re.file,s)}catch{Ke.push(Re.file.name)}Ke.length>0&&o(`Failed to upload: ${Ke.join(", ")}`,"error")}p.forEach(Ke=>URL.revokeObjectURL(Ke.previewUrl)),f([]),m(""),g([]),y(""),k(""),w(""),S(""),_(""),F("default"),$([]),J(!1),ge(null),O(!1),C(void 0),T(vs),W(void 0),o(`Created ${_e.id}`,"success"),n()}catch(oe){o(ke(oe)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,b,N,R,M,x,r,o,n,s,I,z,E,B,q,ie,P,j]),he=a.useCallback(ye=>{ye.key==="Escape"&&(ye.preventDefault(),Ae())},[Ae]),Oe=(q?be.find(ye=>ye.id===q):void 0)?.name??q,at=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:De,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>fe(ye=>!ye),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),ue&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:se,onChange:ye=>Ce(ye.target.value),onClick:ye=>ye.stopPropagation()}),ve.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ve.map(ye=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ye.id)?" selected":""}`,onClick:()=>{g(h.includes(ye.id)?h.filter(oe=>oe!==ye.id):[...h,ye.id]),fe(!1),Ce("")},onMouseDown:oe=>oe.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ye.id}),t.jsx("span",{className:"dep-dropdown-title",children:te(ye.title||ye.description||ye.id,30)})]},ye.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ye=>t.jsxs("span",{className:"dep-chip",children:[ye,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter(oe=>oe!==ye)),disabled:x,children:"×"})]},ye))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:pe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Se?O(!1):We()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(Nn,{size:12,style:{verticalAlign:"middle"}}),Oe?` ${Oe}`:" Assign agent"]}),Se&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ye=>ye.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),le&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!le&&be.filter(ye=>ye.state!=="terminated").map(ye=>t.jsxs("div",{className:`dep-dropdown-item${q===ye.id?" selected":""}`,onMouseDown:oe=>oe.preventDefault(),onClick:()=>{ge(ye.id===q?null:ye.id),O(!1)},"data-testid":`agent-option-${ye.id}`,children:[t.jsx(Nn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ye.role}),t.jsx("span",{className:"dep-dropdown-title",children:ye.name})]},ye.id)),!le&&be.filter(ye=>ye.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ye=>ye.preventDefault(),onClick:()=>{ge(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:he,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ye=>ye.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Ae,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Qe&&t.jsx(cg,{hasAiProvider:qe,hasGithub:et}),t.jsx(Zf,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:b,onExecutorModelChange:y,validatorModel:N,onValidatorModelChange:k,presetMode:I,onPresetModeChange:F,selectedPresetId:z,onSelectedPresetIdChange:_,selectedWorkflowSteps:E,onWorkflowStepsChange:it,onDefaultOnApplied:Ie,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Ae,planningModel:R,onPlanningModelChange:w,thinkingLevel:M,onThinkingLevelChange:S,reviewLevel:ie,onReviewLevelChange:C,priority:P,onPriorityChange:T,nodeId:j,onNodeIdChange:W,nodeOptions:Xe,renderBelowPrimary:at,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Fe,disabled:!d.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function ci(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 gh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function QR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function XR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function ZR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function rc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function eT(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function tT({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),[x,v]=a.useState(!1),[b,y]=a.useState(null),[N,k]=a.useState(null),[R,w]=a.useState(null),M=a.useCallback(async P=>{l(!0);try{const T=await Bj(s);r(T),u(null),w(Date.now()),P?.preserveKillResult||y(null)}catch(T){u(T instanceof Error?T.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;M();const P=window.setInterval(()=>{M()},5e3);return()=>{window.clearInterval(P)}},[e,M]),a.useEffect(()=>{if(!e)return;(async()=>{try{const T=await Ki();m(T.vitestAutoKillEnabled??!0),g(T.vitestKillThresholdPct??90),k(null)}catch(T){k(T instanceof Error?T.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const P=T=>{T.key==="Escape"&&n()};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n]);const S=a.useMemo(()=>{if(!i)return[];const P=i.systemStats,T=rc(QR(P.heapUsed,P.heapLimit)),j=rc(XR(P.rss,P.systemTotalMem));return[{label:"RSS",value:ci(P.rss),detail:gh(P.rss,P.systemTotalMem),className:j},{label:"Heap Used",value:ci(P.heapUsed),detail:`of ${ci(P.heapTotal)}`,className:T},{label:"Heap Limit",value:ci(P.heapLimit),detail:"V8 limit"},{label:"External",value:ci(P.external)},{label:"Array Buffers",value:ci(P.arrayBuffers)}]},[i]),z=a.useCallback(async P=>{m(P);try{await mn({vitestAutoKillEnabled:P}),k(null)}catch(T){k(T instanceof Error?T.message:"Failed to save vitest settings")}},[]),_=a.useCallback(async P=>{const T=Math.min(99,Math.max(50,Number.isFinite(P)?Math.round(P):90));g(T);try{await mn({vitestKillThresholdPct:T}),k(null)}catch(j){k(j instanceof Error?j.message:"Failed to save vitest settings")}},[]),I=a.useCallback(async()=>{if(!p){if(!x){v(!0);return}f(!0);try{const P=await Hj(s);y(P),v(!1),await M({preserveKillResult:!0})}catch(P){u(P instanceof Error?P.message:"Failed to kill vitest processes")}finally{f(!1)}}},[x,p,M,s]);if(!e)return null;const F=i?.systemStats,V=o&&!!i,D=R?`Updated ${new Date(R).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",E=i?.taskStats,$=F?F.systemTotalMem-F.systemFreeMem:0,B=F?rc(ZR($,F.systemTotalMem)):"",J=i?.vitestProcessCount,ie=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",C=eT(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:P=>{P.target===P.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(hr,{}),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:D})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void M(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Tn,{size:16,className:V?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Gt,{})})]})]}),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:S.map(P=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:P.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${P.className}`.trim(),children:P.value}),P.detail?t.jsx("span",{className:"system-stats-modal__detail",children:P.detail}):null]})]},P.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(P=>P.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",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${B}`.trim(),children:F?ci($):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:F?`${gh($,F.systemTotalMem)} of ${ci(F.systemTotalMem)}`:""})]})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:F?ci(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:E?.total??0})]}),Object.entries(E?.byColumn??{}).map(([P,T])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:P}),t.jsx("dd",{children:T})]},P))]})]}),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:E?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:E?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:E?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:E?.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(Ub,{}),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:J??"—"})]})}),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 I(),disabled:p||J===0,children:[t.jsx(Vb,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:P=>{z(P.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:P=>{const T=Number.parseInt(P.target.value,10);_(Number.isNaN(T)?90:T)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:P=>{const T=Number.parseInt(P.target.value,10);_(Number.isNaN(T)?90:T)},onBlur:()=>{_(h)}})]})]}),b&&t.jsxs("p",{className:ie,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",C]}),N&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:N})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const nT=5e3;function sT(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),x=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let N;o?N=await iu({limit:i,projectId:n,type:s}):N=(await Xd({limit:i,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(N),p(N.length===i),N.length>0&&(x.current=N[N.length-1].timestamp)}catch(N){h(N instanceof Error?N.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),b=a.useCallback(async()=>{if(x.current)try{d(!0);let N;o?N=await iu({limit:i,projectId:n,type:s,since:x.current}):N=(await Xd({limit:i,type:s,since:x.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(k=>[...k,...N]),p(N.length===i),N.length>0&&(x.current=N[N.length-1].timestamp)}catch(N){h(N instanceof Error?N.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},nT),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:b}}const oc={"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"},iT={"task:created":t.jsx(an,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Nr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Tn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Gt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(yn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Sr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(or,{size:14,className:"activity-icon settings"})};function aT(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 rT({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,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:N,refresh:k,hasMore:R}=sT({projectId:x,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),w=b.map(I=>({id:I.id,timestamp:I.timestamp,type:I.type,taskId:I.taskId,taskTitle:I.taskTitle,details:I.details,metadata:I.metadata,projectId:I.projectId,projectName:I.projectName})),M=async()=>{try{await xj(),k(),p(!1)}catch{p(!1)}},S=I=>{i&&i(I)},z=I=>{h(I),l?.(I==="all"?void 0:I)};a.useEffect(()=>{if(!e)return;const I=F=>{F.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,n,g]);const _=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:I=>{I.target===I.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(mr,{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(Hn,{size:14}),t.jsxs("select",{value:m,onChange:I=>z(I.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(I=>t.jsx("option",{value:I.id,children:I.name},I.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(go,{size:14}),t.jsxs("select",{value:u,onChange:I=>d(I.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(oc).map(([I,F])=>t.jsx("option",{value:I,children:F},I))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Tn,{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(sn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(I=>I.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",oc[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:[N&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(as,{size:16}),t.jsx("span",{children:N})]}),w.length===0&&!y&&!N&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(mr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(I=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:iT[I.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:oc[I.type]}),t.jsx("span",{className:"activity-log-entry-time",children:aT(I.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[I.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>S(I.taskId),"data-testid":"activity-task-link",children:I.taskId}),I.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:I.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:I.details})]}),I.metadata&&Object.keys(I.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof I.metadata.from=="string"&&typeof I.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[I.metadata.from," → ",I.metadata.to]}),typeof I.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${I.metadata.merged?"success":"error"}`,children:I.metadata.merged?"Merged":"Not merged"})]})]})]},I.id))}),R&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"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:M,children:"Clear Log"})]})]})})]})}):null}function xh(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=e.slice(i);if(s.length+r.length<=n)return s+r;const o=[];for(let m=1;m<e.length;m++)e[m]==="/"&&o.push(m);const l=n-s.length;let c=null,u=-1;for(let m=o.length-1;m>=0;m--){const h=o[m],g=e.slice(h);if(g.length>l)continue;const p=l-g.length;for(let f=0;f<o.length;f++){const x=o[f],v=e.slice(0,x);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>u&&(u=v.length+g.length,c=v+s+g)}}if(c)return c;const d=n-s.length;return s+e.slice(e.length-d)}const Xa=[{id:"status",label:"Status",icon:Zh},{id:"changes",label:"Changes",icon:Wh},{id:"commits",label:"Commits",icon:Cr},{id:"branches",label:"Branches",icon:Xs},{id:"worktrees",label:"Worktrees",icon:Wx},{id:"stashes",label:"Stashes",icon:To},{id:"remotes",label:"Remotes",icon:Jh}];function bh({status:e}){switch(e){case"added":case"untracked":return t.jsx(Ex,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Kh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Nx,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ui,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(_x,{size:14,className:"gm-file-icon"})}}function vh({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 oT(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 wa(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 lT({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Hs(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);ti(g,e,"fusion:git-modal-size");const p=Si(n),f=oT(i),[x,v]=a.useState(null),[b,y]=a.useState([]),[N,k]=a.useState(new Set),[R,w]=a.useState(""),[M,S]=a.useState(!1),[z,_]=a.useState(null),[I,F]=a.useState(!1),[V,D]=a.useState(null),[E,$]=a.useState(null),B=a.useRef(0),[J,ie]=a.useState([]),[C,P]=a.useState(null),[T,j]=a.useState(null),[W,q]=a.useState(!1),[ge,be]=a.useState(20),[ce,Se]=a.useState(""),[O,le]=a.useState([]),[ee,pe]=a.useState(""),[ue,fe]=a.useState(""),[se,Ce]=a.useState(""),[De,qe]=a.useState(null),[et,Qe]=a.useState([]),[Xe,it]=a.useState(!1),[Ie,We]=a.useState(null),[re,ve]=a.useState(null),[te,Ae]=a.useState(!1),[Fe,he]=a.useState([]),[Me,Oe]=a.useState([]),[at,ye]=a.useState(""),[oe,Te]=a.useState(null),[me,_e]=a.useState(null),[Ke,Re]=a.useState(null),ct=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const H=await Os(r);v(H);break}case"changes":{const[H,xe]=await Promise.all([Os(r),na(r)]);v(H),y(xe),k(new Set),$(null),_(null),D(null);break}case"commits":{const H=await wy(ge,r);ie(H);break}case"branches":{const[H,xe]=await Promise.all([za(r),Os(r)]);le(H),v(xe);break}case"worktrees":{const H=await Ey(r);he(H);break}case"stashes":{const H=await qr(r);Oe(H);break}case"remotes":{const H=await Os(r);v(H);break}}}catch(H){h(ke(H)||"Failed to fetch git data"),i(ke(H)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,ge,i,r]);a.useEffect(()=>{e&&ct()},[ct,e]),a.useEffect(()=>{if(!e)return;const H=xe=>{if(xe.key==="Escape"){n();return}if((xe.key==="ArrowUp"||xe.key==="ArrowDown")&&xe.altKey){xe.preventDefault();const Le=Xa.findIndex(A=>A.id===l);xe.key==="ArrowUp"&&Le>0?c(Xa[Le-1].id):xe.key==="ArrowDown"&&Le<Xa.length-1&&c(Xa[Le+1].id)}};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n,l]);const Y=a.useCallback(async H=>{try{await Kd(H,r),i(`Staged ${H.length} file(s)`,"success");const xe=await na(r);y(xe),k(new Set),$(null),_(null),D(null)}catch(xe){i(ke(xe)||"Failed to stage files","error")}},[i,r]),de=a.useCallback(async H=>{try{await Ly(H,r),i(`Unstaged ${H.length} file(s)`,"success");const xe=await na(r);y(xe),k(new Set),$(null),_(null),D(null)}catch(xe){i(ke(xe)||"Failed to unstage files","error")}},[i,r]),we=a.useCallback(async H=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${H.length} file(s)? This cannot be undone.`,danger:!0}))try{await zy(H,r),i(`Discarded changes to ${H.length} file(s)`,"success");const[Le,A]=await Promise.all([na(r),Os(r)]);y(Le),v(A),k(new Set),$(null),_(null),D(null)}catch(Le){i(ke(Le)||"Failed to discard changes","error")}},[i,r,confirm]),tt=a.useCallback(async H=>{if(H.preventDefault(),!!R.trim()){S(!0);try{const xe=await Gd(R.trim(),r);i(`Committed: ${xe.hash}`,"success"),w("");const[Le,A]=await Promise.all([na(r),Os(r)]);y(Le),v(A),$(null),_(null),D(null)}catch(xe){i(ke(xe)||"Failed to commit","error")}finally{S(!1)}}},[R,i,r]),Z=a.useCallback(async()=>{if(R.trim()){S(!0);try{const H=b.filter(X=>!X.staged).map(X=>X.file);H.length>0&&await Kd(H,r);const xe=await Gd(R.trim(),r);i(`Committed: ${xe.hash}`,"success"),w("");const[Le,A]=await Promise.all([na(r),Os(r)]);y(Le),v(A),$(null),_(null),D(null)}catch(H){i(ke(H)||"Failed to commit","error")}finally{S(!1)}}},[R,b,i,r]),Ge=a.useCallback(async(H,xe)=>{$({file:H,staged:xe}),F(!0),D(null);const Le=B.current+1;B.current=Le;try{const A=await Dy(H,xe,r);if(B.current!==Le)return;_(A)}catch(A){if(B.current!==Le)return;const X=ke(A)||"Failed to load file diff";_(null),D(X),i(X,"error")}finally{B.current===Le&&F(!1)}},[i,r]),dt=a.useCallback(H=>{k(xe=>{const Le=new Set(xe);return Le.has(H)?Le.delete(H):Le.add(H),Le})},[]),pt=a.useCallback(async H=>{if(C===H){P(null),j(null);return}P(H),q(!0);try{const xe=await vo(H,r);j(xe)}catch(xe){i(ke(xe)||"Failed to load diff","error"),j(null)}finally{q(!1)}},[C,i,r]),jt=a.useCallback(()=>{be(H=>Math.min(H+20,100))},[]),yt=a.useMemo(()=>{if(!ce.trim())return J;const H=ce.toLowerCase();return J.filter(xe=>xe.message.toLowerCase().includes(H)||xe.author.toLowerCase().includes(H)||xe.shortHash.toLowerCase().includes(H))},[J,ce]),ft=a.useCallback(async H=>{if(H.preventDefault(),!!ee.trim()){d(!0);try{await My(ee.trim(),ue.trim()||void 0,r),i(`Created branch ${ee}`,"success"),pe(""),fe("");const xe=await za(r);le(xe)}catch(xe){i(ke(xe)||"Failed to create branch","error")}finally{d(!1)}}},[ee,ue,i,r]),St=a.useCallback(async H=>{d(!0);try{await _y(H,r),i(`Switched to ${H}`,"success");const[xe,Le]=await Promise.all([Os(r),za(r)]);v(xe),le(Le)}catch(xe){i(ke(xe)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),Ot=a.useCallback(async H=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${H}"?`,danger:!0})){d(!0);try{await Wd(H,void 0,r),i(`Deleted branch ${H}`,"success");const Le=await za(r);le(Le)}catch(Le){if(ke(Le).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Wd(H,!0,r),i(`Force deleted branch ${H}`,"success");const X=await za(r);le(X)}catch(X){i(ke(X)||"Failed to delete branch","error")}}else i(ke(Le)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Vt=a.useMemo(()=>{if(!se.trim())return O;const H=se.toLowerCase();return O.filter(xe=>xe.name.toLowerCase().includes(H))},[O,se]),Mt=a.useCallback(async H=>{if(De===H){qe(null),Qe([]),We(null),ve(null);return}qe(H),Qe([]),We(null),ve(null),it(!0);try{const xe=await Cy(H,10,r);Qe(xe)}catch{Qe([])}finally{it(!1)}},[De,r]),It=a.useCallback(async H=>{if(Ie===H){We(null),ve(null);return}We(H),ve(null),Ae(!0);try{const xe=await vo(H,r);ve(xe)}catch{ve(null)}finally{Ae(!1)}},[Ie,r]),qt=a.useCallback(()=>{qe(null),Qe([]),We(null),ve(null)},[]),Ft=a.useCallback(async H=>{H.preventDefault(),Te("create");try{await Py(at.trim()||void 0,r),i("Changes stashed","success"),ye("");const xe=await qr(r);Oe(xe)}catch(xe){i(ke(xe)||"Failed to stash changes","error")}finally{Te(null)}},[at,i,r]),Xt=a.useCallback(async(H,xe=!1)=>{Te(`apply-${H}`);try{await Iy(H,xe,r),i(xe?"Stash popped":"Stash applied","success");const Le=await qr(r);Oe(Le)}catch(Le){i(ke(Le)||"Failed to apply stash","error")}finally{Te(null)}},[i,r]),$t=a.useCallback(async H=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${H}}? This cannot be undone.`,danger:!0})){Te(`drop-${H}`);try{await $y(H,r),i("Stash dropped","success");const Le=await qr(r);Oe(Le)}catch(Le){i(ke(Le)||"Failed to drop stash","error")}finally{Te(null)}}},[i,r,confirm]),_t=a.useCallback(async()=>{_e("fetch");try{const H=await Ay(void 0,r);Re(H),i(H.message||"Fetch completed",H.fetched?"success":"info");const xe=await Os(r);v(xe)}catch(H){i(ke(H)||"Fetch failed","error")}finally{_e(null)}},[i,r]),Ct=a.useCallback(async()=>{_e("pull");try{const H=await Ry(r);Re(H),H.conflict?i("Merge conflict detected. Resolve manually.","error"):i(H.message||"Pull completed","success");const xe=await Os(r);v(xe)}catch(H){i(ke(H)||"Pull failed","error")}finally{_e(null)}},[i,r]),Et=a.useCallback(async()=>{_e("push");try{const H=await Ty(r);Re(H),i(H.message||"Push completed","success");const xe=await Os(r);v(xe)}catch(H){i(ke(H)||"Push failed","error")}finally{_e(null)}},[i,r]),tn=a.useMemo(()=>b.filter(H=>H.staged),[b]),At=a.useMemo(()=>b.filter(H=>!H.staged),[b]);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(yc,{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:ct,disabled:u,title:"Refresh",children:t.jsx(Tn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Gt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Xa.map(H=>{const xe=H.icon;return t.jsxs("button",{role:"tab","aria-selected":l===H.id,className:`gm-nav-item${l===H.id?" active":""}`,onClick:()=>c(H.id),children:[t.jsx(xe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:H.label})]},H.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(as,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:ct,children:"Retry"})]}),l==="status"&&!u&&x&&t.jsx(cT,{status:x,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(dT,{status:x,stagedFiles:tn,unstagedFiles:At,selectedFiles:N,toggleFileSelection:dt,onStageFiles:Y,onUnstageFiles:de,onDiscardChanges:we,onSelectDiffFile:Ge,selectedDiffTarget:E,changeDiff:z,loadingChangeDiff:I,changeDiffError:V,commitMessage:R,setCommitMessage:w,onCommit:tt,onStageAllAndCommit:Z,committing:M}),l==="commits"&&!u&&t.jsx(uT,{commits:yt,commitSearch:ce,setCommitSearch:Se,selectedCommit:C,commitDiff:T,loadingDiff:W,onCommitClick:pt,onLoadMore:jt,canLoadMore:J.length>=ge&&ge<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(mT,{branches:Vt,branchSearch:se,setBranchSearch:Ce,newBranchName:ee,setNewBranchName:pe,branchBase:ue,setBranchBase:fe,onCreateBranch:ft,onCheckoutBranch:St,onDeleteBranch:Ot,loading:u,allBranches:O,selectedBranch:De,branchCommits:et,loadingBranchCommits:Xe,expandedBranchCommit:Ie,branchCommitDiff:re,loadingBranchCommitDiff:te,onSelectBranch:Mt,onBranchCommitClick:It,onCloseBranchDetails:qt}),l==="worktrees"&&!u&&t.jsx(hT,{worktrees:Fe}),l==="stashes"&&!u&&t.jsx(pT,{stashes:Me,stashMessage:at,setStashMessage:ye,onCreateStash:Ft,onApplyStash:Xt,onDropStash:$t,stashLoading:oe}),l==="remotes"&&!u&&t.jsx(fT,{status:x,remoteLoading:me,lastRemoteResult:Ke,onFetch:_t,onPull:Ct,onPush:Et,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function cT({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(Xs,{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(Fi,{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(as,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(yn,{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(zi,{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(yn,{size:12}),"Up to date"]})]})]})]})]})}function dT({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:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(k=>i.has(`unstaged:${k.file}`)),N=n.filter(k=>i.has(`staged:${k.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Xs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(an,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(Sr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(k=>{const R=d?.file===k.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>u(k.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(bh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:xh(k.file,40)}),t.jsx(vh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(an,{size:12})})]},`unstaged:${k.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[N.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(N.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",N.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(k=>{const R=d?.file===k.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>u(k.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),u(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(bh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:xh(k.file,40)}),t.jsx(vh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(Gt,{size:12})})]},`staged:${k.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Wh,{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("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>f(k.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(rt,{size:14,className:"spin"}):t.jsx(Li,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function uT({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(ma,{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:wa(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(Fi,{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 mT({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:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:N,onCloseBranchDetails:k}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(ma,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:R=>s(R.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:R=>r(R.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:R=>l(R.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(R=>t.jsx("option",{value:R.name,children:R.name},R.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(an,{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(R=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${R.isCurrent?" current":""}${g===R.name?" selected":""}`,onClick:()=>y(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx(Ln,{size:14,className:"gm-current-icon"}),R.name]}),R.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",R.remote]}),R.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:wa(R.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!R.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),u(R.name)},disabled:m,title:"Checkout",children:t.jsx(Xs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),d(R.name)},disabled:m,title:"Delete",children:t.jsx(sn,{size:14})})]})})]}),g===R.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 ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(Gt,{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:()=>N(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:wa(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?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))})]})]},R.name))})]})}function hT({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:rd(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Xs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function pT({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(To,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Xs,{size:12}),c.branch]}),t.jsx("span",{children:wa(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(sn,{size:14})})]})]},c.index))})]})}function fT({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=te=>{try{return new URL(te).hostname}catch{return te.replace(/^git@/,"").split(":")[0]||te}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,x]=a.useState(null),[v,b]=a.useState(""),[y,N]=a.useState(""),[k,R]=a.useState(null),[w,M]=a.useState(""),[S,z]=a.useState(""),[_,I]=a.useState(!1),[F,V]=a.useState([]),[D,E]=a.useState(!1),[$,B]=a.useState(null),[J,ie]=a.useState([]),[C,P]=a.useState(!1),[T,j]=a.useState(null),W=m.find(te=>te.name===$),[q,ge]=a.useState(null),[be,ce]=a.useState(null),[Se,O]=a.useState(!1),[le,ee]=a.useState(null),[pe,ue]=a.useState(null),[fe,se]=a.useState(!1);a.useEffect(()=>{Ce()},[]),a.useEffect(()=>{e&&e.ahead>0?De():e&&e.ahead===0&&V([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!$&&B(m[0].name)},[m]),a.useEffect(()=>{$?qe($):(ie([]),j(null))},[$]),a.useEffect(()=>{$&&!m.find(te=>te.name===$)&&B(m.length>0?m[0].name:null)},[m,$]);const Ce=async()=>{p(!0);try{const te=await py(c);h(te)}catch(te){l(ke(te)||"Failed to load remotes","error")}finally{p(!1)}},De=async()=>{E(!0);try{const te=await Ny(c);V(te)}catch{V([])}finally{E(!1)}},qe=async te=>{P(!0),j(null);try{const Ae=await Sy(te,void 0,10,c);ie(Ae)}catch(Ae){j(ke(Ae)||"Failed to load remote commits"),ie([])}finally{P(!1)}},et=Hs(),Qe=async te=>{if(te.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await fy(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),N(""),I(!1),await Ce()}catch(Ae){l(ke(Ae)||"Failed to add remote","error")}finally{x(null)}}},Xe=async te=>{if(await et.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${te}'?`,danger:!0})){x(`remove-${te}`);try{await gy(te,c),l(`Remote '${te}' removed`,"success"),await Ce()}catch(Fe){l(ke(Fe)||"Failed to remove remote","error")}finally{x(null)}}},it=async te=>{if(S.trim()){x(`rename-${te}`);try{await xy(te,S.trim(),c),l(`Remote renamed to '${S.trim()}'`,"success"),R(null),z(""),await Ce()}catch(Ae){l(ke(Ae)||"Failed to rename remote","error")}finally{x(null)}}},Ie=async te=>{if(w.trim()){x(`url-${te}`);try{await by(te,w.trim(),c),l("Remote URL updated","success"),R(null),M(""),await Ce()}catch(Ae){l(ke(Ae)||"Failed to update remote URL","error")}finally{x(null)}}},We=a.useCallback(async(te,Ae)=>{if(Ae==="ahead"){if(q===te){ge(null),ce(null);return}ge(te),ce(null),O(!0);try{const Fe=await vo(te);ce(Fe)}catch{ce(null)}finally{O(!1)}}else{if(le===te){ee(null),ue(null);return}ee(te),ue(null),se(!0);try{const Fe=await vo(te);ue(Fe)}catch{ue(null)}finally{se(!1)}}},[q,le]),re=te=>{R(`url-${te.name}`),M(te.pushUrl||te.fetchUrl)},ve=te=>{R(`name-${te.name}`),z(te.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>I(!_),disabled:f!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(Gt,{size:14}):t.jsx(an,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Qe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:te=>b(te.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:te=>N(te.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(an,{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(te=>t.jsxs("div",{className:`gm-remote-selector-item${$===te.name?" selected":""}`,onClick:()=>B(te.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[te.name,te.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(te.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Ae=>{Ae.stopPropagation(),Xe(te.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(sn,{size:14})})]},te.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[$&&W?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:$}),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(zi,{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(Tn,{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(bs,{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(zi,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),k===`url-${$}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:te=>M(te.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ie($),disabled:f===`url-${$}`,children:f===`url-${$}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Ln,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),M("")},title:"Cancel",children:t.jsx(Gt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:W.fetchUrl,children:W.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(W.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Fi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>re(W),disabled:f!==null,title:"Edit remote URL",children:t.jsx(ss,{size:14})})]})]}),W.pushUrl&&W.pushUrl!==W.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:W.pushUrl,children:W.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(W.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Fi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${$}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:S,onChange:te=>z(te.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>it($),disabled:f===`rename-${$}`,children:f===`rename-${$}`?t.jsx(rt,{size:12,className:"spin"}):t.jsx(Ln,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),z("")},title:"Cancel",children:t.jsx(Gt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ve(W),disabled:f!==null,title:"Edit remote name",children:t.jsx(ss,{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(zi,{size:14}),"Commits to Push (",e.ahead,")"]})}),D?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(te=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>We(te.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:te.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:te.message,children:te.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:te.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(te.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:q===te.hash?t.jsx(Qt,{size:14}):t.jsx(vn,{size:14})})]}),q===te.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Se?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):be?t.jsxs(t.Fragment,{children:[te.message&&t.jsx("div",{className:"gm-commit-message-full",children:te.message}),be.stat&&t.jsx("pre",{className:"gm-diff-stat",children:be.stat}),t.jsx("pre",{className:"gm-diff-patch",children:be.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},te.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(Zh,{size:14}),"Recent commits on ",$]})}),C?t.jsxs("div",{className:"gm-loading",children:[t.jsx(rt,{size:14,className:"spin"}),"Loading commits..."]}):T?t.jsxs("div",{className:"gm-error",children:[t.jsx(as,{size:14}),T]}):J.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",$,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:J.map(te=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>We(te.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:te.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:te.message,children:te.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:te.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:wa(te.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:le===te.hash?t.jsx(Qt,{size:14}):t.jsx(vn,{size:14})})]}),le===te.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:fe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(rt,{size:16,className:"spin"}),"Loading diff..."]}):pe?t.jsxs(t.Fragment,{children:[te.message&&t.jsx("div",{className:"gm-commit-message-full",children:te.message}),pe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:pe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:pe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},te.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 Za={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function gT(e,n){return e&&n?`${e}/${n}`:""}function xT(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 bT(e){switch(e){case"file-text":return Ui;case"check-circle":return yn;case"shield":return Hb;case"zap":return Bn;case"eye":return fa;case"globe":return $o;case"layout-grid":return Hi;default:return yn}}function vT(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 yT({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,x]=a.useState(null),[v,b]=a.useState(!1),[y,N]=a.useState(Za),[k,R]=a.useState(!1),[w,M]=a.useState(!1),[S,z]=a.useState(null),[_,I]=a.useState(null),[F,V]=a.useState({}),[D,E]=a.useState([]),$=a.useRef(null);ti($,e,"fusion:workflow-steps-modal-size");const B=a.useCallback(async()=>{try{d(!0);const O=await Uo(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 br(i);V(O||{})}catch{}},[i]),ie=a.useCallback(async()=>{try{const O=await ms();E(O.models||[])}catch{}},[]),C=a.useCallback(async()=>{try{h(!0);const O=await jj();c(O.templates)}catch(O){s(ke(O)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(B(),C(),J(),ie())},[e,B,C,J,ie]);const P=a.useCallback(()=>{b(!0),x(null),N(Za)},[]),T=a.useCallback(O=>{x(O.id),b(!1),N({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||""})},[]),j=a.useCallback(()=>{x(null),b(!1),N(Za)},[]),W=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}R(!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 le={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 Zd(le,i),s("Workflow step created","success")}else f&&(await bj(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"));b(!1),x(null),N(Za),await B()}catch(O){s(ke(O)||"Failed to save workflow step","error")}finally{R(!1)}},[y,v,f,s,B]),q=a.useCallback(async O=>{try{await vj(O,i),s("Workflow step deleted","success"),z(null),f===O&&(x(null),N(Za)),await B()}catch(le){s(ke(le)||"Failed to delete workflow step","error")}},[f,s,B]),ge=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}R(!0);try{const O=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},le={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},ee=await Zd(le,i);b(!1),x(ee.id),M(!0);const pe=await eu(ee.id,i);N(ue=>({...ue,prompt:pe.prompt})),s("Prompt refined with AI","success"),await B()}catch(O){s(ke(O)||"Failed to refine prompt","error")}finally{R(!1),M(!1)}return}if(f){M(!0);try{const O=await eu(f,i);N(le=>({...le,prompt:O.prompt})),s("Prompt refined with AI","success"),await B()}catch(O){s(ke(O)||"Failed to refine prompt","error")}finally{M(!1)}}}},[f,v,y,s,B]),be=a.useCallback(async O=>{I(O.id);try{await kj(O.id,i),s(`Added ${O.name} workflow step`,"success"),await B(),p("my-steps")}catch(le){const ee=ke(le);ee?.includes("already exists")?s(`A workflow step named '${O.name}' already exists`,"error"):s(ee||"Failed to add workflow step from template","error")}finally{I(null)}},[s,B]),ce=Si(n);if(!e)return null;const Se=v||f!==null;return t.jsx("div",{className:"modal-overlay open",...ce,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:$,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:[!Se&&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(zg,{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(Hi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!Se&&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:()=>T(O),title:"Edit","aria-label":`Edit ${O.name}`,children:t.jsx(ss,{size:14})}),S===O.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>q(O.id),title:"Confirm delete","aria-label":`Confirm delete ${O.name}`,children:t.jsx(Ln,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>z(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Gt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>z(O.id),title:"Delete","aria-label":`Delete ${O.name}`,children:t.jsx(sn,{size:14})})]})]})},O.id))})]}),g==="templates"&&!Se&&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 le=bT(O.icon),ee=vT(O.category),pe=_===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(le,{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:ee,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:()=>be(O),disabled:pe,"data-testid":`add-template-${O.id}`,children:pe?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(an,{size:12}),"Add"]})})]})]})},O.id)})})}),Se&&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=>N(le=>({...le,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=>N(le=>({...le,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:()=>N(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:()=>N(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:()=>N(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:()=>N(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:ge,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(Zn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:O=>N(le=>({...le,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:()=>N(O=>({...O,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Gt,{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(qn,{models:D,value:gT(y.modelProvider,y.modelId),onChange:O=>{const le=xT(O);N(ee=>({...ee,modelProvider:le.provider,modelId:le.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=>N(le=>({...le,scriptName:O.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([O,le])=>t.jsxs("option",{value:O,children:[O," (",le,")"]},O))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:O=>N(le=>({...le,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=>N(le=>({...le,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:j,disabled:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:W,disabled:k||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:k?"Saving...":v?"Create":"Save"})]})]})]})]})}),!Se&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:P,"data-testid":"add-workflow-step",children:[t.jsx(an,{size:14}),"Add Workflow Step"]})})]})})}const jT=36e5,kT=3e5,lc=[{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 wT(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 NT(e){return typeof e!="number"||!Number.isFinite(e)?jT:Math.max(kT,Math.round(e))}function FD(e){if(lc.some(s=>s.value===e))return[...lc];const n={value:e,label:`${wT(e)} (custom)`};return[...lc,n].sort((s,i)=>s.value-i.value)}const ST=4,CT=5*6e4;function ET(e){const n=NT(e?.heartbeatIntervalMs);return Math.max(n*ST,CT)}function MT(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 _T(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=MT(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(xs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ts,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Us,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ts,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Us,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Nn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const u=new Date(s).getTime(),d=Date.now()-u,m=ET(o);return d>m?{label:"Unresponsive",icon:t.jsx(Ts,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(Gx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const er=[{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 AT({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,x]=a.useState("all"),[v,b]=a.useState(()=>{if(typeof window>"u")return"list";const T=Vn("fn-agent-view",i);return T==="board"||T==="list"?T:"list"});a.useEffect(()=>{const T=Vn("fn-agent-view",i);if(T==="board"||T==="list"){b(T);return}b("list")},[i]),a.useEffect(()=>{ds("fn-agent-view",v,i)},[i,v]);const[y,N]=a.useState(null),k=a.useRef(null),[R,w]=a.useState(new Set),[M,S]=a.useState(new Map),{confirm:z}=Hs(),_=a.useMemo(()=>M.size===0?r:r.map(T=>{const j=M.get(T.id);return j?{...T,state:j}:T}),[r,M]),I=a.useMemo(()=>f==="all"?_.filter(T=>T.state!=="terminated"):_,[_,f]),F=a.useCallback(async()=>{c(!0);try{const j=await _a(f!=="all"?{state:f}:void 0,i);o(j)}catch(T){s(`Failed to load agents: ${ke(T)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&F()},[e,F]),a.useEffect(()=>{if(!e)return;const T=setInterval(()=>{F()},3e4);return()=>{clearInterval(T)}},[e,F]);const V=async()=>{if(m.trim())try{await Rj({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),F()}catch(T){s(`Failed to create agent: ${ke(T)}`,"error")}},D=async(T,j)=>{if(!R.has(T)){w(W=>new Set(W).add(T)),S(W=>{const q=new Map(W);return q.set(T,j),q});try{await Pj(T,j,i),s(`Agent state updated to ${j}`,"success"),await F(),S(W=>{const q=new Map(W);return q.delete(T),q})}catch(W){S(q=>{const ge=new Map(q);return ge.delete(T),ge}),s(`Failed to update state: ${ke(W)}`,"error")}finally{w(W=>{const q=new Set(W);return q.delete(T),q})}}},E=async(T,j)=>{if(await z({title:"Delete Agent",message:`Delete agent "${j}"? This cannot be undone.`,danger:!0}))try{await Ij(T,i),s(`Agent "${j}" deleted`,"success"),F()}catch(q){s(`Failed to delete agent: ${ke(q)}`,"error")}},$=async(T,j)=>{const W=r.find(q=>q.id===T);if(W){if(W.role===j){N(null);return}try{await Tj(T,{role:j},i),s(`Agent role updated to ${er.find(q=>q.value===j)?.label??j}`,"success"),N(null),F()}catch(q){s(`Failed to update role: ${ke(q)}`,"error")}}},B=(T,j)=>{T.key==="Escape"&&N(null)},J=T=>er.find(j=>j.value===T)?.label??T,ie=T=>er.find(j=>j.value===T)?.icon??"◆",C=T=>_T(T),P=T=>T.color==="var(--state-active-text)"?"active":T.color==="var(--state-paused-text)"?"paused":T.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Nn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Hi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(jc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void F(),title:"Refresh",disabled:l,children:t.jsx(Tn,{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(go,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:T=>x(T.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(an,{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:T=>h(T.target.value),onKeyDown:T=>T.key==="Enter"&&V(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:T=>p(T.target.value),children:er.map(T=>t.jsxs("option",{value:T.value,children:[T.icon," ",T.label]},T.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void V(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:I.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Nn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?I.map(T=>{const j=C(T),W=P(j);return t.jsxs("div",{className:"agent-board-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:ie(T.role)}),t.jsx("span",{className:"agent-board-badge","data-state":T.state,children:T.state}),t.jsx("span",{className:"agent-board-health","data-health":W,title:j.label,children:j.icon})]}),t.jsx("div",{className:"agent-board-name",title:T.name,children:T.name}),t.jsx("div",{className:"agent-board-id",children:T.id}),t.jsxs("div",{className:"agent-board-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:t.jsx(sn,{size:14})})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Us,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(xs,{size:14})})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(xs,{size:14})})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Us,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(xs,{size:14})})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:t.jsx(Sn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(xs,{size:14})})]}),T.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:t.jsx(sn,{size:14})})]})]},T.id)}):I.map(T=>{const j=C(T),W=P(j);return t.jsxs("div",{className:"agent-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===T.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:T.role,onChange:q=>void $(T.id,q.target.value),onKeyDown:q=>B(q,T.id),onBlur:()=>N(null),autoFocus:!0,children:er.map(q=>t.jsxs("option",{value:q.value,children:[q.icon," ",q.label]},q.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>N(T.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:q=>{(q.key==="Enter"||q.key===" ")&&N(T.id)},children:ie(T.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:T.name}),t.jsx("span",{className:"agent-id text-secondary",children:T.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":T.state,children:T.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":W,title:j.label,children:[j.icon,!j.stateDerived&&` ${j.label}`]}),t.jsx("span",{className:"badge text-secondary",children:J(T.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[T.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:T.taskId})]}),T.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(T.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:[t.jsx(Sn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:[t.jsx(sn,{size:14})," Delete"]})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Us,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(xs,{size:14})," Stop"]})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:[t.jsx(Sn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(xs,{size:14})," Stop"]})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Us,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(xs,{size:14})," Stop"]})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:[t.jsx(Sn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(xs,{size:14})," Stop"]})]}),T.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void D(T.id,"active"),disabled:R.has(T.id),title:"Start",children:[t.jsx(Sn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(T.id,T.name),title:"Delete",children:[t.jsx(sn,{size:14})," Delete"]})]})]})]},T.id)})})]})]})}):null}function RT({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 b=await sy();return d.current&&r(b),b}catch(b){return d.current&&u({kind:"error",message:b instanceof Error?b.message:String(b)}),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 b=>{l(b?"enabling":"disabling"),u(null);try{const y=await iy(b);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,x=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(zn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(TT,{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:[x,t.jsx(yh,{status:i,authenticated:e}),c&&t.jsx(jh,{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(zn,{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"}),x,t.jsx(yh,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(jh,{action:c})]})}function TT({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 yh({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 jh({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 PT(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 cc({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=PT(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(Ln,{size:12}):t.jsx(Fi,{size:12})})]})]},d))}):e})}const Wi="fusion_model_onboarding_state",Na=[],Sa=[],Ao=!1,Ro=!1,Ca={},IT=void 0,yi=["ai-setup","github","project-setup","first-task"],$T={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function js(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Wi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?DT(n):null}catch{return null}}function DT(e){const n=e.postOnboardingDismissedAt??IT;return{...e,completedSteps:e.completedSteps??Na,skippedSteps:e.skippedSteps??Sa,dismissed:e.dismissed??Ao,completed:e.completed??Ro,stepData:e.stepData??Ca,...n?{postOnboardingDismissedAt:n}:{}}}function lo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Na,skippedSteps:Sa,dismissed:Ao,completed:Ro,stepData:Ca};try{localStorage.setItem(Wi,JSON.stringify(s))}catch{}return}try{const s=js(),i=new Date().toISOString(),r=n.completed??Ro;let o=n.dismissed??Ao;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Na,c=n.skippedSteps??s?.skippedSteps??Sa,u={...s?.stepData??Ca};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(Wi,JSON.stringify(d))}catch{}}}function LT(e){if(!(typeof window>"u"))try{const n=js(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Na,skippedSteps:[e],dismissed:Ao,completed:Ro,stepData:Ca};localStorage.setItem(Wi,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(Wi,JSON.stringify(r))}catch{}}function kh(){if(!(typeof window>"u"))try{const e=js(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!0,stepData:Ca};localStorage.setItem(Wi,JSON.stringify(s))}catch{}}function Ea(){const e=js();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function zT(){if(!(typeof window>"u"))try{const e=js(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Na,skippedSteps:Sa,dismissed:!1,completed:!1,stepData:Ca,postOnboardingDismissedAt:n};localStorage.setItem(Wi,JSON.stringify(s))}catch{}}function dg(){const e=js();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function OT(){const e=js();return!e||Ea()?!1:e.currentStep!=="complete"}function FT(){const e=js();if(!e||Ea()||e.currentStep==="complete")return null;const n=e.currentStep,s=$T[n]??HT(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function UT(){const e=js();return e?e.skippedSteps:Sa}function BT(e){const n=js();return!n||!n.stepData?null:n.stepData[e]??null}function HT(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const ug="fusion_onboarding_events",wh="fusion_onboarding_session_id",qT=200,VT=50;function _s(e,n={}){if(!(typeof window>"u"))try{const s=KT(),i=YT(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:WT()},o=JT([...s,r]);GT(o)}catch{}}function WT(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(wh);if(e)return e;const n=Nh();return sessionStorage.setItem(wh,n),n}catch{return Nh()}}function Nh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function KT(){try{const e=localStorage.getItem(ug);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(QT):[]}catch{return[]}}function GT(e){try{localStorage.setItem(ug,JSON.stringify(e))}catch{}}function JT(e){const n=[...e];for(;n.length>qT;)n.splice(0,VT);return n}function YT(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function QT(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 XT={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"}}},mg={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:"..."}},ZT={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Sh={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 Kc(e){if(Sh[e])return Sh[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 dc=["anthropic","openai","google","gemini","ollama"],e4=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],t4={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"},n4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Gc(e){return t4[e]??e}function Ch(e){const n=Gc(e),s=e4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Eh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Ch(e.id),i=Ch(n.id);if(s!==i)return s-i;const r=Gc(e.id),o=Gc(n.id);if(r!==o)return r.localeCompare(o);const l=n4[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 s4(e,n){const s=n.trim();if(!s)return"API key is required";const i=mg[e]??ZT;return i.pattern.test(s)?null:`${Kc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const hg={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"},i4={description:"AI provider — connect to start using AI models",apiKeyInfo:hg};function Jc(e){return XT[e]??i4}function a4(e){return Jc(e.id).apiKeyInfo??hg}function Ys({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(vn,{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 r4({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 o4({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=mg[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(Ys,{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:x=>c(e.id,x.target.value),onKeyDown:x=>{x.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(Ys,{summary:"Advanced setup details",children:f})]})}const l4=150;function c4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=js(),d=u?.currentStep,m=d==="complete"?"ai-setup":yi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??UT(),[p,f]=a.useState(!0),[x,v]=a.useState(m),[b,y]=a.useState(h),[N,k]=a.useState(g),[R,w]=a.useState(!1),[M,S]=a.useState(""),[z,_]=a.useState(!1),[I,F]=a.useState(null),[V,D]=a.useState(null),[E,$]=a.useState([]),[B,J]=a.useState(void 0),[ie,C]=a.useState(!0),[P,T]=a.useState(null),[j,W]=a.useState({}),[q,ge]=a.useState([]),[be,ce]=a.useState(""),[Se,O]=a.useState(!1),[le,ee]=a.useState({}),[pe,ue]=a.useState({}),[fe,se]=a.useState({}),Ce=a.useRef({}),De=a.useRef(null),qe=a.useRef(null),et=a.useRef(null),[Qe,Xe]=a.useState({}),[it,Ie]=a.useState(()=>js()?.stepData?.github?.skipped===!0),We=a.useRef(0),re=a.useRef(l),ve=a.useRef(!1),te=u?.currentStep,Ae=!!u&&u.currentStep!=="complete";ti(qe,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const G=De.current;G&&(G.scrollTop=0)},[x]);const[Fe,he]=a.useState(()=>js()?.stepData?.["ai-setup"]?.skippedProviders??{}),Me=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Oe=Me.findIndex(G=>G.key===x),at=x==="complete"?Me.length:Oe;a.useEffect(()=>{x!=="complete"&&lo(x,{completedSteps:b,skippedSteps:N})},[x,b,N]),a.useEffect(()=>{ve.current||(ve.current=!0,_s("onboarding:wizard-opened",{source:Ae?"resume":"initial",resumedFromStep:te}))},[Ae,te]),a.useEffect(()=>{const G=re.current!=null,Pe=l!=null;!G&&Pe&&w(!0),Pe||w(!1),re.current=l},[l]);const ye=a.useRef(m);a.useEffect(()=>{if(ye.current==="ai-setup"&&x!=="ai-setup"&&!E.some(Pe=>Pe.id!=="github"&&Pe.authenticated)){const Pe={};for(const Ye of E)Ye.id!=="github"&&!Ye.authenticated&&!Fe[Ye.id]&&(Pe[Ye.id]=!0);if(Object.keys(Pe).length>0){const Ye={...Fe,...Pe};he(Ye),lo(x,{stepData:{"ai-setup":{skippedProviders:Ye}}})}}ye.current=x},[x,E,Fe]);const oe=a.useCallback(async()=>{try{const{providers:G,ghCli:Pe}=await xr();$(G),J(Pe),W(Ye=>{const nt={};for(const[mt,Nt]of Object.entries(Ye)){const Lt=G.find(Cn=>Cn.id===mt);Lt&&!Lt.authenticated&&(nt[mt]=Nt)}return Object.keys(nt).length===Object.keys(Ye).length?Ye:nt}),he(Ye=>{const nt={...Ye};for(const mt of G)mt.authenticated&&nt[mt.id]&&delete nt[mt.id];return Object.keys(nt).length===Object.keys(Ye).length?Ye:nt})}catch{}},[]),Te=a.useRef(!1);a.useEffect(()=>{Te.current&&oe(),Te.current=x!=="ai-setup"},[x,oe]);const me=E.find(G=>G.id==="github"),_e=!!me,Ke=me?.authenticated??!1,Re=B?.authenticated??!1,ct=Ke||Re,Y=!Ke&&Re,de=a.useCallback(G=>{if(G.authenticated)return"connected";const Pe=Qe?.[G.id];return Pe==="timeout"||Pe==="failed"?"retry":Fe[G.id]?"skipped":"not-connected"},[Qe,Fe]);function we({status:G}){const Pe={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:Ye,className:nt}=Pe[G];return t.jsx("span",{"data-testid":"provider-status-badge",className:nt,"data-status":G,children:Ye})}const tt=a.useCallback(()=>{if(ct)return"connected";const G=Qe.github;return G==="pending"?"pending":G==="failed"||G==="timeout"?"failed":it?"skipped":"not-connected"},[ct,Qe,it]);function Z({status:G}){const Pe={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:Ye,className:nt}=Pe[G];return t.jsx("span",{"data-testid":"github-status-badge",className:nt,"data-status":G,children:Ye})}const Ge=a.useCallback(async()=>{try{const G=await ms();ge(G.models)}catch{}},[]),dt=a.useCallback(async()=>{try{const G=await Ki();if(G.defaultProvider&&G.defaultModelId){const Pe=`${G.defaultProvider}/${G.defaultModelId}`;ce(Pe)}}catch{}},[]);a.useEffect(()=>{Promise.all([oe(),Ge(),dt()]).finally(()=>C(!1))},[oe,Ge,dt]),a.useEffect(()=>{const G=BT("ai-setup");if(G?.loginOutcomes){const Pe=G.loginOutcomes,Ye={};for(const[nt,mt]of Object.entries(Pe))mt!=="pending"&&(Ye[nt]=mt);Object.keys(Ye).length>0&&Xe(Ye)}},[]);const pt=a.useCallback((G,Pe)=>{lo(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[G]:Pe}}}})},[x,b]);a.useEffect(()=>{const G=Object.entries(Qe).filter(([Pe,Ye])=>Ye!=="pending");for(const[Pe,Ye]of G)pt(Pe,Ye)},[Qe,pt]),a.useEffect(()=>()=>{et.current&&clearInterval(et.current),Object.values(Ce.current).forEach(clearTimeout),Ce.current={}},[]);const jt=a.useCallback(G=>{Ie(G),lo(x,{completedSteps:b,stepData:{github:{skipped:G}}})},[x,b]),yt=a.useCallback(G=>G==="complete"?-1:yi.indexOf(G),[]),ft=a.useCallback(()=>{y(Pe=>[...new Set([...Pe,x])]),k(Pe=>Pe.filter(Ye=>Ye!==x)),_s("onboarding:step-completed",{step:x}),x==="github"&&!Ke&&jt(!1);const G=yt(x);G>=0&&G<yi.length-1&&v(yi[G+1])},[x,Ke,jt,yt]),St=a.useCallback(()=>{k(Pe=>[...new Set([...Pe,x])]),LT(x),_s("onboarding:step-skipped",{step:x}),x==="github"&&!Ke&&jt(!0);const G=yt(x);G>=0&&G<yi.length-1&&v(yi[G+1])},[x,Ke,jt,yt]),Ot=a.useCallback(()=>{const G=x;y(Ye=>Ye.filter(nt=>nt!==G)),k(Ye=>Ye.filter(nt=>nt!==G)),G==="github"&&!Ke&&jt(!1);const Pe=yt(x);Pe>0&&v(yi[Pe-1])},[x,Ke,jt,yt]),Vt=a.useCallback(()=>{St()},[St]),Mt=a.useCallback(async G=>{Xe(Pe=>{const Ye=Pe[G];if(Ye&&Ye!=="pending"){const{[G]:nt,...mt}=Pe;return mt}return Pe}),W(Pe=>{if(!(G in Pe))return Pe;const Ye={...Pe};return delete Ye[G],Ye}),Xe(Pe=>({...Pe,[G]:"pending"})),T(G),We.current=0;try{const{url:Pe,instructions:Ye}=await ay(G);Ye?.trim()&&W(nt=>({...nt,[G]:Ye})),window.open(ei(Pe),"_blank"),et.current=setInterval(async()=>{if(We.current++,We.current>=l4){et.current&&(clearInterval(et.current),et.current=null),T(null),Xe(nt=>({...nt,[G]:"timeout"})),W(nt=>{if(!(G in nt))return nt;const mt={...nt};return delete mt[G],mt}),n("Login timed out. Please try again.","warning");return}try{const{providers:nt,ghCli:mt}=await xr();$(nt),J(mt),nt.find(Lt=>Lt.id===G)?.authenticated&&(et.current&&(clearInterval(et.current),et.current=null),T(null),Xe(Lt=>({...Lt,[G]:"success"})),W(Lt=>{if(!(G in Lt))return Lt;const Cn={...Lt};return delete Cn[G],Cn}),G==="github"&&jt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Pe){Pe instanceof Error&&Pe.message.includes("already in progress")||Pe&&typeof Pe=="object"&&"status"in Pe&&Pe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Xe(nt=>({...nt,[G]:"failed"}))):(n(Pe instanceof Error?Pe.message:"Login failed","error"),Xe(nt=>({...nt,[G]:"failed"}))),T(null),W(nt=>{if(!(G in nt))return nt;const mt={...nt};return delete mt[G],mt})}},[n,jt]),It=a.useCallback(G=>{et.current&&(clearInterval(et.current),et.current=null),T(null),We.current=0,Xe(Pe=>({...Pe,[G]:"cancelled"})),W(Pe=>{if(!(G in Pe))return Pe;const Ye={...Pe};return delete Ye[G],Ye})},[]),qt=a.useCallback((G,Pe)=>{ee(nt=>({...nt,[G]:Pe}));const Ye=Ce.current[G];Ye&&(clearTimeout(Ye),delete Ce.current[G]),ue(nt=>{if(!nt[G])return nt;const mt={...nt};return delete mt[G],mt}),se(nt=>{if(!nt[G])return nt;const mt={...nt};return delete mt[G],mt})},[]),Ft=a.useCallback(()=>{const G=De.current;if(!G)return;const Pe=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:Pe?"auto":"smooth"});return}}catch{}G.scrollTop=0},[]),Xt=a.useCallback(async(G,Pe)=>{const Ye=(Pe??le[G]??"").trim(),nt=s4(G,Ye);if(nt){ue(Nt=>({...Nt,[G]:nt}));return}const mt=Ce.current[G];mt&&(clearTimeout(mt),delete Ce.current[G]),T(G),ue(Nt=>{const Lt={...Nt};return delete Lt[G],Lt}),se(Nt=>{if(!Nt[G])return Nt;const Lt={...Nt};return delete Lt[G],Lt});try{await oy(G,Ye),await oe(),Ft(),ee(Nt=>{const Lt={...Nt};return delete Lt[G],Lt}),ue(Nt=>{if(!Nt[G])return Nt;const Lt={...Nt};return delete Lt[G],Lt}),se(Nt=>({...Nt,[G]:"✓ Key saved"})),Ce.current[G]=setTimeout(()=>{se(Nt=>{if(!Nt[G])return Nt;const Lt={...Nt};return delete Lt[G],Lt}),delete Ce.current[G]},3e3),n("API key saved","success")}catch(Nt){const Lt=Nt instanceof TypeError&&Nt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Nt instanceof Error?Nt.message:"Failed to save API key";ue(Cn=>({...Cn,[G]:Lt})),se(Cn=>{if(!Cn[G])return Cn;const rn={...Cn};return delete rn[G],rn}),n(Lt,"error")}finally{T(null)}},[le,n,oe,Ft]),$t=a.useCallback(async G=>{T(G);try{await ly(G),await oe(),n("API key removed","success")}catch(Pe){n(Pe instanceof Error?Pe.message:"Failed to clear API key","error")}finally{T(null)}},[n,oe]),_t=a.useCallback(async G=>{T(G);try{await ry(G),await oe(),n("Logged out","success")}catch(Pe){n(Pe instanceof Error?Pe.message:"Logout failed","error")}finally{T(null)}},[n,oe]),Ct=a.useCallback(G=>{ce(G)},[]),Et=a.useCallback(async()=>{try{const G={modelOnboardingComplete:!0};if(be){const Pe=be.indexOf("/"),Ye=Pe!==-1?be.slice(0,Pe):void 0,nt=Pe!==-1?be.slice(Pe+1):be,mt=q.find(Nt=>Nt.id===nt);mt?(G.defaultProvider=mt.provider,G.defaultModelId=mt.id):Ye&&nt&&(G.defaultProvider=Ye,G.defaultModelId=nt)}await mn(G),kh()}catch{}},[be,q,mn,kh]),tn=a.useCallback(async()=>{const G=[...new Set([...b,"first-task"])];O(!0);try{await Et(),_s("onboarding:completed",{completedSteps:G,skippedSteps:N}),y(G),k(Pe=>Pe.filter(Ye=>Ye!=="first-task")),v("complete")}finally{O(!1)}},[Et,b,N]),At=a.useCallback(async()=>{if(!s)return;const G=M.trim();if(!G){F("Please enter a task description.");return}F(null),_(!0);let Pe=!1;try{const Ye=await ap({description:G},s);D(Ye),w(!0),_s("onboarding:first-task-created",{taskId:Ye?.id}),n("Task created","success"),Pe=!0}catch(Ye){const nt=Ye instanceof Error?Ye.message:"Something went wrong creating your task. Please try again.";F(nt),n(nt,"error")}finally{_(!1)}Pe&&Et()},[s,M,n,Et]),H=a.useCallback(async()=>{O(!0);try{await Et()}finally{O(!1)}_s("onboarding:open-new-task",{}),r?.()},[Et,r]),xe=a.useCallback(async()=>{if(ct){O(!0);try{await Et()}finally{O(!1)}f(!1),e(),_s("onboarding:open-github-import",{}),o?.()}},[Et,ct,e,o]),Le=a.useCallback(async()=>{_s("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:N}),O(!0);try{await mn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[x,b,N,e]),A=a.useCallback(()=>{_s("onboarding:finished",{}),f(!1),e()},[e]),X=a.useCallback(()=>{const G=l??V;G&&(Et(),c?.(G),e())},[l,V,Et,c,e]),ze=a.useCallback(()=>{Et(),e()},[Et,e]);if(!p)return null;const ot=tt(),Rt=E.filter(G=>G.id!=="github"),Tt=[...Rt].sort(Eh),Pt=Tt.some(G=>!G.type||G.type==="oauth"),ln=Tt.some(G=>G.type==="api_key"),kn=Rt.filter(G=>G.authenticated),_n=kn.length>0,Yt=!!s,An=x==="github"&&!_n,je=(()=>{if(!be)return"";const G=be.indexOf("/"),Pe=G===-1?void 0:be.slice(0,G),Ye=G===-1?be:be.slice(G+1),nt=q.find(mt=>mt.id===Ye&&(!Pe||mt.provider===Pe));return nt?.name?nt.name:Pe?`${Kc(Pe)} ${Ye}`:be})(),ae=[];if(Yt?ae.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):ae.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),_n){const G=Kc(kn[0]?.id??"");ae.push({label:"AI Provider",status:"connected",detail:`${G} connected — AI agents can work on tasks`})}else Rt.length>0&&Rt.some(G=>Fe[G.id])?ae.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):ae.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});ct?ae.push({label:"GitHub",status:"connected",detail:Y?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!_e||it?ae.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):ae.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),je&&ae.push({label:"Default Model",status:"connected",detail:je});const Je=l??V,ut=Je?.description?.split(`
656
- `)[0]?.trim()||Je?.title||"",Dt=new Set(dc),Wt=Tt.filter(G=>Dt.has(G.id)).sort((G,Pe)=>{const Ye=dc.indexOf(G.id),nt=dc.indexOf(Pe.id);return Ye!==nt?Ye-nt:Eh(G,Pe)}),Mn=Tt.filter(G=>G.authenticated&&!Dt.has(G.id)),on=Tt.filter(G=>!G.authenticated&&!Dt.has(G.id)),Ut=G=>{if(G.id==="claude-cli"&&G.type==="cli")return t.jsx(RT,{authenticated:G.authenticated,onToggled:()=>{oe()}},G.id);if(G.type==="api_key"){const Pe=Jc(G.id),Ye=a4(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(zn,{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(Qh,{size:14,className:"onboarding-provider-key-icon"}),G.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Pe.description}),t.jsx(we,{status:de(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(o4,{provider:G,apiKeyInfo:Ye,inputValue:le[G.id]??"",isSaving:P===G.id,error:pe[G.id],success:fe[G.id],isConnected:G.authenticated,onInputChange:qt,onSave:Xt,onClear:$t})})]},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(zn,{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:Jc(G.id).description}),t.jsx(we,{status:de(G)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:P===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:()=>It(G.id),children:"Cancel"})]}):G.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>_t(G.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Mt(G.id),children:"Login"})}),P===G.id&&j[G.id]&&t.jsx(cc,{instructions:j[G.id],"data-testid":`onboarding-login-instructions-${G.id}`}),Qe[G.id]==="timeout"&&P!==G.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Qe[G.id]==="failed"&&P!==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:qe,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Bn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(bs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Dd,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Dd,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(yn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Le,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Gt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Me.map((G,Pe)=>{const Ye=at>Pe,nt=b.includes(G.key)&&Ye,mt=N.includes(G.key)&&!b.includes(G.key)&&Ye,Nt=nt||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Pe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Pe<=at?"done":""}`}),Nt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===G.key?"active":""} ${nt?"done":""} ${mt?"skipped":""}`,onClick:()=>v(G.key),"aria-label":`Go back to ${G.label}`,title:`Review ${G.label}`,children:[t.jsx("span",{className:"step-number",children:nt?t.jsx(yn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Pe+1}),t.jsx("span",{className:"step-label",children:G.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===G.key?"active":""} ${nt?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:nt?t.jsx(yn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Pe+1}),t.jsx("span",{className:"step-label",children:G.label})]})]},G.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:De,children:[x==="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."}),!ie&&E.length>0&&(()=>{const G=E.filter(Nt=>Nt.id!=="github"&&Nt.authenticated).length,Pe=E.filter(Nt=>Nt.id!=="github").length,Ye=Object.keys(Fe).filter(Nt=>!E.find(Lt=>Lt.id===Nt)?.authenticated).length;if(Pe===0)return null;let nt="onboarding-provider-summary",mt="";return G>0?(nt+=" onboarding-provider-summary--connected",mt=`✓ ${G} of ${Pe} provider${Pe!==1?"s":""} connected`):Ye>0?(nt+=" onboarding-provider-summary--skipped",mt=`${Ye} provider${Ye!==1?"s":""} skipped`):(nt+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:nt,"data-testid":"provider-summary",children:mt})})(),t.jsx(Ys,{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."})}),E.length>0&&!E.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."}),ie?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(rt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):E.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"}),Wt.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Wt.map(G=>Ut(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Mn.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:Mn.map(G=>Ut(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(Ys,{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."})}),q.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(qn,{models:q,value:be,onChange:Ct,placeholder:"Select a default model…",label:"Default model"})}),be&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",q.find(G=>G.id===be)?.name??be]})})]}),t.jsx(Ys,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:on.length>0?t.jsx("div",{className:"model-onboarding-providers",children:on.map(G=>Ut(G))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Pt&&t.jsx(Ys,{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."})}),ln&&t.jsx(Ys,{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."})})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[ct?t.jsx("p",{className:"model-onboarding-description",children:Y?"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."}),!ct&&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"})]})}),An&&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(Ys,{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."})}),_e?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(bs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Z,{status:ot})})]}),Ke&&(P==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>_t("github"),children:"Disconnect"}))]}),(ot==="not-connected"||ot==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[P==="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:()=>It("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Mt("github"),children:[t.jsx(bs,{size:16}),"Connect"]}),P==="github"&&j.github&&t.jsx(cc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]}),ot==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Y?"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."}),ot==="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:()=>Mt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Vt,children:"Skip for now"})]})]}),ot==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),ot==="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:()=>Mt("github"),children:"Connect anyway"})})]}),ot==="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(zn,{provider:"github",size:"lg"})}),Y?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:Y?"Continue with gh CLI auth →":"Continue without GitHub →"}),Y&&(P==="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:()=>Mt("github"),children:[t.jsx(zn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Y&&P==="github"&&j.github&&t.jsx(cc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="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."}),Yt?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(Ys,{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."})})]}),x==="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."}),R&&Je?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(yn,{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:Je.id}),ut&&t.jsx("p",{className:"onboarding-task-created__description",children:ut}),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:X,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:ze,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Yt?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:M,onChange:G=>{S(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:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),I&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:I}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(r4,{items:ae}),Yt&&t.jsxs(t.Fragment,{children:[t.jsx(Ys,{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:H,disabled:Se,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(an,{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${ct?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:xe,disabled:Se||!ct,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(bs,{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"}),!ct&&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."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(yn,{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:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Le,disabled:Se,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:St,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:ft,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ot,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:St,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:ft,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ot,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:ft,disabled:!Yt,children:"Next →"})]}),x==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ot,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,disabled:Se,children:Se?t.jsxs(t.Fragment,{children:[t.jsx(rt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:A,children:[t.jsx(yn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function pg({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 d4=a.lazy(()=>un(()=>import("./SetupWizardModal-JBNr-XIW.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),u4=a.lazy(()=>un(()=>import("./SettingsModal-Cs5qO84M.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function m4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{un(()=>import("./SettingsModal-Cs5qO84M.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function h4({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[x,v]=a.useState(null),b=c.detailTask?(()=>{const M=n.find(S=>S.id===c.detailTask?.id);return M?"prompt"in c.detailTask?{...c.detailTask,...M,prompt:c.detailTask.prompt,log:c.detailTask.log}:M:c.detailTask})():null,y=p??c.closeSettings,N=a.useCallback(()=>{c.openNewTask()},[c]),k=a.useCallback(()=>{c.openGitHubImport()},[c]),R=a.useCallback(M=>{v(null),c.closeModelOnboarding(),c.openDetailTask(M)},[c]),w=a.useCallback(async M=>{const S=await d.handleModalCreate(M);return c.modelOnboardingOpen&&v(S),S},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{m4()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Pi,{children:t.jsx(uA,{task:b,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(Pi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(u4,{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(hA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Pi,{children:t.jsx(xA,{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(Pi,{children:t.jsx(EA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(GA,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(YA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(xR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(CR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(tT,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(WR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Pi,{children:t.jsx(YR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(rT,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:M=>{const S=n.find(z=>z.id===M);S&&c.openDetailTask(S)}}),t.jsx(Pi,{children:t.jsx(lT,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Pi,{children:t.jsx(yT,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(AT,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(d4,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(c4,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:N,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:R}),t.jsx(pg,{toasts:o,onRemove:l})]})}function p4({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 Yc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function f4(e,n){if(n==="ready")return"done";const s=Yc.findIndex(r=>r.id===n),i=Yc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function g4({stage:e}){const[n]=a.useState(()=>cv());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:Yc.map(s=>{const i=f4(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 x4=5e3;function b4(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function v4(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++,ko(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 y4(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 Uj(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()},x4),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=v4(e,s,i),f=b4(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const j4={planning:Zs,subtask:Bi,mission_interview:us,milestone_interview:us,slice_interview:us},k4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function w4({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Hs(),[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}=Ra(),f=a.useMemo(()=>Gi(),[]);if(a.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),a.useEffect(()=>{const b=new Set,y=new Map;for(const N of e){const k=p.get(N.id),R=[N.status,N.updatedAt,k?.tabId??N.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),w=h.current.get(N.id);w&&w!==R&&b.add(N.id),y.set(N.id,R)}if(h.current=y,b.size!==0)return d(b),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 x=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(b=>!b),title:`${x} background AI task${x!==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(xc,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),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(b=>{const y=j4[b.type],N=b.status==="generating",k=b.status==="awaiting_input",R=b.status==="error",w=p.get(b.id),M=w?.tabId??b.lockedByTab??null,S=!!(M&&M!==f&&!w?.stale),z=u.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{S&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(b),c(!1))},children:[R?t.jsx(as,{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:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[R?"Failed":k4[b.type],N&&" — generating...",k&&!S&&" — needs input",k&&S&&" — active in another tab"]})]}),N&&t.jsx(rt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!S&&t.jsx(xc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&S&&t.jsx(Lo,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Gt,{size:12})})]},b.id)})})]})]})}function N4(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 S4(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Sn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Us};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Bn}}}function C4({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}=y4(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>S4(h.executorState),[h.executorState]),b=a.useMemo(()=>N4(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(ed,{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(w4,{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:()=>x(N=>!N),"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(Hn,{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:b})]}),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 E4={planning:Zs,subtask:Bi,mission_interview:us,milestone_interview:us,slice_interview:us},M4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Di=new Set;function _4({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(Di.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of Di){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&(Di.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!Di.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=>{Di.add(f),l()},g=f=>{Di.delete(f.id),l(),n(f)},p=()=>{for(const f of c)Di.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(as,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Gt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const x=E4[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(as,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{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":M4[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(Gt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function A4({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/releases",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(Gt,{size:16,"aria-hidden":"true"})})]})}function R4({onResume:e}){const n=FT();if(!n)return null;const s=n.completedSteps.length,i=yi.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(Zn,{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(Sn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function T4({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ea(),i=dg(),[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 b=!1;return(async()=>{try{o(!0),c(!1);const[N,k]=await Promise.all([xr(),Ki()]);if(b)return;const R=N.providers??[],w=R.find(I=>I.id==="github"),S=!R.some(I=>I.id!=="github"&&I.authenticated),z=!k.defaultProvider&&!k.defaultModelId,_=w?!w.authenticated:!1;h({needsAiProvider:S,needsDefaultModel:z,needsGitHub:_})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{zT(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),x=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Bn}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Qh}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:bs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,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(Zs,{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(b=>{const y=b.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(as,{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:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Gt,{size:16,"aria-hidden":!0})})]})}function P4({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 uc(e){return e>99?"99+":String(e)}function I4({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:x,onOpenGitHubImport:v,onOpenPlanning:b,onResumePlanning:y,activePlanningSessionCount:N=0,onOpenUsage:k,onRunScript:R,projectId:w,onViewAllProjects:M,showSkillsTab:S,experimentalFeatures:z}){const _=Pr(),[I,F]=a.useState(!1),[V,D]=a.useState(!1),[E,$]=a.useState({}),[B,J]=a.useState(!1),ie=a.useMemo(()=>Object.entries(E).sort(([O],[le])=>O.localeCompare(le)),[E]);a.useEffect(()=>{if(!V)return;let O=!1;return J(!0),br(w).then(le=>{O||$(le)}).catch(()=>{O||$({})}).finally(()=>{O||J(!1)}),()=>{O=!0}},[V,w]);const C=a.useCallback(()=>F(!1),[]),P=a.useCallback(O=>{C(),O?.()},[C]);if(a.useEffect(()=>{if(!I)return;const O=le=>{le.key==="Escape"&&F(!1)};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[I]),_!=="mobile"||i||r)return null;const T=N>0&&y?y:b,j=!!z?.roadmap,W=!!S,q=!!z?.todoView,ge=j&&(!W||e==="roadmaps"),be=W&&(!j||e!=="roadmaps"),ce=W&&!be,Se=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&q||e==="roadmaps"&&!ge||e==="skills"&&!be;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(Hi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(Nn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(us,{}),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(xa,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:uc(d)})]}),be&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="skills"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-skills",role:"tab","aria-selected":e==="skills",onClick:()=>n("skills"),children:[t.jsx(Bn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),ge&&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(kc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Se?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>F(O=>!O),children:[t.jsx(bc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:C}),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:()=>P(u),children:[t.jsx(xa,{}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:uc(d)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>P(l),children:[t.jsx(Ts,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>P(c),children:[t.jsx(hr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>P(m),children:[t.jsx(Xs,{}),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:()=>P(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:()=>D(O=>!O),"aria-expanded":V,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(vn,{size:14,className:`mobile-more-chevron${V?" mobile-more-chevron--open":""}`})})]}),V&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:B?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…"})]}):ie.length>0?t.jsxs(t.Fragment,{children:[ie.map(([O,le])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${O}`,onClick:()=>{R&&R(O,le),C(),D(!1)},children:[t.jsx(Sn,{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:()=>{C(),D(!1),p()},children:[t.jsx(Fs,{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:()=>{C(),D(!1),p()},children:[t.jsx(Fs,{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:()=>P(x),children:[t.jsx(Hn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>P(T),children:[t.jsx(Zs,{}),t.jsx("span",{children:"Planning"}),N>0&&t.jsx("span",{className:"mobile-more-item-badge",children:uc(N)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>P(h),children:[t.jsx(Nc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>P(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:()=>P(v),children:[t.jsx(P4,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>P(k),children:[t.jsx(Ts,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>P(M),children:[t.jsx(Yh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>P(()=>n("documents")),children:[t.jsx(Ui,{}),t.jsx("span",{children:"Documents"})]}),ce&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>P(()=>n("skills")),children:[t.jsx(Bn,{}),t.jsx("span",{children:"Skills"})]}),j&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>P(()=>n("roadmaps")),children:[t.jsx(kc,{}),t.jsx("span",{children:"Roadmaps"})]}),z?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>P(()=>n("insights")),children:[t.jsx(Zn,{}),t.jsx("span",{children:"Insights"})]}),z?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>P(()=>n("memory")),children:[t.jsx(fo,{}),t.jsx("span",{children:"Memory"})]}),z?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{P(()=>n("dev-server"))},children:[t.jsx(hr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>P(()=>n("todos")),children:[t.jsx(tp,{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:()=>P(o),children:[t.jsx(or,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function $4({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(Nn,{size:14,"aria-hidden":"true"}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}const Td="__fn_agent__";function fg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Mh(e,n,s){const i=typeof e=="string"?e.trim():"",r=fg(n,s),o=i||(r.modelProvider&&r.modelId?Td:"");return o?{agentId:o,...r}:null}function mc(e,n,s){const i=fg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function D4(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 _h(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:D4(e.metadata),createdAt:e.createdAt}}function L4(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,x]=a.useState(""),[v,b]=a.useState([]),[y,N]=a.useState(""),k=a.useRef(null),R=a.useRef(!1),w=a.useRef(""),M=a.useRef(null),S=a.useRef(""),z=a.useRef(null);a.useEffect(()=>{w.current=y},[y]);const _=a.useCallback(async C=>{const P={agentId:C.agentId};return C.modelProvider&&C.modelId&&(P.modelProvider=C.modelProvider,P.modelId=C.modelId),(await tw(P,e)).session},[e]),I=a.useCallback(async(C,P,T)=>{const j=Mh(C,P,T);if(!j)return;const W=mc(j.agentId,j.modelProvider,j.modelId);o(!0);try{const{session:q}=await ew({agentId:j.agentId,modelProvider:j.modelProvider,modelId:j.modelId},e);if(q)i(q),S.current=W;else{const ge=await _(j);i(ge),S.current=W}}catch(q){console.error("[useQuickChat] Failed to initialize session:",q),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,_]),F=a.useCallback(async()=>{if(s){d(!0);try{const C=await ou(s.id,{limit:50},e);c(C.messages.map(_h))}catch(C){console.error("[useQuickChat] Failed to load messages:",C)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?F():c([])},[s,F]);const V=a.useCallback(async()=>{if(s){d(!0);try{const C=await ou(s.id,{limit:50},e);c(C.messages.map(_h))}catch(C){console.error("[useQuickChat] Failed to reload messages:",C)}finally{d(!1)}}},[s,e]),D=a.useCallback(async(C,P,T)=>{const j=Mh(C,P,T);if(!j)return;const W=mc(j.agentId,j.modelProvider,j.modelId);z.current=j;const q=W===S.current&&s;if(q||(k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1)),q){await V();return}i(null),c([]),S.current=W,await I(j.agentId,j.modelProvider,j.modelId)},[I,V,s]),E=a.useCallback(async(C,P)=>{await D(Td,C,P)},[D]),$=a.useCallback(async()=>{const C=z.current;if(!C)return;const P=mc(C.agentId,C.modelProvider,C.modelId);k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),c([]),i(null),o(!0);try{const T=await _(C);i(T),S.current=P}catch(T){console.error("[useQuickChat] Failed to start a fresh session:",T),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,_]),B=a.useCallback(()=>{s&&(R.current=!0,k.current?.close(),k.current=null,nw(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),J=a.useCallback(()=>{w.current="",N("")},[]),ie=a.useCallback((C,P)=>{if(!s||!C.trim()&&(!P||P.length===0))return Promise.resolve();if(m)return P&&P.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(w.current=C,N(C),Promise.resolve());const T=new Promise((j,W)=>{M.current={resolve:j,reject:W},R.current=!1,k.current&&(k.current.close(),k.current=null);const ge={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:C,createdAt:new Date().toISOString()};c(le=>[...le,ge]),p(""),x(""),b([]),h(!0);let be="",ce="",Se=[];const O={onThinking:le=>{ce+=le,x(ce)},onText:le=>{be+=le,p(be)},onToolStart:le=>{Se=[...Se,{toolName:le.toolName,args:le.args,isError:!1,status:"running"}],b(Se)},onToolEnd:le=>{const ee=[...Se];for(let pe=ee.length-1;pe>=0;pe--){const ue=ee[pe];if(ue?.toolName===le.toolName&&ue.status==="running"){ee[pe]={...ue,status:"completed",isError:le.isError,result:le.result},Se=ee,b(ee);return}}Se=[...ee,{toolName:le.toolName,isError:le.isError,result:le.result,status:"completed"}],b(Se)},onDone:le=>{const ee={id:le.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:be,thinkingOutput:ce||void 0,toolCalls:Se.length>0?Se:void 0,createdAt:new Date().toISOString()};c(ue=>[...ue,ee]),p(""),x(""),b([]),h(!1),k.current=null,M.current?.resolve(),M.current=null;const pe=w.current.trim();pe&&(w.current="",N(""),ie(pe))},onError:le=>{if(p(""),x(""),b([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",le),n?.("Failed to get response","error"),M.current?.reject(new Error(typeof le=="string"?le:"Failed to get response")),M.current=null,!R.current){const ee=w.current.trim();ee&&(w.current="",N(""),ie(ee))}V()}};k.current=sw(s.id,C,O,P,e)});return T.catch(()=>{}),T},[s,m,e,n,V]);return a.useEffect(()=>()=>{k.current&&(k.current.close(),k.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:ie,stopStreaming:B,clearPendingMessage:J,switchSession:D,startModelChat:E,startFreshSession:$,loadMessages:F,reloadMessages:V}),[s,r,l,u,m,g,f,v,y,ie,B,J,D,E,$,F,V])}function z4(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,x=n?.showSystemAgents??!1,v=await _a({...f,...g,includeEphemeral:g?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());i(b)}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 $j(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||!Nw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function O4({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=cw(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(Gh,{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 F4=200;function U4(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),x=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=a.useCallback((w,M)=>{if(M<0||M>w.length){r(!1);return}const S=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=M-1;z>=0;z--){if(w[z]==="#")if(z===0){const _=w.slice(z+1,M);u(z),l(_),f(0),r(!0);return}else{const _=w[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const I=w.slice(z+1,M);u(z),l(I),f(0),r(!0);return}r(!1);return}if(!S(w[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),N=a.useCallback(async w=>{if(!w.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const M=await Hy(w,s,n);m(M.files),f(0)}catch(M){M.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{N(o)},F4),()=>{x.current&&clearTimeout(x.current)}},[o,i,N]);const k=a.useCallback((w,M)=>{if(!i||c<0)return M;const S=M.slice(0,c),z=M.slice(c+1),_=z.match(/[\s]|$/),I=_?_.index:z.length,F=z.slice(I);return`${S}#${w.path}${F}`},[i,c]),R=a.useCallback((w,M)=>{if(!i||d.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),f(S=>Math.min(S+1,d.length-1)),!0;case"ArrowUp":return w.preventDefault(),f(S=>Math.max(S-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:b,selectFile:k,dismissMention:y,handleKeyDown:R}}function B4(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let hc=null;function H4(){return hc===null&&(hc=window.innerHeight),hc}function q4(){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=H4()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function gg({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!B4()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=q4();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 V4(e){return`${e.name?.trim()||e.id} (${e.role})`}function W4(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 K4(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 ho(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function G4(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}=${ho(r,50)}`}).join(", ")}function J4(e){if(e===void 0)return null;if(typeof e=="string")return ho(e,200);try{return ho(JSON.stringify(e),200)}catch{return ho(String(e),200)}}function Ah(e,n=!1){if(!e||e.length===0)return null;const s=(g,p)=>{const f=g.status==="running",x=g.status==="completed"&&g.isError,v=G4(g.args),b=J4(g.result),y=f?v:b?`result: ${b}`:v?`args: ${v}`:null,N=f?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${f?" chat-tool-call--running":""}${x?" 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",children:g.toolName}),y&&t.jsx("span",{className:"chat-tool-call-preview",title:y,children:y}),t.jsx("span",{className:"chat-tool-call-status-text",children:N})]}),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})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" 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:b})]})]})]},`${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(zd,{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(zd,{size:12,"aria-hidden":"true"}),t.jsxs("span",{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 Y4={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 Q4(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 co={width:320,height:400},X4=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"]),Z4=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function eP(e){return e.type.startsWith("image/")}function tP(e){if(X4.has(e.type))return!0;const n=e.name.toLowerCase();return Z4.some(s=>n.endsWith(s))}const la={width:280,height:260},Qc=768,ca=8;function nP(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||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 x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,N=window.innerWidth>768?s():0,k=window.innerWidth-v-b,R=window.innerHeight-v-b-y-N;return{x:Math.max(b,Math.min(k,x.x)),y:Math.max(b,Math.min(R,x.y))}},[s]),h=a.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),g=a.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),u.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(x=>{if(!u.current||!l)return;const v=x.clientX-u.current.pointerX,b=x.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,N=u.current.y-b,k=m({x:y,y:N});o(k)}},[l,m]),f=a.useCallback(x=>{if(!u.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.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 sP(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Qc,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(la.width,window.innerWidth-p-ca),v=Math.max(la.height,window.innerHeight-f-ca);return{width:Math.max(la.width,Math.min(x,g.width)),height:Math.max(la.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Qc)return co;try{const g=localStorage.getItem(i);if(!g)return co;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?co:{width:p.width,height:p.height}}catch{return co}},[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 x={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 N=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let R=x.width,w=x.height,M=x.anchorRight,S=x.anchorBottom;if(p.includes("w")&&(R=x.width-N),p.includes("e")){const D=N;R=x.width+D,M=x.anchorRight-D}if(p.includes("n")&&(w=x.height-k),p.includes("s")){const D=k;w=x.height+D,S=x.anchorBottom-D}const z=n+M,_=s+S,I=o({width:R,height:w},z,_),F=Math.max(ca-n,Math.min(window.innerWidth-n-la.width-ca,M)),V=Math.max(ca-s,Math.min(window.innerHeight-s-la.height-ca,S));u(I),m({right:F,bottom:V})},b=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function iP({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=z4(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?ae=>{r?.(typeof ae=="function"?ae(p):ae)}:h,{keyboardOverlap:x,viewportHeight:v}=gg({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,N]=a.useState("agent"),[k,R]=a.useState(""),[w,M]=a.useState([]),[S,z]=a.useState(!1),[_,I]=a.useState(""),[F,V]=a.useState(""),[D,E]=a.useState(""),[$,B]=a.useState(!1),[J,ie]=a.useState(0),[C,P]=a.useState(-1),[T,j]=a.useState(()=>new Set),[W,q]=a.useState([]),[ge,be]=a.useState(!1),[,ce]=a.useState(!1),[Se,O]=a.useState({top:0,left:0}),le=U4({projectId:e}),ee=a.useCallback(ae=>{if(!ae||!le.mentionActive)return;const Je=ae.getBoundingClientRect();O({top:Je.top-260,left:Je.left+8})},[le.mentionActive]),pe=a.useRef(!1),ue=a.useRef(!1),fe=a.useRef(""),se=a.useRef(0),Ce=a.useRef(null),De=a.useRef(0),{position:qe,isDragging:et,handlePointerDown:Qe,handlePointerMove:Xe,handlePointerUp:it}=nP(e,pe),Ie=qe.y+60,{panelSize:We,anchorOffset:re,handleResizeStart:ve}=sP(e,qe.x,Ie),te=typeof window<"u"&&window.innerWidth>Qc,{activeSession:Ae,messages:Fe,isStreaming:he,streamingText:Me,streamingThinking:Oe,streamingToolCalls:at,sessionsLoading:ye,messagesLoading:oe,sendMessage:Te,stopStreaming:me,pendingMessage:_e,clearPendingMessage:Ke,switchSession:Re,startModelChat:ct,startFreshSession:Y}=L4(e,n),de=a.useRef(null),we=a.useRef(null),tt=a.useRef(null),Z=a.useRef(null),Ge=a.useRef(null),dt=a.useRef([]),pt=a.useMemo(()=>W4(_),[_]),jt=a.useMemo(()=>w.find(ae=>`${ae.provider}/${ae.id}`===_)??null,[w,_]),yt=a.useMemo(()=>K4(jt,pt),[jt,pt]),ft=a.useMemo(()=>y==="model"?pt?`${Td}::${pt.modelProvider}/${pt.modelId}`:"":k?`${k}::`:"",[y,pt,k]),St=y==="agent"?!!k:!!pt;a.useEffect(()=>{if(d.length===0){R(""),N("model");return}d.some(Je=>Je.id===k)||R(d[0]?.id??"")},[d,k]),a.useEffect(()=>{!p||ue.current||(ue.current=!0,z(!0),ms().then(ae=>{const Je=ae.models??[];if(M(Je),_||Je.length===0)return;const ut=ae.defaultProvider,Dt=ae.defaultModelId;if(ut&&Dt){const Wt=`${ut}/${Dt}`;if(Je.some(on=>`${on.provider}/${on.id}`===Wt)){I(Wt),N("model");return}}if(d.length===0){const Wt=Je[0];Wt&&I(`${Wt.provider}/${Wt.id}`)}}).catch(ae=>{console.error("[QuickChatFAB] Failed to load models:",ae),M([])}).finally(()=>{z(!1)}))},[p,d.length,_]),a.useEffect(()=>{if(!p){fe.current="";return}if(!ft){fe.current="";return}const ae=ft===fe.current&&!Ae&&!ye;if(!(ft===fe.current&&!ae)){if(fe.current=ft,y==="model"&&pt){ct(pt.modelProvider,pt.modelId);return}y==="agent"&&k&&Re(k)}},[p,y,pt,k,ft,Ae,ye,ct,Re]),a.useEffect(()=>{p||(B(!1),E(""),P(-1),dt.current.forEach(ae=>{ae.previewUrl&&URL.revokeObjectURL(ae.previewUrl)}),q([]))},[p]),a.useEffect(()=>{dt.current=W},[W]),a.useEffect(()=>()=>{dt.current.forEach(ae=>{ae.previewUrl&&URL.revokeObjectURL(ae.previewUrl)})},[]);const Ot=a.useCallback(ae=>{R(ae)},[]),Vt=a.useCallback(ae=>{I(ae)},[]),Mt=a.useCallback(()=>{!St||ye||Y()},[St,ye,Y]),It=a.useMemo(()=>d.find(ae=>ae.id===k)??null,[d,k]),qt=a.useMemo(()=>{const ae=D.trim().toLowerCase();return ae?d.filter(Je=>Je.name.toLowerCase().includes(ae)):d},[d,D]),Ft=a.useMemo(()=>{const ae=new Map;for(const Je of d)ae.set(Je.name.toLowerCase(),Je);return ae},[d]);a.useEffect(()=>{ie(0)},[D,$]),a.useEffect(()=>()=>{Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null)},[]),a.useEffect(()=>{if(!p)return;const ae=ut=>{const Dt=ut.target;de.current?.contains(Dt)||we.current?.contains(Dt)||Dt.closest(".model-combobox-dropdown--portal")||f(!1)},Je=ut=>{ut.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",ae),document.addEventListener("keydown",Je),()=>{document.removeEventListener("mousedown",ae),document.removeEventListener("keydown",Je)}},[p,f]),a.useEffect(()=>{if(!p)return;const ae=tt.current;ae&&(ae.scrollTop=ae.scrollHeight)},[Fe,Me,Oe,p]);const Xt=a.useMemo(()=>y==="agent"?It?`Message ${It.name||It.id}`:"Select an agent to start chatting":yt?`Message ${yt}`:"Select a model to start chatting",[y,It,yt]),$t=!St||!Ae,_t=_e.length>50?`${_e.slice(0,50)}…`:_e,Ct=a.useCallback(ae=>{if(!ae||ae.length===0)return;const Je=[];for(let ut=0;ut<ae.length;ut+=1){const Dt=ae[ut];tP(Dt)&&Je.push({file:Dt,previewUrl:eP(Dt)?URL.createObjectURL(Dt):""})}Je.length>0&&q(ut=>[...ut,...Je])},[]),Et=a.useCallback(ae=>{q(Je=>{const ut=Je[ae];return ut?.previewUrl&&URL.revokeObjectURL(ut.previewUrl),Je.filter((Dt,Wt)=>Wt!==ae)})},[]),tn=a.useCallback(ae=>{Ct(ae.clipboardData?.files)},[Ct]),At=a.useCallback(async()=>{const ae=F.trim(),Je=dt.current;if(!(!ae&&Je.length===0)&&!$t){V(""),B(!1),E(""),P(-1);try{await Te(ae,Je.map(ut=>ut.file)),Je.forEach(ut=>{ut.previewUrl&&URL.revokeObjectURL(ut.previewUrl)}),q(ut=>ut.filter(Dt=>!Je.includes(Dt)))}catch{}}},[Te,$t,F]),H=a.useCallback(ae=>{ae.preventDefault(),De.current+=1,be(!0)},[]),xe=a.useCallback(ae=>{ae.preventDefault(),ae.dataTransfer.dropEffect="copy",be(!0)},[]),Le=a.useCallback(ae=>{ae.preventDefault(),De.current=Math.max(0,De.current-1),De.current===0&&be(!1)},[]),A=a.useCallback(ae=>{ae.preventDefault(),De.current=0,be(!1),Ct(ae.dataTransfer?.files)},[Ct]),X=a.useCallback((ae,Je)=>{const ut=Q4(ae,Je);if(ut){B(!0),E(ut.filter),P(ut.start);return}B(!1),E(""),P(-1)},[]),ze=a.useCallback(ae=>{const Je=Z.current;if(!Je||C<0)return;const ut=Je.selectionStart??se.current,Dt=Je.selectionEnd??ut,Wt=Math.max(ut,Dt),Mn=Math.min(C,Wt),Ut=`${`@${ae.name.replace(/\s+/g,"_")}`} `,G=F.slice(0,Mn)+Ut+F.slice(Wt),Pe=Mn+Ut.length;V(G),B(!1),E(""),ie(0),P(-1),window.requestAnimationFrame(()=>{Z.current&&(Z.current.focus(),Z.current.setSelectionRange(Pe,Pe))})},[C,F]),ot=a.useCallback(ae=>{const Je=ae.target.value,ut=ae.target.selectionStart??Je.length;se.current=ut,V(Je),X(Je,ut),le.detectMention(Je,ut),ce(le.mentionActive),le.mentionActive&&ee(ae.target)},[X,le,ee]),Rt=a.useCallback(()=>{Ce.current!==null&&window.clearTimeout(Ce.current),Ce.current=window.setTimeout(()=>{B(!1),E(""),P(-1),ce(!1),le.dismissMention(),Ce.current=null},120)},[le]),Tt=a.useCallback(()=>{Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null)},[]),Pt=a.useCallback(ae=>{const Je=ae.currentTarget,ut=Je.selectionStart??Je.value.length;se.current=ut,X(Je.value,ut),le.detectMention(Je.value,ut),ce(le.mentionActive),le.mentionActive&&ee(Je)},[X,le,ee]),ln=a.useCallback(ae=>{ae.key!=="Escape"&&Pt(ae)},[Pt]),kn=a.useCallback(ae=>{const Je=/@([\w-]+)/g,ut=[];let Dt=0,Wt=Je.exec(ae);for(;Wt;){const[Mn,on=""]=Wt,Ut=Wt.index;Ut>Dt&&ut.push(ae.slice(Dt,Ut));const G=on.replace(/_/g," ").toLowerCase(),Pe=Ft.get(G);Pe?ut.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",Pe.name.replace(/\s+/g,"_")]},`${Pe.id}-${Ut}`)):ut.push(Mn),Dt=Ut+Mn.length,Wt=Je.exec(ae)}return Dt<ae.length&&ut.push(ae.slice(Dt)),ut.length===0?ae:ut},[Ft]),_n=a.useCallback(ae=>{j(Je=>{const ut=new Set(Je);return ut.has(ae)?ut.delete(ae):ut.add(ae),ut})},[]),Yt=a.useCallback((ae,Je=!1)=>Je?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ae}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(pi,{remarkPlugins:[fi],components:Y4,children:ae})}),[]),An=a.useCallback(ae=>{if(se.current=ae.currentTarget.selectionStart??se.current,le.mentionActive&&le.files.length>0){if(le.handleKeyDown(ae,F),ae.key==="Enter"||ae.key==="Tab"){const Je=le.files[le.selectedIndex];if(Je){const ut=le.selectFile(Je,F);V(ut),le.dismissMention(),ce(!1)}}return}if($&&ae.key==="ArrowDown"){ae.preventDefault(),qt.length>0&&ie(Je=>(Je+1)%qt.length);return}if($&&ae.key==="ArrowUp"){ae.preventDefault(),qt.length>0&&ie(Je=>Je===0?qt.length-1:Je-1);return}if($&&ae.key==="Enter"){ae.preventDefault();const Je=qt[J]??qt[0];Je&&ze(Je);return}if($&&ae.key==="Escape"){ae.preventDefault(),ae.stopPropagation(),B(!1),E(""),P(-1);return}ae.key!=="Enter"||ae.shiftKey||(ae.preventDefault(),At())},[$,qt,J,ze,At,le,F]),je=a.useCallback(()=>{if(pe.current){pe.current=!1;return}f(ae=>!ae)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:we,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":et?"true":"false",style:{right:qe.x,bottom:qe.y},onPointerDown:Qe,onPointerMove:Xe,onPointerUp:it,onClick:je,children:t.jsx(ji,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:de,"data-testid":"quick-chat-panel",style:{right:qe.x+re.right,bottom:Ie+re.bottom,...te?{width:We.width,height:We.height}:{},...b},children:[te&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:ve,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:ve,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:ve,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:ve,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:ve,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:ve,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:ve,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:ve,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"}),yt&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:yt,children:yt})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:Mt,disabled:!St||ye,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Gt,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{N("agent"),I("")},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:()=>{N("model"),R("")},children:"Model"})]}),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:k,onChange:ae=>Ot(ae.target.value),"data-testid":"quick-chat-agent-select",children:d.map(ae=>t.jsx("option",{value:ae.id,children:V4(ae)},ae.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(qn,{id:"quick-chat-model-override",models:w,value:_,onChange:Vt,label:"Select model override",placeholder:S?"Loading models…":"Select a model",disabled:S||w.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:tt,"data-testid":"quick-chat-messages",children:ye||oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Fe.length===0&&!Me&&!Oe&&!he?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Fe.map(ae=>{const Je=ae.role==="user",ut=!Je&&T.has(ae.id);return t.jsxs("div",{className:`quick-chat-panel-message ${Je?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${ae.id}`,children:[Je?t.jsx("p",{children:kn(ae.content)}):t.jsxs(t.Fragment,{children:[Yt(ae.content,ut),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${ut?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":ut?"Show rendered markdown":"Show plain text",onClick:()=>_n(ae.id),children:ut?t.jsx(vc,{size:14}):t.jsx(fa,{size:14})})]}),Ah(ae.toolCalls,!0)]},ae.id)}),he&&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:[Me?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Yt(Me,T.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${T.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":T.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>_n("__streaming__"),children:T.has("__streaming__")?t.jsx(vc,{size:14}):t.jsx(fa,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Ah(at,!0),Oe&&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:Oe})]})]})]})}),W.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:W.map((ae,Je)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Je}`,children:[ae.previewUrl?t.jsx("img",{src:ae.previewUrl,alt:ae.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ae.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Je}`,"aria-label":`Remove ${ae.file.name}`,onClick:()=>Et(Je),children:"×"})]},`${ae.file.name}-${Je}`))}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:`quick-chat-input-wrapper${ge?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:H,onDragOver:xe,onDragLeave:Le,onDrop:A,children:[t.jsx("input",{ref:Ge,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:ae=>{Ct(ae.target.files),ae.target.value=""}}),t.jsx("button",{type:"button",className:"btn-icon","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ge.current?.click(),children:t.jsx(Xh,{size:16})}),t.jsx("input",{ref:Z,type:"text",value:F,onChange:ot,onKeyDown:An,onKeyUp:ln,onClick:Pt,onBlur:Rt,onFocus:Tt,onPaste:tn,placeholder:Xt,disabled:$t,"data-testid":"quick-chat-input"}),t.jsx($4,{agents:d,filter:D,highlightedIndex:J,visible:$,onSelect:ze,position:"above"}),t.jsx(O4,{visible:le.mentionActive&&!$,position:Se,files:le.files,selectedIndex:le.selectedIndex,onSelect:ae=>{const Je=le.selectFile(ae,F);V(Je),le.dismissMention(),ce(!1),Z.current?.focus()},loading:le.loading}),_e&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${_t}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Ke,children:"×"})]})]}),he?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:me,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(xs,{size:14})}):t.jsx("button",{type:"button",onClick:()=>{At()},disabled:$t||F.trim().length===0&&W.length===0,"data-testid":"quick-chat-send",children:t.jsx(Li,{size:16})})]})]})]})}function tr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Rh(e){return e.status==="generating"||e.status==="awaiting_input"}function nr(e){return e==="complete"||e==="error"}function aP(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Ra(),d=a.useCallback(()=>{sd(e).then(p=>{const f=p.filter(v=>{const b=tr(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of f)x.set(v.id,tr(v.updatedAt));i.current=x,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 x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(b<y)continue;const N=r.current.get(v.sessionId);if(N!==void 0&&b<=N)continue;if(N!==void 0&&b>N&&!nr(v.status)&&r.current.delete(v.sessionId),nr(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const k=x.get(v.sessionId),R=v.type??k?.type,w=v.title??k?.title;if(!k&&(!R||!w))continue;const M={id:v.sessionId,type:R??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??k?.projectId??e??null,lockedByTab:v.owningTabId??k?.lockedByTab??null,updatedAt:v.updatedAt??k?.updatedAt??new Date(b).toISOString()},S=x.get(v.sessionId);(!S||S.status!==M.status||S.title!==M.title||S.type!==M.type||S.projectId!==M.projectId||S.lockedByTab!==M.lockedByTab||S.updatedAt!==M.updatedAt)&&(x.set(v.sessionId,M),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>tr(b.updatedAt)-tr(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=tr(b.updatedAt)||Date.now();s(N=>{const k=i.current.get(b.id)??0;if(y<k)return N;const R=r.current.get(b.id);if(R!==void 0&&y<=R)return N;if(R!==void 0&&y>R&&!nr(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),nr(b.status))return N.filter(M=>M.id!==b.id);const w=N.findIndex(M=>M.id===b.id);if(w>=0){const M=[...N];return M[w]=b,M}return Rh(b)?[b,...N]:N}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),nr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),i.current.set(b,Math.max(i.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(N=>N.filter(k=>k.id!==b))}catch{}};return qs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":x},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const x=n.find(N=>N.id===p)?.type,v=Gi();let b=!1;if(x==="planning")try{await cp(p,e,v)}catch(N){b=!0,N instanceof Error&&N.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await mp(p,e,v)}catch(N){b=!0,N instanceof Error&&N.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await xp(p,e,v)}catch(N){b=!0,N instanceof Error&&N.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&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 bp(p)}catch{}s(N=>N.filter(k=>k.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Rh(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 Qn(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 Th(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function rP(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),x=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=a.useCallback(async E=>{const $=++m.current,B=n,J=E?.searchQueryOverride??s,ie=E?.includeArchivedOverride??u.current;try{const C=await Rv(void 0,void 0,B,J,ie);if(m.current!==$||n!==B)return;o(C.map(Qn)),f.current=Date.now()}catch{if(m.current!==$||n!==B)return;if(E?.clearOnError){o([]);return}o(C=>C)}},[n,s]);p.current=y;const N=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const E=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(E)},[s]),a.useEffect(()=>{y({clearOnError:!0});const E=()=>{if(document.visibilityState!=="visible")return;const $=Date.now();$-h.current<b||(h.current=$,y())};return document.addEventListener("visibilitychange",E),()=>{document.removeEventListener("visibilitychange",E)}},[y]),a.useEffect(()=>{if(i===!1)return;const E=x.current,$=n?`?projectId=${encodeURIComponent(n)}`:"",B=()=>x.current!==E;let J=!0;const ie=q=>{if(B())return;const ge=Qn(JSON.parse(q.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(be=>be.some(ce=>ce.id===ge.id)?be:[...be,ge])},C=q=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ge,to:be}=JSON.parse(q.data),ce=Qn(ge);o(Se=>Se.map(O=>O.id===ce.id?{...ce,column:be}:O)),f.current=Date.now()},P=q=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ge=Qn(JSON.parse(q.data));o(be=>be.map(ce=>{if(ce.id!==ge.id||Th(ge.updatedAt,ce.updatedAt)<0)return ce;if(ce.column===ge.column)return ge;const O=Th(ce.columnMovedAt,ge.columnMovedAt);return ce.columnMovedAt&&!ge.columnMovedAt?{...ge,column:ce.column,columnMovedAt:ce.columnMovedAt}:O>0?{...ge,column:ce.column,columnMovedAt:ce.columnMovedAt}:ge})),f.current=Date.now()},T=q=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ge=Qn(JSON.parse(q.data));o(be=>be.filter(ce=>ce.id!==ge.id))},j=q=>{if(B())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ge}=JSON.parse(q.data),be=Qn(ge);o(ce=>ce.map(Se=>Se.id===be.id?{...be,column:"done"}:Se))},W=qs(`/api/events${$}`,{events:{"task:created":ie,"task:moved":C,"task:updated":P,"task:deleted":T,"task:merged":j},onReconnect:()=>{J&&(B()||p.current())}});return()=>{J=!1,W()}},[n,i]);const k=a.useCallback(async E=>{const $=Qn(await ap(E,n));return o(B=>B.some(J=>J.id===$.id)?B:[...B,$]),$},[n]),R=a.useCallback(async(E,$)=>Qn(await Pv(E,$,n)),[n]),w=a.useCallback(async E=>Qn(await rp(E,n)),[n]),M=a.useCallback(async E=>Qn(await Iv(E,n)),[n]),S=a.useCallback(async E=>$v(E,n),[n]),z=a.useCallback(async E=>Qn(await Dv(E,n)),[n]),_=a.useCallback(async E=>{const $=Qn(await Lv(E,n));return o(B=>B.some(J=>J.id===$.id)?B:[...B,$]),$},[n]),I=a.useCallback(async(E,$)=>{const B=d.current.find(ie=>ie.id===E),J=B?{...B,...$,updatedAt:new Date().toISOString()}:void 0;J&&o(ie=>ie.map(C=>C.id===E?J:C));try{const ie=Qn(await Qs(E,$,n));return o(C=>C.map(P=>P.id===E?ie:P)),ie}catch(ie){throw B&&o(C=>C.map(P=>P.id===E?B:P)),ie}},[n]),F=a.useCallback(async E=>{const $=Qn(await Ov(E,n));return o(B=>B.map(J=>J.id===E?$:J)),$},[n]),V=a.useCallback(async E=>{const $=Qn(await Fv(E,n));return o(B=>B.map(J=>J.id===E?$:J)),$},[n]),D=a.useCallback(async()=>{const $=(await Uv(n)).map(Qn);return o(B=>B.map(J=>$.find(C=>C.id===J.id)||J)),$},[n]);return{tasks:r,createTask:k,moveTask:R,pauseTask:w,deleteTask:M,mergeTask:S,retryTask:z,duplicateTask:_,updateTask:I,archiveTask:F,unarchiveTask:V,archiveAllDone:D,loadArchivedTasks:N,includeArchived:l,lastFetchTimeMs:f.current}}const oP=5e3,lP=1e3;function cP(){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 nu();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 x=performance.now();try{const v=await nu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),lr("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),lr("[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 x=Date.now();x-c.current<lP||(c.current=x,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},oP),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Fj(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Wj(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await pp(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 dP="kb-dashboard-current-project";function uP(e){return e??"local"}function mP(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=uP(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Ki();if(p)return;d.current=x.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(dP);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await mn({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(x=>x.id===i.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,mn({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,mn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,mn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const xg=a.createContext(null);function hP({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()},[]),po.createElement(xg.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function pP(){const e=a.useContext(xg);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const bg="kb-dashboard-theme-mode",vg="kb-dashboard-color-theme",yg=[...kw],Xc="theme-data",pc="theme-data.css";function fP(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${pc}`:e.replace(/\/[^/]+$/,`/${pc}`):`/${pc}`}const Rs=typeof window<"u",gP=Rs?a.useLayoutEffect:a.useEffect;function jg(e){return e==="dark"||e==="light"||e==="system"}function Ph(){if(!Rs)return"dark";try{const e=localStorage.getItem(bg);if(jg(e))return e}catch{}return"dark"}function Ih(){if(!Rs)return"default";try{const e=localStorage.getItem(vg);if(e&&yg.includes(e))return e}catch{}return"default"}function $h(e){if(Rs)try{localStorage.setItem(bg,e)}catch{}}function Dh(e){if(Rs)try{localStorage.setItem(vg,e)}catch{}}function xP(e,n){return e==="system"?n?"dark":"light":e}function bP(e,n,s){if(!Rs)return;const i=xP(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Lh(){if(!Rs)return;const e=fP(),n=document.getElementById(Xc);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=Xc,document.head.appendChild(s)}function zh(){if(!Rs)return;const e=document.getElementById(Xc);e&&e.remove()}function vP(){const[e,n]=a.useState(()=>Ph()),[s,i]=a.useState(()=>Ih()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Rs?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(!Rs||!r)return;let f=!1;return Ki().then(x=>{f||(jg(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),Ph()!==x.themeMode&&$h(x.themeMode)),x.colorTheme&&yg.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),Ih()!==x.colorTheme&&Dh(x.colorTheme)))}).catch(x=>{console.warn("[useTheme] Failed to hydrate theme from global settings",x)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Rs)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),gP(()=>{bP(e,s,l)},[e,s,l]),a.useEffect(()=>{!Rs||r||(s!=="default"?Lh():zh())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),$h(f),mn({themeMode:f}).catch(x=>{console.warn("[useTheme] Failed to persist themeMode to global settings",x)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),Dh(f),f!=="default"?Lh():zh(),mn({colorTheme:f}).catch(x=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",x)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function yP(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,x]=a.useState(void 0),[v,b]=a.useState(null),[y,N]=a.useState("definition"),[k,R]=a.useState(!1),[w,M]=a.useState(void 0),[S,z]=a.useState(!1),[_,I]=a.useState(!1),[F,V]=a.useState(!1),[D,E]=a.useState(null),[$,B]=a.useState(!1),[J,ie]=a.useState(!1),[C,P]=a.useState(void 0),[T,j]=a.useState(!1),[W,q]=a.useState("project"),[ge,be]=a.useState(!1),[ce,Se]=a.useState(!1),[O,le]=a.useState(!1),[ee,pe]=a.useState(!1),[ue,fe]=a.useState(!1),[se,Ce]=a.useState(!1),[De,qe]=a.useState(!1),et=!!(v||k||s||r||m||J||T||ge||ce||O||ue||ee||F||$||S||_||se||De),Qe=a.useCallback(()=>i(!0),[]),Xe=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Ie=a.useCallback(H=>{c(H),o(!0)},[]),We=a.useCallback(()=>{const H=n[0];H&&(d(H.id),o(!0))},[n]),re=a.useCallback(H=>{d(H),o(!0)},[]),ve=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),te=a.useCallback(H=>{p(H),h(!0)},[]),Ae=a.useCallback(H=>{x(H),h(!0)},[]),Fe=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),he=a.useCallback((H,xe="definition")=>{b(H),N(xe)},[]),Me=a.useCallback(H=>{b(H),N("changes")},[]),Oe=a.useCallback(H=>{b(xe=>xe&&{...xe,...H})},[]),at=a.useCallback(()=>{b(null)},[]),ye=a.useCallback(H=>{M(H),R(!0)},[]),oe=a.useCallback(()=>{R(!1),M(void 0)},[]),Te=a.useCallback(()=>z(!0),[]),me=a.useCallback(()=>z(!1),[]),_e=a.useCallback(()=>I(!0),[]),Ke=a.useCallback(()=>I(!1),[]),Re=a.useCallback(H=>{E(H??null),V(!0)},[]),ct=a.useCallback(()=>{V(!1),E(null)},[]),Y=a.useCallback(()=>B(!0),[]),de=a.useCallback(()=>B(!1),[]),we=a.useCallback(()=>{ie(H=>!H)},[]),tt=a.useCallback(()=>{ie(!1),P(void 0)},[]),Z=a.useCallback(()=>j(!0),[]),Ge=a.useCallback(()=>j(!1),[]),dt=a.useCallback(H=>{q(H)},[]),pt=a.useCallback(()=>be(!0),[]),jt=a.useCallback(()=>be(!1),[]),yt=a.useCallback(()=>Se(!0),[]),ft=a.useCallback(()=>Se(!1),[]),St=a.useCallback(()=>le(!0),[]),Ot=a.useCallback(()=>le(!1),[]),Vt=a.useCallback(()=>pe(!0),[]),Mt=a.useCallback(()=>pe(!1),[]),It=a.useCallback(()=>fe(!0),[]),qt=a.useCallback(()=>fe(!1),[]),Ft=a.useCallback(async(H,xe)=>{fe(!1),P(xe),ie(!0)},[]),Xt=a.useCallback(()=>Ce(!0),[]),$t=a.useCallback(()=>Ce(!1),[]),_t=a.useCallback(()=>qe(!0),[]),Ct=a.useCallback(()=>qe(!1),[]),Et=a.useCallback((H,xe)=>{xe(`Created ${H.id} from planning mode`,"success"),o(!1),c(null)},[]),tn=a.useCallback((H,xe)=>{const Le=H.map(A=>A.id).join(", ");xe(`Created ${Le} from planning mode`,"success"),o(!1),c(null)},[]),At=a.useCallback((H,xe)=>{const Le=H.map(A=>A.id).join(", ");xe(`Created ${Le} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:k,settingsInitialSection:w,schedulesOpen:S,githubImportOpen:_,usageOpen:F,usageAnchorRect:D,systemStatsOpen:$,terminalOpen:J,terminalInitialCommand:C,filesOpen:T,fileBrowserWorkspace:W,activityLogOpen:ge,gitManagerOpen:ce,workflowStepsOpen:O,agentsOpen:ee,scriptsOpen:ue,setupWizardOpen:se,modelOnboardingOpen:De,anyModalOpen:et,openNewTask:Qe,closeNewTask:Xe,openPlanning:it,openPlanningWithInitialPlan:Ie,resumePlanning:We,openPlanningWithSession:re,closePlanning:ve,openSubtaskBreakdown:te,openSubtaskWithSession:Ae,closeSubtask:Fe,openDetailTask:he,openDetailWithChangesTab:Me,updateDetailTask:Oe,closeDetailTask:at,openSettings:ye,closeSettings:oe,openSchedules:Te,closeSchedules:me,openGitHubImport:_e,closeGitHubImport:Ke,openUsage:Re,closeUsage:ct,openSystemStats:Y,closeSystemStats:de,toggleTerminal:we,closeTerminal:tt,openFiles:Z,closeFiles:Ge,setFileWorkspace:dt,openActivityLog:pt,closeActivityLog:jt,openGitManager:yt,closeGitManager:ft,openWorkflowSteps:St,closeWorkflowSteps:Ot,openAgents:Vt,closeAgents:Mt,openScripts:It,closeScripts:qt,runScript:Ft,openSetupWizard:Xt,closeSetupWizard:$t,openModelOnboarding:_t,closeModelOnboarding:Ct,onPlanningTaskCreated:Et,onPlanningTasksCreated:tn,onSubtaskTasksCreated:At}}function jP(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),[x,v]=a.useState(!1),[b,y]=a.useState({}),[N,k]=a.useState(!1),[R,w]=a.useState(!1),[M,S]=a.useState(!1),[z,_]=a.useState(!1),[I,F]=a.useState(!1),V=a.useCallback(async()=>{const[J,ie]=await Promise.allSettled([qv(e),Fo(e)]);if(J.status==="fulfilled"&&(s(J.value.maxConcurrent),r(J.value.rootDir)),ie.status==="fulfilled"){const C=ie.value;l(!!C.autoMerge),u(!!C.globalPause),m(!!C.enginePaused),v(!!C.prAuthAvailable),g(C.taskStuckTimeoutMs),f(C.showQuickChatFAB===!0),y(C.experimentalFeatures??{});const P=C.experimentalFeatures??{};k(P.insights===!0),w(P.roadmap===!0),S(P.memoryView===!0),_(P.devServerView===!0||P.devServer===!0),F(P.todoView===!0)}},[e]);a.useEffect(()=>{V()},[V]);const D=a.useCallback(async()=>{const J=!o;l(J);try{await Br({autoMerge:J},e)}catch{l(!J)}},[o,e]),E=a.useCallback(async()=>{const J=!c;u(J);try{await Br({globalPause:J,globalPauseReason:J?"manual":void 0},e)}catch{u(!J)}},[c,e]),$=a.useCallback(async()=>{const J=!d;m(J);try{await Br({enginePaused:J},e)}catch{m(!J)}},[d,e]),B=a.useCallback(async()=>{const J=!p;f(J);try{await Br({showQuickChatFAB:J},e)}catch{f(!J)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,experimentalFeatures:b,insightsEnabled:N,roadmapEnabled:R,memoryEnabled:M,devServerEnabled:z,todosEnabled:I,toggleAutoMerge:D,toggleGlobalPause:E,toggleEnginePause:$,toggleShowQuickChatFAB:B,refresh:V}}function kP(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(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,fr(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 wP(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{ms().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 mn({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 mn({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 NP({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 Ki().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!Ea()?l=!0:!d&&!Ea()&&(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 Oh="kb-update-banner-dismissed";function SP(){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(Oh)==="true";d(h);let g=!1;return Vv().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(Oh,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const CP=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Fh(e){return e!==null&&CP.includes(e)}function EP(e){return e==="devserver"?"dev-server":e}function MP(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 b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[g,p]=a.useState(()=>{const b=Vn("kb-dashboard-task-view");return Fh(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=Vn("kb-dashboard-task-view",r?.id);if(Fh(b)){const y=!f.current&&b==="devserver";p(y?"devserver":EP(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ds("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 b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,i,r,l,c]);const x=a.useCallback(b=>{p(b)},[]),v=a.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(u),N=b[(y+1)%b.length];d(N)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function _P(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(S=>{n(S),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),x=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),b=a.useCallback(S=>{h(),n(S),i("project"),u(`Project ${S.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),N=a.useCallback(async S=>{try{await qj(S.id),u(`Project ${S.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${S.name}`,"error")}},[u,o]),k=a.useCallback(async S=>{try{await Vj(S.id),u(`Project ${S.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${S.name}`,"error")}},[u,o]),R=a.useCallback(async S=>{try{await pp(S.id),u(`Project ${S.name} removed`,"success"),r?.id===S.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${S.name}`,"error")}},[r,s,i,u,o]),w=a.useCallback(async S=>{try{await l(S)}catch{u("Failed to update favorites","error")}},[l,u]),M=a.useCallback(async S=>{try{await c(S)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:N,handleResumeProject:k,handleRemoveProject:R,handleToggleFavorite:w,handleToggleModelFavorite:M}}function AP(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function RP(e){return Bo("/health",{nodeId:e})}async function TP(e){return Bo("/projects",{nodeId:e})}async function PP(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Bo(`/tasks?${i.toString()}`,{nodeId:e})}async function IP(e,n){return Bo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function UD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function BD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function HD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function qD(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function $P(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),x=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const b=new AbortController;f.current=b,h(!0),p(null);try{const y=[RP(e),TP(e)];s&&(y.push(PP(e,s,i)),y.push(IP(e,s)));const N=await Promise.allSettled(y);if(b.signal.aborted)return;const k=N[0],R=N[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&N[2]){const w=N[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){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(x(),()=>{f.current?.abort()}),[x]);const v=a.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function DP(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 LP="fusion-dashboard-current-node",kg=a.createContext(null);function zP({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 Ki();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(LP);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await mn({dashboardCurrentNodeId:x.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,mn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,mn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,mn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(kg.Provider,{value:d,children:e})}function OP(){const e=a.useContext(kg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function FP({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&&(yv(l),window.location.reload())},[n]),o=a.useCallback(()=>{jv(),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 UP=200,BP=a.lazy(()=>un(()=>import("./AgentsView-pile-9ZM.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),HP=a.lazy(()=>un(()=>import("./DocumentsView-D4m9s6Ye.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),qP=a.lazy(()=>un(()=>import("./InsightsView-u535o96R.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),VP=a.lazy(()=>un(()=>import("./NodesView-Blg8NHiu.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),WP=a.lazy(()=>un(()=>import("./ChatView-C4SCF_Hj.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),KP=a.lazy(()=>un(()=>import("./RoadmapsView-DATopkaE.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),GP=a.lazy(()=>un(()=>import("./SkillsView-CkT6-elZ.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),JP=a.lazy(()=>un(()=>import("./MemoryView-DEmn8fA2.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),YP=a.lazy(()=>un(()=>import("./DevServerView-1HvWligZ.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),QP=a.lazy(()=>un(()=>import("./TodoView-CstzLvjw.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function XP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{un(()=>import("./AgentsView-pile-9ZM.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),un(()=>import("./DocumentsView-D4m9s6Ye.js"),__vite__mapDeps([20,1,0,2,21])),un(()=>import("./InsightsView-u535o96R.js"),__vite__mapDeps([22,1,14,0,2,23])),un(()=>import("./NodesView-Blg8NHiu.js"),__vite__mapDeps([24,1,18,0,2,25])),un(()=>import("./ChatView-C4SCF_Hj.js"),__vite__mapDeps([26,1,0,2])),un(()=>import("./RoadmapsView-DATopkaE.js"),__vite__mapDeps([27,1,0,2,28])),un(()=>import("./SkillsView-CkT6-elZ.js"),__vite__mapDeps([29,1,0,2,30])),un(()=>import("./MemoryView-DEmn8fA2.js"),__vite__mapDeps([31,1,12,13,0,2,32])),un(()=>import("./DevServerView-1HvWligZ.js"),__vite__mapDeps([33,1,0,2,34])),un(()=>import("./TodoView-CstzLvjw.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const fc="kb-setup-warning-dismissed";function ZP(){const{toasts:e,addToast:n,removeToast:s}=pP(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{XP()},[]);const{projects:r,loading:o,error:l,refresh:c}=cP(),{nodes:u}=Vo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=OP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=mP(r,{nodeId:m}),{hasAiProvider:y,hasGithub:N,loading:k,hasWarnings:R}=lg(f?.id),{updateAvailable:w,latestVersion:M,currentVersion:S,dismissed:z,dismiss:_}=SP();a.useEffect(()=>{if(m&&!d&&u.length>0){const ht=u.find(pn=>pn.id===m);if(ht){g(ht);return}}m&&u.length>0&&(u.some(pn=>pn.id===m)||p())},[m,d,u,g,p]);const[I,F]=a.useState(""),V=$P(m,{projectId:f?.id,searchQuery:I||void 0});DP(m);const D=h&&V.projects.length>0?V.projects:r,{themeMode:E,colorTheme:$,setThemeMode:B,setColorTheme:J}=vP(),{sessions:ie,generating:C,needsInput:P,planningSessions:T,dismissSession:j}=aP(f?.id),W=ie.filter(ht=>ht.status==="awaiting_input"||ht.status==="error"),q=yP({projectId:f?.id,planningSessions:T}),{viewMode:ge,setViewMode:be,taskView:ce,handleChangeTaskView:Se}=MP({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:q.setupWizardOpen,openSetupWizard:q.openSetupWizard,themeMode:E,setThemeMode:B}),O=a.useCallback(ht=>{ht==="missions"&&(de(void 0),tt(void 0),Ge(void 0)),Se(ht)},[Se]),le=ce==="board"||ce==="list",{tasks:ee,createTask:pe,moveTask:ue,pauseTask:fe,deleteTask:se,mergeTask:Ce,retryTask:De,updateTask:qe,duplicateTask:et,archiveTask:Qe,unarchiveTask:Xe,archiveAllDone:it,loadArchivedTasks:Ie,lastFetchTimeMs:We}=rP({...f?{projectId:f.id}:{},searchQuery:I||void 0,sseEnabled:le}),[re,ve]=a.useState(!1),te=a.useRef(performance.now()),Ae=a.useRef(!1),Fe=a.useRef(!1),he=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!Ae.current){Ae.current=!0;const ht=`projects loaded at ${Math.round(performance.now()-te.current)}ms from mount`;console.log(`[App] ${ht}`),lr("[App]",ht)}if(!b&&!Fe.current){Fe.current=!0;const ht=`current-project resolved at ${Math.round(performance.now()-te.current)}ms from mount`;console.log(`[App] ${ht}`),lr("[App]",ht)}},[o,b]),a.useEffect(()=>{if(re||o||b)return;const ht=performance.now(),pn=window.setTimeout(()=>{const ne=`dashboard ready at ${Math.round(performance.now()-te.current)}ms from mount (settle delay=${Math.round(performance.now()-ht)}ms)`;console.log(`[App] ${ne}`),lr("[App]",ne),ve(!0)},UP);return()=>{window.clearTimeout(pn)}},[re,o,b]);const Oe=Pr()==="mobile",{keyboardOverlap:at}=gg({enabled:Oe}),ye=Oe&&at>0,[oe,Te]=a.useState(0),me=a.useCallback(()=>{vp(f?.id).then(ht=>{Te(ht.unreadCount)}).catch(ht=>{console.warn("[App] Failed to fetch mailbox unread count:",ht)})},[f?.id]);a.useEffect(()=>{me();const ht=new URLSearchParams;f?.id&&ht.set("projectId",f.id);const pn=ht.size>0?`?${ht.toString()}`:"";return qs(`/api/events${pn}`,{events:{"message:sent":me,"message:received":me,"message:read":me,"message:deleted":me}})},[f?.id,me]);const[_e,Ke]=a.useState(!1),[Re,ct]=a.useState(!1),[Y,de]=a.useState(void 0),[we,tt]=a.useState(void 0),[Z,Ge]=a.useState(void 0),[dt,pt]=a.useState(!1),[jt,yt]=a.useState(!1),[ft,St]=a.useState(()=>Vn(fc,f?.id)==="true");a.useEffect(()=>{St(Vn(fc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const ht=()=>{yt(!0)};return window.addEventListener(Ec,ht),()=>{window.removeEventListener(Ec,ht)}},[]);const Ot=a.useCallback(()=>{ds(fc,"true",f?.id),St(!0)},[f?.id]),{maxConcurrent:Vt,autoMerge:Mt,globalPaused:It,enginePaused:qt,taskStuckTimeoutMs:Ft,showQuickChatFAB:Xt,prAuthAvailable:$t,experimentalFeatures:_t,insightsEnabled:Ct,roadmapEnabled:Et,memoryEnabled:tn,devServerEnabled:At,todosEnabled:H,toggleAutoMerge:xe,toggleGlobalPause:Le,toggleEnginePause:A,refresh:X}=jP(f?.id),ze=_t.skillsView===!0,ot=_t.nodesView===!0,Rt=!0;a.useEffect(()=>{Object.keys(_t).length!==0&&(ce==="insights"&&!Ct&&Se("board"),ce==="roadmaps"&&!Et&&Se("board"),ce==="memory"&&!tn&&Se("board"),(ce==="devserver"||ce==="dev-server")&&!At&&Se("board"),ce==="todos"&&!H&&Se("board"))},[ce,Ct,Et,_t,Se,Rt,tn,At,H]),a.useEffect(()=>{_e&&!ot&&Ke(!1)},[_e,ot]);const{availableModels:Tt,favoriteProviders:Pt,favoriteModels:ln,toggleFavoriteProvider:kn,toggleFavoriteModel:_n}=wP();NP({projectId:f?.id,setupWizardOpen:q.setupWizardOpen,openModelOnboarding:q.openModelOnboarding,openSettings:q.openSettings});const{handleSelectProject:Yt,handleViewAllProjects:An,handleOpenSettings:je,handleAddProject:ae,handleSetupComplete:Je,handleModelOnboardingComplete:ut,handlePauseProject:Dt,handleResumeProject:Wt,handleRemoveProject:Mn,handleToggleFavorite:on,handleToggleModelFavorite:Ut}=_P({setCurrentProject:x,clearCurrentProject:v,setViewMode:be,currentProject:f,refreshProjects:c,toggleFavoriteProvider:kn,toggleFavoriteModel:_n,addToast:n,openSettings:q.openSettings,openSetupWizard:q.openSetupWizard,closeSetupWizard:q.closeSetupWizard,closeModelOnboarding:q.closeModelOnboarding}),{handleDetailClose:G}=kP({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:q.openDetailTask,closeTaskDetail:q.closeDetailTask}),{handleBoardQuickCreate:Pe,handleModalCreate:Ye,handlePlanningTaskCreated:nt,handlePlanningTasksCreated:mt,handleSubtaskTasksCreated:Nt,handleGitHubImport:Lt}=AP({createTask:pe,onPlanningTaskCreated:q.onPlanningTaskCreated,onPlanningTasksCreated:q.onPlanningTasksCreated,onSubtaskTasksCreated:q.onSubtaskTasksCreated,addToast:n}),Cn=a.useCallback((ht,pn)=>{if(pn==="changes"){q.openDetailWithChangesTab(ht);return}q.openDetailTask(ht,pn)},[q]),rn=a.useCallback(async ht=>{try{const pn=await fr(ht,f?.id);q.openDetailTask(pn,"logs")}catch(pn){n(`Failed to open task logs: ${pn.message}`,"error")}},[q,f?.id,n]),kt=a.useCallback(()=>{ot&&Ke(ht=>!ht)},[ot]),os=a.useCallback(()=>{q.setFileWorkspace("project"),q.openFiles()},[q]),ks=a.useCallback(async()=>{ct(!0);try{await c()}finally{ct(!1)}},[c]),Is=a.useCallback(ht=>{tt(ht),de(void 0),Se("missions")},[Se]),ws=a.useCallback(ht=>{ht.type==="planning"?q.openPlanningWithSession(ht.id):ht.type==="subtask"?q.openSubtaskWithSession(ht.id):ht.type==="mission_interview"?(tt(void 0),de(ht.id),Ge(void 0),Se("missions")):(ht.type==="milestone_interview"||ht.type==="slice_interview")&&(de(void 0),tt(void 0),Ge(ht.id),Se("missions"))},[Se,q]),si=a.useCallback(()=>{},[]),$s=a.useCallback(()=>{},[]),Ds=!o&&!b&&r.length===0&&!f&&!!l,Yi=()=>Ds?t.jsx(p4,{errorMessage:l??"Failed to fetch projects",isRetrying:Re,onRetry:ks}):_e?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(VP,{addToast:n,onClose:()=>Ke(!1)})})})}):ge==="overview"?t.jsx(ns,{children:t.jsx(XN,{projects:r,loading:o,onSelectProject:Yt,onAddProject:ae,onPauseProject:Dt,onResumeProject:Wt,onRemoveProject:Mn,nodes:u})}):ce==="skills"?ze?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(GP,{addToast:n,projectId:f?.id,onClose:()=>Se("board")})})}):(Se("board"),null):ce==="chat"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(WP,{addToast:n,projectId:f?.id})})}):ce==="mailbox"?t.jsx(ns,{children:t.jsx(q1,{projectId:f?.id,addToast:n,onUnreadCountChange:Te})}):ce==="roadmaps"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(KP,{addToast:n,projectId:f?.id})})}):ce==="missions"?t.jsx(ns,{children:t.jsx(F1,{isInline:!0,isOpen:!0,onClose:()=>{tt(void 0),de(void 0),Ge(void 0),Se("board")},addToast:n,projectId:f?.id,onSelectTask:ht=>{const pn=ee.find(ne=>ne.id===ht);pn&&q.openDetailTask(pn)},availableTasks:ee.map(ht=>({id:ht.id,title:ht.title})),resumeSessionId:Y,targetMissionId:we,milestoneSliceResumeSessionId:Z,onMilestoneSliceResumeFetchError:()=>Ge(void 0)})}):ce==="agents"&&Rt?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(BP,{addToast:n,projectId:f?.id,onOpenTaskLogs:rn})})}):ce==="documents"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(HP,{projectId:f?.id,addToast:n,onOpenDetail:q.openDetailTask})})}):ce==="insights"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(qP,{projectId:f?.id,addToast:n,onClose:()=>Se("board")})})}):ce==="memory"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(JP,{addToast:n,projectId:f?.id})})}):ce==="todos"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(QP,{addToast:n,projectId:f?.id})})}):ce==="devserver"||ce==="dev-server"?t.jsx(ns,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(YP,{addToast:n,projectId:f?.id})})}):ce==="board"?t.jsx(ns,{children:t.jsx(zN,{tasks:h&&V.tasks.length>0?V.tasks:ee,projectId:f?.id,maxConcurrent:Vt,onMoveTask:ue,onPauseTask:fe,onOpenDetail:q.openDetailTask,addToast:n,onQuickCreate:Pe,onNewTask:q.openNewTask,onPlanningMode:q.openPlanningWithInitialPlan,onSubtaskBreakdown:q.openSubtaskBreakdown,autoMerge:Mt,onToggleAutoMerge:xe,globalPaused:It,onUpdateTask:qe,onRetryTask:De,onArchiveTask:Qe,onUnarchiveTask:Xe,onDeleteTask:se,onArchiveAllDone:it,onLoadArchivedTasks:Ie,searchQuery:I,availableModels:Tt,onOpenDetailWithTab:Cn,favoriteProviders:Pt,favoriteModels:ln,onToggleFavorite:on,onToggleModelFavorite:Ut,taskStuckTimeoutMs:Ft,onOpenMission:Is,lastFetchTimeMs:We})}):t.jsx(ns,{children:t.jsx(BN,{tasks:h&&V.tasks.length>0?V.tasks:ee,projectId:f?.id,onMoveTask:ue,onRetryTask:De,onOpenDetail:q.openDetailTask,addToast:n,globalPaused:It,onNewTask:q.openNewTask,onQuickCreate:Pe,onPlanningMode:q.openPlanningWithInitialPlan,onSubtaskBreakdown:q.openSubtaskBreakdown,availableModels:Tt,favoriteProviders:Pt,favoriteModels:ln,onToggleFavorite:on,onToggleModelFavorite:Ut,taskStuckTimeoutMs:Ft,searchQuery:I,lastFetchTimeMs:We})});if(!re)return t.jsxs(t.Fragment,{children:[t.jsx(g4,{stage:he}),t.jsx(pg,{toasts:e,onRemove:s})]});const ii=!q.modelOnboardingOpen&&OT(),ai=!q.modelOnboardingOpen&&!ii&&Ea()&&!dg();return t.jsxs(t.Fragment,{children:[t.jsx(hw,{isElectron:i,onOpenSettings:je,onOpenGitHubImport:q.openGitHubImport,onOpenPlanning:q.openPlanning,onResumePlanning:q.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:q.openUsage,onOpenActivityLog:q.openActivityLog,onOpenSystemStats:q.openSystemStats,onOpenMailbox:()=>O("mailbox"),mailboxUnreadCount:oe,onOpenSchedules:q.openSchedules,onOpenGitManager:q.openGitManager,onOpenNodes:kt,showNodesButton:ot,onOpenWorkflowSteps:q.openWorkflowSteps,onOpenScripts:q.openScripts,onRunScript:q.runScript,onToggleTerminal:q.toggleTerminal,onOpenFiles:q.openFiles,filesOpen:q.filesOpen,globalPaused:It,enginePaused:qt,onToggleGlobalPause:Le,onToggleEnginePause:A,view:ce,onChangeView:ge==="project"&&f?O:void 0,showSkillsTab:ze,showAgentsTab:Rt,searchQuery:I,onSearchChange:F,projects:D,currentProject:f,onSelectProject:Yt,onViewAllProjects:An,projectId:f?.id,mobileNavEnabled:Oe,availableNodes:u,currentNode:d,onSelectNode:ht=>{ht===null?p():g(ht)},isRemote:h,experimentalFeatures:{insights:Ct,roadmap:Et,memoryView:tn,devServer:At,devServerView:At,todoView:H}}),ge==="project"&&f&&!_e&&ce!=="missions"&&!q.isPlanningOpen&&t.jsx(_4,{sessions:W,onResumeSession:ws,onDismissSession:si,onDismissAll:$s}),ge==="project"&&f&&ii&&t.jsx(R4,{onResume:q.openModelOnboarding}),ge==="project"&&f&&ai&&t.jsx(T4,{onOpenModelOnboarding:q.openModelOnboarding,onOpenSettings:ht=>q.openSettings(ht)}),ge==="project"&&f&&w&&M&&S&&!z&&t.jsx(A4,{latestVersion:M,currentVersion:S,onDismiss:_}),ge==="project"&&f&&!k&&R&&!ft&&t.jsx(cg,{hasAiProvider:y,hasGithub:N,onDismiss:Ot}),t.jsx("div",{className:`project-content${ge==="project"&&f?" project-content--with-footer":""}${Oe&&!ye?" project-content--with-mobile-nav":""}`,children:Yi()}),ge==="project"&&f&&!_e&&t.jsx(C4,{tasks:h&&V.tasks.length>0?V.tasks:ee,projectId:f.id,taskStuckTimeoutMs:Ft,backgroundSessions:ie,backgroundGenerating:C,backgroundNeedsInput:P,onOpenBackgroundSession:ws,onDismissBackgroundSession:j,lastFetchTimeMs:We,currentProjectPath:f.path,onOpenProjectDirectory:os}),t.jsx(I4,{view:ce,onChangeView:ge==="project"&&f?O:()=>{},footerVisible:ge==="project"&&!!f,modalOpen:q.anyModalOpen,keyboardOpen:ye,onOpenSettings:je,onOpenActivityLog:q.openActivityLog,onOpenSystemStats:q.openSystemStats,onOpenMailbox:()=>O("mailbox"),mailboxUnreadCount:oe,onOpenGitManager:q.openGitManager,onOpenWorkflowSteps:q.openWorkflowSteps,onOpenSchedules:q.openSchedules,onOpenScripts:q.openScripts,onToggleTerminal:q.toggleTerminal,onOpenFiles:q.openFiles,onOpenGitHubImport:q.openGitHubImport,onOpenPlanning:q.openPlanning,onResumePlanning:q.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:()=>q.openUsage(null),onViewAllProjects:An,onRunScript:q.runScript,projectId:f?.id,showSkillsTab:ze,experimentalFeatures:{insights:Ct,roadmap:Et,memoryView:tn,devServer:At,devServerView:At,todoView:H}}),ge==="project"&&f&&ce!=="chat"&&ce!=="mailbox"&&ce!=="insights"&&ce!=="devserver"&&ce!=="dev-server"&&t.jsx(iP,{projectId:f.id,addToast:n,showFAB:Xt,open:dt,onOpenChange:pt,favoriteProviders:Pt,favoriteModels:ln,onToggleFavorite:on,onToggleModelFavorite:Ut}),t.jsx(h4,{projectId:f?.id,tasks:ee,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:q,projectActions:{handleAddProject:ae,handleSetupComplete:Je,handleModelOnboardingComplete:ut},taskHandlers:{handleModalCreate:Ye,handlePlanningTaskCreated:nt,handlePlanningTasksCreated:mt,handleSubtaskTasksCreated:Nt,handleGitHubImport:Lt},taskOperations:{moveTask:ue,deleteTask:se,mergeTask:Ce,retryTask:De,duplicateTask:et},deepLink:{handleDetailClose:G},settings:{prAuthAvailable:$t,themeMode:E,colorTheme:$,setThemeMode:B,setColorTheme:J},onSettingsClose:()=>{q.closeSettings(),X()},onReopenOnboarding:()=>{q.closeSettings(),q.openModelOnboarding()}}),t.jsx(FP,{open:jt})]})}function eI(){return t.jsx(hP,{children:t.jsx(zP,{children:t.jsx(Ew,{children:t.jsx(ZP,{})})})})}Mv();hv();wg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(pv,{children:t.jsx(eI,{})})}));"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{Ij as $,Ts as A,Nn as B,yn as C,go as D,NT as E,Ui as F,$o as G,FD as H,vn as I,lc as J,Sn as K,rt as L,Us as M,sn as N,Qt as O,zn as P,_T as Q,Tn as R,ma as S,ed as T,Tj as U,kT as V,wT as W,Gt as X,Pj as Y,Bn as Z,g$ as _,ds as a,B$ as a$,un as a0,zI as a1,OI as a2,Uy as a3,vc as a4,fa as a5,Ma as a6,pi as a7,fi as a8,mi as a9,yr as aA,tw as aB,ED as aC,MD as aD,nw as aE,sw as aF,U4 as aG,Pr as aH,gg as aI,Gh as aJ,Po as aK,Xh as aL,$4 as aM,O4 as aN,xs as aO,Li as aP,ji as aQ,zd as aR,P$ as aS,$$ as aT,I$ as aU,D$ as aV,L$ as aW,z$ as aX,O$ as aY,F$ as aZ,U$ as a_,_D as aa,TD as ab,RD as ac,AD as ad,PD as ae,Zn as af,as as ag,ev as ah,Zs as ai,bx as aj,To as ak,wi as al,HD as am,UD as an,BD as ao,qD as ap,pr as aq,Hb as ar,or as as,hx as at,ss as au,ep as av,Vo as aw,cP as ax,CD as ay,ou as az,S$ as b,UI as b$,H$ as b0,q$ as b1,V$ as b2,W$ as b3,G$ as b4,J$ as b5,K$ as b6,Ln as b7,Zc as b8,Fi as b9,dj as bA,a$ as bB,nd as bC,oj as bD,lj as bE,cj as bF,rj as bG,QI as bH,Er as bI,zo as bJ,Ub as bK,hr as bL,Ib as bM,Q$ as bN,X$ as bO,Z$ as bP,eD as bQ,tD as bR,nD as bS,sD as bT,Y$ as bU,ap as bV,ba as bW,Fj as bX,yv as bY,jv as bZ,bD as b_,ND as ba,wD as bb,SD as bc,bI as bd,xI as be,gI as bf,vI as bg,MI as bh,_I as bi,SI as bj,kI as bk,wI as bl,NI as bm,jI as bn,yI as bo,fI as bp,CI as bq,uR as br,e$ as bs,ZI as bt,r$ as bu,XI as bv,t$ as bw,n$ as bx,s$ as by,i$ as bz,Ue as c,lD as c$,FI as c0,vD as c1,BI as c2,YI as c3,KI as c4,HI as c5,GI as c6,qI as c7,JI as c8,VI as c9,DD as cA,T$ as cB,lI as cC,xc as cD,Hn as cE,cR as cF,RT as cG,cc as cH,Ho as cI,dI as cJ,rI as cK,cI as cL,uI as cM,mI as cN,qi as cO,yw as cP,qo as cQ,LD as cR,Jm as cS,zD as cT,OD as cU,EI as cV,iD as cW,rD as cX,cD as cY,oD as cZ,aD as c_,WI as ca,zg as cb,ti as cc,QA as cd,AI as ce,R$ as cf,sI as cg,iI as ch,xr as ci,C$ as cj,aI as ck,oI as cl,pI as cm,hI as cn,py as co,ay as cp,ei as cq,ry as cr,oy as cs,ly as ct,PI as cu,E$ as cv,M$ as cw,_$ as cx,Si as cy,$D as cz,w$ as d,dD as d0,hp as d1,Hd as d2,Gx as d3,uD as d4,b$ as d5,h$ as d6,f$ as d7,p$ as d8,j$ as d9,RI as dA,TI as dB,DI as dC,LI as dD,$I as dE,y$ as da,Kh as db,u$ as dc,d$ as dd,jT as de,x$ as df,Sr as dg,v_ as dh,l$ as di,o$ as dj,By as dk,c$ as dl,m$ as dm,mD as dn,hD as dp,Tb as dq,wc as dr,yD as ds,gD as dt,fD as du,xD as dv,pD as dw,A$ as dx,ID as dy,II as dz,N$ as e,fr as f,Vn as g,kD as h,ms as i,_a as j,jD as k,qn as l,Rj as m,k$ as n,z4 as o,Hs as p,Fo as q,Br as r,qs as s,ke as t,mn as u,Nw as v,v$ as w,jc as x,Xs as y,an as z};