@runfusion/fusion 0.17.1 → 0.17.2

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 (33) hide show
  1. package/dist/bin.js +1706 -787
  2. package/dist/client/assets/{AgentDetailView-BmxnuM0D.js → AgentDetailView-17J-F0Rl.js} +1 -1
  3. package/dist/client/assets/{AgentsView-1xSqjJxs.js → AgentsView-sbBkb7Wd.js} +3 -3
  4. package/dist/client/assets/ChatView-BR5cvK_B.js +1 -0
  5. package/dist/client/assets/{DevServerView-DIrmWI5T.js → DevServerView-GFFVXHVP.js} +1 -1
  6. package/dist/client/assets/{DirectoryPicker-Sqwdifcb.js → DirectoryPicker-WPDSBdT6.js} +1 -1
  7. package/dist/client/assets/{DocumentsView-Cx_02o_z.js → DocumentsView-BHpDsIIt.js} +1 -1
  8. package/dist/client/assets/{InsightsView-DAJSq4gV.js → InsightsView-Bxu0TJkt.js} +1 -1
  9. package/dist/client/assets/{MemoryView-CCIBAre3.js → MemoryView-CmnzZorw.js} +1 -1
  10. package/dist/client/assets/{NodesView-D02HxGCl.js → NodesView-CO9_4hCr.js} +1 -1
  11. package/dist/client/assets/{PiExtensionsManager-DD0fTQNf.js → PiExtensionsManager-4e3MlD62.js} +2 -2
  12. package/dist/client/assets/{PluginManager-Cfl0VBX9.js → PluginManager-DGN2rvOY.js} +1 -1
  13. package/dist/client/assets/{ResearchView-B9RqOVbr.js → ResearchView-Dsa6Gykl.js} +1 -1
  14. package/dist/client/assets/{RoadmapsView-DsH7Hicx.js → RoadmapsView-jHTOK0RQ.js} +1 -1
  15. package/dist/client/assets/{SettingsModal-Cn_CIPXu.js → SettingsModal-4Z8ZJMzD.js} +1 -1
  16. package/dist/client/assets/SettingsModal-D0kuJpBA.js +31 -0
  17. package/dist/client/assets/{SetupWizardModal-k5vqrHZU.js → SetupWizardModal-Bhumd4Rf.js} +1 -1
  18. package/dist/client/assets/{SkillsView-BIdt5cfB.js → SkillsView-MHweJTz4.js} +1 -1
  19. package/dist/client/assets/{folder-open-B3TO7t7Z.js → folder-open-BNQW9dE9.js} +1 -1
  20. package/dist/client/assets/{index-BIJgrHEn.css → index-DEVBHvyW.css} +1 -1
  21. package/dist/client/assets/index-k_85J1DS.js +682 -0
  22. package/dist/client/assets/{star-DW-M-BD_.js → star-7L86NZrT.js} +1 -1
  23. package/dist/client/assets/{upload-BzG6fknr.js → upload-DsAS6tno.js} +1 -1
  24. package/dist/client/assets/{users-DEicv0kj.js → users-D3u6f2Rz.js} +1 -1
  25. package/dist/client/index.html +2 -2
  26. package/dist/client/version.json +1 -1
  27. package/dist/extension.js +1215 -524
  28. package/dist/pi-claude-cli/package.json +1 -1
  29. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  30. package/package.json +1 -1
  31. package/dist/client/assets/ChatView-CkWkEwXL.js +0 -1
  32. package/dist/client/assets/SettingsModal-YH_rM1ZT.js +0 -31
  33. package/dist/client/assets/index-BlkXZ4C5.js +0 -682
@@ -0,0 +1,682 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-17J-F0Rl.js","assets/vendor-react-K0fH_qHe.js","assets/star-7L86NZrT.js","assets/AgentDetailView-yu8Xltqk.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-Bhumd4Rf.js","assets/DirectoryPicker-WPDSBdT6.js","assets/folder-open-BNQW9dE9.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-D0kuJpBA.js","assets/SettingsModal-4Z8ZJMzD.js","assets/SettingsModal-Dq4a5KSX.css","assets/users-D3u6f2Rz.js","assets/SettingsModal-D_AFkDJa.css","assets/AgentsView-sbBkb7Wd.js","assets/upload-DsAS6tno.js","assets/AgentsView-Bs03ptrd.css","assets/DocumentsView-BHpDsIIt.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-Bxu0TJkt.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-Dsa6Gykl.js","assets/ResearchView-BzCcDAS4.css","assets/NodesView-CO9_4hCr.js","assets/NodesView-DuAXX_0j.css","assets/ChatView-BR5cvK_B.js","assets/RoadmapsView-jHTOK0RQ.js","assets/RoadmapsView-DdGlfuu-.css","assets/SkillsView-MHweJTz4.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-CmnzZorw.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-GFFVXHVP.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
2
+ import{r as i,j as t,R as el,a as na,g as Qp,c as Ub}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"]'))a(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"&&a(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 a(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 Xp=(...e)=>e.filter((n,s,a)=>!!n&&n.trim()!==""&&a.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 Bb=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 Hb=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,a)=>a?a.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 ju=e=>{const n=Hb(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 Gl={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 qb=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Vb=i.createContext({}),Wb=()=>i.useContext(Vb),Kb=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=Wb()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Gl,width:n??u??Gl.width,height:n??u??Gl.height,stroke:e??f,strokeWidth:g,className:Xp("lucide",p,r),...!o&&!qb(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>i.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 Ze=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Kb,{ref:o,iconNode:n,className:Xp(`lucide-${Bb(ju(e))}`,`lucide-${e}`,a),...r}));return s.displayName=ju(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 Gb=[["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"}]],qs=Ze("activity",Gb);/**
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 Jb=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]],Yb=Ze("archive-restore",Jb);/**
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 Qb=[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]],Jr=Ze("archive",Qb);/**
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 Xb=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Yr=Ze("arrow-down",Xb);/**
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 Zb=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ha=Ze("arrow-left",Zb);/**
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 ex=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Qr=Ze("arrow-right",ex);/**
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 tx=[["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"}]],Zp=Ze("arrow-up-down",tx);/**
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 nx=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],ia=Ze("arrow-up",nx);/**
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 sx=[["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"}]],ix=Ze("book-open",sx);/**
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 ax=[["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"}]],Tn=Ze("bot",ax);/**
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 rx=[["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"}]],id=Ze("box",rx);/**
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 ox=[["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"}]],zr=Ze("brain",ox);/**
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 lx=[["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"}]],ef=Ze("calendar",lx);/**
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 cx=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],dx=Ze("check-check",cx);/**
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 ux=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],ns=Ze("check",ux);/**
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 mx=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],mn=Ze("chevron-down",mx);/**
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 hx=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],kl=Ze("chevron-left",hx);/**
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 px=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],In=Ze("chevron-right",px);/**
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 fx=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],hi=Ze("chevron-up",fx);/**
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 gx=[["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"}]],zs=Ze("circle-alert",gx);/**
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 bx=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Un=Ze("circle-check-big",bx);/**
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 xx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],jl=Ze("circle-dot",xx);/**
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 vx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],yx=Ze("circle-plus",vx);/**
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 wx=[["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"}]],ad=Ze("circle-question-mark",wx);/**
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 kx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],jx=Ze("circle-stop",kx);/**
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 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"}]],Xr=Ze("circle-x",Nx);/**
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 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"}]],Cx=Ze("clipboard-list",Sx);/**
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 Ex=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ii=Ze("clock",Ex);/**
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 Mx=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],tf=Ze("code",Mx);/**
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 _x=[["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"}]],Nu=Ze("columns-3",_x);/**
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 Ax=[["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"}]],ra=Ze("copy",Ax);/**
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=[["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"}]],Rx=Ze("cpu",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 Tx=[["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"}]],Ix=Ze("download",Tx);/**
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 $x=[["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"}]],Dx=Ze("ellipsis-vertical",$x);/**
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 Lx=[["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"}]],rd=Ze("ellipsis",Lx);/**
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 Ox=[["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"}]],zx=Ze("external-link",Ox);/**
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 Fx=[["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"}]],qd=Ze("eye-off",Fx);/**
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 Ux=[["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"}]],Ja=Ze("eye",Ux);/**
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 Bx=[["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"}]],di=Ze("file-code",Bx);/**
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 Hx=[["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"}]],od=Ze("file-diff",Hx);/**
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 qx=[["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"}]],Vx=Ze("file-minus",qx);/**
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 Wx=[["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"}]],nf=Ze("file-pen",Wx);/**
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 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:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]],Gx=Ze("file-plus",Kx);/**
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 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:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]],Yx=Ze("file-question-mark",Jx);/**
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 Qx=[["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"}]],Vi=Ze("file-text",Qx);/**
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 Xx=[["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"}]],Zx=Ze("file-type",Xx);/**
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 ev=[["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"}]],sf=Ze("file",ev);/**
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 tv=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],nv=Ze("flag",tv);/**
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 sv=[["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"}]],ld=Ze("folder-git-2",sv);/**
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 iv=[["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"}]],Su=Ze("folder-root",iv);/**
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 av=[["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"}]],fs=Ze("folder",av);/**
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 rv=[["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"}]],tl=Ze("funnel",rv);/**
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 ov=[["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"}]],Ks=Ze("git-branch",ov);/**
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 lv=[["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"}]],Zr=Ze("git-commit-horizontal",lv);/**
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 cv=[["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"}]],af=Ze("git-merge",cv);/**
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 dv=[["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"}]],Hs=Ze("git-pull-request",dv);/**
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 uv=[["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"}]],Nl=Ze("globe",uv);/**
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 mv=[["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"}]],Sl=Ze("grid-3x3",mv);/**
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 hv=[["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"}]],Cl=Ze("grip-vertical",hv);/**
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 pv=[["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"}]],fv=Ze("hard-drive",pv);/**
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 gv=[["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"}]],bv=Ze("heart",gv);/**
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 xv=[["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"}]],Fr=Ze("history",xv);/**
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 vv=[["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=Ze("inbox",vv);/**
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 yv=[["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"}]],rf=Ze("key",yv);/**
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 wv=[["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"}]],kv=Ze("keyboard",wv);/**
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 jv=[["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"}]],oa=Ze("layers",jv);/**
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 Nv=[["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"}]],Wi=Ze("layout-grid",Nv);/**
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 Sv=[["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"}]],pi=Ze("lightbulb",Sv);/**
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 Cv=[["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"}]],$a=Ze("link",Cv);/**
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 Ev=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],cd=Ze("list-checks",Ev);/**
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 Mv=[["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"}]],_v=Ze("list-plus",Mv);/**
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 Av=[["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"}]],El=Ze("list-tree",Av);/**
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 Pv=[["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"}]],dd=Ze("list",Pv);/**
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 Rv=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],ft=Ze("loader-circle",Rv);/**
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 Tv=[["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"}]],Ml=Ze("lock",Tv);/**
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 Iv=[["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"}]],la=Ze("mail",Iv);/**
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 $v=[["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"}]],ud=Ze("map",$v);/**
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 Dv=[["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"}]],_l=Ze("maximize-2",Dv);/**
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 Lv=[["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"}]],Ov=Ze("message-square-plus",Lv);/**
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 zv=[["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"}]],Ri=Ze("message-square",zv);/**
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 Fv=[["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"}]],eo=Ze("minimize-2",Fv);/**
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 Uv=[["path",{d:"M5 12h14",key:"1ays0h"}]],Bv=Ze("minus",Uv);/**
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 Hv=[["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"}]],Da=Ze("monitor",Hv);/**
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 qv=[["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"}]],Vv=Ze("move",qv);/**
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 Wv=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],Kv=Ze("network",Wv);/**
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 Gv=[["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"}]],md=Ze("package",Gv);/**
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 Jv=[["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"}]],of=Ze("paperclip",Jv);/**
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 Yv=[["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"}]],ui=Ze("pause",Yv);/**
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 Qv=[["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"}]],js=Ze("pencil",Qv);/**
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 Xv=[["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"}]],Yn=Ze("play",Xv);/**
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 Zv=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Nn=Ze("plus",Zv);/**
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 ey=[["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"}]],lf=Ze("radio",ey);/**
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 ty=[["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"}]],os=Ze("refresh-cw",ty);/**
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 ny=[["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"}]],Cu=Ze("rocket",ny);/**
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 sy=[["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"}]],iy=Ze("rotate-ccw",sy);/**
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 ay=[["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"}]],ry=Ze("rotate-cw",ay);/**
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 oy=[["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"}]],cf=Ze("save",oy);/**
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 ly=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Pi=Ze("search",ly);/**
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 cy=[["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"}]],sa=Ze("send",cy);/**
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 dy=[["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"}]],Ur=Ze("server",dy);/**
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 uy=[["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"}]],Rr=Ze("settings",uy);/**
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 my=[["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"}]],hy=Ze("shield-alert",my);/**
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 py=[["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"}]],fy=Ze("shield",py);/**
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 gy=[["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"}]],by=Ze("skull",gy);/**
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 xy=[["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"}]],vs=Ze("sparkles",xy);/**
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 vy=[["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"}]],nl=Ze("square-check-big",vy);/**
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 yy=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Bs=Ze("square",yy);/**
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 wy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],Es=Ze("target",wy);/**
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 ky=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Ti=Ze("terminal",ky);/**
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 jy=[["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"}]],sl=Ze("text-wrap",jy);/**
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 Ny=[["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=Ze("trash-2",Ny);/**
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 Sy=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Cy=Ze("trending-up",Sy);/**
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 Ey=[["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"}]],Al=Ze("triangle-alert",Ey);/**
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 My=[["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"}]],Eu=Ze("unlink",My);/**
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 _y=[["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"}]],ya=Ze("user",_y);/**
613
+ * @license lucide-react v1.7.0 - ISC
614
+ *
615
+ * This source code is licensed under the ISC license.
616
+ * See the LICENSE file in the root directory of this source tree.
617
+ */const Ay=[["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"}]],df=Ze("webhook",Ay);/**
618
+ * @license lucide-react v1.7.0 - ISC
619
+ *
620
+ * This source code is licensed under the ISC license.
621
+ * See the LICENSE file in the root directory of this source tree.
622
+ */const Py=[["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"}]],il=Ze("workflow",Py);/**
623
+ * @license lucide-react v1.7.0 - ISC
624
+ *
625
+ * This source code is licensed under the ISC license.
626
+ * See the LICENSE file in the root directory of this source tree.
627
+ */const Ry=[["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"}]],Mu=Ze("wrench",Ry);/**
628
+ * @license lucide-react v1.7.0 - ISC
629
+ *
630
+ * This source code is licensed under the ISC license.
631
+ * See the LICENSE file in the root directory of this source tree.
632
+ */const Ty=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],tn=Ze("x",Ty);/**
633
+ * @license lucide-react v1.7.0 - ISC
634
+ *
635
+ * This source code is licensed under the ISC license.
636
+ * See the LICENSE file in the root directory of this source tree.
637
+ */const Iy=[["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"}]],is=Ze("zap",Iy),hd="fusion:version-reload",pd="fusion:version-update";let Vd=!0;function Jl(e){Vd=e}function $y(){try{if(sessionStorage.getItem(pd))return sessionStorage.removeItem(pd),!0}catch{}return!1}function Wd(e){if(sessionStorage.getItem(hd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(hd,"1"),!Vd){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function Dy(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 Ly(e){return Dy(e)?(Wd(`chunk load error: ${e?.message??e}`),!0):!1}async function Oy(){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}}async function zy(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Vd=!1)}catch{}}const Fy=6e4;let _u=0,Yl=!1;async function Ql(){if(!(Yl||document.visibilityState!=="visible")&&!(Date.now()-_u<Fy)){_u=Date.now(),Yl=!0;try{const e=await Oy();if(e&&e!=="17a663433-7b23395c"){try{sessionStorage.setItem(pd,"1")}catch{}Wd(`build version changed: 17a663433-7b23395c -> ${e}`)}}finally{Yl=!1}}}function Uy(){zy(),window.setTimeout(()=>sessionStorage.removeItem(hd),5e3),document.addEventListener("visibilitychange",()=>{Ql()}),window.addEventListener("focus",()=>{Ql()}),window.setTimeout(()=>void Ql(),2e3)}class Pl extends i.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),!Ly(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",a=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(Al,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),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(Pl,{level:"page",onError:n,children:e})}function Xi({children:e,onError:n}){return t.jsx(Pl,{level:"modal",onError:n,children:e})}function By({children:e,onError:n}){return t.jsx(Pl,{level:"root",onError:n,children:e})}const Hy="modulepreload",qy=function(e){return"/"+e},Au={},An=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.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]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=qy(u),u in Au)return;Au[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Hy,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}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)})},Kd="fn.authToken",Pu="token",Vy="fn_token";let Pa,Ru=!1,al=!1;const fd="fn:auth-token-recovery-required";function Wy(){try{const e=window.localStorage.getItem(Kd);return e&&e.length>0?e:void 0}catch{return}}function uf(e){try{window.localStorage.setItem(Kd,e)}catch{}}function Ky(){if(!(Ru||typeof window>"u")){Ru=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Pu);if(!n)return;uf(n),e.searchParams.delete(Pu);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function La(){if(Pa!==void 0)return Pa;const e=Ky();if(e)return Pa=e,e;const n=Wy();if(n)return Pa=n,n}function Gy(e){Pa=e,al=!1,uf(e)}function Jy(){Pa=void 0,al=!1;try{window.localStorage.removeItem(Kd)}catch{}}function Tu(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Yy(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Qy(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Yy(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Tu(e.protocol)===Tu(n.protocol);return s&&a&&r}function Xy(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 ki(e){const n=La();if(!n||typeof window>"u")return e;const s=Xy(e);return!s||!Qy(s.parsed)?e:(s.parsed.searchParams.set(Vy,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function $i(e){const n=La();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Zy(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function ew(){typeof window>"u"||al||(al=!0,window.dispatchEvent(new CustomEvent(fd)))}async function tw(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();Zy(a)&&ew()}catch{}}function nw(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,La();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=La(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(tw(d),d))}}class sw extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function iw(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function _s(e){return`/api${e}`}async function L(e,n={}){const s=_s(e),a=La(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),$i(f)}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(),d=l.includes("application/json");if(l.includes("text/html")||iw(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){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 sw(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function bL(){return L("/health")}function xL(){return L("/updates/check")}function aw(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return L(`/tasks${l}`)}async function Oa(e,n){const a=_s(W(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:$i({"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 rl(e,n){const{title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:j,priority:C,source:A}=e;return L(W("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:j,priority:C,source:A})})}function ci(e,n,s){return L(W(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function rw(e,n,s,a,r,o,l,c,d){return L(W("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function ow(e,n,s,a){return L(W(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function lw(e,n,s){const a=new URLSearchParams,r=a.size>0?`?${a.toString()}`:"";return L(W(`/tasks/${e}${r}`,n),{method:"DELETE"})}function cw(e,n){return L(W(`/tasks/${e}/merge`,n),{method:"POST"})}function dw(e,n){return L(W(`/tasks/${e}/retry`,n),{method:"POST"})}function uw(e,n){return L(W(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function mw(e,n){return L(W(`/tasks/${e}/duplicate`,n),{method:"POST"})}function mf(e,n){return L(W(`/tasks/${e}/pause`,n),{method:"POST"})}function hw(e,n){return L(W(`/tasks/${e}/unpause`,n),{method:"POST"})}function pw(e,n){return L(W(`/tasks/${e}/archive`,n),{method:"POST"})}function fw(e,n){return L(W(`/tasks/${e}/unarchive`,n),{method:"POST"})}function gw(e){return L(W("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function bw(e,n){return L(W(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function xw(e,n){return L(W(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function vw(e){return L(W("/config",e))}function Rl(e){return L(W("/settings",e))}function xo(e,n){return L(W("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function yw(e){return L(W("/update-check",e))}function vL(e){return L(W("/remote/settings",e))}function yL(e,n){return L(W("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function wL(e){return L(W("/remote/status",e))}function kL(e){return L(W("/remote/install-cloudflared",e),{method:"POST"})}function jL(e){return L(W("/remote/tunnel/start",e),{method:"POST"})}function NL(e){return L(W("/remote/tunnel/stop",e),{method:"POST"})}function SL(e){return L(W("/remote/tunnel/kill-external",e),{method:"POST"})}function CL(e){return L(W("/remote/token/persistent/regenerate",e),{method:"POST"})}function EL(e,n){return L(W("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function hf(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function ML(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=hf(null,s,a);return L(W(`/remote/url${r}`,n))}function _L(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=hf(e,a,r);return L(W(`/remote/qr${o}`,s))}function AL(e){return L(W("/memory",e))}function PL(e,n){return L(W("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function RL(e){return L(W("/memory/files",e))}function TL(e,n){const s=`path=${encodeURIComponent(e)}`;return L(W(`/memory/file?${s}`,n))}function IL(e,n,s){return L(W("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function $L(e,n){let s,a=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:a=r}return L(W("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function DL(e){return L(W("/memory/dream",e),{method:"POST"})}function LL(e){return L(W("/memory/insights",e))}function OL(e,n){return L(W("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function zL(e){return L(W("/memory/extract",e),{method:"POST"})}function FL(e){return L(W("/memory/audit",e))}function UL(e){return L(W("/memory/stats",e))}function BL(e){return L(W("/memory/backend",e))}function HL(e){return L(W("/memory/install-qmd",e),{method:"POST"})}function qL(e,n){return L(W("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function pa(){return L("/settings/global")}function Pn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function VL(e){return L(W("/settings/scopes",e))}function WL(e){return L(W("/settings/pi-extensions",e))}function KL(e,n){return L(W("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function GL(e,n,s){return L(W("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function JL(){return L("/pi-settings")}async function YL(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function QL(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function XL(e){return L(W("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Br(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(_s(W(`/tasks/${e}/attachments`,s)),{method:"POST",headers:$i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function ww(e,n,s){return L(W(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Iu(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=W(`/tasks/${e}/logs${r}`,n),l=await fetch(_s(o),{headers:$i()});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(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function kw(e,n,s,a){return L(W(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function jw(e,n,s){return L(W(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Nw(e,n){return L(W(`/tasks/${e}/documents`,n))}function Sw(e,n,s){return L(W(`/tasks/${e}/documents/${n}/revisions`,s))}async function ZL(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 a=s.toString(),r=`/documents${a?`?${a}`:""}`;return L(W(r,n))}function eO(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return L(W(r,e))}function $u(e,n,s,a,r){return L(W(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function Cw(e,n,s){return L(W(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Ew(e,n,s){return L(W(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Mw(e,n,s){return L(W(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function _w(e,n){return L(W(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Aw(e,n,s){return L(W(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ds(){return L("/models")}function Pw(){return L("/usage")}function Rw(){return L("/providers/claude-cli/status")}function Tw(){return L("/system/fn-binary/status")}function Iw(){return L("/system/fn-binary/install",{method:"POST"})}function $w(){return L("/providers/droid-cli/status")}async function tO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/hermes/status${n}`)}async function nO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await L(`/providers/hermes/profiles${n}`)).profiles??[]}async function sO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/openclaw/status${n}`)}async function iO(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),L(`/providers/paperclip/status?${n.toString()}`)}async function aO(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 rO(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 oO(e){return L("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function lO(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 cO(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 dO(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 uO(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 Dw(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Lw(e){return L("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function Ow(){const n=(await L("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function zw(e){return L("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function mO(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return L(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function hO(e){return L(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function Fw(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return zw({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function Hr(){return L("/auth/status")}function Uw(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Bw(e,n){return L("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function Hw(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function qw(e){return L("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Vw(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Ww(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Kw(e,n,s,a){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function Gw(e,n,s,a){return L(W("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Jw(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Yw(e,n,s,a){return L(W("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Qw(e){return L(W("/git/remotes",e))}function Xw(e){return L(W("/git/remotes/detailed",e))}function Zw(e,n,s){return L(W("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function ek(e,n){return L(W(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function tk(e,n,s){return L(W(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function nk(e,n,s){return L(W(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function sk(e,n,s){return L(W(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function ik(e,n){return L(W(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function ak(e,n){return(await L(W("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function vo(e,n,s,a){return L(W("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Du(e,n){return L(W(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rk(e){return L(W("/terminal/sessions",e))}function oi(e){return L(W("/git/status",e))}function ok(e,n){const s=e?`?limit=${e}`:"";return L(W(`/git/commits${s}`,n))}function ol(e,n){return L(W(`/git/commits/${e}/diff`,n))}function lk(e){return L(W("/git/commits/ahead",e))}function ck(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(W(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function or(e){return L(W("/git/branches",e))}function dk(e,n,s){const a=`?limit=${n}`;return L(W(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function uk(e){return L(W("/git/worktrees",e))}function mk(e,n,s){return L(W("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function hk(e,n){return L(W(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Lu(e,n,s){const a=n?"?force=true":"";return L(W(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function pk(e,n){return L(W("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function fk(e){return L(W("/git/pull",e),{method:"POST"})}function gk(e){return L(W("/git/push",e),{method:"POST"})}function yo(e){return L(W("/git/stashes",e))}function bk(e,n){return L(W("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function xk(e,n,s){return L(W(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function vk(e,n){return L(W(`/git/stashes/${e}`,n),{method:"DELETE"})}function yk(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),L(W(`/git/diff/file?${a.toString()}`,s))}function wa(e){return L(W("/git/changes",e))}function Ou(e,n){return L(W("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function wk(e,n){return L(W("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function zu(e,n){return L(W("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function kk(e,n){return L(W("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function jk(e){return L(W("/workspaces",e))}function Nk(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),L(`/files?${a.toString()}`)}function Sk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function Ck(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Ek(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),L(`/files/search?${a.toString()}`)}function Mk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function _k(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ak(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function Pk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function pf(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function Rk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function Tk(e,n,s){return L(W("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Ik(e,n,s,a,r){return L(W("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function $k(e,n,s,a){return L(W("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function Dk(e,n,s){return L(W(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Lk(e,n,s){return L(W(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function ff(e,n,s){return L(W("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function pO(e,n,s,a){return L(W("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function fO(e,n,s){return L(W("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function gO(e,n){return L(W("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function Ok(e,n,s){return L(W("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function zk(e,n,s){return L(W("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Fk(e,n,s){return L(W("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const gd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(gd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Uk(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ya(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const x=Number.parseInt(g,10);return Number.isFinite(x)?d!==null&&x<=d?!1:(d=x,!0):!0},h=()=>{if(o)return;const p=Uk(e,d),g=new EventSource(ki(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const y=b;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),gd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return gd.add(f),f}function Fu(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,a=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:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function za(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=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:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Bk(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 Hk(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>Bk(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function qk(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=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((u,m)=>({id:m+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function Uu(e){return Array.isArray(e)?e.map(Fu):(e.candidates??[]).map(Fu)}async function Vk(e){try{const n=await L(W("/dev-server/candidates",e));return Uu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(W("/dev-server/detect",e));return Uu(s)}throw n}}function Gd(e){return L(W("/dev-server/status",e)).then(za)}async function bO(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 a=s.size>0?`?${s.toString()}`:"";try{const r=await L(W(`/dev-server/logs/history${a}`,n));return Hk(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Gd(n);return qk(o.logs,e)}throw r}}function Wk(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return L(W("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(za)}function Kk(e){return L(W("/dev-server/stop",e),{method:"POST"}).then(za)}function Gk(e){return L(W("/dev-server/restart",e),{method:"POST"}).then(za)}async function Jk(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await L(W("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return za(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await L(W("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return za(r)}throw a}}function xO(e){return _s(W("/dev-server/logs/stream",e))}async function vO(e){try{return(await L(W("/devserver",e))).sessions??[]}catch{try{const n=await Gd(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function yO(e,n){try{return await L(W(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Gd(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function wO(e,n){try{return await L(W(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Wk({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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function kO(e,n){try{return await L(W(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Kk(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function jO(e,n){try{return await L(W(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Gk(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function NO(e,n,s){try{const a=await L(W(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await Jk({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function SO(e){try{return(await L(W("/devserver/detect",e))).candidates??[]}catch{try{return(await Vk(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function CO(e,n){return _s(W(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function to(e,n,s=25e3){const a=setInterval(()=>{FN(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function Yk(e,n){return _s(W(`/planning/${encodeURIComponent(e)}/stream`,n))}function Qk(e,n){return _s(W(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function EO(e,n,s,a){const r=Qk(e,n),o=Ya(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function Xk(e,n,s,a){const r=Yk(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ya(r,{onOpen:()=>{c(),o=to(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function no(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function Zk(e){return L(no("/routines",e))}function ej(e,n){return L(no("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Bu(e,n,s){return L(no(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function tj(e,n){await L(no(`/routines/${e}`,n),{method:"DELETE"})}function nj(e,n){return L(no(`/routines/${e}/trigger`,n),{method:"POST"})}function Hu(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 sj(e){const n=W("/activity",e);return L(n,{method:"DELETE"})}function so(e){return L(W("/workflow-steps",e))}function qu(e,n){return L(W("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function ij(e,n,s){return L(W(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function aj(e,n){return L(W(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Vu(e,n){return L(W(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function rj(e,n){return L(W(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function oj(){return L("/workflow-step-templates")}function lj(e,n){return L(W(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function qr(e){return L(W("/scripts",e))}function cj(e,n,s){return L(W("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function dj(e,n){return L(W(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function gf(e,n,s){return(await L(W("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const wo={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 bf(e){if(!(e instanceof Error))return wo.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?wo.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?wo.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:wo.NETWORK}function uj(e,n){return L(W("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function mj(e,n,s){return L(W(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function hj(e,n){return _s(W(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function pj(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ya(hj(e,n),{onOpen:()=>{l(),r=to(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function fj(e,n,s,a){return L(W("/subtasks/create-tasks",a),{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 xf(e,n,s){return L(W("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function W(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function gj(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Tl(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=gj(e,s,a);return L(o,r)}function fa(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 a=s.size>0?`?${s.toString()}`:"";return L(`/agents${a}`)}function bd(e,n){return L(W(`/agents/${encodeURIComponent(e)}`,n))}function bj(e,n){return L(W("/agents",n),{method:"POST",body:JSON.stringify(e)})}function xj(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function MO(e,n){return L(W(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function _O(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function AO(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function PO(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function RO(e,n){return L(W(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function TO(e,n,s){const a=`path=${encodeURIComponent(n)}`;return L(W(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function IO(e,n,s,a){return L(W(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function vj(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function yj(e,n){return L(W(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $O(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/runs${r}`)}function DO(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function LO(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function OO(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(W(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function zO(e,n){return L(W(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function wj(e){return L(W("/agents/stats",e))}function FO(e,n){return L(W(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function UO(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return L(`/agents/org-tree${a?`?${a}`:""}`)}function BO(e,n){return L(W(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Wu(e,n,s){return L(W(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function HO(e,n){return L(W(`/agents/${encodeURIComponent(e)}/tasks`,n))}function qO(){return L("/agents/companies")}function VO(e,n){return L(W("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function WO(e,n){return L(W("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function KO(e,n){return L(W(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function GO(e){return L(W("/backups",e))}function JO(e){return L(W("/backups",e),{method:"POST"})}function YO(e,n){const s=W("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(a)}function QO(e,n,s){return L(W("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function Ku(){return L("/projects/across-nodes")}function Tr(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function ll(){return L("/nodes")}function XO(){return L("/docker-nodes")}function ZO(e){return L("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function kj(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function jj(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Nj(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Sj(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 ez(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=La();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return L(d)}function Cj(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function vf(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function Gu(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function Ej(e){return L(W("/executor/stats",e))}function Mj(e){return L(W("/system-stats",e))}function _j(e){return L(W("/kill-vitest",e),{method:"POST"})}function Ju(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 Aj(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Pj(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function tz(){return L("/global-concurrency")}function nz(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Rj(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function yf(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return L(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Tj(e){return L(W("/missions",e))}function Ij(e,n){return L(W("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wf(e,n){return L(W(`/missions/${encodeURIComponent(e)}`,n))}function $j(e,n,s){return L(W(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Dj(e,n){return L(W(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Lj(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return L(W(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Oj(e){return L(W("/missions/health",e))}function zj(e,n,s){return L(W(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Fj(e,n,s){return L(W(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Uj(e,n){return L(W(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Bj(e,n,s){return L(W(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Hj(e,n,s){return L(W(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function qj(e,n){return L(W(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Vj(e,n){return L(W(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Wj(e,n,s){return L(W(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Kj(e,n,s){return L(W(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Gj(e,n){return L(W(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Jj(e,n,s){return L(W(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Yj(e,n){return L(W(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Qj(e,n,s,a){return L(W(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Xj(e,n){return L(W(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Xl(e,n){return L(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Zj(e,n,s){return L(W(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function eN(e,n,s){return L(W(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function tN(e,n,s){return L(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function nN(e,n,s){return L(W(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function sN(e,n){return L(W(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Zl(e,n){return L(W(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Yu(e,n){return L(W(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function iN(e,n){return L(W(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Qu(e,n){return L(W(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function aN(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return L(W(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function rN(e,n){return L(W(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function oN(e,n){return L(W(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function lN(e,n){return L(W(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function cN(e,n){return L(W(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function dN(e,n,s){return L(W(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function uN(e,n,s){return L(W("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function mN(e,n,s,a){return L(W("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function hN(e,n,s){return L(W(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function kf(e,n,s){return L(W("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function pN(e,n,s){return L(W("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function fN(e,n,s,a){const r=_s(W(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ya(r,{onOpen:()=>{c(),o=to(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function io(e,n,s){return W(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function ao(e,n,s){return W(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function gN(e,n){return L(io(e,"/start",n),{method:"POST"})}function bN(e,n,s,a){return L(io(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function xN(e,n,s,a){const r=_s(io(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ya(r,{onOpen:()=>{c(),o=to(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function vN(e,n,s){return L(io(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function yN(e,n){return L(io(e,"/skip",n),{method:"POST"})}function wN(e,n){return L(ao(e,"/start",n),{method:"POST"})}function kN(e,n,s,a){return L(ao(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function jN(e,n,s,a){const r=_s(ao(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ya(r,{onOpen:()=>{c(),o=to(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function NN(e,n,s){return L(ao(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function SN(e,n){return L(ao(e,"/skip",n),{method:"POST"})}async function CN(e,n){try{return await L(W(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function sz(e){return L(W("/roadmaps",e))}function iz(e,n){return L(W("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function az(e,n){return L(W(`/roadmaps/${encodeURIComponent(e)}`,n))}function rz(e,n,s){return L(W(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oz(e,n){return L(W(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function lz(e,n,s){return L(W(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function cz(e,n,s){return L(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function dz(e,n){return L(W(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function uz(e,n,s){return L(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function mz(e,n,s){return L(W(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function hz(e,n){return L(W(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function pz(e,n,s){return L(W(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function fz(e,n,s){return L(W(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function gz(e,n,s,a){return L(W(`/roadmaps/features/${encodeURIComponent(e)}/move`,a),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function bz(e,n){return L(W(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function xz(e,n,s,a){return L(W(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,a),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function vz(e,n,s){return L(W(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function EN(e){return L(W("/todos",e))}function MN(e,n){const s={title:e};return L(W("/todos",n),{method:"POST",body:JSON.stringify(s)})}function _N(e,n,s){const a={title:n};return L(W(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function AN(e,n){return L(W(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function PN(e,n,s){const a={text:n};return L(W(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function RN(e,n,s){const a=n;return L(W(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function TN(e,n){return L(W(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function IN(e,n,s){return L(W(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Fa(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Jd(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(_s(`/ai-sessions${a?`?${a}`:""}`),{headers:$i()});return r.ok?(await r.json()).sessions??[]:[]}async function $N(e){return L(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function DN(e){return L(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function wi(e){const n=await fetch(_s(`/ai-sessions/${encodeURIComponent(e)}`),{headers:$i()});return n.ok?n.json():null}async function LN(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 ON(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function zN(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function jf(e){await fetch(_s(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:$i()})}function FN(e,n){return L(W(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function UN(e,n,s){return L(W(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function BN(e,n){return L(W(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function HN(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 a=s.size>0?`?${s.toString()}`:"";return L(`/messages/inbox${a}`)}function qN(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 a=s.size>0?`?${s.toString()}`:"";return L(`/messages/outbox${a}`)}function Nf(e){return L(W("/messages/unread-count",e))}function VN(e,n){return L(W("/messages",n),{method:"POST",body:JSON.stringify(e)})}function WN(e,n){return L(W(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function KN(e){return L(W("/messages/read-all",e),{method:"POST"})}function GN(e,n){return L(W(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function JN(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(W(a,s))}function YN(e,n){return L(W(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function yz(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function wz(e,n){return L(W(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function kz(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/performance${r}`)}function jz(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function Nz(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function Sz(e,n){return L(W(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function Cz(e,n,s){return L(W(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function Ez(e,n){return L(W(`/agents/${encodeURIComponent(e)}/budget`,n))}function Mz(e,n){return L(W(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function _z(e){return L(W("/plugins",e))}async function Az(e,n){return L(W("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function Pz(e,n){return L(W(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function Rz(e,n){return L(W(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function Tz(e,n){return L(W(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Iz(e,n){return L(W(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function $z(e,n,s){return L(W(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function Dz(e,n){return L(W(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function QN(e){return L(W("/plugins/ui-slots",e))}async function XN(e){return L(W("/plugins/dashboard-views",e))}async function Lz(e){return L(W("/plugins/runtimes",e))}async function ZN(e){return(await L(W("/skills/discovered",e))).skills}async function Oz(e,n,s){return L(W("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function zz(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return L(W(`/skills/catalog${r}`,s))}async function Fz(e,n){return(await L(W(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Xu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return L(`/chat/sessions${a?`?${a}`:""}`)}async function e1(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&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),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await L(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function t1(e,n){return L(W("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function n1(e,n){return L(W(`/chat/sessions/${encodeURIComponent(e)}`,n))}function Uz(e,n,s){return L(W(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Bz(e,n){return L(W(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ec(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return L(W(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function s1(e,n){return L(W(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function i1(e,n,s,a,r,o){const l=_s(W(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1;const u=(m,h)=>{if(m)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"fallback":try{s.onFallback?.(JSON.parse(h))}catch{}break;case"done":try{s.onDone?.(JSON.parse(h))}catch{s.onDone?.({messageId:""})}break;case"error":try{const f=JSON.parse(h);s.onError?.(f.message||f)}catch{s.onError?.(h||"Stream error")}break}};return(async()=>{try{const m=Array.isArray(a)&&a.length>0,h=m?(()=>{const j=new FormData;return j.append("content",n),a.forEach(C=>j.append("attachments",C)),j})():JSON.stringify({content:n}),f=await fetch(l,{method:"POST",headers:m?$i():$i({"Content-Type":"application/json"}),body:h,signal:c.signal});if(!f.ok){const j=await f.text();let C=`Request failed: ${f.status}`;try{C=JSON.parse(j).error||C}catch{}s.onError?.(C);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let x="",v="",b=[];const y=(j,C=!1)=>{x+=j;const A=x.split(`
638
+ `);x=A.pop()||"",C&&x.length>0&&(A.push(x),x="");for(const N of A){const S=N.endsWith("\r")?N.slice(0,-1):N;if(S.startsWith("event:"))v=S.slice(6).trim();else if(S.startsWith("data:")){const _=S.slice(5);b.push(_.startsWith(" ")?_.slice(1):_)}else if(S===""){const _=b.join(`
639
+ `);u(v,_),v="",b=[]}}if(C&&v&&b.length>0){const N=b.join(`
640
+ `);u(v,N),v="",b=[]}};for(;;){const{done:j,value:C}=await p.read();if(j){y(g.decode(),!0);break}y(g.decode(C,{stream:!0}))}}catch(m){if(m instanceof DOMException&&m.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(m instanceof Error?m.message:"Connection error")}})(),{close:()=>{d=!0,c.abort()},isConnected:()=>!d}}function Hz(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 a=s.size>0?`?${s.toString()}`:"";return L(W(`/insights${a}`,n))}function qz(e,n){return L(W(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function Vz(e="manual",n,s){return L(W("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function Wz(e){return L(W("/insights/runs",e))}function Kz(e,n){return L(W(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Gz(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.status&&s.set("status",e.status),e.limit!==void 0&&s.set("limit",String(e.limit));const a=s.size>0?`?${s.toString()}`:"";return L(W(`/research/runs${a}`,n))}function Jz(e,n){return L(W("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function Yz(e,n){return L(W(`/research/runs/${encodeURIComponent(e)}`,n))}function Qz(e,n){return L(W(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Xz(e,n){return L(W(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function Zz(e,n,s){return L(W(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function e3(e,n,s){const a=n.findingId??"finding-1";return L(W(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function t3(e,n,s){const a=n.findingId??"finding-1";return L(W(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}function a1(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 r1({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:a}=a1(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 ${a}`,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 o1(e){return e.charAt(0).toUpperCase()+e.slice(1)}function ca({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=o1(e);return t.jsxs("span",{className:`node-health-dot${a?" 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 Zu=new Map,l1=6e4;function Sf(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),u=i.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return i.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=Zu.get(m);if(p&&Date.now()<p.expiresAt){if(h||d.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await QN(e);if(h||d.current)return;Zu.set(m,{slots:x,expiresAt:Date.now()+l1}),s(x),c.current=!0}catch(x){if(h||d.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!d.current&&r(!1)}}return f(),()=>{h=!0}},[e]),i.useEffect(()=>{c.current=!1,d.current=!1},[e]),i.useEffect(()=>()=>{d.current=!0},[]),i.useMemo(()=>({slots:n,getSlotsForId:u,loading:a,error:o}),[n,u,a,o])}function Hi({slotId:e,projectId:n,pluginIds:s}){const{getSlotsForId:a,loading:r,error:o}=Sf(n);if(r||o||!e)return null;const l=a(e).filter(c=>s&&s.length>0?s.includes(c.pluginId):!0);return l.length===0?null:t.jsx(Pl,{level:"page",children:t.jsx(t.Fragment,{children:l.map((c,d)=>t.jsxs("section",{className:"plugin-slot-shell","data-plugin-slot":!0,"data-slot-id":c.slot.slotId,"data-plugin-id":c.pluginId,"aria-label":c.slot.label,children:[t.jsx("p",{className:"plugin-slot-shell__title",children:c.slot.label}),t.jsx("p",{className:"plugin-slot-shell__message",children:"Extension content available."})]},`${c.pluginId}-${c.slot.slotId}-${d}`))})})}function c1(){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 Di(){const[e,n]=i.useState(c1);return i.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),a=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):a.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),a.addEventListener("change",r),()=>{s.removeEventListener("change",r),a.removeEventListener("change",r)}},[]),e}function Qa(e){return e.replace(/\\/g,"/")}function Yd(e){return e.replace(/[\\/]+$/g,"")}function Qd(e){const n=Qa(Yd(e));return n?n.split("/").filter(Boolean):[]}function Xd(e){const n=Qa(Yd(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Cf(e,n){const s=Qd(e);return s.length===0?Qa(e):s.slice(-2).join("/")}function d1(e){const n=Qa(Yd(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function u1(e,n){return!e||e==="."?n:[...Qd(e),n].join("/")}function m1(e){const n=Qd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function n3(e){const n=Qa(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 a=n.split("/").filter(Boolean);return a.map((r,o)=>({label:r,path:a.slice(0,o+1).join("/")}))}const h1="dependency-graph-positions";function Ef(e){return`kb:${e??"default"}:${h1}`}function p1(e){if(typeof window>"u")return{};try{const n=window.localStorage.getItem(Ef(e));return n?JSON.parse(n)??{}:{}}catch{return{}}}function f1(e,n){typeof window>"u"||window.localStorage.setItem(Ef(e),JSON.stringify(n))}const g1=new Set(["triage","todo","in-progress","in-review"]),ka=18,Zi=9,b1=3,x1=4,em=.5,ko=2,v1=2,jo=.4,No=2,y1=.002,w1=768;function So(e,n){return Math.hypot(e.x-n.x,e.y-n.y)}function k1(){return typeof window>"u"?!1:window.matchMedia(`(max-width: ${w1}px)`).matches}function j1({context:e}){const[n,s]=i.useState(1),[a,r]=i.useState({x:0,y:0}),[o,l]=i.useState({}),[c,d]=i.useState(null),[u,m]=i.useState(null),h=i.useMemo(()=>p1(e.projectId),[e.projectId]),f=i.useRef(null),p=i.useRef(new Map),g=i.useRef(null),x=i.useRef(null),v=i.useRef(!1),b=i.useMemo(()=>e.tasks.filter(U=>g1.has(U.column)),[e.tasks]),y=i.useMemo(()=>b.map((U,k)=>{const I=o[U.id]??h[U.id];return{task:U,x:I?.x??k%4*(ka+b1),y:I?.y??Math.floor(k/4)*(Zi+x1)}}),[o,h,b]),j=i.useMemo(()=>new Map(y.map(U=>[U.task.id,U])),[y]),C=i.useMemo(()=>{const U=[];return y.forEach(k=>{(k.task.dependencies??[]).forEach(I=>{const $=j.get(I);$&&U.push({from:I,to:k.task.id,x1:$.x+ka,y1:$.y+Zi/2,x2:k.x,y2:k.y+Zi/2})})}),U},[j,y]),A=i.useMemo(()=>{if(y.length===0)return{minX:0,minY:0,width:ka*2,height:Zi*2};const U=Math.min(...y.map(w=>w.x))-ko,k=Math.min(...y.map(w=>w.y))-ko,I=Math.max(...y.map(w=>w.x+ka))+ko,$=Math.max(...y.map(w=>w.y+Zi))+ko;return{minX:U,minY:k,width:Math.max(ka*2,I-U),height:Math.max(Zi*2,$-k)}},[y]),N=i.useMemo(()=>y.map(U=>({...U,renderX:U.x-A.minX,renderY:U.y-A.minY})),[A.minX,A.minY,y]),S=i.useMemo(()=>C.map(U=>({...U,renderX1:U.x1-A.minX,renderY1:U.y1-A.minY,renderX2:U.x2-A.minX,renderY2:U.y2-A.minY})),[A.minX,A.minY,C]),_=i.useMemo(()=>{const U=new Map,k=new Map;return C.forEach(I=>{U.set(I.from,(U.get(I.from)??new Set).add(I.to)),k.set(I.to,(k.get(I.to)??new Set).add(I.from))}),{downstream:U,upstream:k}},[C]),T=u??c,M=i.useMemo(()=>{if(!T)return null;const U=new Set([T]),k=(I,$)=>{const w=[I];for(;w.length>0;){const H=w.shift();H&&($.get(H)??new Set).forEach(J=>{U.has(J)||(U.add(J),w.push(J))})}};return k(T,_.downstream),k(T,_.upstream),U},[_.downstream,_.upstream,T]),E=i.useCallback(()=>{const U=f.current;if(!U)return;const k=Number.parseFloat(globalThis.getComputedStyle(document.documentElement).fontSize)||16,I=A.width*k,$=A.height*k,w=v1*k,H=Math.max(1,U.clientWidth-w*2),J=Math.max(1,U.clientHeight-w*2),fe=Math.min(No,Math.max(jo,Math.min(H/I,J/$))),de=(U.clientWidth-I*fe)/(2*k*fe),D=(U.clientHeight-$*fe)/(2*k*fe);s(fe),r({x:de,y:D})},[A.width,A.height]);i.useEffect(()=>{if(v.current||!k1()||y.length===0)return;const U=f.current;U&&(U.clientWidth===0||U.clientHeight===0||(v.current=!0,requestAnimationFrame(()=>{E()})))},[E,y.length]);const O=(U,k)=>{l(I=>({...I,[U]:k})),f1(e.projectId,{...h,...o,[U]:k})},B=(U,k)=>{if(d($=>$===U?null:U),k.button!==0)return;k.preventDefault(),k.stopPropagation();const I=j.get(U);I&&(p.current.set(k.pointerId,{x:k.clientX,y:k.clientY}),g.current={kind:"node",taskId:U,startPointer:{x:k.clientX,y:k.clientY},startNode:{x:I.x,y:I.y},moved:!1})},R=U=>{if(U.button===0){if(p.current.set(U.pointerId,{x:U.clientX,y:U.clientY}),p.current.size===2){g.current=null;const[k,I]=Array.from(p.current.values()),$=So(k,I);x.current={startDistance:$,startScale:n};return}g.current={kind:"pan",startPointer:{x:U.clientX,y:U.clientY},startPan:a,moved:!1}}},P=U=>{if(p.current.has(U.pointerId)&&p.current.set(U.pointerId,{x:U.clientX,y:U.clientY}),p.current.size>=2&&x.current){const[w,H]=Array.from(p.current.values()),fe=So(w,H)/x.current.startDistance,de=Math.min(No,Math.max(jo,x.current.startScale*fe));s(de);return}const k=g.current;if(!k)return;const I={x:(U.clientX-k.startPointer.x)/16,y:(U.clientY-k.startPointer.y)/16};if(k.kind==="node"){if(So({x:0,y:0},I)>em&&!k.moved&&(k.moved=!0),!k.moved)return;l(H=>({...H,[k.taskId]:{x:k.startNode.x+I.x/n,y:k.startNode.y+I.y/n}}));return}So({x:0,y:0},I)>em&&!k.moved&&(k.moved=!0),k.moved&&r({x:k.startPan.x+I.x,y:k.startPan.y+I.y})},F=U=>{if(p.current.delete(U.pointerId),x.current){p.current.size<2&&(x.current=null);return}const k=g.current;if(g.current=null,!!k&&k.kind==="node"){const I=j.get(k.taskId);if(!I)return;if(!k.moved){e.openTaskDetail(I.task);return}O(k.taskId,{x:I.x,y:I.y})}},q=U=>{p.current.delete(U.pointerId),x.current=null,g.current=null},ee=U=>{U.preventDefault();const k=f.current;if(!k)return;const I=Number.parseFloat(globalThis.getComputedStyle(document.documentElement).fontSize)||16,$=-U.deltaY*y1,w=Math.min(No,Math.max(jo,n*(1+$))),H=k.getBoundingClientRect(),J=U.clientX-H.left,fe=U.clientY-H.top,de=w/n,D=J/I*(1-de)/n,_e=fe/I*(1-de)/n;s(w),r(z=>({x:z.x+D*w/n,y:z.y+_e*w/n}))};return t.jsxs("section",{className:"dependency-graph-view",children:[t.jsxs("div",{className:"dependency-graph-controls",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>s(U=>Math.min(U+.1,No)),children:"Zoom In"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>s(U=>Math.max(U-.1,jo)),children:"Zoom Out"}),t.jsx("button",{className:"btn btn-sm",onClick:E,children:"Fit"})]}),t.jsx("div",{className:"dependency-graph-canvas",ref:f,onPointerDown:R,onPointerMove:P,onPointerUp:F,onPointerCancel:q,onWheel:ee,children:b.length===0?t.jsx("div",{className:"dependency-graph-empty",children:t.jsx("p",{children:"No tasks to display. Tasks in Triage, Todo, In Progress, or In Review columns will appear here."})}):t.jsxs("div",{className:"dependency-graph-scene",style:{width:`${A.width}rem`,height:`${A.height}rem`,transform:`translate(${a.x}rem, ${a.y}rem) scale(${n})`,transformOrigin:"top left"},children:[t.jsx("svg",{className:"dependency-graph-edges",viewBox:`0 0 ${A.width} ${A.height}`,children:S.map(U=>t.jsx("line",{x1:U.renderX1,y1:U.renderY1,x2:U.renderX2,y2:U.renderY2,className:`dependency-graph-edge${M?M.has(U.from)&&M.has(U.to)?" is-related":" is-dimmed":""}`},`${U.from}-${U.to}`))}),N.map(U=>t.jsx("div",{className:`dependency-graph-node${c===U.task.id?" is-selected":""}${M?M.has(U.task.id)?" is-related":" is-dimmed":""}`,style:{width:`${ka}rem`,minHeight:`${Zi}rem`,transform:`translate(${U.renderX}rem, ${U.renderY}rem)`},onPointerDown:k=>B(U.task.id,k),onPointerEnter:()=>m(U.task.id),onPointerLeave:()=>m(k=>k===U.task.id?null:k),children:e.renderTaskCard(U.task)},U.task.id))]})})]})}const N1=[{pluginId:"fusion-plugin-dependency-graph",viewId:"graph",component:j1}];function Ir(e,n){return`plugin:${e}:${n}`}function S1(e){if(!e.startsWith("plugin:"))return null;const[,n,...s]=e.split(":"),a=s.join(":");return!n||!a?null:{pluginId:n,viewId:a}}function C1(e,n){return N1.find(a=>a.pluginId===e&&a.viewId===n)?.component??null}function E1({pluginId:e,viewId:n}){return t.jsxs("section",{className:"card plugin-dashboard-view-missing",children:[t.jsxs("h2",{className:"plugin-dashboard-view-missing-title",children:[t.jsx(Al,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["The dashboard could not resolve ",t.jsxs("code",{children:[e,":",n]})," from the host registry."]})]})}const M1={activity:qs,bot:Tn,brain:zr,checksquare:nl,clock:Ii,filetext:Vi,folder:fs,gitbranch:Ks,grid3x3:Sl,layoutgrid:Wi,mail:la,map:ud,messagesquare:Ri,monitor:Da,search:Pi,sparkles:vs,target:Es,workflow:il,zap:is};function _1(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function cl(e){return M1[_1(e)]??Sl}const Mf={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function A1({projects:e,currentProject:n,onViewAll:s,onSelectProject:a}){const[r,o]=i.useState(!1),l=i.useRef(null);i.useEffect(()=>{if(!r)return;const d=u=>{l.current&&!l.current.contains(u.target)&&o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),i.useEffect(()=>{if(!r)return;const d=u=>{u.key==="Escape"&&o(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=i.useCallback(d=>{a?.(d),o(!1)},[a]);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(d=>!d),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(mn,{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(d=>{const u=n?.id===d.id,m=Mf[d.status]?.color;return t.jsxs("button",{className:`project-selector-item${u?" project-selector-item--current":""}`,onClick:()=>c(d),role:"option","aria-selected":u,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:d.name}),t.jsx("span",{className:"project-selector-path",children:Cf(d.path)})]}),u&&t.jsx(ns,{size:14,className:"project-selector-check"})]},d.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 tm({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 P1({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:f,showNodesButton:p,onOpenWorkflowSteps:g,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:j,onOpenTodos:C,todosOpen:A,todosEnabled:N,globalPaused:S,enginePaused:_,onToggleGlobalPause:T,onToggleEnginePause:M,view:E="board",onChangeView:O,showSkillsTab:B,showAgentsTab:R,searchQuery:P="",onSearchChange:F,projects:q=[],currentProject:ee,onSelectProject:U,onViewAllProjects:k,projectId:I,isElectron:$=!1,mobileNavEnabled:w,availableNodes:H=[],currentNode:J,onSelectNode:fe,isRemote:de=!1,experimentalFeatures:D,pluginDashboardViews:_e=[]}){const z=Di(),Z=z==="mobile",Y=Z||z==="tablet",ae=Z&&w,[ce,te]=i.useState(!1),[Re,be]=i.useState(!1),[ke,Ue]=i.useState(!1),[Ge,qe]=i.useState(!1),[Ae,Ee]=i.useState(!1),[ie,se]=i.useState(!1),[xe,ne]=i.useState(!1),[Fe,Qe]=i.useState(!1),[ge,ze]=i.useState(!1),[tt,pt]=i.useState(!1),[ve,le]=i.useState(!1),[Te,pe]=i.useState({}),[$e,st]=i.useState(!1),[at,rt]=i.useState(-1),[Oe,Be]=i.useState(null),[et,jt]=i.useState({}),[De,vt]=i.useState(!1),Et=i.useRef(null),bt=i.useRef(null),zt=i.useRef(null),qt=i.useRef(null),It=i.useRef(null),_t=i.useRef(null),Xt=i.useRef(!1),Lt=i.useRef(null),Ut=i.useRef(null),cn=i.useRef(null),Jt=i.useRef(null),Vt=i.useRef(null),Kt=i.useRef(null),rn=i.useRef(null),fn=i.useRef(null),on=i.useRef(!1),gn=i.useMemo(()=>H.filter(ye=>ye.type==="remote"),[H]),je=gn.length>0,Le=i.useMemo(()=>Object.entries(Te).sort(([ye],[ut])=>ye.localeCompare(ut)),[Te]),re=Le.length>0,Pe=Le.length+(re?1:0),Se=i.useMemo(()=>Object.entries(et).sort(([ye],[ut])=>ye.localeCompare(ut)),[et]),X=i.useMemo(()=>_e.some(ye=>ye.pluginId==="fusion-plugin-roadmap"),[_e]),Ie=i.useMemo(()=>!!(D?.researchView||N||D?.insights||D?.roadmap&&!X||B||D?.memoryView||D?.devServerView||!ae||_e.some(ye=>ye.view.placement!=="primary")),[D,N,B,ae,_e,X]),he=i.useCallback(()=>{const ye=window.visualViewport;return ye&&ye.width>0&&ye.height>0?{width:ye.width,height:ye.height,offsetTop:ye.offsetTop,offsetLeft:ye.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ne=i.useCallback(()=>{const ye=rn.current;if(!ye)return;const ut=ye.getBoundingClientRect(),Qt=fn.current,{width:Cn,height:ue,offsetTop:dt,offsetLeft:wt}=he(),gt=16,ot=16,yt=6,Ft=Qt?.offsetWidth||Math.max(ut.width,260),Zt=Math.min(Ft,Math.max(Cn-gt*2,160)),Ln=Qt?.offsetHeight||280,Wt=Math.min(Ln,Math.max(ue-ot*2,160)),Mt=ut.top-dt,En=ut.bottom-dt,Xn=ut.right-wt,ts=ue-En,Ps=Mt,ws=ts<Wt&&Ps>ts,Bn=Math.min(Math.max(Xn-Zt,gt),Cn-gt-Zt)+wt,rs=ws?Math.max(ot+dt,Mt-Wt-yt+dt):Math.min(En+yt+dt,ue+dt-ot-Wt);Be({top:rs,left:Bn,width:Zt})},[he]),Je=i.useCallback((ye,ut)=>{v?.(ye,ut),le(!1),rt(-1)},[v]),kt=i.useCallback(()=>{x?.(),le(!1),rt(-1)},[x]),Yt=i.useCallback(ye=>{switch(ye.key){case"ArrowDown":ye.preventDefault(),Pe>0&&rt(ut=>ut<Pe-1?ut+1:0);break;case"ArrowUp":ye.preventDefault(),Pe>0&&rt(ut=>ut>0?ut-1:Pe-1);break;case"Enter":if(ye.preventDefault(),at>=0)if(at<Le.length){const[ut,Qt]=Le[at];Je(ut,Qt)}else re&&at===Le.length&&kt();break;case"Home":ye.preventDefault(),Pe>0&&rt(0);break;case"End":ye.preventDefault(),Pe>0&&rt(Pe-1);break}},[kt,Je,at,Le,re,Pe]);i.useEffect(()=>{Xt.current=Ae},[Ae]),i.useEffect(()=>{on.current=ve},[ve]),i.useEffect(()=>{if(!Ae||!Y)return;let ye=!1;return vt(!0),qr(I).then(ut=>{ye||jt(ut)}).catch(()=>{ye||jt({})}).finally(()=>{ye||vt(!1)}),()=>{ye=!0}},[Ae,Y,I]),i.useEffect(()=>{if(!ve||Y)return;let ye=!1;return st(!0),qr(I).then(ut=>{ye||pe(ut)}).catch(()=>{ye||pe({})}).finally(()=>{ye||st(!1)}),()=>{ye=!0}},[ve,Y,I]),i.useEffect(()=>{if(!ve)return;const ye=ut=>{Kt.current&&!Kt.current.contains(ut.target)&&le(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[ve]),i.useEffect(()=>{if(!ve)return;const ye=ut=>{ut.key==="Escape"&&(le(!1),rn.current?.focus())};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[ve]),i.useEffect(()=>{if(ve){rt(-1);const ye=window.setTimeout(()=>fn.current?.focus(),0);return()=>window.clearTimeout(ye)}Be(null)},[ve]),i.useEffect(()=>{if(!ve)return;const ye=requestAnimationFrame(()=>{Ne()});return()=>cancelAnimationFrame(ye)},[ve,$e,Le.length,re,Ne]),i.useEffect(()=>{if(!ve)return;const ye=()=>Ne();window.addEventListener("resize",ye),window.addEventListener("scroll",ye,!0);const ut=window.visualViewport;return ut&&(ut.addEventListener("resize",ye),ut.addEventListener("scroll",ye)),()=>{window.removeEventListener("resize",ye),window.removeEventListener("scroll",ye,!0),ut&&(ut.removeEventListener("resize",ye),ut.removeEventListener("scroll",ye))}},[ve,Ne]),i.useEffect(()=>{Y&&(le(!1),rt(-1))},[Y]);const $t=ce||P.length>0,Tt=(Re||P.length>0)&&!ke,Bt=(E==="board"||E==="list")&&!Z&&F&&!ke&&P.length===0,jn=(E==="board"||E==="list")&&!Z&&F;i.useEffect(()=>{P===""&&Ue(!1)},[P]),i.useEffect(()=>{if(!Ge)return;const ye=ut=>{bt.current&&!bt.current.contains(ut.target)&&Et.current&&!Et.current.contains(ut.target)&&qe(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[Ge]),i.useEffect(()=>{if(!ge)return;const ye=ut=>{qt.current&&!qt.current.contains(ut.target)&&zt.current&&!zt.current.contains(ut.target)&&ze(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[ge]),i.useEffect(()=>{if(!ie)return;const ye=ut=>{Lt.current&&!Lt.current.contains(ut.target)&&se(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[ie]),i.useEffect(()=>{const ye=ut=>{if(ut.key==="Escape"){if(Qe(!1),ze(!1),Xt.current){Ee(!1);return}if(on.current){le(!1),rn.current?.focus();return}qe(!1),te(!1),se(!1),ne(!1)}};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[]),i.useEffect(()=>{if(!xe)return;const ye=ut=>{Ut.current&&!Ut.current.contains(ut.target)&&ne(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[xe]),i.useEffect(()=>{if(!tt)return;const ye=ut=>{Vt.current&&!Vt.current.contains(ut.target)&&pt(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[tt]),i.useEffect(()=>{if(!tt)return;const ye=ut=>{ut.key==="Escape"&&pt(!1)};return document.addEventListener("keydown",ye),()=>document.removeEventListener("keydown",ye)},[tt]),i.useEffect(()=>{if(!Fe)return;const ye=ut=>{cn.current&&!cn.current.contains(ut.target)&&Jt.current&&!Jt.current.contains(ut.target)&&Qe(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[Fe]);const Dn=i.useCallback(()=>{te(ye=>!ye)},[]),hn=i.useCallback(()=>{be(!0),Ue(!1)},[]),Ht=i.useCallback(()=>{be(!1),Ue(!0),F&&F("")},[F]),yn=i.useCallback(()=>{qe(ye=>!ye)},[]),pn=i.useCallback(ye=>{ye&&ye(),qe(!1),Ee(!1)},[]),es=i.useCallback(()=>{te(!1),F&&F("")},[F]);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"})]}),Z&&q.length>=1&&U&&t.jsxs("div",{className:"mobile-project-switch",ref:Ut,children:[t.jsx("button",{className:`mobile-project-switch-trigger${xe?" mobile-project-switch-trigger--open":""}`,onClick:()=>ne(ye=>!ye),title:"Switch project","aria-label":"Switch project","aria-expanded":xe,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(mn,{size:14,className:`mobile-project-switch-chevron${xe?" mobile-project-switch-chevron--open":""}`})}),xe&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:q.map(ye=>{const ut=ee?.id===ye.id,Qt=Mf[ye.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ut?" mobile-project-switch-item--current":""}`,onClick:()=>{U(ye),ne(!1)},role:"option","aria-selected":ut,"data-testid":`mobile-project-switch-item-${ye.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Qt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:ye.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Cf(ye.path)})]}),ut&&t.jsx(ns,{size:14,className:"mobile-project-switch-check"})]},ye.id)})})]}),!Y&&q.length>=1&&k&&t.jsx(A1,{projects:q,currentProject:ee??null,onViewAll:k,onSelectProject:U}),je&&t.jsxs("div",{className:`header-node-selector${Z?" header-node-selector--mobile":""}`,ref:Z?void 0:Lt,children:[t.jsx(r1,{node:J??null,showDetails:!Z}),!Z&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${ie?" node-selector-trigger--open":""}`,onClick:()=>se(ye=>!ye),title:"Switch node","aria-label":"Switch node","aria-expanded":ie,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(In,{size:12,className:`node-selector-chevron${ie?" node-selector-chevron--open":""}`})}),ie&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${de?"":" node-selector-option--active"}`,onClick:()=>{fe?.(null),se(!1)},role:"option","aria-selected":!de,"data-testid":"node-option-local",children:[t.jsx(ca,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),gn.map(ye=>t.jsxs("button",{className:`node-selector-option${J?.id===ye.id?" node-selector-option--active":""}`,onClick:()=>{fe?.(ye),se(!1)},role:"option","aria-selected":J?.id===ye.id,"data-testid":`node-option-${ye.id}`,children:[t.jsx(ca,{status:ye.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:ye.name}),t.jsx("span",{className:"node-selector-option-status",children:ye.status})]},ye.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ae&&O&&(E==="board"||E==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>O("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Wi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>O("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(dd,{size:16})})]}),F&&Z&&(ae||E==="board"||E==="list")&&!$t&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Dn,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Pi,{size:16})}),Bt&&t.jsx("button",{className:"btn-icon",onClick:hn,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Pi,{size:16})}),Z&&ae&&o&&t.jsx("button",{className:"btn-icon",onClick:ye=>o(ye.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(qs,{size:16})}),!ae&&O&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${E==="board"?" active":""}`,onClick:()=>O("board"),title:"Board view","aria-label":"Board view","aria-pressed":E==="board",children:t.jsx(Wi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="list"?" active":""}`,onClick:()=>O("list"),title:"List view","aria-label":"List view","aria-pressed":E==="list",children:t.jsx(dd,{size:16})}),R&&t.jsx("button",{className:`view-toggle-btn${E==="agents"?" active":""}`,onClick:()=>O("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":E==="agents",children:t.jsx(Tn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="missions"?" active":""}`,onClick:()=>O("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":E==="missions",children:t.jsx(Es,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="chat"?" active":""}`,onClick:()=>O("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":E==="chat",children:t.jsx(Ri,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="documents"?" active":""}`,onClick:()=>O("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":E==="documents",children:t.jsx(Vi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${E==="mailbox"?" active":""}`,onClick:()=>O("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":E==="mailbox",children:t.jsx(la,{size:16})}),_e.filter(ye=>ye.view.placement==="primary").sort((ye,ut)=>(ye.view.order??Number.MAX_SAFE_INTEGER)-(ut.view.order??Number.MAX_SAFE_INTEGER)).map(ye=>{const ut=Ir(ye.pluginId,ye.view.viewId),Qt=cl(ye.view.icon);return t.jsx("button",{className:`view-toggle-btn${E===ut?" active":""}`,onClick:()=>O(ut),title:`${ye.view.label} view`,"aria-label":`${ye.view.label} view`,"aria-pressed":E===ut,"data-testid":`view-toggle-plugin-${ye.pluginId}-${ye.view.viewId}`,children:t.jsx(Qt,{size:16})},`${ye.pluginId}:${ye.view.viewId}`)}),Ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Jt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(E)||N&&A||E.startsWith("plugin:")?" active":""}`,onClick:()=>Qe(ye=>!ye),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Fe,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(mn,{size:12})}),Fe&&t.jsxs("div",{ref:cn,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[D?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="research"?" active":""}`,onClick:()=>{O("research"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Pi,{size:14}),t.jsx("span",{children:"Research"})]}),D?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="insights"?" active":""}`,onClick:()=>{O("insights"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(vs,{size:14}),t.jsx("span",{children:"Insights"})]}),D?.roadmap&&!X&&t.jsx("button",{className:`view-toggle-overflow-item${E==="roadmaps"?" active":""}`,onClick:()=>{O("roadmaps"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:t.jsx("span",{children:"Roadmaps"})}),B&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="skills"?" active":""}`,onClick:()=>{O("skills"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(is,{size:14}),t.jsx("span",{children:"Skills"})]}),D?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="memory"?" active":""}`,onClick:()=>{O("memory"),Qe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(zr,{size:14}),t.jsx("span",{children:"Memory"})]}),D?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${E==="dev-server"||E==="devserver"?" active":""}`,onClick:()=>{O("devserver"),Qe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Da,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),N&&C&&t.jsxs("button",{className:`view-toggle-overflow-item${A?" active":""}`,onClick:()=>{C(),Qe(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(nl,{size:14}),t.jsx("span",{children:"Todos"})]}),_e.filter(ye=>ye.view.placement!=="primary").sort((ye,ut)=>(ye.view.order??Number.MAX_SAFE_INTEGER)-(ut.view.order??Number.MAX_SAFE_INTEGER)).map(ye=>{const ut=Ir(ye.pluginId,ye.view.viewId),Qt=cl(ye.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${E===ut?" active":""}`,onClick:()=>{O(ut),Qe(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${ye.pluginId}-${ye.view.viewId}`,children:[t.jsx(Qt,{size:14}),t.jsx("span",{children:ye.view.label})]},`${ye.pluginId}:${ye.view.viewId}`)})]})]})]}),!Y&&o&&t.jsx("button",{className:"btn-icon",onClick:ye=>o(ye.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(qs,{size:16})}),!Y&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(Da,{size:16})}),!Y&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Fr,{size:16})}),!Y&&!$&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(tm,{size:16})}),!Y&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&a?a:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(pi,{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})]}),!Y&&t.jsxs("div",{className:"terminal-split-btn",ref:Kt,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(Ti,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:rn,className:`btn-icon terminal-split-btn__chevron${ve?" btn-icon--active":""}`,onClick:()=>le(ye=>!ye),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ve,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(mn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ve?" rotate":""}`})}),ve&&t.jsx("div",{ref:fn,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:Yt,"data-testid":"quick-scripts-dropdown",style:Oe?{position:"fixed",top:`${Oe.top}px`,left:`${Oe.left}px`,width:`${Oe.width}px`,right:"auto"}:void 0,children:$e?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(ft,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Le.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(Ti,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:kt,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Le.map(([ye,ut],Qt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${at===Qt?"highlighted":""}`,onClick:()=>Je(ye,ut),role:"option","aria-selected":at===Qt,"data-testid":`quick-script-item-${ye}`,children:[t.jsx(Yn,{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:ye}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ut,children:ut.length>50?`${ut.slice(0,50)}...`:ut})]})]},ye))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${re&&at===Le.length?"highlighted":""}`,onClick:kt,"data-testid":"quick-scripts-manage",children:[t.jsx(Rr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Y&&y&&t.jsx("button",{className:`btn-icon${j?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(fs,{size:16})}),!Y&&N&&C&&t.jsx("button",{className:`btn-icon${A?" btn-icon--active":""}`,onClick:C,title:"Open todos","data-testid":"todos-toggle-btn",children:t.jsx(nl,{size:16})}),!Y&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Ks,{size:16})}),!Y&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(il,{size:16})}),!Y&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:zt,className:"btn-icon",onClick:()=>ze(ye=>!ye),title:"More actions","aria-label":"More actions","aria-expanded":ge,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(rd,{size:16})}),ge&&t.jsxs("div",{ref:qt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),ze(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Ur,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{pn(m),ze(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Ii,{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${S?" btn-icon--stopped":""}`,onClick:T,title:S?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:S?t.jsx(Yn,{size:16}):t.jsx(Bs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${tt?" btn-icon--active":""}`,onClick:()=>pt(ye=>!ye),title:"Engine options","aria-haspopup":"menu","aria-expanded":tt,"data-testid":"engine-control-chevron-btn",children:t.jsx(mn,{size:12})}),tt&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${_?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),pt(!1)},role:"menuitem",title:_?"Resume scheduling":"Pause triage",disabled:!!S,"data-testid":"engine-control-pause-triage-btn",children:[_?t.jsx(Yn,{size:14}):t.jsx(ui,{size:14}),t.jsx("span",{children:_?"Resume scheduling":"Pause triage"})]})})]}),!Y&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Rr,{size:16})}),t.jsx(Hi,{slotId:"header-action",projectId:I}),Y&&!ae&&t.jsx("button",{ref:Et,className:"btn-icon compact-overflow-trigger",onClick:yn,title:"More header actions","aria-label":"More header actions","aria-expanded":Ge,"aria-haspopup":"menu",children:t.jsx(rd,{size:16})}),Y&&!ae&&Ge&&t.jsxs("div",{ref:bt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[q.length>=1&&k&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(k),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Sl,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(fs,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>pn(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(pi,{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:()=>pn(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Ks,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Ur,{size:16}),t.jsx("span",{children:"Nodes"})]}),!$&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(n),role:"menuitem",children:[t.jsx(tm,{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:()=>pn(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Ti,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Ee(ye=>!ye),role:"menuitem","aria-expanded":Ae,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(In,{size:14,className:`mobile-overflow-chevron${Ae?" mobile-overflow-chevron--open":""}`})})]}),Ae&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:De?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(ft,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Se.length>0?t.jsxs(t.Fragment,{children:[Se.map(([ye,ut])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(ye,ut),qe(!1),Ee(!1)},role:"menuitem","data-testid":`overflow-script-item-${ye}`,children:[t.jsx(Yn,{size:14}),t.jsx("span",{children:ye})]},ye)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>pn(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(di,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>pn(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(di,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Ii,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Fr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(la,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:ye=>pn(()=>o(ye.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(qs,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(il,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>pn(e),role:"menuitem",children:[t.jsx(Rr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),jn&&Tt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Pi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:P,onChange:ye=>F(ye.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Ht,"aria-label":"Close search",children:t.jsx(tn,{size:14})})]})}),F&&Z&&$t&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:It,className:"header-search mobile-search-expanded",children:[t.jsx(Pi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:_t,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:P,onChange:ye=>F(ye.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:es,"aria-label":"Close search",children:t.jsx(tn,{size:14})})]})})]})}const R1={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,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","fallback-used"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli: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,persistAgentToolOutput:!0,researchGlobalDefaults:{searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},maxSourcesPerRun:20,defaultExportFormat:"markdown"},researchGlobalEnabled:!0,researchGlobalMaxConcurrentRuns:3,researchGlobalDefaultTimeout:3e5,researchGlobalMaxSourcesPerRun:20,researchGlobalMaxSynthesisRounds:2,researchWebSearchProvider:"none",researchSearxngUrl:void 0,researchBraveApiKey:void 0,researchGoogleSearchApiKey:void 0,researchGoogleSearchCx:void 0,researchTavilyApiKey:void 0,researchGitHubEnabled:!1,researchLocalDocsEnabled:!0,researchMaxSearchResults:10,researchFetchTimeoutMs:3e4,researchUserAgent:"FusionResearchBot/1.0",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}},experimentalFeatures:{}},T1={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,completionDocumentationMode:"off",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:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,researchSettings:{enabled:!0,searchProvider:void 0,synthesisProvider:void 0,synthesisModelId:void 0,enabledSources:{webSearch:!0,pageFetch:!0,github:!1,localDocs:!0,llmSynthesis:!0},limits:{maxConcurrentRuns:3,maxSourcesPerRun:20,maxDurationMs:3e5,requestTimeoutMs:3e4}},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},I1=Object.freeze(Object.keys(R1)),$1=Object.freeze(Object.keys(T1));function s3(e){return I1.includes(e)}function i3(e){return $1.includes(e)}function Me(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function D1(e){return!!(e?.provider&&e?.modelId)}function Ki(...e){for(const n of e)if(D1(n))return{provider:n.provider,modelId:n.modelId};return{}}function Il(e){return Ki({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function L1(e){return Ki({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Il(e))}function O1(e){return Ki({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Il(e))}function z1(e){return Ki({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Il(e))}function a3(e){return Ki({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Il(e))}function _f(e,n){return Ki({provider:e.modelProvider,modelId:e.modelId},L1(n))}function Af(e,n){return Ki({provider:e.validatorModelProvider,modelId:e.validatorModelId},z1(n))}function Pf(e,n){return Ki({provider:e.planningModelProvider,modelId:e.planningModelId},O1(n))}const r3=["off","minimal","low","medium","high"],aa=["triage","todo","in-progress","in-review","done","archived"],Xa=["low","normal","high","urgent"],Cs="normal",F1=["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"],ss={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},U1={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"},xd={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 B1(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 H1(e,n=1400){const s=i.useRef(null),[a,r]=i.useState(!1),o=i.useRef(null);return i.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]),a}function q1({isOpen:e,options:n,onConfirm:s,onCancel:a}){const r=i.useRef(null);return i.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),a())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,a]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:a,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:a,"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:a,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const Rf=i.createContext(null);function V1({children:e}){const[n,s]=i.useState([]),a=i.useRef([]),r=i.useCallback(u=>{s(m=>{const h=u(m);return a.current=h,h})},[]),o=i.useCallback(u=>new Promise(m=>{r(h=>[...h,{options:u,resolve:m}])}),[r]),l=i.useCallback(u=>{const m=a.current[0];m&&(m.resolve(u),r(h=>h.slice(1)))},[r]),c=n[0]??null,d=i.useMemo(()=>({confirm:o}),[o]);return el.createElement(Rf.Provider,{value:d},e,el.createElement(q1,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Gs(){const e=i.useContext(Rf);return e||{confirm:async n=>!1}}function W1(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 Tf({prInfo:e,issueInfo:n,onIssueRefresh:s}){const a=()=>{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:a,children:[t.jsx(Hs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${W1(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(jl,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Co(e,n){return`${e??"default"}:${n}`}class K1{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,a=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)a.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of a){const l=Co(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=Co(this.projectId,s),r=this.subscriptionsByTask.get(a)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(a,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const a=Co(this.projectId,s),r=this.subscriptionsByTask.get(a);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(a),this.badgeUpdates.delete(a),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 a=s.split(":").slice(1).join(":");this.unsubscribeTask(n,a)}}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 a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(a+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(ki(a));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=Co(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:nm(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:nm(l,"issueInfo")?l.issueInfo??null:d?.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,a=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},a),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 ea=new K1;let G1=0;function nm(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function If(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${G1++}`);const s=i.useSyncExternalStore(o=>ea.subscribe(o),()=>ea.getSnapshot(),()=>ea.getSnapshot()),a=i.useCallback(o=>{ea.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{ea.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{ea.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{ea.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function dl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function J1({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=If(o),u=!!(n||s);i.useEffect(()=>{if(!u||!r){d(e);return}return c(e),()=>{d(e)}},[u,r,o,c,e,d]);const m=l.get(`${o??"default"}:${e}`),h=dl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=dl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(Tf,{prInfo:h,issueInfo:f})}const Y1=i.memo(J1);Y1.displayName="TaskCardBadge";const Q1={sm:16,md:20,lg:24};function X1({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 sm({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 bi({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 Z1({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 im({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 eS({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 tc({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 am({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 rm({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 om({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 lr({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 lm({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 nc({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 cm({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 sc({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 tS({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 nS({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 dm({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 ic({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 sS({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 um({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 ac({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 mm({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 rc({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 hm({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"})]})}function iS({size:e,color:n,label:s="Factory AI — via Droid 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":"droid-cli-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"3",width:"14",height:"14",rx:"3",fill:n}),t.jsx("path",{d:"M6.5 7.5h2.6a2.9 2.9 0 1 1 0 5.8H6.5zM9 7.5v5.8",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round"}),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 aS={anthropic:{component:X1,color:"var(--provider-anthropic)"},"claude-cli":{component:hm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:hm,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:iS,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},openai:{component:sm,color:"var(--provider-openai)"},"openai-codex":{component:sm,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:bi,color:"var(--provider-gemini)"},gemini:{component:bi,color:"var(--provider-gemini)"},"google-antigravity":{component:bi,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:bi,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:bi,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:bi,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:bi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:bi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:bi,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:bi,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:Z1,color:"var(--text)"},github:{component:um,color:"var(--text)"},"github-copilot":{component:um,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:sS,color:"var(--provider-openrouter)"},minimax:{component:im,color:"var(--provider-minimax)"},"minimax-cn":{component:im,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:eS,color:"var(--provider-zai)"},kimi:{component:tc,color:"var(--provider-kimi)"},moonshot:{component:tc,color:"var(--provider-kimi)"},"kimi-coding":{component:tc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:am,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:am,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:rm,color:"var(--text)"},grok:{component:rm,color:"var(--text)",label:"xAI"},opencode:{component:om,color:"var(--provider-opencode)"},"opencode-go":{component:om,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:lr,color:"var(--provider-qwen)"},"qwen-ai":{component:lr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:lr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:lr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:lr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:lm,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:lm,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:nc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:nc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:nc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:cm,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:cm,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:sc,color:"var(--provider-azure)"},"azure-openai":{component:sc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:sc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:ic,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:ic,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:ic,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:tS,color:"var(--provider-cerebras)"},groq:{component:nS,color:"var(--provider-groq)"},vercel:{component:dm,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:dm,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:ac,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:ac,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:ac,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:mm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:mm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:rc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:rc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:rc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Qn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=aS[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=Q1[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(Rx,{size:c})})}const ei={data:new Map,pendingPromise:null,lastFetchTime:null},rS=5e3;function Yo(e,n){return n?`${n}::${e}`:e}function oS(e,n){const s=ei.data.get(Yo(e,n));if(!(!s||Date.now()-s.timestamp>rS))return s}function lS(e){const[n,s]=i.useState(!1),a=i.useRef(null),r=i.useCallback(async c=>{let u=null;for(let m=0;m<3;m++)try{return await ak(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Me(h);if(f?.includes("429")||f?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(g=>setTimeout(g,p));continue}break}if(u)throw u;return{}},[e]),o=i.useCallback(async c=>{if(c.length===0)return;const u=Date.now()-5e3;if(c.every(f=>{const p=ei.data.get(Yo(f,e));return p&&p.timestamp>u})&&ei.lastFetchTime&&ei.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),ei.pendingPromise){s(!0);try{await ei.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ei.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))ei.data.set(Yo(g,e),{result:x,timestamp:p});ei.lastFetchTime=p}catch{}finally{ei.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>ei.data.get(Yo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ei.lastFetchTime,getBatchData:l}}const vd=new Map,cS=3e4;function $f(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function dS(e,n,s,a){const r=$f(e,n,s,a),o=vd.get(r);return o?Date.now()>o.expiresAt?(vd.delete(r),null):o.stats:null}function uS(e,n,s,a,r){const o=$f(e,n,s,a);vd.set(o,{stats:r,expiresAt:Date.now()+cS})}function mS(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,m]=i.useState(null),[h,f]=i.useState(!1);return i.useEffect(()=>{if(!o){m(null),f(!1);return}const p=n==="done"&&!!s,g=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!g){m(null),f(!1);return}const x=g?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(C=!1){if(!C){const A=dS(e,a,x,v);if(A){b||(m(A),f(!1));return}}f(!0);try{const A=await yf(e,x,a);b||(m(A.stats),uS(e,a,x,v,A.stats))}catch{b||m(null)}finally{b||f(!1)}}y();let j;return d&&g&&(j=setInterval(()=>{y(!0)},d)),()=>{b=!0,j&&clearInterval(j)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const hS=new Set(["failed","stuck-killed"]);function ul(e,n,s){if(e.column!=="in-progress"||e.status&&hS.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function pS(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function fS(e){return e==="done"||e==="skipped"}function gS(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Df(e,n){const s=(e.steps??[]).map((d,u)=>({id:`step-${u}`,name:d.name,status:d.status,source:"step",phase:"pre-merge"})),a=new Map((e.workflowStepResults??[]).map(d=>[d.workflowStepId,d])),r=(e.enabledWorkflowSteps??[]).map(d=>{const u=a.get(d);return{id:`workflow-${d}`,name:gS(d,u,n),status:u?pS(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>fS(d.status)).length;return{total:l,completed:c,items:o}}function bS(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 Lf(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",a=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||a.includes("[timing]")}).map(n=>{const a=`${n.action??""}
641
+ ${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=a?Number(a[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:bS(n)}})}function xS(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Lf(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}const yd=new Map;async function vS(e,n){const s=yd.get(e);if(s)return s;try{const a=await wf(e,n);return yd.set(e,a.title),a.title}catch{return e}}const pm=12;function yS(e){return e.length<=pm?e:e.slice(0,pm-3)+"..."}const wd=new Map;async function wS(e,n){const s=wd.get(e);if(s)return s;try{const a=await bd(e,n);return wd.set(e,a.name),a.name}catch{return e}}function kS(e){return typeof e=="string"&&Xa.includes(e)?e:Cs}function jS(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const NS=new Set(["triage","todo"]),fm=new Set(["planning","researching","executing","finalizing","merging"]),gm=new Set(["merging","merging-pr"]),SS={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},CS=new Set(["in-progress","in-review","done"]),ES=3e4;function da(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function MS(e){const n=da(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function bm(e,n){const s=da(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Cr(e,n){const s=da(e.executionStartedAt);if(s==null)return null;const a=da(e.executionCompletedAt),r=a!=null&&a>=s?a:n;return Math.max(0,r-s)}function _S(e){return e.column==="done"?MS(e):null}function Of(e,n){const s=da(e.updatedAt);return s==null?null:Math.max(0,n-s)}function AS(e,n){const s=Cr(e,n);if(s!=null)return s;const a=Of(e,n),r=Er(e,n);return r!=null?r+(a??0):a}function PS(e,n){const s=e.workflowStepResults;if(!s||s.length===0)return null;let a=0,r=0;for(const o of s){if(!o.startedAt)continue;const l=da(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const d=da(o.completedAt);if(d==null||d<l)continue;c=d}else c=Math.max(l,n);a+=c-l,r+=1}return r>0?a:null}function Er(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:xS(e.log),a=PS(e,n);return s==null&&a==null?null:(s??0)+(a??0)}function xm(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 vm(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 ym(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),a=Object.keys(n);return s.length!==a.length?!1:s.every(r=>e[r]===n[r])}function RS(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function TS(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function IS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function $S(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function DS(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(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function LS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];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 OS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function zS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function FS(e,n){const s=e.task,a=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===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&OS(s.attachments,a.attachments)&&zS(s.comments,a.comments)&&TS(s.dependencies,a.dependencies)&&RS(s.steps,a.steps)&&IS(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&LS(s.workflowStepResults,a.workflowStepResults)&&ym(s.prInfo,a.prInfo)&&ym(s.issueInfo,a.issueInfo)}function US({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:x,workflowStepNameLookup:v}){const[b,y]=i.useState(!1),[j,C]=i.useState(!1),[A,N]=i.useState(!1),[S,_]=i.useState(e.description||""),[T,M]=i.useState(!1),[E,O]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(he=>he.status==="done"||he.status==="skipped")),[B,R]=i.useState(null),[P,F]=i.useState(null),[q,ee]=i.useState(!1),[U,k]=i.useState(!1),[I,$]=i.useState(()=>Date.now()),w=i.useRef(null),H=i.useRef(!1),J=i.useRef(null),fe=i.useRef(null),[de,D]=i.useState(!1),{badgeUpdates:_e,subscribeToBadge:z,unsubscribeFromBadge:Z}=If(n),{confirm:oe}=Gs(),Y=i.useRef(null),ae=i.useRef(!1),ce=i.useCallback(he=>he instanceof Element?!!he.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{_(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!q)return;const he=Ne=>{fe.current&&!fe.current.contains(Ne.target)&&ee(!1)};return document.addEventListener("click",he),()=>document.removeEventListener("click",he)},[q]),i.useEffect(()=>{if(!e.missionId){R(null);return}const he=yd.get(e.missionId);if(he){R(he);return}let Ne=!1;return vS(e.missionId,n).then(Je=>{Ne||R(Je)}),()=>{Ne=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){F(null);return}const he=wd.get(e.assignedAgentId);if(he){F(he);return}F(null);let Ne=!1;return wS(e.assignedAgentId,n).then(Je=>{Ne||F(Je)}),()=>{Ne=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(A&&w.current){const he=w.current;he.focus(),he.style.height="auto",he.style.height=he.scrollHeight+"px"}},[A]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){D(!0);return}const he=J.current;if(!he)return;const Ne=new IntersectionObserver(([Je])=>{D(Je?.isIntersecting??!0)},{rootMargin:"200px"});return Ne.observe(he),()=>Ne.disconnect()},[A,e.id]);const te=i.useCallback(he=>{he.dataTransfer.setData("text/plain",e.id),he.dataTransfer.effectAllowed="move",y(!0)},[e.id]),Re=i.useCallback(()=>{y(!1)},[]),be=i.useCallback(he=>he.dataTransfer.types.includes("Files"),[]),ke=i.useCallback(he=>{be(he)&&(he.preventDefault(),he.stopPropagation(),he.dataTransfer.dropEffect="copy",C(!0))},[be]),Ue=i.useCallback(he=>{be(he)&&(he.preventDefault(),he.stopPropagation(),C(!1))},[be]),Ge=i.useCallback(async he=>{if(!be(he))return;he.preventDefault(),he.stopPropagation(),C(!1);const Ne=Array.from(he.dataTransfer.files);for(const Je of Ne)try{await Br(e.id,Je,n),r(`Attached ${Je.name} to ${e.id}`,"success")}catch(kt){r(`Failed to attach ${Je.name}: ${Me(kt)}`,"error")}},[e.id,be,r]),qe=i.useCallback(()=>{A||a(e)},[e,a,A]),Ae=i.useCallback(he=>{if(H.current){H.current=!1;return}ce(he.target)||qe()},[qe,ce]),Ee=i.useCallback(he=>{const Ne=he.touches[0];Ne&&(Y.current={x:Ne.clientX,y:Ne.clientY,time:Date.now()},ae.current=!1)},[]),ie=i.useCallback(he=>{if(!Y.current)return;const Ne=he.touches[0];if(!Ne)return;const Je=Math.abs(Ne.clientX-Y.current.x),kt=Math.abs(Ne.clientY-Y.current.y);(Je>wm||kt>wm)&&(ae.current=!0)},[]),se=i.useCallback(he=>{if(ce(he.target)||!Y.current)return;const Je=Date.now()-Y.current.time<BS,kt=!ae.current;Je&&kt&&(H.current=!0,qe()),Y.current=null,ae.current=!1},[qe,ce]),xe=i.useCallback(async(he,Ne)=>{he.stopPropagation();try{const Je=await Oa(Ne,n);a(Je)}catch{r(`Failed to load dependency ${Ne}`,"error")}},[a,r]),ne=e.status==="failed",Fe=e.paused===!0,Qe=kS(e.priority),ge=Qe!==Cs,ze=ul(e,f,x),tt=e.column==="triage"&&e.status==="awaiting-approval",pt=e.column==="archived",ve=!o&&!s&&!ne&&!Fe&&!ze&&!tt&&(e.column==="in-progress"||fm.has(e.status)),le=!s&&!Fe&&!A&&!pt,Te=NS.has(e.column)&&!ve&&!Fe&&!s&&l,pe=!!(e.prInfo||e.issueInfo),$e=e.sourceType==="github_import",st=$S(e.sourceMetadata),at=!!(e.assignedAgentId&&P===null),rt=i.useMemo(()=>{const he=[];return e.modelProvider&&he.push(e.modelProvider),e.validatorModelProvider&&!he.includes(e.validatorModelProvider)&&he.push(e.validatorModelProvider),e.planningModelProvider&&!he.includes(e.planningModelProvider)&&he.push(e.planningModelProvider),he},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Oe=i.useMemo(()=>Df(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),Be=Oe.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const he=e.status!=null&&gm.has(e.status);if(e.column==="in-progress"){const Je=Cr(e,Date.now()),kt=bm(e,Date.now()),Yt=Er(e,Date.now());if(Je==null&&kt==null&&Yt==null)return}if(!he&&e.column==="in-review"){const Je=Cr(e,Date.now()),kt=Er(e,Date.now());if(Je==null&&kt==null)return}$(Date.now());const Ne=window.setInterval(()=>{$(Date.now())},ES);return()=>window.clearInterval(Ne)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const et=i.useMemo(()=>{if(!CS.has(e.column))return null;if(e.status!=null&&gm.has(e.status)){const $t=AS(e,I);if($t!=null){const Tt=vm($t);if(Tt){const Bt=Of(e,I),jn=Bt==null?null:xm(Bt),Dn=jn?`Execution time ${Tt}. Merge phase ${jn}`:`Execution time ${Tt}. Merging`;return{label:Tt,title:Dn,ariaLabel:Dn}}}}if(e.column==="in-progress"){const $t=Cr(e,I)??bm(e,I)??Er(e,I);if($t==null)return null;const Tt=xm($t);return Tt?{label:Tt,title:`In progress ${Tt}`,ariaLabel:`In progress ${Tt}`}:null}const Ne=Cr(e,I)??Er(e,I);if(Ne==null)return null;const Je=vm(Ne);if(!Je)return null;const kt=_S(e);if(kt==null)return{label:Je,title:`Execution time ${Je}`,ariaLabel:`Execution time ${Je}`};const Yt=new Date(kt).toLocaleString();return{label:Je,title:`Execution time ${Je}. Completed ${Yt}`,ariaLabel:`Execution time ${Je}. Completed ${Yt}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,I]);i.useEffect(()=>{if(!pe||!de){Z(e.id);return}return z(e.id),()=>{Z(e.id)}},[pe,de,z,e.id,Z]);const jt=_e.get(`${n??"default"}:${e.id}`),De=e.column==="in-progress"||e.column==="in-review",vt=i.useMemo(()=>e.steps.map(he=>`${he.name}:${he.status}`).join("|"),[e.steps]),{stats:Et}=mS(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:de,worktree:e.worktree,stepVersion:De?vt:void 0,pollIntervalMs:De?3e4:void 0}),bt=i.useMemo(()=>oS(e.id,n),[e.id,n]),zt=i.useMemo(()=>{const he=jt?.prInfo,Ne=jt?.timestamp,Je=bt?.result?.prInfo,kt=bt?.timestamp?new Date(bt.timestamp).toISOString():void 0,Yt=e.prInfo,$t=e.prInfo?.lastCheckedAt??e.updatedAt;let Tt=dl(he,Ne,Yt,$t);const Bt=Ne&&Ne>=$t?Ne:$t;return Je&&kt&&(!Bt||kt>Bt)&&(Tt=Je),Tt},[jt,bt,e.prInfo,e.updatedAt]),qt=i.useMemo(()=>{const he=jt?.issueInfo,Ne=jt?.timestamp,Je=bt?.result?.issueInfo,kt=bt?.timestamp?new Date(bt.timestamp).toISOString():void 0,Yt=e.issueInfo,$t=e.issueInfo?.lastCheckedAt??e.updatedAt;let Tt=dl(he,Ne,Yt,$t);const Bt=Ne&&Ne>=$t?Ne:$t;return Je&&kt&&(!Bt||kt>Bt)&&(Tt=Je),Tt},[jt,bt,e.issueInfo,e.updatedAt]),It=i.useCallback(he=>{he?.stopPropagation(),!(!Te||T)&&(N(!0),_(e.description||""))},[Te,T,e.description]),_t=i.useCallback(()=>{N(!1),_(e.description||"")},[e.description]),Xt=i.useCallback(()=>S!==(e.description||""),[S,e.description]),Lt=i.useCallback(async()=>{if(!(!l||T)){if(!Xt()){_t();return}M(!0);try{await l(e.id,{description:S.trim()||void 0}),r(`Updated ${e.id}`,"success"),N(!1)}catch(he){r(`Failed to update ${e.id}: ${Me(he)}`,"error")}finally{M(!1)}}},[l,e.id,S,T,Xt,_t,r]),Ut=i.useCallback(he=>{he.key==="Enter"&&!he.shiftKey?(he.preventDefault(),Lt()):he.key==="Escape"&&(he.preventDefault(),_t())},[Lt,_t]),cn=i.useCallback(()=>{setTimeout(()=>{const he=document.activeElement;he===w.current||he?.closest(".card-editing-content")||(Xt()?Lt():_t())},0)},[Xt,Lt,_t]),Jt=i.useCallback(he=>{Te&&(he.stopPropagation(),It(he))},[Te,It]),Vt=i.useCallback(he=>{he.stopPropagation(),It(he)},[It]),Kt=i.useCallback(he=>{_(he.target.value);const Ne=he.target;Ne.style.height="auto",Ne.style.height=Ne.scrollHeight+"px"},[]),rn=i.useCallback(he=>{he.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(Ne=>{r(`Failed to archive ${e.id}: ${Me(Ne)}`,"error")})},[r,c,e.id]),fn=i.useCallback(he=>{he.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(Ne=>{r(`Failed to unarchive ${e.id}: ${Me(Ne)}`,"error")})},[r,d,e.id]),on=i.useCallback(async he=>{if(he.stopPropagation(),!(!u||!await oe({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(Je){const kt=DS(Je);if(!kt||kt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Me(Je)}`,"error");return}const Yt=kt.dependentIds.join(", ");if(!await oe({title:"Force Delete Task",message:`${e.id} is a dependency of ${Yt}.
642
+
643
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Tt){r(`Failed to delete ${e.id}: ${Me(Tt)}`,"error")}}},[r,oe,u,e.id]),gn=i.useCallback(he=>{he.stopPropagation(),h?.(e,"changes")},[e,h]),je=i.useCallback(he=>{he.stopPropagation(),O(Ne=>!Ne)},[]),Le=i.useCallback(he=>{he.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),re=i.useCallback(he=>{he.stopPropagation(),ee(Ne=>!Ne)},[]),Pe=i.useCallback(async(he,Ne)=>{if(he.stopPropagation(),ee(!1),!!g)try{const Je=e.steps.some($t=>$t.status!=="pending"),kt=(Ne==="todo"||Ne==="triage")&&Je;let Yt;if(kt){if(await oe({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Yt={preserveProgress:!0};else if(!await oe({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await g(e.id,Ne,Yt),r(`Moved ${e.id} to ${ss[Ne]}`,"success")}catch(Je){r(`Failed to move ${e.id}: ${Me(Je)}`,"error")}},[r,oe,g,e.id,e.steps]),Se=i.useCallback(async he=>{if(he.stopPropagation(),!(!m||U)){k(!0);try{await m(e.id)}catch(Ne){r(`Failed to retry ${e.id}: ${Me(Ne)}`,"error")}finally{k(!1)}}},[r,U,m,e.id]),X=`card${b?" dragging":""}${s?" queued":""}${ve?" agent-active":""}${ne?" failed":""}${Fe?" paused":""}${ze?" stuck":""}${tt?" awaiting-approval":""}${j?" file-drop-target":""}${A?" card-editing":""}${T?" card-saving":""}`,Ie=(()=>{if(e.column==="in-progress"){const he=Et?.filesChanged,Ne=he==null||he===0?e.modifiedFiles?.length:void 0,Je=he!=null&&he>0?he:Ne;return Je==null||Je===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:gn,disabled:!h,children:[t.jsx(fs,{size:12}),t.jsxs("span",{children:[Je," ",Je===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const he=Et?.filesChanged,Ne=he==null||he===0?e.modifiedFiles?.length:void 0,Je=he!=null&&he>0?he:Ne;return Je==null||Je===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:gn,disabled:!h,children:[t.jsx(fs,{size:12}),t.jsxs("span",{children:[Je," ",Je===1?"file":"files"," changed"]})]})}if(e.column==="done"){const he=Et?.filesChanged,Ne=e.mergeDetails?.filesChanged,Je=he??Ne;if(Je!=null&&Je>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:gn,disabled:!h,children:[t.jsx(fs,{size:12}),t.jsxs("span",{children:[Je," ",Je===1?"file":"files"," changed"]})]});const kt=e.modifiedFiles?.length;if(kt!=null&&kt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:gn,disabled:!h,children:[t.jsx(fs,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]})}return null})();return A?t.jsx("div",{ref:J,className:X,"data-id":e.id,onDoubleClick:Jt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:w,className:"card-edit-desc-textarea",placeholder:"Task description",value:S,onChange:Kt,onKeyDown:Ut,onBlur:cn,disabled:T,rows:4}),T&&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:J,className:X,"data-id":e.id,draggable:le,onDragStart:le?te:void 0,onDragEnd:le?Re:void 0,onDragOver:ke,onDragLeave:Ue,onDrop:Ge,onClick:Ae,onTouchStart:Ee,onTouchMove:ie,onTouchEnd:se,onDoubleClick:Jt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),Fe&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!Fe&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${tt?" awaiting-approval":""}${fm.has(e.status)?" pulsing":""}${ne?" failed":""}${ze?" stuck":""}`,children:ze?"Stuck":tt?"Awaiting Approval":e.status}),ze&&(Fe||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),pe&&t.jsx(Tf,{prInfo:zt,issueInfo:qt}),ge&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${Qe}`,children:Qe}),e.executionMode==="fast"&&t.jsxs("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(is,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Le,title:`Mission: ${B??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(Es,{size:11}),yS(B??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Te&&t.jsx("button",{className:"card-edit-btn",onClick:Vt,title:"Edit task","aria-label":"Edit task",children:t.jsx(js,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:on,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:rn,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:fn,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:fe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:re,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":q,children:["Send back",t.jsx(mn,{size:10})]}),q&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:xd["in-progress"].filter(he=>he!=="in-review").map(he=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Ne=>Pe(Ne,he),children:ss[he]},he))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:fe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:re,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":q,children:["Move",t.jsx(mn,{size:10})]}),q&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:xd["in-review"].map(he=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:Ne=>Pe(Ne,he),children:he==="done"?"Done (no merge)":ss[he]},he))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ne&&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:Se,disabled:U,children:[t.jsx(ry,{size:12}),U?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:jm(e.title,km)||jm(e.description,km)||e.id}),Be&&(()=>{const he=Oe.completed/Oe.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:`${he}%`,backgroundColor:SS[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Oe.completed,"/",Oe.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:je,"aria-expanded":E,"aria-label":E?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Oe.total," step",Oe.total===1?"":"s"]}),t.jsx(mn,{size:14,className:`card-steps-toggle-icon${E?" expanded":""}`})]}),E&&t.jsx("div",{className:"card-steps-list",children:Oe.items.map(Ne=>{const Je=Ne.source==="workflow"&&Ne.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${Ne.status}${Je?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${Ne.status==="done"?" completed":""}`,children:Ne.name}),Ne.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${Ne.phase}`,title:"Workflow check",children:"workflow"})]},Ne.id)})})]})})(),(Ie||et||$e)&&t.jsxs("div",{className:"card-footer-row",children:[Ie,$e&&t.jsx("span",{className:"card-source-provenance",title:st?`Imported from GitHub: ${st}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Qn,{provider:"github",size:"sm"})}),et&&t.jsxs("span",{className:"card-time-indicator",title:et.title,"aria-label":et.ariaLabel,children:[t.jsx(Ii,{size:12}),t.jsx("span",{children:et.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(he=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:Ne=>void xe(Ne,he),title:`Click to view ${he}`,children:[t.jsx($a,{size:12,style:{verticalAlign:"middle"}})," ",he]},he))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(oa,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Ii,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||rt.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[rt.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:rt.map(he=>t.jsx(Qn,{provider:he,size:"sm"},he))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${at?" card-agent-badge--loading":""}`,title:`Assigned to ${P??e.assignedAgentId}`,children:[t.jsx(Tn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:jS(P??e.assignedAgentId,15)})]})]}),t.jsx(Hi,{slotId:"task-card-badge",projectId:n})]})}const wm=10,BS=300,km=140;function jm(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Vr=i.memo(US,FS);Vr.displayName="TaskCard";function HS({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,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(Cx,{size:14}):t.jsx(Ks,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Vr,{task:g,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(Vr,{task:g,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const zf=i.memo(HS);zf.displayName="WorktreeGroup";function Nm(e){return e.toLowerCase().replace(/[-_./]/g,"")}function qS(e,n){let s=0;for(let a=0;a<n.length&&s<e.length;a++)e[s]===n[a]&&s++;return s===e.length}function VS(e,n,s){const a=e.length,r=n.length;if(a===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<=a;c++){const d=new Array(r+1);d[0]=c;for(let u=1;u<=r;u++){const m=e[c-1]===n[u-1]?0:1;d[u]=Math.min(l[u]+1,d[u-1]+1,l[u-1]+m),c>=2&&u>=2&&e[c-1]===n[u-2]&&e[c-2]===n[u-1]&&(d[u]=Math.min(d[u],o[u-2]+1))}o=l,l=d}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function WS(e,n){const s=Nm(e),a=Nm(n);if(s.length===0||a.includes(s))return!0;const r=a.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&qS(s,o)||s.length>=4&&VS(s,o,1))return!0;return!1}function KS(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(a=>{const r=`${a.provider} ${a.id} ${a.name}`;return s.every(o=>WS(o,r))})}function ys({models:e,value:n,onChange:s,placeholder:a="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:d,favoriteModels:u=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[x,v]=i.useState(""),[b,y]=i.useState(0),[j,C]=i.useState(null),[A,N]=i.useState(null),S=i.useRef(null),_=i.useRef(null),T=i.useRef(null),M=i.useRef(null),E=i.useRef(null),O=i.useMemo(()=>KS(e,x),[e,x]),B=i.useMemo(()=>O.reduce((oe,Y)=>((oe[Y.provider]??=[]).push(Y),oe),{}),[O]),R=i.useMemo(()=>{const oe=[];for(const Y of u){const ae=Y.indexOf("/");if(ae===-1)continue;const ce=Y.slice(0,ae),te=Y.slice(ae+1),Re=O.find(be=>be.provider===ce&&be.id===te);Re&&oe.push({model:Re,fullId:Y})}return oe},[u,O]),P=i.useMemo(()=>{const oe=Object.entries(B),Y=new Set(c);return oe.sort(([ae],[ce])=>{const te=Y.has(ae),Re=Y.has(ce);if(te&&!Re)return-1;if(!te&&Re)return 1;if(te&&Re){const be=c.indexOf(ae),ke=c.indexOf(ce);if(be!==ke)return be-ke}return ae.localeCompare(ce)})},[B,c]),F=typeof h=="string"&&h.length>0,q=i.useMemo(()=>{if(!n||F&&n===h)return null;const oe=n.indexOf("/");return oe===-1?null:n.slice(0,oe)},[F,h,n]),ee=i.useMemo(()=>{const oe=[];return F&&oe.push({type:"no-change",value:h,label:f}),oe.push({type:"default",value:"",label:"Use default"}),oe},[F,f,h]),U=i.useMemo(()=>{const oe=[...ee];for(const{model:Y,fullId:ae}of R)oe.push({type:"favorite",value:ae,label:Y.name,provider:Y.provider});return P.forEach(([Y,ae])=>{oe.push({type:"provider",value:`__group_${Y}`,label:Y,provider:Y}),ae.forEach(ce=>{oe.push({type:"model",value:`${ce.provider}/${ce.id}`,label:ce.name,provider:ce.provider})})}),oe},[R,P,ee]),k=i.useMemo(()=>{if(F&&n===h)return f;if(!n)return"Use default";const oe=n.indexOf("/");if(oe===-1)return n;const Y=n.slice(0,oe),ae=n.slice(oe+1);return e.find(te=>te.provider===Y&&te.id===ae)?.name||n},[F,f,h,n,e]),I=i.useMemo(()=>U.findIndex(oe=>oe.value===n),[U,n]),$=i.useCallback(()=>{const oe=window.visualViewport;return oe&&oe.height>0&&oe.width>0?{width:oe.width,height:oe.height,offsetTop:oe.offsetTop,offsetLeft:oe.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),w=i.useCallback(()=>{const{height:oe}=$(),Y=typeof window.matchMedia=="function",ae=Y?window.matchMedia("(max-width: 640px)").matches:!1,ce=Y?window.matchMedia("(max-width: 768px)").matches:!1;return oe<=0?320:ae?Math.min(oe*.6,360):ce?Math.min(oe*.7,420):320},[$]),H=i.useCallback(()=>{const oe=_.current;if(!oe)return;const Y=oe.getBoundingClientRect(),{width:ae,height:ce,offsetTop:te,offsetLeft:Re}=$(),be=16,ke=16,Ue=4,Ge=w(),qe=Y.bottom-te,Ae=Y.top-te,Ee=Y.left-Re,ie=ce-qe,se=Ae,xe=Math.max(ie-ke-Ue,160),ne=Math.max(se-ke-Ue,160),Fe=ie<Ge&&se>ie,Qe=Math.max(Math.min(Fe?ne:xe,Ge),160),ge=Math.min(Y.width,ae-be*2),ze=Math.min(Math.max(Ee,be),ae-be-ge)+Re,tt=Fe?Math.max(ke+te,Ae-Qe-Ue+te):Math.min(qe+Ue+te,ce+te-ke-Qe);C({top:tt,left:ze,width:ge,maxHeight:Qe})},[$,w]);i.useEffect(()=>{N(document.body)},[]);const J=i.useRef(!1);i.useEffect(()=>{if(!p){J.current=!1;return}if(J.current||U.length===0)return;const oe=U.findIndex((Y,ae)=>ae>=(I>=0?I:0)&&Y.type!=="provider");y(oe>=0?oe:0),J.current=!0},[p,U,I]),i.useEffect(()=>{p&&J.current&&(y(0),E.current&&(E.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;H();const oe=requestAnimationFrame(()=>M.current?.focus());return()=>cancelAnimationFrame(oe)},[p,H]),i.useEffect(()=>{if(!p)return;const oe=()=>H();window.addEventListener("resize",oe),window.addEventListener("scroll",oe,!0);const Y=window.visualViewport;return Y&&(Y.addEventListener("resize",oe),Y.addEventListener("scroll",oe)),()=>{window.removeEventListener("resize",oe),window.removeEventListener("scroll",oe,!0),Y&&(Y.removeEventListener("resize",oe),Y.removeEventListener("scroll",oe))}},[p,H]),i.useEffect(()=>{if(!p)return;const oe=Y=>{const ae=Y.target,ce=S.current?.contains(ae),te=T.current?.contains(ae);!ce&&!te&&(g(!1),v(""))};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[p]);const fe=i.useCallback(oe=>{switch(oe.key){case"ArrowDown":if(oe.preventDefault(),!p)g(!0);else{let Y=b;for(let ae=1;ae<=U.length;ae++){const ce=(b+ae)%U.length;if(U[ce]?.type!=="provider"){Y=ce;break}}y(Y)}break;case"ArrowUp":if(oe.preventDefault(),p){let Y=b;for(let ae=1;ae<=U.length;ae++){const ce=(b-ae+U.length)%U.length;if(U[ce]?.type!=="provider"){Y=ce;break}}y(Y)}break;case"Enter":if(oe.preventDefault(),p){const Y=U[b];Y&&Y.type!=="provider"&&Y.type!=="favorite"&&(s(Y.value),g(!1),v(""))}else g(!0);break;case"Escape":oe.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,b,U,s]),de=i.useCallback(oe=>{s(oe),g(!1),v("")},[s]),D=i.useCallback(()=>{v(""),M.current?.focus()},[]),_e=i.useCallback(()=>{r||g(oe=>!oe)},[r]);i.useEffect(()=>{if(p&&E.current){const oe=E.current.querySelector(`[data-index="${b}"]`);oe&&typeof oe.scrollIntoView=="function"&&oe.scrollIntoView({block:"nearest"})}},[b,p]);const z=x.length>0,Z=p&&j?t.jsxs("div",{ref:T,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:fe,style:{top:`${j.top}px`,left:`${j.left}px`,width:`${j.width}px`,maxHeight:`${j.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:M,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:oe=>v(oe.target.value),onClick:oe=>oe.stopPropagation()}),z&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:D,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[O.length," model",O.length!==1?"s":""]}),t.jsxs("div",{ref:E,className:"model-combobox-list",children:[ee.map((oe,Y)=>t.jsx("div",{"data-index":Y,className:`model-combobox-option ${b===Y?"model-combobox-option--highlighted":""} ${n===oe.value?"model-combobox-option--selected":""}`,onClick:()=>de(oe.value),onMouseEnter:()=>y(Y),role:"option","aria-selected":n===oe.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:oe.label})},`${oe.type}-${oe.value}`)),R.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),R.map(({model:oe,fullId:Y},ae)=>{const ce=ae+ee.length,te=b===ce,Re=n===Y;return t.jsxs("div",{"data-index":ce,className:`model-combobox-option model-combobox-option--favorite ${te?"model-combobox-option--highlighted":""} ${Re?"model-combobox-option--selected":""}`,onClick:()=>de(Y),onMouseEnter:()=>y(ce),role:"option","aria-selected":Re,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Qn,{provider:oe.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:oe.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:oe.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:be=>{be.stopPropagation(),m(Y)},title:"Remove from favorites","aria-label":`Remove ${oe.name} from favorites`,children:"★"})]},Y)}),t.jsx("div",{className:"model-combobox-divider"})]}),P.map(([oe,Y])=>{const ae=U.findIndex(Re=>Re.value===`__group_${oe}`),ce=c.includes(oe),te=Y.filter(Re=>{const be=`${Re.provider}/${Re.id}`;return!u.includes(be)});return te.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":ae,children:[t.jsx(Qn,{provider:oe,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:oe}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${ce?"model-combobox-optgroup-favorite--active":""}`,onClick:Re=>{Re.stopPropagation(),d(oe)},title:ce?"Remove from favorites":"Add to favorites","aria-label":ce?`Remove ${oe} from favorites`:`Add ${oe} to favorites`,children:"★"})]}),te.map(Re=>{const be=`${Re.provider}/${Re.id}`,ke=U.findIndex(Ae=>Ae.value===be),Ue=b===ke,Ge=n===be,qe=u.includes(be);return t.jsxs("div",{"data-index":ke,className:`model-combobox-option ${Ue?"model-combobox-option--highlighted":""} ${Ge?"model-combobox-option--selected":""}`,onClick:()=>de(be),onMouseEnter:()=>y(ke),role:"option","aria-selected":Ge,children:[t.jsx("span",{className:"model-combobox-option-text",children:Re.name}),t.jsx("span",{className:"model-combobox-option-id",children:Re.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${qe?"model-combobox-option-favorite--active":""}`,onClick:Ae=>{Ae.stopPropagation(),m(be)},title:qe?"Remove from favorites":"Add to favorites","aria-label":qe?`Remove ${Re.name} from favorites`:`Add ${Re.name} to favorites`,children:qe?"★":"☆"})]},be)})]},oe)}),O.length===0&&z&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:S,className:"model-combobox",onKeyDown:fe,children:t.jsxs("button",{ref:_,type:"button",id:o,className:"model-combobox-trigger",onClick:_e,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[q&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Qn,{provider:q,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:k||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),A&&Z?na.createPortal(Z,A):null]})}function Zd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function as(e,n){return typeof window>"u"?null:window.localStorage.getItem(Zd(e,n))}function xs(e,n,s){typeof window>"u"||window.localStorage.setItem(Zd(e,s),n)}function Ua(e,n){typeof window>"u"||window.localStorage.removeItem(Zd(e,n))}const GS=1e4,JS=1e3;function $l(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const p=await ll();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let p=!1;async function g(){a(!0);try{const v=await ll();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||a(!1)}}g();const x=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<JS||(c.current=v,d())};return document.addEventListener("visibilitychange",x),()=>{p=!0,document.removeEventListener("visibilitychange",x)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},GS),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async p=>{const g=await kj(p);return n(x=>[...x,g]),g},[]),m=i.useCallback(async(p,g)=>{const x=await jj(p,g);return n(v=>v.map(b=>b.id===p?x:b)),x},[]),h=i.useCallback(async p=>{await Nj(p),n(g=>g.filter(x=>x.id!==p))},[]),f=i.useCallback(async p=>{const g=await Sj(p);n(x=>x.map(v=>v.id===p?{...v,status:g.status,updatedAt:g.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f}}const cr="kb-quick-entry-text",YS=["image/png","image/jpeg","image/gif","image/webp"];function QS(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function oc(e,n){return e&&n?`${e}/${n}`:""}function lc(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 Ff({onCreate:e,addToast:n,tasks:s=[],availableModels:a,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:d,favoriteModels:u,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=i.useState(()=>typeof window<"u"&&as(cr,l)||""),[g,x]=i.useState(!1),[v,b]=i.useState(!1),[y,j]=i.useState(!1),C=i.useRef(null),A=i.useRef(null),N=i.useRef(!1),S=i.useRef(l),[_,T]=i.useState([]),M=i.useRef([]),[E,O]=i.useState([]),[B,R]=i.useState(!1),[P,F]=i.useState(""),[q,ee]=i.useState(null),[U,k]=i.useState([]),[I,$]=i.useState(void 0),[w,H]=i.useState(!1),[J,fe]=i.useState(!1),[de,D]=i.useState(!1),[_e,z]=i.useState(!1),[Z,oe]=i.useState(!1),[Y,ae]=i.useState(null),[ce,te]=i.useState(void 0),[Re,be]=i.useState(void 0),[ke,Ue]=i.useState(void 0),[Ge,qe]=i.useState(void 0),[Ae,Ee]=i.useState(void 0),[ie,se]=i.useState(void 0),xe=i.useRef(null),ne=i.useRef(null),Fe=i.useRef(null),Qe=i.useRef(null),ge=i.useRef(null),ze=i.useRef(null),tt=i.useRef(null),pt=i.useRef(null),[ve,le]=i.useState(null),[Te,pe]=i.useState(null),[$e,st]=i.useState(null),[at,rt]=i.useState(null),Oe=i.useRef(null),Be=i.useRef(null),[et,jt]=i.useState(null),[De]=i.useState(()=>typeof document<"u"?document.body:null),[vt,Et]=i.useState(!1),[bt,zt]=i.useState(null),[qt,It]=i.useState(a??[]),[_t,Xt]=i.useState([]),[Lt,Ut]=i.useState([]),[cn,Jt]=i.useState(null),[Vt,Kt]=i.useState(void 0),[rn,fn]=i.useState(!1),[on,gn]=i.useState(Cs),[je,Le]=i.useState(void 0),{nodes:re}=$l(),[Pe,Se]=i.useState(!1),[X,Ie]=i.useState(!1),he=i.useRef(null),Ne=i.useRef(null),[Je,kt]=i.useState(null),Yt=d??_t,$t=u??Lt,Tt=!e;i.useEffect(()=>{if(a)It(a),Et(!1),zt(null);else{let G=!1;return Et(!0),zt(null),Ds().then(we=>{G||(It(we.models),d||Xt(we.favoriteProviders),u||Ut(we.favoriteModels))}).catch(we=>{G||zt(Me(we)||"Failed to load models")}).finally(()=>{G||Et(!1)}),Rl(l).then(we=>{G||Jt(we)}).catch(()=>{}),()=>{G=!0}}},[a,d,u,l]);const Bt=oc(ce,Re),jn=oc(ke,Ge),Dn=oc(Ae,ie),hn=!!(ce&&Re),Ht=!!(ke&&Ge),yn=!!(Ae&&ie),pn=Number(hn)+Number(Ht)+Number(yn),es=Vt?cn?.modelPresets?.find(G=>G.id===Vt)?.name??"Models":pn>0?`${pn} model${pn===1?"":"s"}`:"Models",ye=i.useCallback((G,we)=>{if(!G||!we)return"Using default";const it=qt.find(St=>St.provider===G&&St.id===we);return it?`${it.provider}/${it.id}`:`${G}/${we}`},[qt]);i.useEffect(()=>{p(as(cr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&xs(cr,f,l)},[f,l]),i.useEffect(()=>{S.current!==l&&(S.current=l,k([]),$(void 0),ee(null),H(!1),le(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{M.current=_},[_]),i.useEffect(()=>()=>{M.current.forEach(G=>URL.revokeObjectURL(G.previewUrl))},[]);const ut=i.useCallback(()=>{const G=C.current;if(!G)return;G.style.height="auto";const we=Math.min(G.scrollHeight,200);G.style.height=`${we}px`},[]);i.useEffect(()=>{v&&ut()},[f,v,ut]),i.useEffect(()=>{if(!g&&f===""&&C.current){const G=setTimeout(()=>{C.current?.focus()},0);return()=>clearTimeout(G)}},[g,f]),i.useEffect(()=>{B||F("")},[B]),i.useEffect(()=>{if(!Pe)return;const G=we=>{const it=we.target,St=he.current?.contains(it),Nt=Ne.current?.contains(it);!St&&!Nt&&Se(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Pe]),i.useEffect(()=>{if(!Z)return;const G=we=>{const it=we.target,St=xe.current?.contains(it),Nt=ne.current?.contains(it),Mn=it instanceof Element&&it.closest?.(".model-combobox-dropdown--portal")!=null;!St&&!Nt&&!Mn&&(oe(!1),ae(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Z]),i.useEffect(()=>{if(!J)return;const G=we=>{const it=we.target;ge.current?.contains(it)||ze.current?.contains(it)||(fe(!1),pe(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[J]),i.useEffect(()=>{if(!w)return;const G=we=>{const it=we.target;Fe.current?.contains(it)||Qe.current?.contains(it)||(H(!1),le(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[w]),i.useEffect(()=>{if(!de)return;const G=we=>{const it=we.target;tt.current?.contains(it)||pt.current?.contains(it)||(D(!1),st(null))};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[de]);const Qt=i.useCallback(()=>{_.forEach(G=>URL.revokeObjectURL(G.previewUrl)),T([]),A.current&&(A.current.value=""),p(""),O([]),ee(null),H(!1),le(null),fe(!1),pe(null),D(!1),st(null),te(void 0),be(void 0),Ue(void 0),qe(void 0),Ee(void 0),se(void 0),Kt(void 0),fn(!1),gn(Cs),Le(void 0),R(!1),oe(!1),rt(null),ae(null),Se(!1),Ie(!1),b(!1),j(!1),N.current=!0,C.current&&(C.current.style.height="auto"),typeof window<"u"&&Ua(cr,l)},[_,l]),Cn=i.useCallback(G=>{if(!G||G.length===0)return;const we=[];for(let it=0;it<G.length;it++){const St=G[it];YS.includes(St.type)&&we.push({file:St,previewUrl:URL.createObjectURL(St)})}we.length>0&&T(it=>[...it,...we])},[]),ue=i.useCallback(G=>{g||Cn(G.clipboardData?.files)},[Cn,g]),dt=i.useCallback(G=>{T(we=>{const it=we[G];return it&&URL.revokeObjectURL(it.previewUrl),we.filter((St,Nt)=>Nt!==G)})},[]),wt=i.useCallback(async()=>{const G=f.trim();if(!G||g||!e)return;const we=f;x(!0),p("");try{const it=await e({description:G,column:"triage",dependencies:E.length?E:void 0,...q?{assignedAgentId:q}:{},modelPresetId:Vt,modelProvider:hn?ce:void 0,modelId:hn?Re:void 0,validatorModelProvider:Ht?ke:void 0,validatorModelId:Ht?Ge:void 0,planningModelProvider:yn?Ae:void 0,planningModelId:yn?ie:void 0,...rn?{executionMode:"fast"}:{},priority:on,nodeId:je});if(it&&_.length>0){const St=[];for(const Nt of _)try{await Br(it.id,Nt.file,l)}catch{St.push(Nt.file.name)}St.length>0&&n(`Failed to upload: ${St.join(", ")}`,"error")}Qt()}catch(it){p(we),n(Me(it)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,E,q,hn,ce,Re,Ht,ke,Ge,yn,Ae,ie,_,l,n,Qt,rn,on,je]),gt=i.useCallback(G=>{if(G.key==="Enter"){if(G.shiftKey&&v)return;G.preventDefault(),wt()}else if(G.key==="Escape"){if(G.preventDefault(),Y){ae(null);return}if(Z){oe(!1),rt(null);return}if(B){R(!1);return}if(Pe){Se(!1);return}if(J){fe(!1),pe(null);return}if(de){D(!1),st(null);return}if(w){H(!1),le(null);return}f.trim()&&(p(""),C.current&&(C.current.style.height="auto"),typeof window<"u"&&Ua(cr,l)),b(!1),j(!1),C.current?.blur()}},[wt,f,v,B,w,J,Z,Y,Pe,de,l,j]),ot=i.useCallback(()=>{N.current&&(N.current=!1)},[]),yt=i.useCallback(()=>{c&&b(!0)},[c]),Ft=i.useCallback(G=>{O(we=>we.includes(G)?we.filter(it=>it!==G):[...we,G])},[]),Zt=i.useCallback(()=>{const G=window.visualViewport;return G&&G.width>0&&G.height>0?{width:G.width,height:G.height,offsetTop:G.offsetTop,offsetLeft:G.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Ln=i.useCallback(()=>{const G=xe.current;if(!G)return;const we=G.getBoundingClientRect(),{width:it,height:St,offsetTop:Nt,offsetLeft:Mn}=Zt(),nn=16,un=16,sn=4,Hn=it<=768,qn=Math.min(Hn?St*.6:St*.5,360),ls=Math.max(we.width*1.35,320),Rn=Hn?Math.min(it-nn*2,360):ls,On=Math.min(Rn,Math.max(it-nn*2,240)),_n=we.top-Nt,cs=we.bottom-Nt,Wn=we.left-Mn,Vn=St-cs,ms=_n,Kn=Math.max(Vn-un-sn,160),hs=Math.max(ms-un-sn,160),Gn=Vn<qn&&ms>Vn,Rs=Math.max(Math.min(Gn?hs:Kn,qn),160),Ts=Math.min(Math.max(Wn,nn),it-nn-On)+Mn,zi=Gn?Math.max(un+Nt,_n-Rs-sn+Nt):Math.min(cs+sn+Nt,St+Nt-un-Rs);rt({top:zi,left:Ts,width:On,maxHeight:Rs})},[Zt]),Wt=i.useCallback(()=>{const G=he.current?.querySelector(".refine-button");if(!G)return;const we=G.getBoundingClientRect(),{width:it,height:St,offsetTop:Nt,offsetLeft:Mn}=Zt(),nn=8,un=12,sn=4,Hn=Math.min(200,Math.max(St-un*2,160)),qn=Math.min(200,it-nn*2),ls=we.top-Nt,Rn=we.bottom-Nt,On=we.left-Mn,_n=St-Rn,cs=ls,Wn=_n<Hn&&cs>_n,Vn=Math.min(Math.max(On,nn),it-nn-qn)+Mn,ms=Wn?Math.max(un+Nt,ls-Hn-sn+Nt):Math.min(Rn+sn+Nt,St+Nt-un-Hn);kt({top:ms,left:Vn})},[Zt]),Mt=i.useCallback(()=>{const G=Oe.current;if(!G)return;const we=G.getBoundingClientRect(),{width:it,height:St,offsetTop:Nt,offsetLeft:Mn}=Zt(),nn=16,un=16,sn=4,Hn=it<=768,qn=Math.min(Hn?St*.6:St*.5,320),ls=Hn?Math.min(it-nn*2,360):Math.max(we.width,280),Rn=Math.min(ls,Math.max(it-nn*2,240)),On=we.top-Nt,_n=we.bottom-Nt,cs=we.left-Mn,Wn=St-_n,Vn=On,ms=Math.max(Wn-un-sn,200),Kn=Math.max(Vn-un-sn,200),hs=Wn<qn&&Vn>Wn,Gn=Math.max(Math.min(hs?Kn:ms,qn),200),Rs=Math.min(Math.max(cs,nn),it-nn-Rn)+Mn,Ts=hs?Math.max(un+Nt,On-Gn-sn+Nt):Math.min(_n+sn+Nt,St+Nt-un-Gn);jt({top:Ts,left:Rs,width:Rn,maxHeight:Gn})},[Zt]),En=i.useCallback(()=>{const G=Fe.current?.querySelector("button");if(!G)return;const we=G.getBoundingClientRect(),{width:it,height:St,offsetTop:Nt,offsetLeft:Mn}=Zt(),nn=16,un=16,sn=4,Hn=it<=768,qn=Math.min(Hn?St*.6:St*.5,320),ls=Hn?Math.min(it-nn*2,280):Math.max(we.width,240),Rn=Math.min(ls,Math.max(it-nn*2,200)),On=we.top-Nt,_n=we.bottom-Nt,cs=we.left-Mn,Wn=St-_n,Vn=On,ms=Math.max(Wn-un-sn,160),Kn=Math.max(Vn-un-sn,160),hs=Wn<qn&&Vn>Wn,Gn=Math.max(Math.min(hs?Kn:ms,qn),160),Rs=Math.min(Math.max(cs,nn),it-nn-Rn)+Mn,Ts=hs?Math.max(un+Nt,On-Gn-sn+Nt):Math.min(_n+sn+Nt,St+Nt-un-Gn);le({top:Ts,left:Rs,width:Rn,maxHeight:Gn})},[Zt]),Xn=i.useCallback(()=>{const G=ge.current?.querySelector("button");if(!G)return;const we=G.getBoundingClientRect(),{width:it,height:St,offsetTop:Nt,offsetLeft:Mn}=Zt(),nn=16,un=16,sn=4,Hn=it<=768,qn=Math.min(Hn?St*.6:St*.5,320),ls=Hn?Math.min(it-nn*2,280):Math.max(we.width,240),Rn=Math.min(ls,Math.max(it-nn*2,200)),On=we.top-Nt,_n=we.bottom-Nt,cs=we.left-Mn,Wn=St-_n,Vn=On,ms=Math.max(Wn-un-sn,160),Kn=Math.max(Vn-un-sn,160),hs=Wn<qn&&Vn>Wn,Gn=Math.max(Math.min(hs?Kn:ms,qn),160),Rs=Math.min(Math.max(cs,nn),it-nn-Rn)+Mn,Ts=hs?Math.max(un+Nt,On-Gn-sn+Nt):Math.min(_n+sn+Nt,St+Nt-un-Gn);pe({top:Ts,left:Rs,width:Rn,maxHeight:Gn})},[Zt]),ts=i.useCallback(()=>{const G=tt.current?.querySelector("button");if(!G)return;const we=G.getBoundingClientRect(),{width:it,height:St,offsetTop:Nt,offsetLeft:Mn}=Zt(),nn=16,un=16,sn=4,Hn=220,qn=Math.min(Math.max(we.width,200),Math.max(it-nn*2,200)),ls=we.top-Nt,Rn=we.bottom-Nt,On=we.left-Mn,_n=St-Rn,cs=ls,Wn=Math.max(_n-un-sn,160),Vn=Math.max(cs-un-sn,160),ms=_n<Hn&&cs>_n,Kn=Math.max(Math.min(ms?Vn:Wn,Hn),160),hs=Math.min(Math.max(On,nn),it-nn-qn)+Mn,Gn=ms?Math.max(un+Nt,ls-Kn-sn+Nt):Math.min(Rn+sn+Nt,St+Nt-un-Kn);st({top:Gn,left:hs,width:qn,maxHeight:Kn})},[Zt]);i.useEffect(()=>{if(!Z)return;const G=()=>Ln();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",G),we.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),we&&(we.removeEventListener("resize",G),we.removeEventListener("scroll",G))}},[Z,Ln]),i.useEffect(()=>{if(!Pe)return;const G=()=>Wt();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",G),we.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),we&&(we.removeEventListener("resize",G),we.removeEventListener("scroll",G))}},[Pe,Wt]),i.useEffect(()=>{if(!B)return;const G=()=>Mt();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",G),we.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),we&&(we.removeEventListener("resize",G),we.removeEventListener("scroll",G))}},[B,Mt]),i.useEffect(()=>{if(!w)return;const G=()=>En();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",G),we.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),we&&(we.removeEventListener("resize",G),we.removeEventListener("scroll",G))}},[w,En]),i.useEffect(()=>{if(!J)return;const G=()=>Xn();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",G),we.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),we&&(we.removeEventListener("resize",G),we.removeEventListener("scroll",G))}},[J,Xn]),i.useEffect(()=>{if(!de)return;const G=()=>ts();window.addEventListener("resize",G),window.addEventListener("scroll",G,!0);const we=window.visualViewport;return we&&(we.addEventListener("resize",G),we.addEventListener("scroll",G)),()=>{window.removeEventListener("resize",G),window.removeEventListener("scroll",G,!0),we&&(we.removeEventListener("resize",G),we.removeEventListener("scroll",G))}},[de,ts]);const Ps=i.useCallback(G=>{const we=lc(G);Ee(we.provider),se(we.modelId)},[]),ws=i.useCallback(G=>{const we=lc(G);te(we.provider),be(we.modelId)},[]),Bn=i.useCallback(G=>{const we=lc(G);Ue(we.provider),qe(we.modelId)},[]),rs=i.useCallback(async G=>{if(m){m(G);return}const we=_t,St=we.includes(G)?we.filter(Nt=>Nt!==G):[G,...we];Xt(St);try{await Pn({favoriteProviders:St,favoriteModels:Lt})}catch{Xt(we)}},[_t,Lt,m]),V=i.useCallback(async G=>{if(h){h(G);return}const we=Lt,St=we.includes(G)?we.filter(Nt=>Nt!==G):[G,...we];Ut(St);try{await Pn({favoriteProviders:_t,favoriteModels:St})}catch{Ut(we)}},[Lt,_t,h]),Ve=i.useCallback(()=>{const G=f.trim();if(!G){n("Enter a description first","error");return}r?.(G),Qt()},[f,r,n,Qt]),Ye=i.useCallback(()=>{const G=f.trim();if(!G){n("Enter a description first","error");return}o?.(G),Qt()},[f,o,n,Qt]),mt=i.useCallback(()=>{wt()},[wt]),Ct=i.useCallback(async G=>{const we=f.trim();if(!(!we||X)){Se(!1),Ie(!0);try{const it=await gf(we,G,l);p(it),n("Description refined with AI","success"),C.current&&(C.current.style.height="auto",C.current.style.height=`${Math.min(C.current.scrollHeight,200)}px`)}catch(it){const St=bf(it);n(St,"error")}finally{Ie(!1)}}},[f,X,n,l]),Rt=(G,we)=>G.length>we?G.slice(0,we)+"…":G,dn=i.useCallback(async()=>{if(a){It(a),zt(null),Et(!1);return}Et(!0),zt(null);try{const G=await Ds();It(G.models),d||Xt(G.favoriteProviders),u||Ut(G.favoriteModels)}catch(G){zt(Me(G)||"Failed to load models")}finally{Et(!1)}},[a,d,u]),Dt=i.useCallback(async()=>{if(U.length>0&&I===l){H(!0),En();return}z(!0);try{const G=await fa(void 0,l);k(G),$(l),H(!0),En()}catch(G){const we=Me(G);n(we?`Failed to load agents: ${we}`:"Failed to load agents","error"),H(!1)}finally{z(!1)}},[U.length,I,l,n,En]),Zn=(q?U.find(G=>G.id===q):void 0)?.name??q,me=je?re.find(G=>G.id===je):void 0,He=y,lt=i.useCallback(()=>{j(G=>{const we=!G;return b(we),we})},[]);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:C,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:G=>p(G.target.value),onKeyDown:gt,onPaste:ue,onFocus:yt,onBlur:ot,disabled:g||Tt,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":y})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:lt,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(hi,{size:14}):t.jsx(mn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!He,"aria-hidden":!He,children:[He&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Ve,onMouseDown:G=>G.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(pi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Ye,onMouseDown:G=>G.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(El,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:he,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${X?"refine-button--loading":""}`,onClick:()=>{Se(G=>{const we=!G;return we?Wt():kt(null),we})},disabled:!f.trim()||X,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(vs,{size:12,style:{verticalAlign:"middle"}}),X?"Refining...":"Refine"]}),Pe&&De&&Je&&na.createPortal(t.jsxs("div",{ref:Ne,className:"refine-menu refine-menu--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${Je.top}px`,left:`${Je.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ct("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:()=>Ct("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:()=>Ct("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:()=>Ct("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"})]})]}),De)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Oe,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{R(G=>{const we=!G;return we?(oe(!1),rt(null),ae(null),H(!1),le(null),fe(!1),pe(null),D(!1),st(null),Mt()):jt(null),we})},children:[t.jsx($a,{size:12,style:{verticalAlign:"middle"}}),E.length>0?`${E.length} deps`:"Deps"]})}),B&&De&&et&&(()=>{const G=P.toLowerCase(),we=(G?s.filter(it=>it.id.toLowerCase().includes(G)||it.title&&it.title.toLowerCase().includes(G)||it.description&&it.description.toLowerCase().includes(G)):[...s]).sort((it,St)=>{const Nt=St.createdAt.localeCompare(it.createdAt);if(Nt!==0)return Nt;const Mn=parseInt(it.id.slice(it.id.lastIndexOf("-")+1),10)||0;return(parseInt(St.id.slice(St.id.lastIndexOf("-")+1),10)||0)-Mn});return na.createPortal(t.jsxs("div",{ref:Be,className:"dep-dropdown dep-dropdown--portal",onMouseDown:it=>it.preventDefault(),style:{position:"fixed",top:`${et.top}px`,left:`${et.left}px`,width:`${et.width}px`,maxHeight:et.maxHeight?`${et.maxHeight}px`:void 0,overflowY:et.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:P,onChange:it=>F(it.target.value),onClick:it=>it.stopPropagation()}),we.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):we.map(it=>t.jsxs("div",{className:`dep-dropdown-item${E.includes(it.id)?" selected":""}`,onMouseDown:St=>St.preventDefault(),onClick:()=>Ft(it.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:it.id}),t.jsx("span",{className:"dep-dropdown-title",children:Rt(it.title||it.description||it.id,60)})]},it.id))]}),De)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>A.current?.click(),children:[t.jsx(of,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`Attach (${_.length})`:"Attach"]}),t.jsxs("button",{ref:xe,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{R(!1),H(!1),le(null),fe(!1),pe(null),D(!1),st(null),ae(null),oe(!0),Ln()},children:[t.jsx(zr,{size:12,style:{verticalAlign:"middle"}}),es]}),t.jsx("div",{className:"node-trigger-wrap",ref:ge,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{R(!1),H(!1),le(null),oe(!1),rt(null),ae(null),D(!1),st(null),fe(G=>{const we=!G;return we?Xn():pe(null),we})},children:[t.jsx(Ur,{size:12,style:{verticalAlign:"middle"}}),` ${me?.name??"Node"}`,me&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(ca,{status:me.status,showLabel:!0})})]})}),J&&De&&Te&&na.createPortal(t.jsxs("div",{ref:ze,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${Te.top}px`,left:`${Te.left}px`,width:`${Te.width}px`,maxHeight:Te.maxHeight?`${Te.maxHeight}px`:void 0,overflowY:Te.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select execution node"}),t.jsx("div",{className:`dep-dropdown-item node-picker-item${je==null?" selected":""}`,onMouseDown:G=>G.preventDefault(),onClick:()=>{Le(void 0),fe(!1),pe(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),re.map(G=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${je===G.id?" selected":""}`,onMouseDown:we=>we.preventDefault(),onClick:()=>{Le(G.id),fe(!1),pe(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(ca,{status:G.status})}),t.jsx("span",{className:"node-picker-item-name",children:G.name}),t.jsx("span",{className:"node-picker-item-status",children:QS(G.status)})]},G.id))]}),De),t.jsx("div",{className:"agent-trigger-wrap",ref:Fe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{w?(H(!1),le(null)):(fe(!1),pe(null),D(!1),st(null),Dt())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Tn,{size:12,style:{verticalAlign:"middle"}}),Zn?` ${Zn}`:" Agent"]})}),w&&De&&ve&&na.createPortal(t.jsxs("div",{ref:Qe,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:G=>G.preventDefault(),style:{position:"fixed",top:`${ve.top}px`,left:`${ve.left}px`,width:`${ve.width}px`,maxHeight:ve.maxHeight?`${ve.maxHeight}px`:void 0,overflowY:ve.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),_e&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!_e&&U.filter(G=>G.state!=="terminated").map(G=>t.jsxs("div",{className:`dep-dropdown-item${q===G.id?" selected":""}`,onMouseDown:we=>we.preventDefault(),onClick:()=>{ee(G.id===q?null:G.id),H(!1),le(null)},children:[t.jsx(Tn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:G.role}),t.jsx("span",{className:"dep-dropdown-title",children:G.name})]},G.id)),!_e&&U.filter(G=>G.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:G=>G.preventDefault(),onClick:()=>{ee(null),H(!1),le(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),De),t.jsx("div",{className:"priority-trigger-wrap",ref:tt,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{R(!1),H(!1),le(null),fe(!1),pe(null),oe(!1),rt(null),ae(null),D(G=>{const we=!G;return we?ts():st(null),we})},children:[t.jsx(nv,{size:12,style:{verticalAlign:"middle"}}),` ${on[0].toUpperCase()}${on.slice(1)}`]})}),de&&De&&$e&&na.createPortal(t.jsxs("div",{ref:pt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:G=>G.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("div",{className:"dep-dropdown-search-header",children:"Select priority"}),Xa.map(G=>{const we=`${G[0].toUpperCase()}${G.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${on===G?" selected":""}`,"data-testid":`quick-entry-priority-option-${G}`,onMouseDown:it=>it.preventDefault(),onClick:()=>{gn(G),D(!1),st(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:we})},G)})]}),De),t.jsx("button",{type:"button",className:`btn btn-sm ${rn?"btn-primary":""}`,onClick:()=>fn(G=>!G),onMouseDown:G=>G.preventDefault(),"aria-pressed":rn,"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:mt,onMouseDown:G=>G.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(cf,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),_.length>0&&t.jsx("div",{className:"inline-create-previews",children:_.map((G,we)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:G.previewUrl,alt:G.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>dt(we),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${we}`,children:"×"})]},G.previewUrl))}),Z&&De&&at&&na.createPortal(t.jsx("div",{ref:ne,className:"model-nested-menu model-nested-menu--portal",onMouseDown:G=>G.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${at.top}px`,left:`${at.left}px`,width:`${at.width}px`,maxHeight:at.maxHeight?`${at.maxHeight}px`:void 0,overflowY:at.maxHeight?"auto":void 0},children:Y===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${yn?"model-menu-item--active":""}`,onClick:()=>ae("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(pi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:yn?ye(Ae,ie):"Using default"}),t.jsx(In,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${hn?"model-menu-item--active":""}`,onClick:()=>ae("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(vs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:hn?ye(ce,Re):"Using default"}),t.jsx(In,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Ht?"model-menu-item--active":""}`,onClick:()=>ae("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(zr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Ht?ye(ke,Ge):"Using default"}),t.jsx(In,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>ae(null),"data-testid":"model-submenu-back",children:[t.jsx(mn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[Y==="plan"&&"Plan Model",Y==="executor"&&"Executor Model",Y==="validator"&&"Reviewer Model"]}),t.jsx(ys,{models:qt,value:Y==="plan"?Dn:Y==="executor"?Bt:jn,onChange:Y==="plan"?Ps:Y==="executor"?ws:Bn,placeholder:"Using default",disabled:vt,id:`model-${Y}-select`,label:`${Y} model`,favoriteProviders:Yt,onToggleFavorite:rs,favoriteModels:$t,onToggleModelFavorite:V}),bt&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:bt}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:dn,children:"Retry"})]})]})}),De)]}),t.jsx("input",{ref:A,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:G=>{Cn(G.target.files),G.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function XS(e){return Xd(e)||e}function ZS(e){const n=new Map(e.map(l=>[l.id,l])),s=[],a=new Set,r=new Set;function o(l){if(a.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const d of c.dependencies||[])n.has(d)&&o(d);r.delete(l),a.add(l),s.push(l)}for(const l of e)o(l.id);return s}function e0(e,n,s){const a=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of a){const x=g.worktree,v=o.get(x)||[];v.push(g),o.set(x,v)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=ZS(d).map(g=>l.get(g)).filter(g=>g!==void 0&&d.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:XS(g),activeTasks:o.get(g),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 Sm=100,cc=50,Cm=25;function t0({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:j,onToggleCollapse:C,allTasks:A,availableModels:N,onPlanningMode:S,onSubtaskBreakdown:_,onOpenDetailWithTab:T,favoriteProviders:M,favoriteModels:E,onToggleFavorite:O,onToggleModelFavorite:B,isSearchActive:R,taskStuckTimeoutMs:P,onOpenMission:F,lastFetchTimeMs:q,workflowStepNameLookup:ee}){const[U,k]=i.useState(!1),[I,$]=i.useState(cc),[w,H]=i.useState(!1),[J,fe]=i.useState(!1),[de,D]=i.useState(!1),[_e,z]=i.useState(!1),Z=i.useRef(null),oe=H1(n.length),{confirm:Y}=Gs();i.useEffect(()=>{if(!w)return;function ze(pt){Z.current?.contains(pt.target)||H(!1)}function tt(pt){pt.key==="Escape"&&H(!1)}return document.addEventListener("mousedown",ze),document.addEventListener("keydown",tt),()=>{document.removeEventListener("mousedown",ze),document.removeEventListener("keydown",tt)}},[w]);const ae=e==="archived",ce=ae&&j,te=!ae&&!R&&e!=="in-progress"&&n.length>Sm;i.useEffect(()=>{$(ze=>e==="in-progress"||ae||n.length<=Sm?cc:Math.min(Math.max(ze,cc),n.length))},[e,ae,n.length]);const Re=i.useCallback(ze=>{ae||(ze.preventDefault(),ze.dataTransfer.dropEffect="move",k(!0))},[ae]),be=i.useCallback(ze=>{ze.currentTarget.contains(ze.relatedTarget)||k(!1)},[]),ke=i.useCallback(async ze=>{ze.preventDefault(),k(!1);const tt=ze.dataTransfer.getData("text/plain");if(!tt)return;const pt=n.find(ve=>ve.id===tt);if(!(pt&&pt.column===e))try{const le=(A?.find($e=>$e.id===tt)??pt)?.steps.some($e=>$e.status!=="pending")??!1,Te=(e==="todo"||e==="triage")&&le;let pe;if(Te){if(await Y({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))pe={preserveProgress:!0};else if(!await Y({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(tt,e,pe)}catch(ve){c(Me(ve),"error")}},[c,A,e,Y,r,n]),Ue=i.useMemo(()=>e!=="in-progress"?[]:e0(n,n,a),[e,n,a]),Ge=i.useMemo(()=>te?n.slice(0,I):n,[te,n,I]),qe=Math.max(0,n.length-Ge.length),Ae=i.useCallback(()=>{$(ze=>Math.min(ze+Cm,n.length))},[n.length]),Ee=i.useCallback(async()=>{if(H(!1),!(n.length===0||!await Y({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){fe(!0);try{const tt=await Promise.allSettled(n.map(le=>r(le.id,"triage"))),pt=tt.filter(le=>le.status==="rejected").length,ve=tt.length-pt;pt===0?c(`Moved ${ve} task${ve===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ve} of ${tt.length} tasks; ${pt} failed`,"error")}finally{fe(!1)}}},[n,r,c,Y]),ie=i.useMemo(()=>n.filter(ze=>!ze.paused),[n]),se=ie.length,xe=e==="todo"||e==="in-progress"||e==="in-review",ne=J||de||_e,Fe=i.useCallback(async()=>{if(!(!o||(H(!1),se===0)||!await Y({title:"Stop All Tasks",message:`Stop all ${se} ${ss[e].toLowerCase()} task${se===1?"":"s"}?`,danger:!0}))){D(!0);try{const tt=await Promise.allSettled(ie.map(le=>o(le.id))),pt=tt.filter(le=>le.status==="rejected").length,ve=tt.length-pt;pt===0?c(`Stopped ${ve} task${ve===1?"":"s"}`,"success"):c(`Stopped ${ve} of ${tt.length} tasks; ${pt} failed`,"error")}finally{D(!1)}}},[o,se,e,ie,c,Y]),Qe=i.useCallback(async()=>{if(H(!1),n.length===0||!await Y({title:"Move All to Todo",message:`Move all ${n.length} ${ss[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const tt=n.some(ve=>ve.steps.some(le=>le.status!=="pending"));let pt=!1;if(tt){if(await Y({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))pt=!0;else if(!await Y({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}z(!0);try{const ve=await Promise.allSettled(n.map(pe=>r(pe.id,"todo",pt?{preserveProgress:!0}:void 0))),le=ve.filter(pe=>pe.status==="rejected").length,Te=ve.length-le;le===0?c(`Moved ${Te} task${Te===1?"":"s"} to Todo`,"success"):c(`Moved ${Te} of ${ve.length} tasks to Todo; ${le} failed`,"error")}finally{z(!1)}},[n,e,r,c,Y]),ge=i.useCallback(async()=>{if(!(!y||n.length===0||!await Y({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const tt=await y();c(`Archived ${tt.length} tasks`,"success")}catch(tt){c(Me(tt)||"Failed to archive tasks","error")}},[y,n.length,c,Y]);return t.jsxs("div",{className:`column${U?" drag-over":""}${ae?" column-archived":""}${ce?" column-collapsed":""}`,"data-column":e,onDragOver:Re,onDragLeave:be,onDrop:ke,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ss[e]}),t.jsx("span",{className:`column-count${oe?" 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"})]}),u&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:u,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:ge,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Jr,{})}),ae&&C&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:C,title:j?"Expand archived tasks":"Collapse archived tasks","aria-label":j?"Expand archived tasks":"Collapse archived tasks",children:j?t.jsx(mn,{size:16}):t.jsx(hi,{size:16})}),xe&&t.jsxs("div",{className:"column-menu",ref:Z,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(ze=>!ze),"aria-haspopup":"menu","aria-expanded":w,"aria-label":`${ss[e]} column actions`,title:"Column actions",disabled:ne,children:t.jsx(Dx,{})}),w&&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 Ee(),disabled:n.length===0||J,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 Fe(),disabled:se===0||de||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":se===0?"All tasks are already paused":`Pause ${se} active task${se===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Qe(),disabled:n.length===0||_e,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!ce&&t.jsx("p",{className:"column-desc",children:U1[e]}),!ce&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(Ff,{onCreate:d,addToast:c,tasks:A??[],availableModels:N,onPlanningMode:S,onSubtaskBreakdown:_,projectId:s,autoExpand:!1,favoriteProviders:M,favoriteModels:E,onToggleFavorite:O,onToggleModelFavorite:B}),e==="in-progress"?Ue.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Ue.map(ze=>t.jsx(zf,{label:ze.label,activeTasks:ze.activeTasks,queuedTasks:ze.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:T,taskStuckTimeoutMs:P,onOpenMission:F,lastFetchTimeMs:q,workflowStepNameLookup:ee},ze.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Ge.map(ze=>t.jsx(Vr,{task:ze,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:T,taskStuckTimeoutMs:P,onOpenMission:F,onMoveTask:r,lastFetchTimeMs:q,workflowStepNameLookup:ee},ze.id)),te&&qe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,children:["Load ",Math.min(Cm,qe)," more (",qe," remaining)"]})]}),t.jsx(Hi,{slotId:"board-column-footer",projectId:s})]})]})}const Uf=i.memo(t0);Uf.displayName="Column";const Em={low:0,normal:1,high:2,urgent:3};function Mm(e){return typeof e=="string"&&Xa.includes(e)?e:Cs}function n0(e,n){return Em[Mm(n)]-Em[Mm(e)]}function s0(e,n){const s=Number.parseInt(e.slice(e.lastIndexOf("-")+1),10),a=Number.parseInt(n.slice(n.lastIndexOf("-")+1),10);return Number.isFinite(s)&&Number.isFinite(a)&&s!==a?s-a:e.localeCompare(n)}function i0(e,n){return[...e].sort((s,a)=>{if(n==="in-review"){const o=s.status==="merging"||s.status==="merging-pr",l=a.status==="merging"||a.status==="merging-pr";if(o!==l)return o?-1:1}const r=n0(s.priority,a.priority);return r!==0?r:s0(s.id,a.id)})}function a0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const _m=new Map;function r0(e,n){if(e.size!==n.size)return!1;for(const[s,a]of e)if(n.get(s)!==a)return!1;return!0}function o0({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:j="",availableModels:C,onPlanningMode:A,onSubtaskBreakdown:N,onOpenDetailWithTab:S,favoriteProviders:_,favoriteModels:T,onToggleFavorite:M,onToggleModelFavorite:E,taskStuckTimeoutMs:O,onOpenMission:B,lastFetchTimeMs:R}){const[P,F]=i.useState(!0),q=i.useRef(!1),{fetchBatch:ee}=lS(n),U=i.useRef(null),[k,I]=i.useState(_m),$=j.trim()!=="",w=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),H=i.useCallback(()=>{F(de=>{const D=!de;return!D&&!q.current&&y&&(q.current=!0,y()),D})},[y]),J=i.useMemo(()=>{const de=Object.fromEntries(aa.map(z=>[z,[]]));for(const z of e)de[z.column].push(z);const D=w.current,_e={};for(const z of aa){const Z=i0(de[z],z);_e[z]=a0(D[z],Z)?D[z]:Z}return w.current=_e,_e},[e]);i.useEffect(()=>{let de=!1;return so(n).then(D=>{if(de)return;const _e=new Map(D.map(z=>[z.id,z.name]));I(z=>r0(z,_e)?z:_e)}).catch(()=>{de||I(D=>D.size===0?D:_m)}),()=>{de=!0}},[n]);const fe=i.useMemo(()=>e.filter(de=>de.prInfo||de.issueInfo).map(de=>de.id),[e]);return i.useEffect(()=>{if(fe.length!==0)return U.current&&clearTimeout(U.current),U.current=setTimeout(()=>{const de=[];for(let D=0;D<fe.length;D+=50)de.push(fe.slice(D,D+50));de.forEach(D=>{ee(D)})},500),()=>{U.current&&clearTimeout(U.current)}},[fe,ee]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:aa.map(de=>t.jsx(Uf,{column:de,tasks:J[de],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:C,onOpenDetailWithTab:S,favoriteProviders:_,favoriteModels:T,onToggleFavorite:M,onToggleModelFavorite:E,isSearchActive:$,taskStuckTimeoutMs:O,onOpenMission:B,lastFetchTimeMs:R,workflowStepNameLookup:k,...de==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:A,onSubtaskBreakdown:N}:{},...de==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...de==="done"?{onArchiveAllDone:b}:{},...de==="archived"?{collapsed:P,onToggleCollapse:H}:{}},de))})})}function Si(e,n,s){i.useEffect(()=>{if(!n)return;const a=e.current;if(!a)return;try{const d=localStorage.getItem(s);if(d){const{width:u,height:m}=JSON.parse(d);typeof u=="number"&&u>0&&(a.style.width=`${u}px`),typeof m=="number"&&m>0&&(a.style.height=`${m}px`)}}catch{}if(typeof ResizeObserver>"u")return;let r=a.offsetWidth,o=a.offsetHeight,l=null;const c=new ResizeObserver(()=>{const d=a.offsetWidth,u=a.offsetHeight;d===r&&u===o||(r=d,o=u,l&&clearTimeout(l),l=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:d,height:u}))}catch{}},200))});return c.observe(a),()=>{c.disconnect(),l&&clearTimeout(l)}},[e,n,s])}function l0(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ta=0,$r=null;function c0(){if(typeof window>"u")return;if(Ta>0){Ta+=1;return}const e=document.documentElement,n=document.body;$r={htmlOverflow:e.style.overflow,bodyPosition:n.style.position,bodyTop:n.style.top,bodyLeft:n.style.left,bodyRight:n.style.right,bodyWidth:n.style.width,bodyOverflow:n.style.overflow,scrollY:window.scrollY},e.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${$r.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",Ta=1}function d0(){if(typeof window>"u"||Ta===0||(Ta-=1,Ta>0||!$r))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=$r;e.style.overflow=s,n.style.position=a,n.style.top=r,n.style.left=o,n.style.right=l,n.style.width=c,n.style.overflow=d,$r=null,window.scrollTo(0,0)}function Ci(e){i.useEffect(()=>{if(!(!e||!l0()))return c0(),()=>{d0()}},[e])}function Li(e){const n=i.useRef(!1),s=i.useCallback(r=>{n.current=r.target===r.currentTarget},[]),a=i.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:a}}function u0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const m0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,h0=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,p0={};function Am(e,n){return(p0.jsx?h0:m0).test(e)}const f0=/[ \t\n\f\r]/g;function g0(e){return typeof e=="object"?e.type==="text"?Pm(e.value):!1:Pm(e)}function Pm(e){return e.replace(f0,"")===""}class ro{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}ro.prototype.normal={};ro.prototype.property={};ro.prototype.space=void 0;function Bf(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new ro(s,a,n)}function kd(e){return e.toLowerCase()}class Fs{constructor(n,s){this.attribute=s,this.property=n}}Fs.prototype.attribute="";Fs.prototype.booleanish=!1;Fs.prototype.boolean=!1;Fs.prototype.commaOrSpaceSeparated=!1;Fs.prototype.commaSeparated=!1;Fs.prototype.defined=!1;Fs.prototype.mustUseProperty=!1;Fs.prototype.number=!1;Fs.prototype.overloadedBoolean=!1;Fs.prototype.property="";Fs.prototype.spaceSeparated=!1;Fs.prototype.space=void 0;let b0=0;const ln=ga(),us=ga(),jd=ga(),ht=ga(),Fn=ga(),Ia=ga(),Us=ga();function ga(){return 2**++b0}const Nd=Object.freeze(Object.defineProperty({__proto__:null,boolean:ln,booleanish:us,commaOrSpaceSeparated:Us,commaSeparated:Ia,number:ht,overloadedBoolean:jd,spaceSeparated:Fn},Symbol.toStringTag,{value:"Module"})),dc=Object.keys(Nd);class eu extends Fs{constructor(n,s,a,r){let o=-1;if(super(n,s),Rm(this,"space",r),typeof a=="number")for(;++o<dc.length;){const l=dc[o];Rm(this,dc[o],(a&Nd[l])===Nd[l])}}}eu.prototype.defined=!0;function Rm(e,n,s){s&&(e[n]=s)}function Za(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new eu(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[kd(a)]=a,s[kd(o.attribute)]=a}return new ro(n,s,e.space)}const Hf=Za({properties:{ariaActiveDescendant:null,ariaAtomic:us,ariaAutoComplete:null,ariaBusy:us,ariaChecked:us,ariaColCount:ht,ariaColIndex:ht,ariaColSpan:ht,ariaControls:Fn,ariaCurrent:null,ariaDescribedBy:Fn,ariaDetails:null,ariaDisabled:us,ariaDropEffect:Fn,ariaErrorMessage:null,ariaExpanded:us,ariaFlowTo:Fn,ariaGrabbed:us,ariaHasPopup:null,ariaHidden:us,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Fn,ariaLevel:ht,ariaLive:null,ariaModal:us,ariaMultiLine:us,ariaMultiSelectable:us,ariaOrientation:null,ariaOwns:Fn,ariaPlaceholder:null,ariaPosInSet:ht,ariaPressed:us,ariaReadOnly:us,ariaRelevant:null,ariaRequired:us,ariaRoleDescription:Fn,ariaRowCount:ht,ariaRowIndex:ht,ariaRowSpan:ht,ariaSelected:us,ariaSetSize:ht,ariaSort:null,ariaValueMax:ht,ariaValueMin:ht,ariaValueNow:ht,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function qf(e,n){return n in e?e[n]:n}function Vf(e,n){return qf(e,n.toLowerCase())}const x0=Za({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ia,acceptCharset:Fn,accessKey:Fn,action:null,allow:null,allowFullScreen:ln,allowPaymentRequest:ln,allowUserMedia:ln,alt:null,as:null,async:ln,autoCapitalize:null,autoComplete:Fn,autoFocus:ln,autoPlay:ln,blocking:Fn,capture:null,charSet:null,checked:ln,cite:null,className:Fn,cols:ht,colSpan:null,content:null,contentEditable:us,controls:ln,controlsList:Fn,coords:ht|Ia,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ln,defer:ln,dir:null,dirName:null,disabled:ln,download:jd,draggable:us,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ln,formTarget:null,headers:Fn,height:ht,hidden:jd,high:ht,href:null,hrefLang:null,htmlFor:Fn,httpEquiv:Fn,id:null,imageSizes:null,imageSrcSet:null,inert:ln,inputMode:null,integrity:null,is:null,isMap:ln,itemId:null,itemProp:Fn,itemRef:Fn,itemScope:ln,itemType:Fn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ln,low:ht,manifest:null,max:null,maxLength:ht,media:null,method:null,min:null,minLength:ht,multiple:ln,muted:ln,name:null,nonce:null,noModule:ln,noValidate:ln,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:ln,optimum:ht,pattern:null,ping:Fn,placeholder:null,playsInline:ln,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ln,referrerPolicy:null,rel:Fn,required:ln,reversed:ln,rows:ht,rowSpan:ht,sandbox:Fn,scope:null,scoped:ln,seamless:ln,selected:ln,shadowRootClonable:ln,shadowRootDelegatesFocus:ln,shadowRootMode:null,shape:null,size:ht,sizes:null,slot:null,span:ht,spellCheck:us,src:null,srcDoc:null,srcLang:null,srcSet:null,start:ht,step:null,style:null,tabIndex:ht,target:null,title:null,translate:null,type:null,typeMustMatch:ln,useMap:null,value:us,width:ht,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Fn,axis:null,background:null,bgColor:null,border:ht,borderColor:null,bottomMargin:ht,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ln,declare:ln,event:null,face:null,frame:null,frameBorder:null,hSpace:ht,leftMargin:ht,link:null,longDesc:null,lowSrc:null,marginHeight:ht,marginWidth:ht,noResize:ln,noHref:ln,noShade:ln,noWrap:ln,object:null,profile:null,prompt:null,rev:null,rightMargin:ht,rules:null,scheme:null,scrolling:us,standby:null,summary:null,text:null,topMargin:ht,valueType:null,version:null,vAlign:null,vLink:null,vSpace:ht,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ln,disableRemotePlayback:ln,prefix:null,property:null,results:ht,security:null,unselectable:null},space:"html",transform:Vf}),v0=Za({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:Us,accentHeight:ht,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:ht,amplitude:ht,arabicForm:null,ascent:ht,attributeName:null,attributeType:null,azimuth:ht,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:ht,by:null,calcMode:null,capHeight:ht,className:Fn,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:ht,diffuseConstant:ht,direction:null,display:null,dur:null,divisor:ht,dominantBaseline:null,download:ln,dx:null,dy:null,edgeMode:null,editable:null,elevation:ht,enableBackground:null,end:null,event:null,exponent:ht,externalResourcesRequired:null,fill:null,fillOpacity:ht,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:Ia,g2:Ia,glyphName:Ia,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:ht,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:ht,horizOriginX:ht,horizOriginY:ht,id:null,ideographic:ht,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:ht,k:ht,k1:ht,k2:ht,k3:ht,k4:ht,kernelMatrix:Us,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:ht,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:ht,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:ht,overlineThickness:ht,paintOrder:null,panose1:null,path:null,pathLength:ht,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Fn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:ht,pointsAtY:ht,pointsAtZ:ht,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Us,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Us,rev:Us,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Us,requiredFeatures:Us,requiredFonts:Us,requiredFormats:Us,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:ht,specularExponent:ht,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:ht,strikethroughThickness:ht,string:null,stroke:null,strokeDashArray:Us,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:ht,strokeOpacity:ht,strokeWidth:null,style:null,surfaceScale:ht,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Us,tabIndex:ht,tableValues:null,target:null,targetX:ht,targetY:ht,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Us,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:ht,underlineThickness:ht,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:ht,values:null,vAlphabetic:ht,vMathematical:ht,vectorEffect:null,vHanging:ht,vIdeographic:ht,version:null,vertAdvY:ht,vertOriginX:ht,vertOriginY:ht,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:ht,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:qf}),Wf=Za({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()}}),Kf=Za({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Vf}),Gf=Za({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),y0={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"},w0=/[A-Z]/g,Tm=/-[a-z]/g,k0=/^data[-\w.:]+$/i;function j0(e,n){const s=kd(n);let a=n,r=Fs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&k0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Tm,S0);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Tm.test(o)){let l=o.replace(w0,N0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=eu}return new r(a,n)}function N0(e){return"-"+e.toLowerCase()}function S0(e){return e.charAt(1).toUpperCase()}const C0=Bf([Hf,x0,Wf,Kf,Gf],"html"),tu=Bf([Hf,v0,Wf,Kf,Gf],"svg");function E0(e){return e.join(" ").trim()}var ja={},uc,Im;function M0(){if(Im)return uc;Im=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
644
+ `,u="/",m="*",h="",f="comment",p="declaration";function g(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,j=1;function C(R){var P=R.match(n);P&&(y+=P.length);var F=R.lastIndexOf(d);j=~F?R.length-F:j+R.length}function A(){var R={line:y,column:j};return function(P){return P.position=new N(R),T(),P}}function N(R){this.start=R,this.end={line:y,column:j},this.source=b.source}N.prototype.content=v;function S(R){var P=new Error(b.source+":"+y+":"+j+": "+R);if(P.reason=R,P.filename=b.source,P.line=y,P.column=j,P.source=v,!b.silent)throw P}function _(R){var P=R.exec(v);if(P){var F=P[0];return C(F),v=v.slice(F.length),P}}function T(){_(s)}function M(R){var P;for(R=R||[];P=E();)P!==!1&&R.push(P);return R}function E(){var R=A();if(!(u!=v.charAt(0)||m!=v.charAt(1))){for(var P=2;h!=v.charAt(P)&&(m!=v.charAt(P)||u!=v.charAt(P+1));)++P;if(P+=2,h===v.charAt(P-1))return S("End of comment missing");var F=v.slice(2,P-2);return j+=2,C(F),v=v.slice(P),j+=2,R({type:f,comment:F})}}function O(){var R=A(),P=_(a);if(P){if(E(),!_(r))return S("property missing ':'");var F=_(o),q=R({type:p,property:x(P[0].replace(e,h)),value:F?x(F[0].replace(e,h)):h});return _(l),q}}function B(){var R=[];M(R);for(var P;P=O();)P!==!1&&(R.push(P),M(R));return R}return T(),B()}function x(v){return v?v.replace(c,h):h}return uc=g,uc}var $m;function _0(){if($m)return ja;$m=1;var e=ja&&ja.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(ja,"__esModule",{value:!0}),ja.default=s;const n=e(M0());function s(a,r){let o=null;if(!a||typeof a!="string")return o;const l=(0,n.default)(a),c=typeof r=="function";return l.forEach(d=>{if(d.type!=="declaration")return;const{property:u,value:m}=d;c?r(u,m,d):m&&(o=o||{},o[u]=m)}),o}return ja}var dr={},Dm;function A0(){if(Dm)return dr;Dm=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,a=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(u){return!u||s.test(u)||e.test(u)},l=function(u,m){return m.toUpperCase()},c=function(u,m){return"".concat(m,"-")},d=function(u,m){return m===void 0&&(m={}),o(u)?u:(u=u.toLowerCase(),m.reactCompat?u=u.replace(r,c):u=u.replace(a,c),u.replace(n,l))};return dr.camelCase=d,dr}var ur,Lm;function P0(){if(Lm)return ur;Lm=1;var e=ur&&ur.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(_0()),s=A0();function a(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,d){c&&d&&(l[(0,s.camelCase)(c,o)]=d)}),l}return a.default=a,ur=a,ur}var R0=P0();const T0=Qp(R0),Jf=Yf("end"),nu=Yf("start");function Yf(e){return n;function n(s){const a=s&&s.position&&s.position[e]||{};if(typeof a.line=="number"&&a.line>0&&typeof a.column=="number"&&a.column>0)return{line:a.line,column:a.column,offset:typeof a.offset=="number"&&a.offset>-1?a.offset:void 0}}}function I0(e){const n=nu(e),s=Jf(e);if(n&&s)return{start:n,end:s}}function Dr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Om(e.position):"start"in e||"end"in e?Om(e):"line"in e||"column"in e?Sd(e):""}function Sd(e){return zm(e&&e.line)+":"+zm(e&&e.column)}function Om(e){return Sd(e&&e.start)+"-"+Sd(e&&e.end)}function zm(e){return e&&typeof e=="number"?e:1}class As extends Error{constructor(n,s,a){super(),typeof s=="string"&&(a=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 a=="string"){const d=a.indexOf(":");d===-1?o.ruleId=a:(o.source=a.slice(0,d),o.ruleId=a.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=Dr(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}As.prototype.file="";As.prototype.name="";As.prototype.reason="";As.prototype.message="";As.prototype.stack="";As.prototype.column=void 0;As.prototype.line=void 0;As.prototype.ancestors=void 0;As.prototype.cause=void 0;As.prototype.fatal=void 0;As.prototype.place=void 0;As.prototype.ruleId=void 0;As.prototype.source=void 0;const su={}.hasOwnProperty,$0=new Map,D0=/[A-Z]/g,L0=new Set(["table","tbody","thead","tfoot","tr"]),O0=new Set(["td","th"]),Qf="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function z0(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let a;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");a=K0(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");a=W0(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:a,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"?tu:C0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Xf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Xf(e,n,s){if(n.type==="element")return F0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return U0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return H0(e,n,s);if(n.type==="mdxjsEsm")return B0(e,n);if(n.type==="root")return q0(e,n,s);if(n.type==="text")return V0(e,n)}function F0(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=tu,e.schema=r),e.ancestors.push(n);const o=eg(e,n.tagName,!1),l=G0(e,n);let c=au(e,n);return L0.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!g0(d):!0})),Zf(e,l,o,n),iu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function U0(e,n){if(n.data&&n.data.estree&&e.evaluater){const a=n.data.estree.body[0];return a.type,e.evaluater.evaluateExpression(a.expression)}Wr(e,n.position)}function B0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Wr(e,n.position)}function H0(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=tu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:eg(e,n.name,!0),l=J0(e,n),c=au(e,n);return Zf(e,l,o,n),iu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function q0(e,n,s){const a={};return iu(a,au(e,n)),e.create(n,e.Fragment,a,s)}function V0(e,n){return n.value}function Zf(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function iu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function W0(e,n,s){return a;function a(r,o,l,c){const u=Array.isArray(l.children)?s:n;return c?u(o,l,c):u(o,l)}}function K0(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=nu(a);return n(r,o,l,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function G0(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&su.call(n.properties,r)){const o=Y0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&O0.has(n.tagName)?a=c:s[l]=c}}if(a){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=a}return s}function J0(e,n){const s={};for(const a of n.attributes)if(a.type==="mdxJsxExpressionAttribute")if(a.data&&a.data.estree&&e.evaluater){const o=a.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 Wr(e,n.position);else{const r=a.name;let o;if(a.value&&typeof a.value=="object")if(a.value.data&&a.value.data.estree&&e.evaluater){const c=a.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else Wr(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function au(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:$0;for(;++a<n.children.length;){const o=n.children[a];let l;if(e.passKeys){const d=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(d){const u=r.get(d)||0;l=d+"-"+u,r.set(d,u+1)}}const c=Xf(e,o,l);c!==void 0&&s.push(c)}return s}function Y0(e,n,s){const a=j0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?u0(s):E0(s)),a.property==="style"){let r=typeof s=="object"?s:Q0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=X0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?y0[a.property]||a.property:a.attribute,s]}}function Q0(e,n){try{return T0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new As("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:a,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=Qf+"#cannot-parse-style-attribute",r}}function eg(e,n,s){let a;if(!s)a={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=Am(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}a=l}else a=Am(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return su.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);Wr(e)}function Wr(e,n){const s=new As("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=Qf+"#cannot-handle-mdx-estrees-without-createevaluater",s}function X0(e){const n={};let s;for(s in e)su.call(e,s)&&(n[Z0(s)]=e[s]);return n}function Z0(e){let n=e.replace(D0,eC);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function eC(e){return"-"+e.toLowerCase()}const mc={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"]},tC={};function ru(e,n){const s=tC,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return tg(e,a,r)}function tg(e,n,s){if(nC(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 Fm(e.children,n,s)}return Array.isArray(e)?Fm(e,n,s):""}function Fm(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=tg(e[r],n,s);return a.join("")}function nC(e){return!!(e&&typeof e=="object")}const Um=document.createElement("i");function ou(e){const n="&"+e+";";Um.innerHTML=n;const s=Um.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Vs(e,n,s,a){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,a.length<1e4)l=Array.from(a),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<a.length;)l=a.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function si(e,n){return e.length>0?(Vs(e,e.length,0,n),e):n}const Bm={}.hasOwnProperty;function ng(e){const n={};let s=-1;for(;++s<e.length;)sC(n,e[s]);return n}function sC(e,n){let s;for(s in n){const r=(Bm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Bm.call(r,l)||(r[l]=[]);const c=o[l];iC(r[l],Array.isArray(c)?c:c?[c]:[])}}}function iC(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Vs(e,0,0,a)}function sg(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 mi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const $s=Gi(/[A-Za-z]/),Ms=Gi(/[\dA-Za-z]/),aC=Gi(/[#-'*+\--9=?A-Z^-~]/);function ml(e){return e!==null&&(e<32||e===127)}const Cd=Gi(/\d/),rC=Gi(/[\dA-Fa-f]/),oC=Gi(/[!-/:-@[-`{-~]/);function Ot(e){return e!==null&&e<-2}function $n(e){return e!==null&&(e<0||e===32)}function xn(e){return e===-2||e===-1||e===32}const Dl=Gi(/\p{P}|\p{S}/u),ua=Gi(/\s/);function Gi(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function er(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&Ms(e.charCodeAt(s+1))&&Ms(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(a,s),encodeURIComponent(l)),a=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(a)}function kn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return xn(d)?(e.enter(s),c(d)):n(d)}function c(d){return xn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const lC={tokenize:cC};function cC(e){const n=e.attempt(this.parser.constructs.contentInitial,a,r);let s;return n;function a(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),kn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const d=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=d),s=d,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Ot(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const dC={tokenize:uC},Hm={tokenize:mC};function uC(e){const n=this,s=[];let a=0,r,o,l;return c;function c(j){if(a<s.length){const C=s[a];return n.containerState=C[1],e.attempt(C[0].continuation,d,u)(j)}return u(j)}function d(j){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const C=n.events.length;let A=C,N;for(;A--;)if(n.events[A][0]==="exit"&&n.events[A][1].type==="chunkFlow"){N=n.events[A][1].end;break}b(a);let S=C;for(;S<n.events.length;)n.events[S][1].end={...N},S++;return Vs(n.events,A+1,0,n.events.slice(C)),n.events.length=S,u(j)}return c(j)}function u(j){if(a===s.length){if(!r)return f(j);if(r.currentConstruct&&r.currentConstruct.concrete)return g(j);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Hm,m,h)(j)}function m(j){return r&&y(),b(a),f(j)}function h(j){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(j)}function f(j){return n.containerState={},e.attempt(Hm,p,g)(j)}function p(j){return a++,s.push([n.currentConstruct,n.containerState]),f(j)}function g(j){if(j===null){r&&y(),b(0),e.consume(j);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(j)}function x(j){if(j===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(j);return}return Ot(j)?(e.consume(j),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(j),x)}function v(j,C){const A=n.sliceStream(j);if(C&&A.push(null),j.previous=o,o&&(o.next=j),o=j,r.defineSkip(j.start),r.write(A),n.parser.lazy[j.start.line]){let N=r.events.length;for(;N--;)if(r.events[N][1].start.offset<l&&(!r.events[N][1].end||r.events[N][1].end.offset>l))return;const S=n.events.length;let _=S,T,M;for(;_--;)if(n.events[_][0]==="exit"&&n.events[_][1].type==="chunkFlow"){if(T){M=n.events[_][1].end;break}T=!0}for(b(a),N=S;N<n.events.length;)n.events[N][1].end={...M},N++;Vs(n.events,_+1,0,n.events.slice(S)),n.events.length=N}}function b(j){let C=s.length;for(;C-- >j;){const A=s[C];n.containerState=A[1],A[0].exit.call(n,e)}s.length=j}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function mC(e,n,s){return kn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ba(e){if(e===null||$n(e)||ua(e))return 1;if(Dl(e))return 2}function Ll(e,n,s){const a=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!a.includes(o)&&(n=o(n,s),a.push(o))}return n}const Ed={name:"attention",resolveAll:hC,tokenize:pC};function hC(e,n){let s=-1,a,r,o,l,c,d,u,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(a=s;a--;)if(e[a][0]==="exit"&&e[a][1].type==="attentionSequence"&&e[a][1]._open&&n.sliceSerialize(e[a][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[a][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[a][1].end.offset-e[a][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;d=e[a][1].end.offset-e[a][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[a][1].end},f={...e[s][1].start};qm(h,-d),qm(f,d),l={type:d>1?"strongSequence":"emphasisSequence",start:h,end:{...e[a][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:d>1?"strongText":"emphasisText",start:{...e[a][1].end},end:{...e[s][1].start}},r={type:d>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[a][1].end={...l.start},e[s][1].start={...c.end},u=[],e[a][1].end.offset-e[a][1].start.offset&&(u=si(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=si(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=si(u,Ll(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=si(u,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,u=si(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Vs(e,a-1,s-a+3,u),s=a+u.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function pC(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Ba(a);let o;return l;function l(d){return o=d,e.enter("attentionSequence"),c(d)}function c(d){if(d===o)return e.consume(d),c;const u=e.exit("attentionSequence"),m=Ba(d),h=!m||m===2&&r||s.includes(d),f=!r||r===2&&m||s.includes(a);return u._open=!!(o===42?h:h&&(r||!f)),u._close=!!(o===42?f:f&&(m||!h)),n(d)}}function qm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const fC={name:"autolink",tokenize:gC};function gC(e,n,s){let a=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 $s(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||Ms(p)?(a=1,c(p)):u(p)}function c(p){return p===58?(e.consume(p),a=0,d):(p===43||p===45||p===46||Ms(p))&&a++<32?(e.consume(p),c):(a=0,u(p))}function d(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||ml(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):aC(p)?(e.consume(p),u):s(p)}function m(p){return Ms(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),a=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||Ms(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const oo={partial:!0,tokenize:bC};function bC(e,n,s){return a;function a(o){return xn(o)?kn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Ot(o)?n(o):s(o)}}const ig={continuation:{tokenize:vC},exit:yC,name:"blockQuote",tokenize:xC};function xC(e,n,s){const a=this;return r;function r(l){if(l===62){const c=a.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 xn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function vC(e,n,s){const a=this;return r;function r(l){return xn(l)?kn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(ig,n,s)(l)}}function yC(e){e.exit("blockQuote")}const ag={name:"characterEscape",tokenize:wC};function wC(e,n,s){return a;function a(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return oC(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const rg={name:"characterReference",tokenize:kC};function kC(e,n,s){const a=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),d}function d(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,l=Ms,m(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=rC,m):(e.enter("characterReferenceValue"),o=7,l=Cd,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===Ms&&!ou(a.sliceSerialize(f))?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 Vm={partial:!0,tokenize:NC},Wm={concrete:!0,name:"codeFenced",tokenize:jC};function jC(e,n,s){const a=this,r={partial:!0,tokenize:A};let o=0,l=0,c;return d;function d(N){return u(N)}function u(N){const S=a.events[a.events.length-1];return o=S&&S[1].type==="linePrefix"?S[2].sliceSerialize(S[1],!0).length:0,c=N,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(N)}function m(N){return N===c?(l++,e.consume(N),m):l<3?s(N):(e.exit("codeFencedFenceSequence"),xn(N)?kn(e,h,"whitespace")(N):h(N))}function h(N){return N===null||Ot(N)?(e.exit("codeFencedFence"),a.interrupt?n(N):e.check(Vm,x,C)(N)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(N))}function f(N){return N===null||Ot(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(N)):xn(N)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),kn(e,p,"whitespace")(N)):N===96&&N===c?s(N):(e.consume(N),f)}function p(N){return N===null||Ot(N)?h(N):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(N))}function g(N){return N===null||Ot(N)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(N)):N===96&&N===c?s(N):(e.consume(N),g)}function x(N){return e.attempt(r,C,v)(N)}function v(N){return e.enter("lineEnding"),e.consume(N),e.exit("lineEnding"),b}function b(N){return o>0&&xn(N)?kn(e,y,"linePrefix",o+1)(N):y(N)}function y(N){return N===null||Ot(N)?e.check(Vm,x,C)(N):(e.enter("codeFlowValue"),j(N))}function j(N){return N===null||Ot(N)?(e.exit("codeFlowValue"),y(N)):(e.consume(N),j)}function C(N){return e.exit("codeFenced"),n(N)}function A(N,S,_){let T=0;return M;function M(P){return N.enter("lineEnding"),N.consume(P),N.exit("lineEnding"),E}function E(P){return N.enter("codeFencedFence"),xn(P)?kn(N,O,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(P):O(P)}function O(P){return P===c?(N.enter("codeFencedFenceSequence"),B(P)):_(P)}function B(P){return P===c?(T++,N.consume(P),B):T>=l?(N.exit("codeFencedFenceSequence"),xn(P)?kn(N,R,"whitespace")(P):R(P)):_(P)}function R(P){return P===null||Ot(P)?(N.exit("codeFencedFence"),S(P)):_(P)}}}function NC(e,n,s){const a=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 a.parser.lazy[a.now().line]?s(l):n(l)}}const hc={name:"codeIndented",tokenize:CC},SC={partial:!0,tokenize:EC};function CC(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),kn(e,o,"linePrefix",5)(u)}function o(u){const m=a.events[a.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(u):s(u)}function l(u){return u===null?d(u):Ot(u)?e.attempt(SC,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Ot(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function EC(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Ot(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):kn(e,o,"linePrefix",5)(l)}function o(l){const c=a.events[a.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):Ot(l)?r(l):s(l)}}const MC={name:"codeText",previous:AC,resolve:_C,tokenize:PC};function _C(e){let n=e.length-4,s=3,a,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(a=s;++a<n;)if(e[a][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(a=s-1,n++;++a<=n;)r===void 0?a!==n&&e[a][1].type!=="lineEnding"&&(r=a):(a===n||e[a][1].type==="lineEnding")&&(e[r][1].type="codeTextData",a!==r+2&&(e[r][1].end=e[a-1][1].end,e.splice(r+2,a-r-2),n-=a-r-2,a=r+2),r=void 0);return e}function AC(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function PC(e,n,s){let a=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),a++,c):(e.exit("codeTextSequence"),d(h))}function d(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),d):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):Ot(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||Ot(h)?(e.exit("codeTextData"),d(h)):(e.consume(h),u)}function m(h){return h===96?(e.consume(h),r++,m):r===a?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",u(h))}}class RC{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 a=s??Number.POSITIVE_INFINITY;return a<this.left.length?this.left.slice(n,a):n>this.left.length?this.right.slice(this.right.length-a+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-a+this.left.length).reverse())}splice(n,s,a){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return a&&mr(this.left,a),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),mr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),mr(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);mr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);mr(this.left,s.reverse())}}}function mr(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 og(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new RC(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(a=m.get(s),s&&a[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(d=a[1]._tokenizer.events,o=0,o<d.length&&d[o][1].type==="lineEndingBlank"&&(o+=2),o<d.length&&d[o][1].type==="content"))for(;++o<d.length&&d[o][1].type!=="content";)d[o][1].type==="chunkText"&&(d[o][1]._isInFirstContentOfListItem=!0,o++);if(a[0]==="enter")a[1].contentType&&(Object.assign(n,TC(m,s)),s=n[s],u=!0);else if(a[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&&(a[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(a),m.splice(r,s-r+1,c))}}return Vs(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function TC(e,n){const s=e.get(n)[1],a=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=a.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,d=[],u={};let m,h,f=-1,p=s,g=0,x=0;const v=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=a.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;++f<c.length;)c[f][0]==="exit"&&c[f-1][0]==="enter"&&c[f][1].type===c[f-1][1].type&&c[f][1].start.line!==c[f][1].end.line&&(x=f+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(),f=v.length;f--;){const b=c.slice(v[f],v[f+1]),y=o.pop();d.push([y,y+b.length-1]),e.splice(y,2,b)}for(d.reverse(),f=-1;++f<d.length;)u[g+d[f][0]]=g+d[f][1],g+=d[f][1]-d[f][0]-1;return u}const IC={resolve:DC,tokenize:LC},$C={partial:!0,tokenize:OC};function DC(e){return og(e),e}function LC(e,n){let s;return a;function a(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):Ot(c)?e.check($C,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 OC(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),kn(e,o,"linePrefix")}function o(l){if(l===null||Ot(l))return s(l);const c=a.events[a.events.length-1];return!a.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(a.parser.constructs.flow,s,n)(l)}}function lg(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(a),e.enter(r),e.enter(o),e.consume(b),e.exit(o),f):b===null||b===32||b===41||ml(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function f(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(a),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),f(b)):b===null||b===60||Ot(b)?s(b):(e.consume(b),b===92?g:p)}function g(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||$n(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):m<u&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||ml(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 cg(e,n,s,a,r,o){const l=this;let c=0,d;return u;function u(p){return e.enter(a),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&&!d||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(a),n):Ot(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||Ot(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!xn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function dg(e,n,s,a,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(a),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,d):s(f)}function d(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(a),n):(e.enter(o),u(f))}function u(f){return f===l?(e.exit(o),d(l)):f===null?s(f):Ot(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),kn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Ot(f)?(e.exit("chunkString"),u(f)):(e.consume(f),f===92?h:m)}function h(f){return f===l||f===92?(e.consume(f),m):m(f)}}function Lr(e,n){let s;return a;function a(r){return Ot(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):xn(r)?kn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const zC={name:"definition",tokenize:UC},FC={partial:!0,tokenize:BC};function UC(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return cg.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=mi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),d):s(p)}function d(p){return $n(p)?Lr(e,u)(p):u(p)}function u(p){return lg(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(FC,h,h)(p)}function h(p){return xn(p)?kn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Ot(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function BC(e,n,s){return a;function a(c){return $n(c)?Lr(e,r)(c):s(c)}function r(c){return dg(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return xn(c)?kn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Ot(c)?n(c):s(c)}}const HC={name:"hardBreakEscape",tokenize:qC};function qC(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Ot(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const VC={name:"headingAtx",resolve:WC,tokenize:KC};function WC(e,n){let s=e.length-2,a=3,r,o;return e[a][1].type==="whitespace"&&(a+=2),s-2>a&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(a===s-1||s-4>a&&e[s-2][1].type==="whitespace")&&(s-=a+1===s?2:4),s>a&&(r={type:"atxHeadingText",start:e[a][1].start,end:e[s][1].end},o={type:"chunkText",start:e[a][1].start,end:e[s][1].end,contentType:"text"},Vs(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function KC(e,n,s){let a=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&&a++<6?(e.consume(m),l):m===null||$n(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||Ot(m)?(e.exit("atxHeading"),n(m)):xn(m)?kn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),u(m))}function d(m){return m===35?(e.consume(m),d):(e.exit("atxHeadingSequence"),c(m))}function u(m){return m===null||m===35||$n(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const GC=["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"],Km=["pre","script","style","textarea"],JC={concrete:!0,name:"htmlFlow",resolveTo:XC,tokenize:ZC},YC={partial:!0,tokenize:t2},QC={partial:!0,tokenize:e2};function XC(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 ZC(e,n,s){const a=this;let r,o,l,c,d;return u;function u(w){return m(w)}function m(w){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(w),h}function h(w){return w===33?(e.consume(w),f):w===47?(e.consume(w),o=!0,x):w===63?(e.consume(w),r=3,a.interrupt?n:k):$s(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function f(w){return w===45?(e.consume(w),r=2,p):w===91?(e.consume(w),r=5,c=0,g):$s(w)?(e.consume(w),r=4,a.interrupt?n:k):s(w)}function p(w){return w===45?(e.consume(w),a.interrupt?n:k):s(w)}function g(w){const H="CDATA[";return w===H.charCodeAt(c++)?(e.consume(w),c===H.length?a.interrupt?n:O:g):s(w)}function x(w){return $s(w)?(e.consume(w),l=String.fromCharCode(w),v):s(w)}function v(w){if(w===null||w===47||w===62||$n(w)){const H=w===47,J=l.toLowerCase();return!H&&!o&&Km.includes(J)?(r=1,a.interrupt?n(w):O(w)):GC.includes(l.toLowerCase())?(r=6,H?(e.consume(w),b):a.interrupt?n(w):O(w)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(w):o?y(w):j(w))}return w===45||Ms(w)?(e.consume(w),l+=String.fromCharCode(w),v):s(w)}function b(w){return w===62?(e.consume(w),a.interrupt?n:O):s(w)}function y(w){return xn(w)?(e.consume(w),y):M(w)}function j(w){return w===47?(e.consume(w),M):w===58||w===95||$s(w)?(e.consume(w),C):xn(w)?(e.consume(w),j):M(w)}function C(w){return w===45||w===46||w===58||w===95||Ms(w)?(e.consume(w),C):A(w)}function A(w){return w===61?(e.consume(w),N):xn(w)?(e.consume(w),A):j(w)}function N(w){return w===null||w===60||w===61||w===62||w===96?s(w):w===34||w===39?(e.consume(w),d=w,S):xn(w)?(e.consume(w),N):_(w)}function S(w){return w===d?(e.consume(w),d=null,T):w===null||Ot(w)?s(w):(e.consume(w),S)}function _(w){return w===null||w===34||w===39||w===47||w===60||w===61||w===62||w===96||$n(w)?A(w):(e.consume(w),_)}function T(w){return w===47||w===62||xn(w)?j(w):s(w)}function M(w){return w===62?(e.consume(w),E):s(w)}function E(w){return w===null||Ot(w)?O(w):xn(w)?(e.consume(w),E):s(w)}function O(w){return w===45&&r===2?(e.consume(w),F):w===60&&r===1?(e.consume(w),q):w===62&&r===4?(e.consume(w),I):w===63&&r===3?(e.consume(w),k):w===93&&r===5?(e.consume(w),U):Ot(w)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(YC,$,B)(w)):w===null||Ot(w)?(e.exit("htmlFlowData"),B(w)):(e.consume(w),O)}function B(w){return e.check(QC,R,$)(w)}function R(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),P}function P(w){return w===null||Ot(w)?B(w):(e.enter("htmlFlowData"),O(w))}function F(w){return w===45?(e.consume(w),k):O(w)}function q(w){return w===47?(e.consume(w),l="",ee):O(w)}function ee(w){if(w===62){const H=l.toLowerCase();return Km.includes(H)?(e.consume(w),I):O(w)}return $s(w)&&l.length<8?(e.consume(w),l+=String.fromCharCode(w),ee):O(w)}function U(w){return w===93?(e.consume(w),k):O(w)}function k(w){return w===62?(e.consume(w),I):w===45&&r===2?(e.consume(w),k):O(w)}function I(w){return w===null||Ot(w)?(e.exit("htmlFlowData"),$(w)):(e.consume(w),I)}function $(w){return e.exit("htmlFlow"),n(w)}}function e2(e,n,s){const a=this;return r;function r(l){return Ot(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}function t2(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(oo,n,s)}}const n2={name:"htmlText",tokenize:s2};function s2(e,n,s){const a=this;let r,o,l;return c;function c(k){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(k),d}function d(k){return k===33?(e.consume(k),u):k===47?(e.consume(k),A):k===63?(e.consume(k),j):$s(k)?(e.consume(k),_):s(k)}function u(k){return k===45?(e.consume(k),m):k===91?(e.consume(k),o=0,g):$s(k)?(e.consume(k),y):s(k)}function m(k){return k===45?(e.consume(k),p):s(k)}function h(k){return k===null?s(k):k===45?(e.consume(k),f):Ot(k)?(l=h,q(k)):(e.consume(k),h)}function f(k){return k===45?(e.consume(k),p):h(k)}function p(k){return k===62?F(k):k===45?f(k):h(k)}function g(k){const I="CDATA[";return k===I.charCodeAt(o++)?(e.consume(k),o===I.length?x:g):s(k)}function x(k){return k===null?s(k):k===93?(e.consume(k),v):Ot(k)?(l=x,q(k)):(e.consume(k),x)}function v(k){return k===93?(e.consume(k),b):x(k)}function b(k){return k===62?F(k):k===93?(e.consume(k),b):x(k)}function y(k){return k===null||k===62?F(k):Ot(k)?(l=y,q(k)):(e.consume(k),y)}function j(k){return k===null?s(k):k===63?(e.consume(k),C):Ot(k)?(l=j,q(k)):(e.consume(k),j)}function C(k){return k===62?F(k):j(k)}function A(k){return $s(k)?(e.consume(k),N):s(k)}function N(k){return k===45||Ms(k)?(e.consume(k),N):S(k)}function S(k){return Ot(k)?(l=S,q(k)):xn(k)?(e.consume(k),S):F(k)}function _(k){return k===45||Ms(k)?(e.consume(k),_):k===47||k===62||$n(k)?T(k):s(k)}function T(k){return k===47?(e.consume(k),F):k===58||k===95||$s(k)?(e.consume(k),M):Ot(k)?(l=T,q(k)):xn(k)?(e.consume(k),T):F(k)}function M(k){return k===45||k===46||k===58||k===95||Ms(k)?(e.consume(k),M):E(k)}function E(k){return k===61?(e.consume(k),O):Ot(k)?(l=E,q(k)):xn(k)?(e.consume(k),E):T(k)}function O(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),r=k,B):Ot(k)?(l=O,q(k)):xn(k)?(e.consume(k),O):(e.consume(k),R)}function B(k){return k===r?(e.consume(k),r=void 0,P):k===null?s(k):Ot(k)?(l=B,q(k)):(e.consume(k),B)}function R(k){return k===null||k===34||k===39||k===60||k===61||k===96?s(k):k===47||k===62||$n(k)?T(k):(e.consume(k),R)}function P(k){return k===47||k===62||$n(k)?T(k):s(k)}function F(k){return k===62?(e.consume(k),e.exit("htmlTextData"),e.exit("htmlText"),n):s(k)}function q(k){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),ee}function ee(k){return xn(k)?kn(e,U,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(k):U(k)}function U(k){return e.enter("htmlTextData"),l(k)}}const lu={name:"labelEnd",resolveAll:o2,resolveTo:l2,tokenize:c2},i2={tokenize:d2},a2={tokenize:u2},r2={tokenize:m2};function o2(e){let n=-1;const s=[];for(;++n<e.length;){const a=e[n][1];if(s.push(e[n]),a.type==="labelImage"||a.type==="labelLink"||a.type==="labelEnd"){const r=a.type==="labelImage"?4:2;a.type="data",n+=r}}return e.length!==s.length&&Vs(e,0,e.length,s),e}function l2(e,n){let s=e.length,a=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")){a=2;break}}else r.type==="labelEnd"&&(l=s);const d={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+a+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",d,n],["enter",u,n]],c=si(c,e.slice(o+1,o+a+3)),c=si(c,[["enter",m,n]]),c=si(c,Ll(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=si(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=si(c,e.slice(l+1)),c=si(c,[["exit",d,n]]),Vs(e,o,e.length,c),e}function c2(e,n,s){const a=this;let r=a.events.length,o,l;for(;r--;)if((a.events[r][1].type==="labelImage"||a.events[r][1].type==="labelLink")&&!a.events[r][1]._balanced){o=a.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=a.parser.defined.includes(mi(a.sliceSerialize({start:o.end,end:a.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),d):s(f)}function d(f){return f===40?e.attempt(i2,m,l?m:h)(f):f===91?e.attempt(a2,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(r2,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function d2(e,n,s){return a;function a(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return $n(h)?Lr(e,o)(h):o(h)}function o(h){return h===41?m(h):lg(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return $n(h)?Lr(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?dg(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return $n(h)?Lr(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 u2(e,n,s){const a=this;return r;function r(c){return cg.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(mi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function m2(e,n,s){return a;function a(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 h2={name:"labelStartImage",resolveAll:lu.resolveAll,tokenize:p2};function p2(e,n,s){const a=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 a.parser.constructs?s(c):n(c)}}const f2={name:"labelStartLink",resolveAll:lu.resolveAll,tokenize:g2};function g2(e,n,s){const a=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 a.parser.constructs?s(l):n(l)}}const pc={name:"lineEnding",tokenize:b2};function b2(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),kn(e,n,"linePrefix")}}const Qo={name:"thematicBreak",tokenize:x2};function x2(e,n,s){let a=0,r;return o;function o(u){return e.enter("thematicBreak"),l(u)}function l(u){return r=u,c(u)}function c(u){return u===r?(e.enter("thematicBreakSequence"),d(u)):a>=3&&(u===null||Ot(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),xn(u)?kn(e,c,"whitespace")(u):c(u))}}const Ls={continuation:{tokenize:k2},exit:N2,name:"list",tokenize:w2},v2={partial:!0,tokenize:S2},y2={partial:!0,tokenize:j2};function w2(e,n,s){const a=this,r=a.events[a.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 g=a.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!a.containerState.marker||p===a.containerState.marker:Cd(p)){if(a.containerState.type||(a.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Qo,s,u)(p):u(p);if(!a.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(p)}return s(p)}function d(p){return Cd(p)&&++l<10?(e.consume(p),d):(!a.interrupt||l<2)&&(a.containerState.marker?p===a.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):s(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),a.containerState.marker=a.containerState.marker||p,e.check(oo,a.interrupt?s:m,e.attempt(v2,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return xn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return a.containerState.size=o+a.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function k2(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(oo,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,kn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!xn(c)?(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,l(c)):(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,e.attempt(y2,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,kn(e,e.attempt(Ls,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function j2(e,n,s){const a=this;return kn(e,r,"listItemIndent",a.containerState.size+1);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===a.containerState.size?n(o):s(o)}}function N2(e){e.exit(this.containerState.type)}function S2(e,n,s){const a=this;return kn(e,r,"listItemPrefixWhitespace",a.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=a.events[a.events.length-1];return!xn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Gm={name:"setextUnderline",resolveTo:C2,tokenize:E2};function C2(e,n){let s=e.length,a,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){a=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[a][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[a][1],n]),e[a][1].end={...e[o][1].end}):e[a][1]=l,e.push(["exit",l,n]),e}function E2(e,n,s){const a=this;let r;return o;function o(u){let m=a.events.length,h;for(;m--;)if(a.events[m][1].type!=="lineEnding"&&a.events[m][1].type!=="linePrefix"&&a.events[m][1].type!=="content"){h=a.events[m][1].type==="paragraph";break}return!a.parser.lazy[a.now().line]&&(a.interrupt||h)?(e.enter("setextHeadingLine"),r=u,l(u)):s(u)}function l(u){return e.enter("setextHeadingLineSequence"),c(u)}function c(u){return u===r?(e.consume(u),c):(e.exit("setextHeadingLineSequence"),xn(u)?kn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Ot(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const M2={tokenize:_2};function _2(e){const n=this,s=e.attempt(oo,a,e.attempt(this.parser.constructs.flowInitial,r,kn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(IC,r)),"linePrefix")));return s;function a(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 A2={resolveAll:mg()},P2=ug("string"),R2=ug("text");function ug(e){return{resolveAll:mg(e==="text"?T2:void 0),tokenize:n};function n(s){const a=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return u(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),d}function d(m){return u(m)?(s.exit("data"),o(m)):(s.consume(m),d)}function u(m){if(m===null)return!0;const h=r[m];let f=-1;if(h)for(;++f<h.length;){const p=h[f];if(!p.previous||p.previous.call(a,a.previous))return!0}return!1}}}function mg(e){return n;function n(s,a){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,a):s}}function T2(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 a=e[s-1][1],r=n.sliceStream(a);let o=r.length,l=-1,c=0,d;for(;o--;){const u=r[o];if(typeof u=="string"){for(l=u.length;u.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(u===-2)d=!0,c++;else if(u!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const u={type:s===e.length||d||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:a.start._bufferIndex+l,_index:a.start._index+o,line:a.end.line,column:a.end.column-c,offset:a.end.offset-c},end:{...a.end}};a.end={...u.start},a.start.offset===a.end.offset?Object.assign(a,u):(e.splice(s,0,["enter",u,n],["exit",u,n]),s+=2)}s++}return e}const I2={42:Ls,43:Ls,45:Ls,48:Ls,49:Ls,50:Ls,51:Ls,52:Ls,53:Ls,54:Ls,55:Ls,56:Ls,57:Ls,62:ig},$2={91:zC},D2={[-2]:hc,[-1]:hc,32:hc},L2={35:VC,42:Qo,45:[Gm,Qo],60:JC,61:Gm,95:Qo,96:Wm,126:Wm},O2={38:rg,92:ag},z2={[-5]:pc,[-4]:pc,[-3]:pc,33:h2,38:rg,42:Ed,60:[fC,n2],91:f2,92:[HC,ag],93:lu,95:Ed,96:MC},F2={null:[Ed,A2]},U2={null:[42,95]},B2={null:[]},H2=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:U2,contentInitial:$2,disable:B2,document:I2,flow:L2,flowInitial:D2,insideSpan:F2,string:O2,text:z2},Symbol.toStringTag,{value:"Module"}));function q2(e,n,s){let a={_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 d={attempt:S(A),check:S(N),consume:y,enter:j,exit:C,interrupt:S(N,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(E){return l=si(l,E),v(),l[l.length-1]!==null?[]:(_(n,0),u.events=Ll(o,u.events,u),u.events)}function f(E,O){return W2(p(E),O)}function p(E){return V2(l,E)}function g(){const{_bufferIndex:E,_index:O,line:B,column:R,offset:P}=a;return{_bufferIndex:E,_index:O,line:B,column:R,offset:P}}function x(E){r[E.line]=E.column,M()}function v(){let E;for(;a._index<l.length;){const O=l[a._index];if(typeof O=="string")for(E=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===E&&a._bufferIndex<O.length;)b(O.charCodeAt(a._bufferIndex));else b(O)}}function b(E){m=m(E)}function y(E){Ot(E)?(a.line++,a.column=1,a.offset+=E===-3?2:1,M()):E!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=E}function j(E,O){const B=O||{};return B.type=E,B.start=g(),u.events.push(["enter",B,u]),c.push(B),B}function C(E){const O=c.pop();return O.end=g(),u.events.push(["exit",O,u]),O}function A(E,O){_(E,O.from)}function N(E,O){O.restore()}function S(E,O){return B;function B(R,P,F){let q,ee,U,k;return Array.isArray(R)?$(R):"tokenize"in R?$([R]):I(R);function I(fe){return de;function de(D){const _e=D!==null&&fe[D],z=D!==null&&fe.null,Z=[...Array.isArray(_e)?_e:_e?[_e]:[],...Array.isArray(z)?z:z?[z]:[]];return $(Z)(D)}}function $(fe){return q=fe,ee=0,fe.length===0?F:w(fe[ee])}function w(fe){return de;function de(D){return k=T(),U=fe,fe.partial||(u.currentConstruct=fe),fe.name&&u.parser.constructs.disable.null.includes(fe.name)?J():fe.tokenize.call(O?Object.assign(Object.create(u),O):u,d,H,J)(D)}}function H(fe){return E(U,k),P}function J(fe){return k.restore(),++ee<q.length?w(q[ee]):F}}}function _(E,O){E.resolveAll&&!o.includes(E)&&o.push(E),E.resolve&&Vs(u.events,O,u.events.length-O,E.resolve(u.events.slice(O),u)),E.resolveTo&&(u.events=E.resolveTo(u.events,u))}function T(){const E=g(),O=u.previous,B=u.currentConstruct,R=u.events.length,P=Array.from(c);return{from:R,restore:F};function F(){a=E,u.previous=O,u.currentConstruct=B,u.events.length=R,c=P,M()}}function M(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function V2(e,n){const s=n.start._index,a=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(a,o)];else{if(l=e.slice(s,r),a>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(a):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function W2(e,n){let s=-1;const a=[];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=`
645
+ `;break}case-3:{l=`\r
646
+ `;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function K2(e){const a={constructs:ng([H2,...(e||{}).extensions||[]]),content:r(lC),defined:[],document:r(dC),flow:r(M2),lazy:{},string:r(P2),text:r(R2)};return a;function r(o){return l;function l(c){return q2(a,o,c)}}}function G2(e){for(;!og(e););return e}const Jm=/[\0\t\n\r]/g;function J2(){let e=1,n="",s=!0,a;return r;function r(o,l,c){const d=[];let u,m,h,f,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(Jm.lastIndex=h,u=Jm.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){n=o.slice(h);break}if(p===10&&h===f&&a)d.push(-3),a=void 0;else switch(a&&(d.push(-5),a=void 0),h<f&&(d.push(o.slice(h,f)),e+=f-h),p){case 0:{d.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,d.push(-2);e++<m;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:a=!0,e=1}h=f+1}return c&&(a&&d.push(-5),n&&d.push(n),d.push(null)),d}}const Y2=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Q2(e){return e.replace(Y2,X2)}function X2(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return sg(s.slice(o?2:1),o?16:10)}return ou(s)||e}const hg={}.hasOwnProperty;function Z2(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),eE(s)(G2(K2(s).document().write(J2()(e,n,!0))))}function eE(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(ke),autolinkProtocol:T,autolinkEmail:T,atxHeading:o(ce),blockQuote:o(z),characterEscape:T,characterReference:T,codeFenced:o(Z),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Z,l),codeText:o(oe,l),codeTextData:T,data:T,codeFlowValue:T,definition:o(Y),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(ae),hardBreakEscape:o(te),hardBreakTrailing:o(te),htmlFlow:o(Re,l),htmlFlowData:T,htmlText:o(Re,l),htmlTextData:T,image:o(be),label:l,link:o(ke),listItem:o(Ge),listItemValue:f,listOrdered:o(Ue,h),listUnordered:o(Ue),paragraph:o(qe),reference:w,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(ce),strong:o(Ae),thematicBreak:o(ie)},exit:{atxHeading:d(),atxHeadingSequence:A,autolink:d(),autolinkEmail:_e,autolinkProtocol:D,blockQuote:d(),characterEscapeValue:M,characterReferenceMarkerHexadecimal:J,characterReferenceMarkerNumeric:J,characterReferenceValue:fe,characterReference:de,codeFenced:d(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:M,codeIndented:d(b),codeText:d(P),codeTextData:M,data:M,definition:d(),definitionDestinationString:C,definitionLabelString:y,definitionTitleString:j,emphasis:d(),hardBreakEscape:d(O),hardBreakTrailing:d(O),htmlFlow:d(B),htmlFlowData:M,htmlText:d(R),htmlTextData:M,image:d(q),label:U,labelText:ee,lineEnding:E,link:d(F),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:H,resourceDestinationString:k,resourceTitleString:I,resource:$,setextHeading:d(_),setextHeadingLineSequence:S,setextHeadingText:N,strong:d(),thematicBreak:d()}};pg(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(se){let xe={type:"root",children:[]};const ne={stack:[xe],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},Fe=[];let Qe=-1;for(;++Qe<se.length;)if(se[Qe][1].type==="listOrdered"||se[Qe][1].type==="listUnordered")if(se[Qe][0]==="enter")Fe.push(Qe);else{const ge=Fe.pop();Qe=r(se,ge,Qe)}for(Qe=-1;++Qe<se.length;){const ge=n[se[Qe][0]];hg.call(ge,se[Qe][1].type)&&ge[se[Qe][1].type].call(Object.assign({sliceSerialize:se[Qe][2].sliceSerialize},ne),se[Qe][1])}if(ne.tokenStack.length>0){const ge=ne.tokenStack[ne.tokenStack.length-1];(ge[1]||Ym).call(ne,void 0,ge[0])}for(xe.position={start:Fi(se.length>0?se[0][1].start:{line:1,column:1,offset:0}),end:Fi(se.length>0?se[se.length-2][1].end:{line:1,column:1,offset:0})},Qe=-1;++Qe<n.transforms.length;)xe=n.transforms[Qe](xe)||xe;return xe}function r(se,xe,ne){let Fe=xe-1,Qe=-1,ge=!1,ze,tt,pt,ve;for(;++Fe<=ne;){const le=se[Fe];switch(le[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{le[0]==="enter"?Qe++:Qe--,ve=void 0;break}case"lineEndingBlank":{le[0]==="enter"&&(ze&&!ve&&!Qe&&!pt&&(pt=Fe),ve=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ve=void 0}if(!Qe&&le[0]==="enter"&&le[1].type==="listItemPrefix"||Qe===-1&&le[0]==="exit"&&(le[1].type==="listUnordered"||le[1].type==="listOrdered")){if(ze){let Te=Fe;for(tt=void 0;Te--;){const pe=se[Te];if(pe[1].type==="lineEnding"||pe[1].type==="lineEndingBlank"){if(pe[0]==="exit")continue;tt&&(se[tt][1].type="lineEndingBlank",ge=!0),pe[1].type="lineEnding",tt=Te}else if(!(pe[1].type==="linePrefix"||pe[1].type==="blockQuotePrefix"||pe[1].type==="blockQuotePrefixWhitespace"||pe[1].type==="blockQuoteMarker"||pe[1].type==="listItemIndent"))break}pt&&(!tt||pt<tt)&&(ze._spread=!0),ze.end=Object.assign({},tt?se[tt][1].start:le[1].end),se.splice(tt||Fe,0,["exit",ze,le[2]]),Fe++,ne++}if(le[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},le[1].start),end:void 0};ze=Te,se.splice(Fe,0,["enter",Te,le[2]]),Fe++,ne++,pt=void 0,ve=!0}}}return se[xe][1]._spread=ge,ne}function o(se,xe){return ne;function ne(Fe){c.call(this,se(Fe),Fe),xe&&xe.call(this,Fe)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(se,xe,ne){this.stack[this.stack.length-1].children.push(se),this.stack.push(se),this.tokenStack.push([xe,ne||void 0]),se.position={start:Fi(xe.start),end:void 0}}function d(se){return xe;function xe(ne){se&&se.call(this,ne),u.call(this,ne)}}function u(se,xe){const ne=this.stack.pop(),Fe=this.tokenStack.pop();if(Fe)Fe[0].type!==se.type&&(xe?xe.call(this,se,Fe[0]):(Fe[1]||Ym).call(this,se,Fe[0]));else throw new Error("Cannot close `"+se.type+"` ("+Dr({start:se.start,end:se.end})+"): it’s not open");ne.position.end=Fi(se.end)}function m(){return ru(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(se){if(this.data.expectingFirstListItemValue){const xe=this.stack[this.stack.length-2];xe.start=Number.parseInt(this.sliceSerialize(se),10),this.data.expectingFirstListItemValue=void 0}}function p(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.lang=se}function g(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.meta=se}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.value=se.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.value=se.replace(/(\r?\n|\r)$/g,"")}function y(se){const xe=this.resume(),ne=this.stack[this.stack.length-1];ne.label=xe,ne.identifier=mi(this.sliceSerialize(se)).toLowerCase()}function j(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.title=se}function C(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.url=se}function A(se){const xe=this.stack[this.stack.length-1];if(!xe.depth){const ne=this.sliceSerialize(se).length;xe.depth=ne}}function N(){this.data.setextHeadingSlurpLineEnding=!0}function S(se){const xe=this.stack[this.stack.length-1];xe.depth=this.sliceSerialize(se).codePointAt(0)===61?1:2}function _(){this.data.setextHeadingSlurpLineEnding=void 0}function T(se){const ne=this.stack[this.stack.length-1].children;let Fe=ne[ne.length-1];(!Fe||Fe.type!=="text")&&(Fe=Ee(),Fe.position={start:Fi(se.start),end:void 0},ne.push(Fe)),this.stack.push(Fe)}function M(se){const xe=this.stack.pop();xe.value+=this.sliceSerialize(se),xe.position.end=Fi(se.end)}function E(se){const xe=this.stack[this.stack.length-1];if(this.data.atHardBreak){const ne=xe.children[xe.children.length-1];ne.position.end=Fi(se.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(xe.type)&&(T.call(this,se),M.call(this,se))}function O(){this.data.atHardBreak=!0}function B(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.value=se}function R(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.value=se}function P(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.value=se}function F(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const xe=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=xe,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function q(){const se=this.stack[this.stack.length-1];if(this.data.inReference){const xe=this.data.referenceType||"shortcut";se.type+="Reference",se.referenceType=xe,delete se.url,delete se.title}else delete se.identifier,delete se.label;this.data.referenceType=void 0}function ee(se){const xe=this.sliceSerialize(se),ne=this.stack[this.stack.length-2];ne.label=Q2(xe),ne.identifier=mi(xe).toLowerCase()}function U(){const se=this.stack[this.stack.length-1],xe=this.resume(),ne=this.stack[this.stack.length-1];if(this.data.inReference=!0,ne.type==="link"){const Fe=se.children;ne.children=Fe}else ne.alt=xe}function k(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.url=se}function I(){const se=this.resume(),xe=this.stack[this.stack.length-1];xe.title=se}function $(){this.data.inReference=void 0}function w(){this.data.referenceType="collapsed"}function H(se){const xe=this.resume(),ne=this.stack[this.stack.length-1];ne.label=xe,ne.identifier=mi(this.sliceSerialize(se)).toLowerCase(),this.data.referenceType="full"}function J(se){this.data.characterReferenceType=se.type}function fe(se){const xe=this.sliceSerialize(se),ne=this.data.characterReferenceType;let Fe;ne?(Fe=sg(xe,ne==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):Fe=ou(xe);const Qe=this.stack[this.stack.length-1];Qe.value+=Fe}function de(se){const xe=this.stack.pop();xe.position.end=Fi(se.end)}function D(se){M.call(this,se);const xe=this.stack[this.stack.length-1];xe.url=this.sliceSerialize(se)}function _e(se){M.call(this,se);const xe=this.stack[this.stack.length-1];xe.url="mailto:"+this.sliceSerialize(se)}function z(){return{type:"blockquote",children:[]}}function Z(){return{type:"code",lang:null,meta:null,value:""}}function oe(){return{type:"inlineCode",value:""}}function Y(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function ae(){return{type:"emphasis",children:[]}}function ce(){return{type:"heading",depth:0,children:[]}}function te(){return{type:"break"}}function Re(){return{type:"html",value:""}}function be(){return{type:"image",title:null,url:"",alt:null}}function ke(){return{type:"link",title:null,url:"",children:[]}}function Ue(se){return{type:"list",ordered:se.type==="listOrdered",start:null,spread:se._spread,children:[]}}function Ge(se){return{type:"listItem",spread:se._spread,checked:null,children:[]}}function qe(){return{type:"paragraph",children:[]}}function Ae(){return{type:"strong",children:[]}}function Ee(){return{type:"text",value:""}}function ie(){return{type:"thematicBreak"}}}function Fi(e){return{line:e.line,column:e.column,offset:e.offset}}function pg(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?pg(e,a):tE(e,a)}}function tE(e,n){let s;for(s in n)if(hg.call(n,s))switch(s){case"canContainEols":{const a=n[s];a&&e[s].push(...a);break}case"transforms":{const a=n[s];a&&e[s].push(...a);break}case"enter":case"exit":{const a=n[s];a&&Object.assign(e[s],a);break}}}function Ym(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Dr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Dr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Dr({start:n.start,end:n.end})+") is still open")}function nE(e){const n=this;n.parser=s;function s(a){return Z2(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function sE(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 iE(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
647
+ `}]}function aE(e,n){const s=n.value?n.value+`
648
+ `:"",a={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(a.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:a,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 rE(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function oE(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function lE(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=er(a.toLowerCase()),o=e.footnoteOrder.indexOf(a);let l,c=e.footnoteCounts.get(a);c===void 0?(c=0,e.footnoteOrder.push(a),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(a,c);const d={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,d);const u={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(n,u),e.applyData(n,u)}function cE(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 dE(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function fg(e,n){const s=n.referenceType;let a="]";if(s==="collapsed"?a+="[]":s==="full"&&(a+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+a}];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+=a:r.push({type:"text",value:a}),r}function uE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return fg(e,n);const r={src:er(a.url||""),alt:n.alt};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function mE(e,n){const s={src:er(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 a={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,a),e.applyData(n,a)}function hE(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const a={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,a),e.applyData(n,a)}function pE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return fg(e,n);const r={href:er(a.url||"")};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function fE(e,n){const s={href:er(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function gE(e,n,s){const a=e.all(n),r=s?bE(s):gg(n),o={},l=[];if(typeof n.checked=="boolean"){const m=a[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},a.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<a.length;){const m=a[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
649
+ `}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
650
+ `});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function bE(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let a=-1;for(;!n&&++a<s.length;)n=gg(s[a])}return n}function gg(e){const n=e.spread;return n??e.children.length>1}function xE(e,n){const s={},a=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<a.length;){const l=a[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(a,!0)};return e.patch(n,o),e.applyData(n,o)}function vE(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function yE(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function wE(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function kE(e,n){const s=e.all(n),a=s.shift(),r=[];if(a){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([a],!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=nu(n.children[1]),d=Jf(n.children[n.children.length-1]);c&&d&&(l.position={start:c,end:d}),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 jE(e,n,s){const a=s?s.children:void 0,o=(a?a.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let d=-1;const u=[];for(;++d<c;){const h=n.children[d],f={},p=l?l[d]:void 0;p&&(f.align=p);let g={type:"element",tagName:o,properties:f,children:[]};h&&(g.children=e.all(h),e.patch(h,g),g=e.applyData(h,g)),u.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(n,m),e.applyData(n,m)}function NE(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Qm=9,Xm=32;function SE(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(Zm(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(Zm(n.slice(r),r>0,!1)),o.join("")}function Zm(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===Qm||o===Xm;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===Qm||o===Xm;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function CE(e,n){const s={type:"text",value:SE(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function EE(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const ME={blockquote:sE,break:iE,code:aE,delete:rE,emphasis:oE,footnoteReference:lE,heading:cE,html:dE,imageReference:uE,image:mE,inlineCode:hE,linkReference:pE,link:fE,listItem:gE,list:xE,paragraph:vE,root:yE,strong:wE,table:kE,tableCell:NE,tableRow:jE,text:CE,thematicBreak:EE,toml:Eo,yaml:Eo,definition:Eo,footnoteDefinition:Eo};function Eo(){}const bg=-1,Ol=0,Or=1,hl=2,cu=3,du=4,uu=5,mu=6,xg=7,vg=8,eh=typeof self=="object"?self:globalThis,_E=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),a=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case Ol:case bg:return s(l,r);case Or:{const c=s([],r);for(const d of l)c.push(a(d));return c}case hl:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case cu:return s(new Date(l),r);case du:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case uu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case mu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case xg:{const{name:c,message:d}=l;return s(new eh[c](d),r)}case vg: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 eh[o](l),r)};return a},th=e=>_E(new Map,e)(0),Na="",{toString:AE}={},{keys:PE}=Object,hr=e=>{const n=typeof e;if(n!=="object"||!e)return[Ol,n];const s=AE.call(e).slice(8,-1);switch(s){case"Array":return[Or,Na];case"Object":return[hl,Na];case"Date":return[cu,Na];case"RegExp":return[du,Na];case"Map":return[uu,Na];case"Set":return[mu,Na];case"DataView":return[Or,s]}return s.includes("Array")?[Or,s]:s.includes("Error")?[xg,s]:[hl,s]},Mo=([e,n])=>e===Ol&&(n==="function"||n==="symbol"),RE=(e,n,s,a)=>{const r=(l,c)=>{const d=a.push(l)-1;return s.set(c,d),d},o=l=>{if(s.has(l))return s.get(l);let[c,d]=hr(l);switch(c){case Ol:{let m=l;switch(d){case"bigint":c=vg,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([bg],l)}return r([c,m],l)}case Or:{if(d){let f=l;return d==="DataView"?f=new Uint8Array(l.buffer):d==="ArrayBuffer"&&(f=new Uint8Array(l)),r([d,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case hl:{if(d)switch(d){case"BigInt":return r([d,l.toString()],l);case"Boolean":case"Number":case"String":return r([d,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of PE(l))(e||!Mo(hr(l[f])))&&m.push([o(f),o(l[f])]);return h}case cu:return r([c,l.toISOString()],l);case du:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case uu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(Mo(hr(f))||Mo(hr(p))))&&m.push([o(f),o(p)]);return h}case mu:{const m=[],h=r([c,m],l);for(const f of l)(e||!Mo(hr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},nh=(e,{json:n,lossy:s}={})=>{const a=[];return RE(!(n||s),!!n,new Map,a)(e),a},pl=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?th(nh(e,n)):structuredClone(e):(e,n)=>th(nh(e,n));function TE(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 IE(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function $E(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||TE,a=e.options.footnoteBackLabel||IE,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let d=-1;for(;++d<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[d]);if(!u)continue;const m=e.all(u),h=String(u.identifier).toUpperCase(),f=er(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(d,p);typeof y=="string"&&(y={type:"text",value:y}),g.push({type:"element",tagName:"a",properties:{href:"#"+n+"fnref-"+f+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof a=="string"?a:a(d,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(...g)}else m.push(...g);const b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...pl(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
651
+ `},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
652
+ `}]}}const zl=(function(e){if(e==null)return zE;if(typeof e=="function")return Fl(e);if(typeof e=="object")return Array.isArray(e)?DE(e):LE(e);if(typeof e=="string")return OE(e);throw new Error("Expected function, string, or object as test")});function DE(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=zl(e[s]);return Fl(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function LE(e){const n=e;return Fl(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function OE(e){return Fl(n);function n(s){return s&&s.type===e}}function Fl(e){return n;function n(s,a,r){return!!(FE(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function zE(){return!0}function FE(e){return e!==null&&typeof e=="object"&&"type"in e}const yg=[],UE=!0,Md=!1,BE="skip";function wg(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=zl(r),l=a?-1:1;c(e,void 0,[])();function c(d,u,m){const h=d&&typeof d=="object"?d:{};if(typeof h.type=="string"){const p=typeof h.tagName=="string"?h.tagName:typeof h.name=="string"?h.name:void 0;Object.defineProperty(f,"name",{value:"node ("+(d.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=yg,g,x,v;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=HE(s(d,m)),p[0]===Md))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==BE)for(x=(a?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(g=c(y,x,v)(),g[0]===Md)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function HE(e){return Array.isArray(e)?e:typeof e=="number"?[UE,e]:e==null?yg:[e]}function hu(e,n,s,a){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=a),wg(e,o,c,r);function c(d,u){const m=u[u.length-1],h=m?m.children.indexOf(d):void 0;return l(d,h,m)}}const _d={}.hasOwnProperty,qE={};function VE(e,n){const s=n||qE,a=new Map,r=new Map,o=new Map,l={...ME,...s.handlers},c={all:u,applyData:KE,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:WE,wrap:JE};return hu(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?a:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function d(m,h){const f=m.type,p=c.handlers[f];if(_d.call(c.handlers,f)&&p)return p(c,m,h);if(c.options.passThrough&&c.options.passThrough.includes(f)){if("children"in m){const{children:x,...v}=m,b=pl(v);return b.children=c.all(m),b}return pl(m)}return(c.options.unknownHandler||GE)(c,m,h)}function u(m){const h=[];if("children"in m){const f=m.children;let p=-1;for(;++p<f.length;){const g=c.one(f[p],m);if(g){if(p&&f[p-1].type==="break"&&(!Array.isArray(g)&&g.type==="text"&&(g.value=sh(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=sh(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function WE(e,n){e.position&&(n.position=I0(e))}function KE(e,n){let s=n;if(e&&e.data){const a=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof a=="string")if(s.type==="element")s.tagName=a;else{const l="children"in s?s.children:[s];s={type:"element",tagName:a,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,pl(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function GE(e,n){const s=n.data||{},a="value"in n&&!(_d.call(s,"hProperties")||_d.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function JE(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
653
+ `});++a<e.length;)a&&s.push({type:"text",value:`
654
+ `}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
655
+ `}),s}function sh(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function ih(e,n){const s=VE(e,n),a=s.one(e,void 0),r=$E(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
656
+ `},r),o}function YE(e,n){return e&&"run"in e?async function(s,a){const r=ih(s,{file:a,...n});await e.run(r,a)}:function(s,a){return ih(s,{file:a,...e||n})}}function ah(e){if(e)throw e}var fc,rh;function QE(){if(rh)return fc;rh=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):n.call(u)==="[object Array]"},o=function(u){if(!u||n.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,m){s&&m.name==="__proto__"?s(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},c=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(a)return a(u,m).value}else return;return u[m]};return fc=function d(){var u,m,h,f,p,g,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(u=arguments[v],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(x,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},fc}var XE=QE();const gc=Qp(XE);function Ad(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 ZE(){const e=[],n={run:s,use:a};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(d,...u){const m=e[++o];let h=-1;if(d){l(d);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,m?eM(m,c)(...u):l(null,...u)}}function a(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function eM(e,n){let s;return a;function a(...l){const c=e.length>l.length;let d;c&&l.push(r);try{d=e.apply(this,l)}catch(u){const m=u;if(c&&s)throw m;return r(m)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const yi={basename:tM,dirname:nM,extname:sM,join:iM,sep:"/"};function tM(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');lo(e);let s=0,a=-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 a<0&&(o=!0,a=r+1);return a<0?"":e.slice(s,a)}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&&(a=r):(c=-1,a=l));return s===a?a=l:a<0&&(a=e.length),e.slice(s,a)}function nM(e){if(lo(e),e.length===0)return".";let n=-1,s=e.length,a;for(;--s;)if(e.codePointAt(s)===47){if(a){n=s;break}}else a||(a=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function sM(e){lo(e);let n=e.length,s=-1,a=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){a=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===a+1?"":e.slice(r,s)}function iM(...e){let n=-1,s;for(;++n<e.length;)lo(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":aM(s)}function aM(e){lo(e);const n=e.codePointAt(0)===47;let s=rM(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function rM(e,n){let s="",a=0,r=-1,o=0,l=-1,c,d;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||a!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(d=s.lastIndexOf("/"),d!==s.length-1){d<0?(s="",a=0):(s=s.slice(0,d),a=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",a=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",a=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),a=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function lo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const oM={cwd:lM};function lM(){return"/"}function Pd(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function cM(e){if(typeof e=="string")e=new URL(e);else if(!Pd(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 dM(e)}function dM(e){if(e.hostname!==""){const a=new TypeError('File URL host must be "localhost" or empty on darwin');throw a.code="ERR_INVALID_FILE_URL_HOST",a}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const a=n.codePointAt(s+2);if(a===70||a===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 bc=["history","path","basename","stem","extname","dirname"];class kg{constructor(n){let s;n?Pd(n)?s={path:n}:typeof n=="string"||uM(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":oM.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<bc.length;){const o=bc[a];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)bc.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?yi.basename(this.path):void 0}set basename(n){vc(n,"basename"),xc(n,"basename"),this.path=yi.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?yi.dirname(this.path):void 0}set dirname(n){oh(this.basename,"dirname"),this.path=yi.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?yi.extname(this.path):void 0}set extname(n){if(xc(n,"extname"),oh(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=yi.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Pd(n)&&(n=cM(n)),vc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?yi.basename(this.path,this.extname):void 0}set stem(n){vc(n,"stem"),xc(n,"stem"),this.path=yi.join(this.dirname||"",n+(this.extname||""))}fail(n,s,a){const r=this.message(n,s,a);throw r.fatal=!0,r}info(n,s,a){const r=this.message(n,s,a);return r.fatal=void 0,r}message(n,s,a){const r=new As(n,s,a);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 xc(e,n){if(e&&e.includes(yi.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+yi.sep+"`")}function vc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function oh(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function uM(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const mM=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),hM={}.hasOwnProperty;class pu extends mM{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=ZE()}copy(){const n=new pu;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(gc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(kc("data",this.frozen),this.namespace[n]=s,this):hM.call(this.namespace,n)&&this.namespace[n]||void 0:n?(kc("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,...a]=this.attachers[this.freezeIndex];if(a[0]===!1)continue;a[0]===!0&&(a[0]=void 0);const r=s.call(n,...a);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=_o(n),a=this.parser||this.Parser;return yc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),yc("process",this.parser||this.Parser),wc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=_o(n),d=a.parse(c);a.run(d,c,function(m,h,f){if(m||!h||!f)return u(m);const p=h,g=a.stringify(p,f);gM(g)?f.value=g:f.result=g,u(m,f)});function u(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,a;return this.freeze(),yc("processSync",this.parser||this.Parser),wc("processSync",this.compiler||this.Compiler),this.process(n,r),ch("processSync","process",s),a;function r(o,l){s=!0,ah(o),a=l}}run(n,s,a){lh(n),this.freeze();const r=this.transformers;return!a&&typeof s=="function"&&(a=s,s=void 0),a?o(void 0,a):new Promise(o);function o(l,c){const d=_o(s);r.run(n,d,u);function u(m,h,f){const p=h||n;m?c(m):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),ch("runSync","run",a),r;function o(l,c){ah(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=_o(s),r=this.compiler||this.Compiler;return wc("stringify",r),lh(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(kc("use",this.frozen),n!=null)if(typeof n=="function")d(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(u){if(typeof u=="function")d(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[m,...h]=u;d(m,h)}else l(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function l(u){if(!("plugins"in u)&&!("settings"in u))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(u.plugins),u.settings&&(r.settings=gc(!0,r.settings,u.settings))}function c(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function d(u,m){let h=-1,f=-1;for(;++h<a.length;)if(a[h][0]===u){f=h;break}if(f===-1)a.push([u,...m]);else if(m.length>0){let[p,...g]=m;const x=a[f][1];Ad(x)&&Ad(p)&&(p=gc(!0,x,p)),a[f]=[u,p,...g]}}}}const pM=new pu().freeze();function yc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function wc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function kc(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 lh(e){if(!Ad(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function ch(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function _o(e){return fM(e)?e:new kg(e)}function fM(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function gM(e){return typeof e=="string"||bM(e)}function bM(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const xM="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",dh=[],uh={allowDangerousHtml:!0},vM=/^(https?|ircs?|mailto|xmpp)$/i,yM=[{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 ji(e){const n=wM(e),s=kM(e);return jM(n.runSync(n.parse(s),s),e)}function wM(e){const n=e.rehypePlugins||dh,s=e.remarkPlugins||dh,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...uh}:uh;return pM().use(nE).use(s).use(YE,a).use(n)}function kM(e){const n=e.children||"",s=new kg;return typeof n=="string"&&(s.value=n),s}function jM(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||NM;for(const m of yM)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+xM+m.id,void 0);return hu(e,u),z0(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function u(m,h,f){if(m.type==="raw"&&f&&typeof h=="number")return l?f.children.splice(h,1):f.children[h]={type:"text",value:m.value},h;if(m.type==="element"){let p;for(p in mc)if(Object.hasOwn(mc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=mc[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=d(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&a&&typeof h=="number"&&(p=!a(m,h,f)),p&&f&&typeof h=="number")return c&&m.children?f.children.splice(h,1,...m.children):f.children.splice(h,1),h}}}function NM(e){const n=e.indexOf(":"),s=e.indexOf("?"),a=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||a!==-1&&n>a||vM.test(e.slice(0,n))?e:""}function mh(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let a=0,r=s.indexOf(n);for(;r!==-1;)a++,r=s.indexOf(n,r+n.length);return a}function SM(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function CM(e,n,s){const r=zl((s||{}).ignore||[]),o=EM(n);let l=-1;for(;++l<o.length;)wg(e,"text",c);function c(u,m){let h=-1,f;for(;++h<m.length;){const p=m[h],g=f?f.children:void 0;if(r(p,g?g.indexOf(p):void 0,f))return;f=p}if(f)return d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let j=f.exec(u.value);for(;j;){const C=j.index,A={index:j.index,input:j.input,stack:[...m,u]};let N=p(...j,A);if(typeof N=="string"&&(N=N.length>0?{type:"text",value:N}:void 0),N===!1?f.lastIndex=C+1:(g!==C&&y.push({type:"text",value:u.value.slice(g,C)}),Array.isArray(N)?y.push(...N):N&&y.push(N),g=C+j[0].length,b=!0),!f.global)break;j=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(v,1,...y)):y=[u],v+y.length}}function EM(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 a=-1;for(;++a<s.length;){const r=s[a];n.push([MM(r[0]),_M(r[1])])}return n}function MM(e){return typeof e=="string"?new RegExp(SM(e),"g"):e}function _M(e){return typeof e=="function"?e:function(){return e}}const jc="phrasing",Nc=["autolink","link","image","label"];function AM(){return{transforms:[LM],enter:{literalAutolink:RM,literalAutolinkEmail:Sc,literalAutolinkHttp:Sc,literalAutolinkWww:Sc},exit:{literalAutolink:DM,literalAutolinkEmail:$M,literalAutolinkHttp:TM,literalAutolinkWww:IM}}}function PM(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:jc,notInConstruct:Nc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:jc,notInConstruct:Nc},{character:":",before:"[ps]",after:"\\/",inConstruct:jc,notInConstruct:Nc}]}}function RM(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Sc(e){this.config.enter.autolinkProtocol.call(this,e)}function TM(e){this.config.exit.autolinkProtocol.call(this,e)}function IM(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 $M(e){this.config.exit.autolinkEmail.call(this,e)}function DM(e){this.exit(e)}function LM(e){CM(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,OM],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,zM]],{ignore:["link","linkReference"]})}function OM(e,n,s,a,r){let o="";if(!jg(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!FM(s)))return!1;const l=UM(s+a);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 zM(e,n,s,a){return!jg(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function FM(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 UM(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],a=s.indexOf(")");const r=mh(e,"(");let o=mh(e,")");for(;a!==-1&&r>o;)e+=s.slice(0,a+1),s=s.slice(a+1),a=s.indexOf(")"),o++;return[e,s]}function jg(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||ua(s)||Dl(s))&&(!n||s!==47)}Ng.peek=YM;function BM(){this.buffer()}function HM(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function qM(){this.buffer()}function VM(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function WM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=mi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function KM(e){this.exit(e)}function GM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=mi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function JM(e){this.exit(e)}function YM(){return"["}function Ng(e,n,s,a){const r=s.createTracker(a);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 QM(){return{enter:{gfmFootnoteCallString:BM,gfmFootnoteCall:HM,gfmFootnoteDefinitionLabelString:qM,gfmFootnoteDefinition:VM},exit:{gfmFootnoteCallString:WM,gfmFootnoteCall:KM,gfmFootnoteDefinitionLabelString:GM,gfmFootnoteDefinition:JM}}}function XM(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:Ng},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(a,r,o,l){const c=o.createTracker(l);let d=c.move("[^");const u=o.enter("footnoteDefinition"),m=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),m(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
657
+ `:" ")+o.indentLines(o.containerFlow(a,c.current()),n?Sg:ZM))),u(),d}}function ZM(e,n,s){return n===0?e:Sg(e,n,s)}function Sg(e,n,s){return(s?"":" ")+e}const e_=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Cg.peek=a_;function t_(){return{canContainEols:["delete"],enter:{strikethrough:s_},exit:{strikethrough:i_}}}function n_(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:e_}],handlers:{delete:Cg}}}function s_(e){this.enter({type:"delete",children:[]},e)}function i_(e){this.exit(e)}function Cg(e,n,s,a){const r=s.createTracker(a),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function a_(){return"~"}function r_(e){return e.length}function o_(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||r_,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=l_(e[m][b]);if(s.alignDelimiters!==!1){const j=r(y);v[b]=j,(d[b]===void 0||j>d[b])&&(d[b]=j)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=hh(a[h]);else{const x=hh(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){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,d[h]-v.length-b.length);const j=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=j}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<u;){const y=x[h]||"";let j="",C="";if(s.alignDelimiters!==!1){const A=d[h]-(v[h]||0),N=o[h];N===114?j=" ".repeat(A):N===99?A%2?(j=" ".repeat(A/2+.5),C=" ".repeat(A/2-.5)):(j=" ".repeat(A/2),C=j):C=" ".repeat(A)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(j),b.push(y),s.alignDelimiters!==!1&&b.push(C),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
658
+ `)}function l_(e){return e==null?"":String(e)}function hh(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 c_(e,n,s,a){const r=s.enter("blockquote"),o=s.createTracker(a);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),d_);return r(),l}function d_(e,n,s){return">"+(s?"":" ")+e}function u_(e,n){return ph(e,n.inConstruct,!0)&&!ph(e,n.notInConstruct,!1)}function ph(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let a=-1;for(;++a<n.length;)if(e.includes(n[a]))return!0;return!1}function fh(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
659
+ `&&u_(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
660
+ `}function m_(e,n){const s=String(e);let a=s.indexOf(n),r=a,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===r?++o>l&&(l=o):o=1,r=a+n.length,a=s.indexOf(n,r);return l}function h_(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 p_(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 f_(e,n,s,a){const r=p_(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(h_(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,g_);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(m_(o,r)+1,3)),u=s.enter("codeFenced");let m=c.move(d);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:`
661
+ `,encode:["`"],...c.current()})),h()}return m+=c.move(`
662
+ `),o&&(m+=c.move(o+`
663
+ `)),m+=c.move(d),u(),m}function g_(e,n,s){return(s?"":" ")+e}function fu(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 b_(e,n,s,a){const r=fu(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("[");return u+=d.move(s.safe(s.associationId(e),{before:u,after:"]",...d.current()})),u+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":`
664
+ `,...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),l(),u}function x_(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 fl(e,n,s){const a=Ba(e),r=Ba(n);return a===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===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}}Eg.peek=v_;function Eg(e,n,s,a){const r=x_(s),o=s.enter("emphasis"),l=s.createTracker(a),c=l.move(r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=fl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Kr(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=fl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Kr(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function v_(e,n,s){return s.options.emphasis||"*"}function y_(e,n){let s=!1;return hu(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,Md}),!!((!e.depth||e.depth<3)&&ru(e)&&(n.options.setext||s))}function w_(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(y_(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
665
+ `,after:`
666
+ `});return h(),m(),f+`
667
+ `+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
668
+ `))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
669
+ `,...o.current()});return/^[\t ]/.test(u)&&(u=Kr(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}Mg.peek=k_;function Mg(e){return e.value||""}function k_(){return"<"}_g.peek=j_;function _g(e,n,s,a){const r=fu(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("![");return u+=d.move(s.safe(e.alt,{before:u,after:"]",...d.current()})),u+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),u+=d.move(")"),l(),u}function j_(){return"!"}Ag.peek=N_;function Ag(e,n,s,a){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("![");const u=s.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function N_(){return"!"}Pg.peek=S_;function Pg(e,n,s){let a=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(a);)r+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let d;if(l.atBreak)for(;d=c.exec(a);){let u=d.index;a.charCodeAt(u)===10&&a.charCodeAt(u-1)===13&&u--,a=a.slice(0,u)+" "+a.slice(d.index+1)}}return r+a+r}function S_(){return"`"}function Rg(e,n){const s=ru(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))}Tg.peek=C_;function Tg(e,n,s,a){const r=fu(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(Rg(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"),d=s.enter("label");let u=l.move("[");return u+=l.move(s.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=s.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(s.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(d=s.enter("destinationRaw"),u+=l.move(s.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),d(),e.title&&(d=s.enter(`title${o}`),u+=l.move(" "+r),u+=l.move(s.safe(e.title,{before:u,after:r,...l.current()})),u+=l.move(r),d()),u+=l.move(")"),c(),u}function C_(e,n,s){return Rg(e,s)?"<":"["}Ig.peek=E_;function Ig(e,n,s,a){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("[");const u=s.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function E_(){return"["}function gu(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 M_(e){const n=gu(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 __(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 $g(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 A_(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?__(s):gu(s);const c=e.ordered?l==="."?")":".":M_(s);let d=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&&(d=!0),$g(s)===l&&m){let h=-1;for(;++h<e.children.length;){const f=e.children[h];if(f&&f.type==="listItem"&&f.children&&f.children[0]&&f.children[0].type==="thematicBreak"){d=!0;break}}}}d&&(l=c),s.bulletCurrent=l;const u=s.containerFlow(e,a);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),u}function P_(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 R_(e,n,s,a){const r=P_(s);let o=s.bulletCurrent||gu(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(a);c.move(o+" ".repeat(l-o.length)),c.shift(l);const d=s.enter("listItem"),u=s.indentLines(s.containerFlow(e,c.current()),m);return d(),u;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function T_(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const I_=zl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function $_(e,n,s,a){return(e.children.some(function(l){return I_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function D_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Dg.peek=L_;function Dg(e,n,s,a){const r=D_(s),o=s.enter("strong"),l=s.createTracker(a),c=l.move(r+r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=fl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Kr(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=fl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Kr(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function L_(e,n,s){return s.options.strong||"*"}function O_(e,n,s,a){return s.safe(e.value,a)}function z_(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 F_(e,n,s){const a=($g(s)+(s.options.ruleSpaces?" ":"")).repeat(z_(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Lg={blockquote:c_,break:fh,code:f_,definition:b_,emphasis:Eg,hardBreak:fh,heading:w_,html:Mg,image:_g,imageReference:Ag,inlineCode:Pg,link:Tg,linkReference:Ig,list:A_,listItem:R_,paragraph:T_,root:$_,strong:Dg,text:O_,thematicBreak:F_};function U_(){return{enter:{table:B_,tableData:gh,tableHeader:gh,tableRow:q_},exit:{codeText:V_,table:H_,tableData:Cc,tableHeader:Cc,tableRow:Cc}}}function B_(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 H_(e){this.exit(e),this.data.inTable=void 0}function q_(e){this.enter({type:"tableRow",children:[]},e)}function Cc(e){this.exit(e)}function gh(e){this.enter({type:"tableCell",children:[]},e)}function V_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,W_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function W_(e,n){return n==="|"?n:e}function K_(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
670
+ `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:d,tableRow:c}};function l(p,g,x,v){return u(m(p,x,v),p.align)}function c(p,g,x,v){const b=h(p,x,v),y=u([b]);return y.slice(0,y.indexOf(`
671
+ `))}function d(p,g,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),j=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),j}function u(p,g){return o_(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const v=p.children;let b=-1;const y=[],j=g.enter("table");for(;++b<v.length;)y[b]=h(v[b],g,x);return j(),y}function h(p,g,x){const v=p.children;let b=-1;const y=[],j=g.enter("tableRow");for(;++b<v.length;)y[b]=d(v[b],p,g,x);return j(),y}function f(p,g,x){let v=Lg.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function G_(){return{exit:{taskListCheckValueChecked:bh,taskListCheckValueUnchecked:bh,paragraph:Y_}}}function J_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Q_}}}function bh(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function Y_(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 a=s.children[0];if(a&&a.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&&(a.value=a.value.slice(1),a.value.length===0?s.children.shift():s.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,s.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function Q_(e,n,s,a){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(a);o&&c.move(l);let d=Lg.listItem(e,n,s,{...a,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),d;function u(m){return m+l}}function X_(){return[AM(),QM(),t_(),U_(),G_()]}function Z_(e){return{extensions:[PM(),XM(e),n_(),K_(e),J_()]}}const eA={tokenize:rA,partial:!0},Og={tokenize:oA,partial:!0},zg={tokenize:lA,partial:!0},Fg={tokenize:cA,partial:!0},tA={tokenize:dA,partial:!0},Ug={name:"wwwAutolink",tokenize:iA,previous:Hg},Bg={name:"protocolAutolink",tokenize:aA,previous:qg},Oi={name:"emailAutolink",tokenize:sA,previous:Vg},Ei={};function nA(){return{text:Ei}}let ta=48;for(;ta<123;)Ei[ta]=Oi,ta++,ta===58?ta=65:ta===91&&(ta=97);Ei[43]=Oi;Ei[45]=Oi;Ei[46]=Oi;Ei[95]=Oi;Ei[72]=[Oi,Bg];Ei[104]=[Oi,Bg];Ei[87]=[Oi,Ug];Ei[119]=[Oi,Ug];function sA(e,n,s){const a=this;let r,o;return l;function l(h){return!Rd(h)||!Vg.call(a,a.previous)||bu(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Rd(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(tA,m,u)(h):h===45||h===95||Ms(h)?(o=!0,e.consume(h),d):m(h)}function u(h){return e.consume(h),r=!0,d}function m(h){return o&&r&&$s(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function iA(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!Hg.call(a,a.previous)||bu(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(eA,e.attempt(Og,e.attempt(zg,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function aA(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&qg.call(a,a.previous)&&!bu(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if($s(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),d}return s(h)}function d(h){return h===47?(e.consume(h),o?u:(o=!0,d)):s(h)}function u(h){return h===null||ml(h)||$n(h)||ua(h)||Dl(h)?s(h):e.attempt(Og,e.attempt(zg,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function rA(e,n,s){let a=0;return r;function r(l){return(l===87||l===119)&&a<3?(a++,e.consume(l),r):l===46&&a===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function oA(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(Fg,d,c)(u):u===null||$n(u)||ua(u)||u!==45&&Dl(u)?d(u):(o=!0,e.consume(u),l)}function c(u){return u===95?a=!0:(r=a,a=void 0),e.consume(u),l}function d(u){return r||a||!o?s(u):n(u)}}function lA(e,n){let s=0,a=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&a<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(Fg,n,o)(l):l===null||$n(l)||ua(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function cA(e,n,s){return a;function a(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),a):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||$n(c)||ua(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||$n(c)||ua(c)?n(c):a(c)}function o(c){return $s(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):$s(c)?(e.consume(c),l):s(c)}}function dA(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return Ms(o)?s(o):n(o)}}function Hg(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||$n(e)}function qg(e){return!$s(e)}function Vg(e){return!(e===47||Rd(e))}function Rd(e){return e===43||e===45||e===46||e===95||Ms(e)}function bu(e){let n=e.length,s=!1;for(;n--;){const a=e[n][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){s=!0;break}if(a._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const uA={tokenize:vA,partial:!0};function mA(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:gA,continuation:{tokenize:bA},exit:xA}},text:{91:{name:"gfmFootnoteCall",tokenize:fA},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:hA,resolveTo:pA}}}}function hA(e,n,s){const a=this;let r=a.events.length;const o=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let l;for(;r--;){const d=a.events[r][1];if(d.type==="labelImage"){l=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return c;function c(d){if(!l||!l._balanced)return s(d);const u=mi(a.sliceSerialize({start:l.end,end:a.now()}));return u.codePointAt(0)!==94||!o.includes(u.slice(1))?s(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),n(d))}}function pA(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 a={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",a,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",a,n]];return e.splice(s,e.length-s+1,...c),e}function fA(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),d}function d(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(h){if(o>999||h===93&&!l||h===null||h===91||$n(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(mi(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return $n(h)||(l=!0),o++,e.consume(h),h===92?m:u}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,u):u(h)}}function gA(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o,l=0,c;return d;function d(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(g){return g===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(g)}function m(g){if(l>999||g===93&&!c||g===null||g===91||$n(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=mi(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return $n(g)||(c=!0),l++,e.consume(g),g===92?h:m}function h(g){return g===91||g===92||g===93?(e.consume(g),l++,m):m(g)}function f(g){return g===58?(e.enter("definitionMarker"),e.consume(g),e.exit("definitionMarker"),r.includes(o)||r.push(o),kn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function bA(e,n,s){return e.check(oo,n,e.attempt(uA,n,s))}function xA(e){e.exit("gfmFootnoteDefinition")}function vA(e,n,s){const a=this;return kn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function yA(e){let s=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function r(l,c){let d=-1;for(;++d<l.length;)if(l[d][0]==="enter"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._close){let u=d;for(;u--;)if(l[u][0]==="exit"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._open&&l[d][1].end.offset-l[d][1].start.offset===l[u][1].end.offset-l[u][1].start.offset){l[d][1].type="strikethroughSequence",l[u][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[u][1].start),end:Object.assign({},l[d][1].end)},h={type:"strikethroughText",start:Object.assign({},l[u][1].end),end:Object.assign({},l[d][1].start)},f=[["enter",m,c],["enter",l[u][1],c],["exit",l[u][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Vs(f,f.length,0,Ll(p,l.slice(u+1,d),c)),Vs(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Vs(l,u-1,d-u+3,f),d=u+f.length-2;break}}for(d=-1;++d<l.length;)l[d][1].type==="strikethroughSequenceTemporary"&&(l[d][1].type="data");return l}function o(l,c,d){const u=this.previous,m=this.events;let h=0;return f;function f(g){return u===126&&m[m.length-1][1].type!=="characterEscape"?d(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const x=Ba(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const v=l.exit("strikethroughSequenceTemporary"),b=Ba(g);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(g)}}}class wA{constructor(){this.map=[]}add(n,s,a){kA(this,n,s,a)}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 a=[];for(;s>0;)s-=1,a.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];a.push(n.slice()),n.length=0;let r=a.pop();for(;r;){for(const o of r)n.push(o);r=a.pop()}this.map.length=0}}function kA(e,n,s,a){let r=0;if(!(s===0&&a.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...a);return}r+=1}e.map.push([n,s,a])}}function jA(e,n){let s=!1;const a=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&a.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=a.length-1;a[o]=a[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return a}function NA(){return{flow:{null:{name:"table",tokenize:SA,resolveAll:CA}}}}function SA(e,n,s){const a=this;let r=0,o=0,l;return c;function c(M){let E=a.events.length-1;for(;E>-1;){const R=a.events[E][1].type;if(R==="lineEnding"||R==="linePrefix")E--;else break}const O=E>-1?a.events[E][1].type:null,B=O==="tableHead"||O==="tableRow"?N:d;return B===N&&a.parser.lazy[a.now().line]?s(M):B(M)}function d(M){return e.enter("tableHead"),e.enter("tableRow"),u(M)}function u(M){return M===124||(l=!0,o+=1),m(M)}function m(M){return M===null?s(M):Ot(M)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),p):s(M):xn(M)?kn(e,m,"whitespace")(M):(o+=1,l&&(l=!1,r+=1),M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(M)))}function h(M){return M===null||M===124||$n(M)?(e.exit("data"),m(M)):(e.consume(M),M===92?f:h)}function f(M){return M===92||M===124?(e.consume(M),h):h(M)}function p(M){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(M):(e.enter("tableDelimiterRow"),l=!1,xn(M)?kn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):g(M))}function g(M){return M===45||M===58?v(M):M===124?(l=!0,e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),x):A(M)}function x(M){return xn(M)?kn(e,v,"whitespace")(M):v(M)}function v(M){return M===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),b):M===45?(o+=1,b(M)):M===null||Ot(M)?C(M):A(M)}function b(M){return M===45?(e.enter("tableDelimiterFiller"),y(M)):A(M)}function y(M){return M===45?(e.consume(M),y):M===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(M),e.exit("tableDelimiterMarker"),j):(e.exit("tableDelimiterFiller"),j(M))}function j(M){return xn(M)?kn(e,C,"whitespace")(M):C(M)}function C(M){return M===124?g(M):M===null||Ot(M)?!l||r!==o?A(M):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(M)):A(M)}function A(M){return s(M)}function N(M){return e.enter("tableRow"),S(M)}function S(M){return M===124?(e.enter("tableCellDivider"),e.consume(M),e.exit("tableCellDivider"),S):M===null||Ot(M)?(e.exit("tableRow"),n(M)):xn(M)?kn(e,S,"whitespace")(M):(e.enter("data"),_(M))}function _(M){return M===null||M===124||$n(M)?(e.exit("data"),S(M)):(e.consume(M),M===92?T:_)}function T(M){return M===92||M===124?(e.consume(M),_):_(M)}}function CA(e,n){let s=-1,a=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,d=0,u,m,h;const f=new wA;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(xh(f,n,d,u,m),m=void 0,d=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",u,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(a=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",m,n]])),r=g.type==="tableDelimiterRow"?2:m?3:1):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")?(a=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=Ao(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(a?a=!1:(o[1]!==0&&(l[0]=l[1],h=Ao(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,d=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(d=s,o[1]!==0?(l[0]=l[1],h=Ao(f,n,o,r,s,h)):l[1]!==0&&(h=Ao(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&xh(f,n,d,u,m),f.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=jA(n.events,s))}return e}function Ao(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Aa(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=Aa(n.events,s[1]);if(o={type:l,start:Object.assign({},d),end:Object.assign({},d)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const u=Aa(n.events,s[2]),m=Aa(n.events,s[3]),h={type:c,start:Object.assign({},u),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),a!==2){const f=n.events[s[2]],p=n.events[s[3]];if(f[1].end=Object.assign({},p[1].end),f[1].type="chunkText",f[1].contentType="text",s[3]>s[2]+1){const g=s[2]+1,x=s[3]-s[2]-1;e.add(g,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Aa(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function xh(e,n,s,a,r){const o=[],l=Aa(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),a.end=Object.assign({},l),o.push(["exit",a,n]),e.add(s+1,0,o)}function Aa(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const EA={name:"tasklistCheck",tokenize:_A};function MA(){return{text:{91:EA}}}function _A(e,n,s){const a=this;return r;function r(d){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?s(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return $n(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),l):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),l):s(d)}function l(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(d)}function c(d){return Ot(d)?n(d):xn(d)?e.check({tokenize:AA},n,s)(d):s(d)}}function AA(e,n,s){return kn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function PA(e){return ng([nA(),mA(),yA(e),NA(),MA()])}const RA={};function Ni(e){const n=this,s=e||RA,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(PA(s)),o.push(X_()),l.push(Z_(s))}const TA=45e3,IA=3e3,$A=2e3,DA=1500,vh="fusion:sse-client-id";let Sa=null;const qi=new Map;function yh(){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 Wg(){if(!(typeof window>"u")){if(Sa)return Sa;try{const e=window.sessionStorage.getItem(vh);if(e)return Sa=e,e;const n=yh();return window.sessionStorage.setItem(vh,n),Sa=n,n}catch{return Sa=yh(),Sa}}}function Kg(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Gg(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function LA(e){const n=Wg();if(!n)return e;const s=Kg(e);return!s||!Gg(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function xu(e,n){const s=Wg();if(!s)return;const a=Kg(e);if(!a||!Gg(a.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=a.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),ki(`${r.pathname}${r.search}${r.hash}`)}function OA(e){if(typeof window>"u")return;const n=xu(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 Ul(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function wh(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=xu(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),DA):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function zA(e){Ul(e),xu(e.url,"keepalive")&&(wh(e),e.keepaliveTimer=window.setInterval(()=>{wh(e)},$A))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(qi.values()))if(!s.closed){if(Ul(s),OA(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const a of Array.from(qi.values()))a.subscribers.size!==0&&(a.closed=!1,vu(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Mr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Jg(e)},TA)}function Jg(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Ul(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=qi.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=qi.get(e.url);s&&s===e&&e.subscribers.size>0&&vu(e)},IA)}}function vu(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(ki(LA(e.url)));e.es=n,zA(e),n.addEventListener("open",()=>{Mr(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const a of e.subscribers)a.onOpen?.(),s&&a.onReconnect?.()}),n.addEventListener("error",s=>{for(const a of e.subscribers)a.onError?.(s);Jg(e)}),n.addEventListener("message",()=>Mr(e)),n.addEventListener("heartbeat",()=>Mr(e)),Yg(e),Mr(e)}function Yg(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const a of s.events.keys())n.add(a);for(const s of n){if(e.nativeListeners.has(s))continue;const a=r=>{Mr(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const d of c)d(o)}};e.nativeListeners.set(s,a),e.es.addEventListener(s,a)}}function FA(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Ul(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),qi.delete(e.url)}function fi(e,n={}){let s=qi.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},qi.set(e,s));const a={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[l,c]of Object.entries(n.events)){let d=a.events.get(l);d||(d=new Set,a.events.set(l,d)),d.add(c)}s.subscribers.add(a);const r=!!s.es&&s.hasOpenedOnce;vu(s),Yg(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=qi.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&FA(l))}}const kh=100;function Qg(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),x=i.useRef(0),v=i.useRef(e),b=i.useRef(s),y=i.useRef(n),j=i.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const S=x.current,_=++j.current;g.current=!1;const T=e,M=s;async function E(){if(!T)return;l(!0),f(!1);try{const B=await Iu(T,M,{limit:kh});if(g.current||x.current!==S||j.current!==_)return;r(B.entries),d(B.hasMore),m(B.total)}catch{if(g.current||x.current!==S||j.current!==_)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===S&&j.current===_&&l(!1)}const O=M?`?projectId=${encodeURIComponent(M)}`:"";p.current=fi(`/api/tasks/${T}/logs/stream${O}`,{events:{"agent:log":B=>{if(!(g.current||x.current!==S))try{const R=JSON.parse(B.data);r(P=>[...P,R]),m(P=>P!==null?P+1:null)}catch{}}}})}return E(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const A=i.useCallback(async()=>{if(!e||h)return;const S=x.current,_=a.length,T=e;f(!0);try{const M=await Iu(T,s,{limit:kh,offset:_});if(g.current||x.current!==S)return;r(E=>[...M.entries,...E]),d(M.hasMore),m(M.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),N=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:N,loadMore:A,hasMore:c,total:u,loadingMore:h}}function UA(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/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 jh={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})},Xg=50,BA={triage:"Plan"};function Nh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Xg}function Td(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function HA(e){const n=new Map;return e.map(s=>{const a=Td(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function qA(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Ec({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
672
+ `).length,o=n?"Hide output":`Show output${r>1?` (${r} lines)`:""}`;return t.jsxs("div",{className:"agent-log-tool-detail-wrapper",children:[t.jsxs("button",{type:"button",className:"agent-log-tool-detail-toggle",onClick:()=>s(l=>!l),"aria-expanded":n,"aria-controls":a,"data-testid":"tool-detail-toggle",children:[n?t.jsx(mn,{size:14}):t.jsx(In,{size:14}),t.jsx("span",{children:o})]}),t.jsx("div",{id:a,className:n?"agent-log-tool-detail-content":"agent-log-tool-detail-content agent-log-tool-detail-content--collapsed","data-testid":"tool-detail-content",children:t.jsx("pre",{className:"agent-log-tool-detail",children:e})})]})}function VA(e,n){return e.agent?qA(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function WA(e,n){const s=[];for(let a=0;a<e.length;a+=1){const r=e[a],o=n[a]??`${Td(r)}|fallback`,l=a>0?e[a-1]:void 0,c=VA(r,l);if(r.type==="text"||r.type==="thinking"){const d=[r];let u=a+1;for(;u<e.length;){const h=e[u];if(h.type!==r.type||h.agent!==r.agent)break;d.push(h),u+=1}const m=n[u-1]??`${Td(e[u-1])}|fallback`;s.push({kind:r.type,entries:d,key:`${o}->${m}`,showBadge:c}),a=u-1;continue}s.push({kind:"single",entry:r,key:o,showBadge:c})}return s}function KA({entries:e,loading:n,executorModel:s,validatorModel:a,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:d=null}){const u=i.useRef(null),m=i.useRef(0),h=i.useRef(0),f=i.useRef(null),p=i.useRef(null),[g,x]=i.useState(!0),[v,b]=i.useState(!1),[y,j]=i.useState(!1),[C,A]=i.useState(!0),N=i.useMemo(()=>HA(e),[e]),S=i.useMemo(()=>WA(e,N),[e,N]);i.useLayoutEffect(()=>{const P=u.current;if(!P)return;const F=e.length,q=m.current,ee=h.current||P.scrollHeight,U=N[0]??null,k=N[N.length-1]??null,I=f.current!==U,$=p.current!==k;if(F>q)if(q===0)P.scrollTop=P.scrollHeight;else{const w=ee-(P.scrollTop+P.clientHeight)<=Xg,H=$&&!I,J=I&&!$;if(H&&w&&(P.scrollTop=P.scrollHeight),J){const fe=P.scrollHeight-ee;fe>0&&(P.scrollTop+=fe)}}m.current=F,h.current=P.scrollHeight,f.current=U,p.current=k,A(Nh(P))},[e,N]);const _=i.useCallback(()=>{const P=u.current;P&&A(Nh(P))},[]),T=i.useCallback(()=>{const P=u.current;P&&(P.scrollTop=P.scrollHeight,A(!0))},[]),M=i.useCallback(P=>{P.key==="Escape"&&v&&b(!1)},[v]);i.useEffect(()=>{if(v)return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[v,M]);const E=s?.provider&&s?.modelId,O=a?.provider&&a?.modelId,B=r?.provider&&r?.modelId,R=i.useMemo(()=>{const P=[];return E&&P.push({role:"Executor",provider:s.provider,modelId:s.modelId}),O&&P.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),B&&P.push({role:"Planning",provider:r.provider,modelId:r.modelId}),P},[E,s,O,a,B,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:[R.map(P=>t.jsx(Qn,{provider:P.provider,size:"sm"},`${P.role}-${P.provider}-${P.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>j(P=>!P),"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(mn,{size:14}):t.jsx(In,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(P=>!P),"aria-label":g?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":g,"data-testid":"agent-log-mode-toggle",title:g?"Show raw text":"Show formatted markdown",children:g?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(P=>!P),"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(eo,{size:14}):t.jsx(_l,{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:"}),E?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Qn,{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:"}),O?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Qn,{provider:a.provider,size:"sm"}),t.jsxs("span",{children:[a.provider,"/",a.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:"}),B?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Qn,{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:u,className:"agent-log-viewer-scroll",onScroll:_,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",d," 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(ft,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),S.map(P=>{const F=P.kind==="single"?P.entry:P.entries[0],q=P.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:UA(F.timestamp)}):null,ee=P.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",BA[F.agent]??F.agent,"]"]}),q]}):null;if(P.kind==="single"){const{entry:k}=P;if(k.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[ee,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",k.text]}),k.detail?t.jsx(Ec,{detail:k.detail,type:"tool"}):null]},P.key);if(k.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[ee,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",k.text]}),k.detail?t.jsx(Ec,{detail:k.detail,type:"tool_result"}):null]},P.key);if(k.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[ee,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",k.text]}),k.detail?t.jsx(Ec,{detail:k.detail,type:"tool_error"}):null]},P.key)}const U=P.kind==="single"?F.text:P.entries.map(k=>k.text).join("");return P.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[ee,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],components:jh,children:U})}):t.jsx("pre",{className:"agent-log-plain-block",children:U})]},P.key):t.jsxs("div",{className:"agent-log-text",children:[ee,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],components:jh,children:U})}):t.jsx("pre",{className:"agent-log-plain-block",children:U})]},P.key)}),!C&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:T,"data-testid":"agent-log-return-to-live",children:[t.jsx(mn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Ha(e){return e??void 0}function Po(e){return{provider:Ha(e.modelProvider),modelId:Ha(e.modelId)}}function Ro(e){return{provider:Ha(e.validatorModelProvider),modelId:Ha(e.validatorModelId)}}function To(e){return{provider:Ha(e.planningModelProvider),modelId:Ha(e.planningModelId)}}function GA(e,n){return _f(e,n)}function JA(e,n){return Af(e,n)}function YA(e,n){return Pf(e,n)}function Mc(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 _c(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Ac(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function QA(e,n){const a={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${a} model set to default`:`${a} model set to ${n.provider}/${n.modelId}`}function XA({task:e,addToast:n,onTaskUpdated:s,settings:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(()=>Po(e)),[v,b]=i.useState(()=>Po(e)),[y,j]=i.useState(()=>Ro(e)),[C,A]=i.useState(()=>Ro(e)),[N,S]=i.useState(()=>To(e)),[_,T]=i.useState(()=>To(e)),[M,E]=i.useState(()=>e.thinkingLevel??null),[O,B]=i.useState(()=>e.thinkingLevel??null),[R,P]=i.useState(null),F=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Ds().then(ae=>{o(ae.models),c(ae.favoriteProviders),u(ae.favoriteModels)}).catch(ae=>{p(ae.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const q=i.useCallback(async ae=>{const ce=l,Re=ce.includes(ae)?ce.filter(be=>be!==ae):[ae,...ce];c(Re);try{await Pn({favoriteProviders:Re,favoriteModels:d})}catch{c(ce),n("Failed to update favorites","error")}},[l,d,n]),ee=i.useCallback(async ae=>{const ce=d,Re=ce.includes(ae)?ce.filter(be=>be!==ae):[ae,...ce];u(Re);try{await Pn({favoriteProviders:l,favoriteModels:Re})}catch{u(ce),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{F.current=e.id;const ae=Po(e),ce=Ro(e),te=To(e);x(ae),b(ae),j(ce),A(ce),S(te),T(te);const Re=e.thinkingLevel??null;E(Re),B(Re),P(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const U=i.useMemo(()=>_c(g),[g]),k=i.useMemo(()=>_c(y),[y]),I=i.useMemo(()=>_c(N),[N]),$=i.useMemo(()=>GA(e,a),[e,a]),w=i.useMemo(()=>JA(e,a),[e,a]),H=i.useMemo(()=>YA(e,a),[e,a]),J=R!==null,fe=i.useCallback(async(ae,ce)=>{const te=e.id,Re=v,be=C,ke=_;P(ae);try{const Ue=s?ae==="executor"?{modelProvider:ce.provider??null,modelId:ce.modelId??null}:ae==="validator"?{validatorModelProvider:ce.provider??null,validatorModelId:ce.modelId??null}:{planningModelProvider:ce.provider??null,planningModelId:ce.modelId??null}:{modelProvider:(ae==="executor"?ce:v).provider??null,modelId:(ae==="executor"?ce:v).modelId??null,validatorModelProvider:(ae==="validator"?ce:C).provider??null,validatorModelId:(ae==="validator"?ce:C).modelId??null,planningModelProvider:(ae==="planning"?ce:_).provider??null,planningModelId:(ae==="planning"?ce:_).modelId??null},Ge=await ci(te,Ue);if(F.current!==te)return;const qe=Po(Ge),Ae=Ro(Ge),Ee=To(Ge);b(qe),x(qe),A(Ae),j(Ae),T(Ee),S(Ee),s?.(Ge),n(QA(ae,{executor:qe,validator:Ae,planning:Ee}[ae]),"success")}catch(Ue){if(F.current!==te)return;ae==="executor"?x(Re):ae==="validator"?j(be):S(ke),n(Me(Ue)||"Failed to save model settings","error")}finally{F.current===te&&P(null)}},[e.id,v,C,_,n,s]),de=i.useCallback(ae=>{const ce=Mc(ae);x(ce),!Ac(ce,v)&&fe("executor",ce)},[v,fe]),D=i.useCallback(ae=>{const ce=Mc(ae);j(ce),!Ac(ce,C)&&fe("validator",ce)},[C,fe]),_e=i.useCallback(ae=>{const ce=Mc(ae);S(ce),!Ac(ce,_)&&fe("planning",ce)},[_,fe]),z=i.useCallback(async ae=>{const ce=e.id,te=O,Re=ae===""?null:ae;E(Re),P("thinking");try{const be=await ci(ce,{thinkingLevel:Re});if(F.current!==ce)return;const ke=be.thinkingLevel??null;B(ke),E(ke),s?.(be);const Ue=a?.defaultThinkingLevel??"off";n(ke===null?`Thinking level set to default (${Ue})`:`Thinking level set to ${ke}`,"success")}catch(be){if(F.current!==ce)return;E(te),n(Me(be)||"Failed to save thinking level","error")}finally{F.current===ce&&P(null)}},[e.id,O,a,n,s]),Z=!v.provider&&!v.modelId,oe=!C.provider&&!C.modelId,Y=!_.provider&&!_.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…"}):f?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",f,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),Ds().then(ae=>{o(ae.models),c(ae.favoriteProviders),u(ae.favoriteModels)}).catch(ae=>p(ae.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Z?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",$.provider&&$.modelId?` (${$.provider}/${$.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Qn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(ys,{id:"executorModel",label:"Executor Model",value:U,onChange:de,models:r,disabled:J,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:d,onToggleModelFavorite:ee}),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:oe?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:[C.provider&&t.jsx(Qn,{provider:C.provider,size:"sm"}),C.provider,"/",C.modelId]})}),t.jsx(ys,{id:"validatorModel",label:"Reviewer Model",value:k,onChange:D,models:r,disabled:J,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:d,onToggleModelFavorite:ee}),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:Y?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",H.provider&&H.modelId?` (${H.provider}/${H.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[_.provider&&t.jsx(Qn,{provider:_.provider,size:"sm"}),_.provider,"/",_.modelId]})}),t.jsx(ys,{id:"planningModel",label:"Planning Model",value:I,onChange:_e,models:r,disabled:J,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:d,onToggleModelFavorite:ee}),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:O===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:O})}),t.jsxs("select",{id:"thinkingLevel",value:M??"",onChange:ae=>z(ae.target.value),disabled:J,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",a?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Z&&oe&&Y&&O===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const ZA={open:t.jsx(jl,{size:16}),closed:t.jsx(Xr,{size:16}),merged:t.jsx(af,{size:16})};function eP({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:d}){const[u,m]=i.useState(!1),[h,f]=i.useState(""),[p,g]=i.useState(""),[x,v]=i.useState(!1),[b,y]=i.useState(!1),[j,C]=i.useState(null),A=i.useCallback(async()=>{if(h.trim()){v(!0);try{const T=await sk(e,{title:h.trim(),body:p.trim()||void 0},n);l(T),m(!1),f(""),g(""),d(`Created PR #${T.number}`,"success")}catch(T){d(Me(T)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,d]),N=i.useCallback(async()=>{if(s){y(!0);try{const T=await ik(e,n);C(T),c(T.prInfo),d("PR status refreshed","success")}catch(T){d(Me(T)||"Failed to refresh PR","error")}finally{y(!1)}}},[e,s,n,c,d]);if(!s)return a==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Hs,{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(Hs,{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."})]}):u?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Hs,{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:T=>f(T.target.value),disabled:x,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:T=>g(T.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:A,disabled:!h.trim()||x,children:x?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Hs,{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(Nn,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const S=ZA[s.status]??t.jsx(jl,{size:16}),_=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Hs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:S}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:b,title:"Refresh PR status",children:t.jsx(os,{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})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:_.length>0?`Waiting for: ${_.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(Ri,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(zx,{size:14}),"View on GitHub"]})]})]})]})}const Sh=2e3;function tP(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function nP(e){return e==="agent"||e==="system"}function sP({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((S,_)=>new Date(_.createdAt).getTime()-new Date(S.createdAt).getTime()),[e.comments]),v=o.length>Sh;async function b(){const S=o.trim();if(S){f(!0);try{const _=await Ew(e.id,S,r);l(""),n?.(_),s("Comment added","success")}catch(_){s(Me(_)||"Failed to add comment","error")}finally{f(!1)}}}async function y(S){const _=u.trim();if(_){f(!0);try{const T=await kw(e.id,S,_,r);d(null),m(""),n?.(T),s("Comment updated","success")}catch(T){s(Me(T)||"Failed to update comment","error")}finally{f(!1)}}}async function j(S){g(S);try{const _=await jw(e.id,S,r);n?.(_),s("Comment deleted","success")}catch(_){s(Me(_)||"Failed to delete comment","error")}finally{g(null)}}function C(S){S.key==="Enter"&&(S.ctrlKey||S.metaKey)&&(S.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(S=>{const _=S.author===a,T=c===S.id,M=nP(S.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[M?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:S.author}),t.jsx("span",{className:"detail-log-timestamp",children:tP(S)})]}),_&&!T?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(S.id),m(S.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void j(S.id),disabled:p===S.id,children:p===S.id?"Deleting…":"Delete"})]}):null]}),T?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:E=>m(E.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(S.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:S.text})]},S.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:S=>l(S.target.value),onKeyDown:C,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," / ",Sh]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function iP(e){return e?e.slice(0,7):"Unknown"}function aP({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:iP(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 Zg(e){return e.split(`
673
+ `).map((s,a)=>{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}
674
+ `},a):t.jsx(el.Fragment,{children:`${s}
675
+ `},a)})}function rP(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function oP({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[m,h]=i.useState(!0),f=i.useRef(null);Si(f,e,"fusion:changes-diff-modal-size");const p=Li(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),x=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=j=>{if(j.key==="Escape"){l();return}j.key==="ArrowUp"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),g()),j.key==="ArrowDown"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,x]),!e)return null;const v=d!==null?s[d]: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:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(di,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",a.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",a.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:d===null||d<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(kl,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:d!==null?`${d+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:x,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(In,{})})]}),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(sl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(os,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(tn,{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(Zr,{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,j)=>t.jsxs("button",{className:`changes-diff-file-item ${d===j?"selected":""}`,onClick:()=>u(j),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:rP(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:Zg(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(di,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function eb(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Pc(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(Zr,{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(di,{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(a=>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:eb("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function lP({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(new Set),[v,b]=i.useState(null),[y,j]=i.useState(!0),[C,A]=i.useState(!1),N=a==="done",S=N&&!!r?.commitSha,_=a==="in-progress"||a==="in-review"||S,T=i.useCallback(async()=>{if(!_){h(!1);return}try{h(!0),p(null);const R=await yf(e,void 0,s),P=R.files.map(F=>({path:F.path,status:F.status,additions:F.additions,deletions:F.deletions,patch:F.patch}));c(P),u(R.stats),P.length>0&&(x(new Set([P[0].path])),b(0))}catch(R){p(Me(R)||"Failed to load diff")}finally{h(!1)}},[e,s,_]);i.useEffect(()=>{T()},[T]);const M=R=>{x(P=>{const F=new Set(P);if(F.has(R))F.delete(R);else{F.add(R);const q=l.findIndex(ee=>ee.path===R);q!==-1&&b(q)}return F})},E=R=>{if(R<0||R>=l.length)return;const P=l[R].path;x(new Set([P])),b(R)},O=v!==null&&v>0,B=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(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(zs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!N&&!n)return o&&o.length>0?Pc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(di,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(N&&!S){if(o&&o.length>0)return Pc(o,!0,r);const R=r?.filesChanged,P=r?.insertions,F=r?.deletions,q=R!=null||P!=null||F!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(di,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:q?`Merge summary: ${R??0} file${(R??0)===1?"":"s"} changed, +${P??0} additions, -${F??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Pc(o,N,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(di,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:N?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[N&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Zr,{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(di,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.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:()=>O&&E(v-1),disabled:!O,title:"Previous file","aria-label":"Previous file",children:t.jsx(kl,{})}),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:()=>B&&E(v+1),disabled:!B,title:"Next file","aria-label":"Next file",children:t.jsx(In,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>j(R=>!R),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(sl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:T,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>A(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(_l,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(R=>{const P=g.has(R.path);return t.jsxs("div",{className:`changes-file-item ${P?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>M(R.path),children:[t.jsx("span",{className:"changes-file-toggle",children:P?t.jsx(mn,{size:14}):t.jsx(In,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${R.status}`,title:R.status,children:eb(R.status)}),t.jsx("span",{className:"changes-file-path",title:R.path,children:t.jsx("bdo",{dir:"ltr",children:R.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${R.additions} -${R.deletions}`,children:["+",R.additions," -",R.deletions]})]}),P&&R.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${y?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Zg(R.patch)})})})]},R.path)})}),t.jsx(oP,{isOpen:C,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>A(!1),onRefresh:T})]})}function Ch(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function cP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function o3(e,n){const s=cP(e),a=new Set(n.map(c=>c.id));if(!a.has(s))return s;const r=30;let o=s,l=1;for(;a.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function dP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Eh=["image/png","image/jpeg","image/gif","image/webp"];function uP(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function tb({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,nodeId:c,onNodeIdChange:d,nodeOptions:u,nodeOverrideDisabled:m=!1,nodeOverrideDisabledReason:h,priority:f,onPriorityChange:p,executorModel:g,onExecutorModelChange:x,validatorModel:v,onValidatorModelChange:b,planningModel:y,onPlanningModelChange:j,thinkingLevel:C,onThinkingLevelChange:A,presetMode:N,onPresetModeChange:S,selectedPresetId:_,onSelectedPresetIdChange:T,selectedWorkflowSteps:M,onWorkflowStepsChange:E,onDefaultOnApplied:O,pendingImages:B,onImagesChange:R,tasks:P,projectId:F,disabled:q=!1,addToast:ee,isActive:U=!0,onAutoSaveDescription:k,onPlanningMode:I,onSubtaskBreakdown:$,onClose:w,renderBelowPrimary:H,renderBelowModelConfiguration:J,hideDependencies:fe,autoExpandMoreOptionsOnSelection:de=!0,reviewLevel:D,onReviewLevelChange:_e,executionMode:z,onExecutionModeChange:Z}){const oe=(fe?!1:o.length>0)||B.length>0||M.length>0||N!=="default"||(f??Cs)!==Cs||g!==""||v!==""||(y||"")!==""||(C||"")!==""||D!==void 0||z==="fast"||(c||"")!=="",[Y,ae]=i.useState(!1),[ce,te]=i.useState(de?oe:!1),[Re,be]=i.useState(""),[ke,Ue]=i.useState([]),[Ge,qe]=i.useState([]),[Ae,Ee]=i.useState([]),[ie,se]=i.useState(!1),[xe,ne]=i.useState(null),[Fe,Qe]=i.useState([]),[ge,ze]=i.useState("idle"),[tt,pt]=i.useState(!1),[ve,le]=i.useState(!1),[Te,pe]=i.useState(!1),$e=i.useRef(null),st=i.useRef(null),at=i.useRef(null),rt=i.useRef(null),Oe=i.useRef(null),Be=i.useRef(null),et=i.useRef(null),jt=i.useRef(!1),De=i.useRef(oe),vt=i.useRef(n.trim()),Et=i.useRef(n.trim());i.useEffect(()=>{U&&(se(!0),Ds().then(X=>{Ue(X.models),qe(X.favoriteProviders),Ee(X.favoriteModels)}).catch(()=>{}).finally(()=>se(!1)),Rl(F).then(X=>ne(X)).catch(()=>ne(null)),so(F).then(X=>Qe(X.filter(Ie=>Ie.enabled))).catch(()=>Qe([])))},[U,F]);const bt=xe?.modelPresets||[],zt=bt.find(X=>X.id===_),qt=(fe?!1:o.length>0)||B.length>0||M.length>0||N!=="default"||(f??Cs)!==Cs||g!==""||v!==""||(y||"")!==""||(C||"")!==""||D!==void 0||z==="fast"||(c||"")!=="";i.useEffect(()=>{if(e!=="create"||!U||!xe?.autoSelectModelPreset)return;const X=(xe.defaultPresetBySize,void 0);if(X){const Ie=Ch(X);T(X.id),S("preset"),x(Ie.executorValue),b(Ie.validatorValue)}},[U,xe,bt,e]);const It=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!U||It.current||Fe.length===0)return;const X=Fe.filter(he=>he.defaultOn);if(X.length===0)return;It.current=!0;const Ie=X.map(he=>he.id);E(Ie),O?.(Ie)},[e,U,Fe]),i.useEffect(()=>{U||(It.current=!1)},[U]),i.useEffect(()=>{if(!de){De.current=qt;return}qt&&!De.current&&te(!0),De.current=qt},[qt,de]),i.useEffect(()=>{ce||(ae(!1),be(""))},[ce]),i.useEffect(()=>{e!=="edit"||!U||rt.current&&(rt.current.focus(),rt.current.select())},[e,U]),i.useEffect(()=>{if(!Y)return;const X=Ie=>{st.current&&!st.current.contains(Ie.target)&&ae(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[Y]),i.useEffect(()=>{(e!=="edit"||q)&&pe(!1)},[e,q]),i.useEffect(()=>{if(e!=="edit"){ze("idle");return}const X=n.trim();vt.current=X,Et.current=X,ze("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!k||!U)return;const X=n.trim(),Ie=vt.current;if(X===Ie||X===Et.current){Be.current&&(clearTimeout(Be.current),Be.current=null),jt.current||ze("idle");return}return Be.current&&clearTimeout(Be.current),Be.current=setTimeout(async()=>{if(!jt.current){jt.current=!0,ze("saving");try{await k(X),Et.current=X,ze("saved"),et.current&&clearTimeout(et.current),et.current=setTimeout(()=>{ze("idle"),et.current=null},2e3)}catch{ze("idle")}finally{jt.current=!1,Be.current=null}}},1500),()=>{Be.current&&(clearTimeout(Be.current),Be.current=null)}},[e,n,k,U]),i.useEffect(()=>()=>{Be.current&&clearTimeout(Be.current),et.current&&clearTimeout(et.current)},[]),i.useEffect(()=>{if(!tt)return;const X=Ie=>{$e.current&&!$e.current.contains(Ie.target)&&pt(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[tt]);const _t=i.useCallback(X=>{const Ie=X.clipboardData?.items;if(Ie)for(let he=0;he<Ie.length;he++){const Ne=Ie[he];if(Ne.type.startsWith("image/")){const Je=Ne.getAsFile();if(Je&&Eh.includes(Je.type)){X.preventDefault(),R([...B,{file:Je,previewUrl:URL.createObjectURL(Je)}]);return}}}},[B,R]),Xt=i.useCallback(X=>{X.preventDefault();const Ie=X.dataTransfer.files;for(let he=0;he<Ie.length;he++){const Ne=Ie[he];if(Eh.includes(Ne.type)){R([...B,{file:Ne,previewUrl:URL.createObjectURL(Ne)}]);return}}},[B,R]),Lt=i.useCallback(X=>{const Ie=B[X];Ie&&URL.revokeObjectURL(Ie.previewUrl),R(B.filter((he,Ne)=>Ne!==X))},[B,R]),Ut=i.useCallback(X=>{l(o.includes(X)?o.filter(Ie=>Ie!==X):[...o,X])},[o,l]),cn=(X,Ie)=>X.length>Ie?X.slice(0,Ie)+"…":X,Jt=i.useCallback(X=>{s(X.target.value);const Ie=X.target;Ie.style.height="auto",Ie.style.height=Ie.scrollHeight+"px"},[s]),Vt=i.useCallback(()=>{pe(X=>!X)},[]),Kt=i.useCallback(X=>{!Te||X.key!=="Escape"||(X.preventDefault(),X.stopPropagation(),pe(!1))},[Te]),rn=i.useCallback(async X=>{const Ie=n.trim();if(!(!Ie||ve)){le(!0);try{const he=await gf(Ie,X,F);s(he),pt(!1),ee("Description refined with AI","success"),at.current&&(at.current.style.height="auto",at.current.style.height=at.current.scrollHeight+"px")}catch(he){const Ne=bf(he);ee(Ne,"error")}finally{le(!1)}}},[n,ve,ee,s,F]),fn=i.useCallback(async X=>{const Ie=Ge,Ne=Ie.includes(X)?Ie.filter(Je=>Je!==X):[X,...Ie];qe(Ne);try{await Pn({favoriteProviders:Ne,favoriteModels:Ae})}catch{qe(Ie)}},[Ge,Ae]),on=i.useCallback(async X=>{const Ie=Ae,Ne=Ie.includes(X)?Ie.filter(Je=>Je!==X):[X,...Ie];Ee(Ne);try{await Pn({favoriteProviders:Ge,favoriteModels:Ne})}catch{Ee(Ie)}},[Ae,Ge]),gn=i.useCallback(X=>{if(X<=0)return;const Ie=[...M];[Ie[X-1],Ie[X]]=[Ie[X],Ie[X-1]],E(Ie)},[M,E]),je=i.useCallback(X=>{if(X>=M.length-1)return;const Ie=[...M];[Ie[X],Ie[X+1]]=[Ie[X+1],Ie[X]],E(Ie)},[M,E]),Le=i.useCallback(X=>{E(M.filter(Ie=>Ie!==X))},[M,E]),re=new Map;for(const X of Fe)re.set(X.id,{name:X.name,description:X.description});const Pe=P.filter(X=>!o.includes(X.id)).sort((X,Ie)=>{const he=Ie.createdAt.localeCompare(X.createdAt);if(he!==0)return he;const Ne=parseInt(X.id.slice(X.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-Ne}),Se=Re?Pe.filter(X=>X.id.toLowerCase().includes(Re.toLowerCase())||X.title&&X.title.toLowerCase().includes(Re.toLowerCase())||X.description&&X.description.toLowerCase().includes(Re.toLowerCase())):Pe;return t.jsxs("div",{className:"task-form",onDrop:Xt,onDragOver:X=>X.preventDefault(),onPaste:_t,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:rt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:X=>r(X.target.value),disabled:q})]}),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${ge==="idle"?"":" is-visible"}`,"aria-live":"polite",children:ge==="saving"?"Saving...":ge==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Te?" description--fullscreen":""}`,ref:$e,onKeyDown:Kt,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:Vt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(eo,{size:14})})]}),t.jsx("textarea",{ref:at,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Jt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:q||ve}),(()=>{const X=!!n.trim()&&!q;return t.jsxs(t.Fragment,{children:[!Te&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${X?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Vt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(_l,{size:14})}),X&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ve?"refine-button--loading":""}`,onClick:()=>pt(Ie=>!Ie),disabled:ve,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(vs,{size:12,style:{verticalAlign:"middle"}}),ve?"Refining...":"Refine"]})]})})(),tt&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:X=>X.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>rn("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:()=>rn("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:()=>rn("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:()=>rn("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"&&(I||$)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[I&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const X=n.trim();if(!X){ee("Enter a description first","error");return}w?.(),I(X)},disabled:q||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),$&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const X=n.trim();if(!X){ee("Enter a description first","error");return}w?.(),$(X)},disabled:q||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),H,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>te(X=>!X),"aria-expanded":ce,"aria-controls":"task-form-more-options",disabled:q,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ce?t.jsx(hi,{size:14}):t.jsx(mn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ce?"":" collapsed"}`,"aria-hidden":!ce,hidden:!ce,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),B.length>0&&t.jsx("div",{className:"inline-create-previews",children:B.map((X,Ie)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:X.previewUrl,alt:X.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Lt(Ie),disabled:q,title:"Remove image",children:"×"})]},X.previewUrl))}),t.jsx("input",{ref:Oe,type:"file",accept:"image/*",onChange:X=>{const Ie=X.target.files?.[0];Ie&&(R([...B,{file:Ie,previewUrl:URL.createObjectURL(Ie)}]),X.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Oe.current?.click(),disabled:q,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),d&&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:X=>d(X.target.value||void 0),disabled:q||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(u??[]).map(X=>t.jsxs("option",{value:X.id,children:[X.name," (",dP(X.status),")"]},X.id))]}),(()=>{const X=(u??[]).find(Ie=>Ie.id===c);return X?t.jsx("div",{className:"task-form-node-status",children:t.jsx(ca,{status:X.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!fe&&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:st,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ae(X=>!X),disabled:q,children:o.length>0?`${o.length} selected`:"Add dependencies"}),Y&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Re,onChange:X=>be(X.target.value),onClick:X=>X.stopPropagation()}),Se.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Se.map(X=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(X.id)?" selected":""}`,onClick:()=>Ut(X.id),onMouseDown:Ie=>Ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:X.id}),t.jsx("span",{className:"dep-dropdown-title",children:cn(X.title||X.description||X.id,30)})]},X.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(X=>t.jsxs("span",{className:"dep-chip",children:[X,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Ut(X),disabled:q,children:"×"})]},X))})]})}),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:f??Cs,onChange:X=>p(X.target.value),disabled:q,children:Xa.map(X=>t.jsx("option",{value:X,children:X[0].toUpperCase()+X.slice(1)},X))})]}),Z&&z!==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:z,onChange:X=>Z(X.target.value),disabled:q,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),ie?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):ke.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:N==="preset"?_:N,onChange:X=>{const Ie=X.target.value;if(Ie==="default"){S("default"),T(""),x(""),b("");return}if(Ie==="custom"){S("custom"),T("");return}const he=bt.find(Je=>Je.id===Ie),Ne=Ch(he);S("preset"),T(Ie),x(Ne.executorValue),b(Ne.validatorValue)},disabled:q,children:[t.jsx("option",{value:"default",children:"Use default"}),bt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,bt.map(X=>t.jsx("option",{value:X.id,children:X.name},X.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),N==="preset"&&zt?t.jsxs("small",{children:["Using preset: ",zt.name]}):null,N==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>S("custom"),disabled:q,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(ys,{id:"executor-model",label:"Executor Model",value:g,onChange:X=>{S("custom"),T(""),x(X)},models:ke,disabled:q||N==="preset",favoriteProviders:Ge,onToggleFavorite:fn,favoriteModels:Ae,onToggleModelFavorite:on})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(ys,{id:"validator-model",label:"Reviewer Model",value:v,onChange:X=>{S("custom"),T(""),b(X)},models:ke,disabled:q||N==="preset",favoriteProviders:Ge,onToggleFavorite:fn,favoriteModels:Ae,onToggleModelFavorite:on})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(ys,{id:"planning-model",label:"Planning Model",value:y||"",onChange:X=>{S("custom"),T(""),j(X)},models:ke,disabled:q||N==="preset",favoriteProviders:Ge,onToggleFavorite:fn,favoriteModels:Ae,onToggleModelFavorite:on})]}),A&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:C||"",onChange:X=>A(X.target.value),disabled:q||N==="preset",children:[t.jsxs("option",{value:"",children:["Default (",xe?.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"})]})]}),_e&&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:D??"",onChange:X=>_e(X.target.value===""?void 0:parseInt(X.target.value,10)),disabled:q,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"})]})]})]})]}),J,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:Fe.length>0&&Fe.map(X=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${X.id}`,children:[t.jsx("input",{type:"checkbox",checked:M.includes(X.id),onChange:Ie=>{E(Ie.target.checked?[...M,X.id]:M.filter(he=>he!==X.id))},disabled:q}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[X.name,uP(X.phase||"pre-merge",X.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:X.description})]})]},X.id))})]}),M.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:"}),M.map((X,Ie)=>{const he=re.get(X);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${X}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Ie+1}),t.jsx("span",{className:"workflow-step-order-name",children:he?.name||X}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>gn(Ie),disabled:q||Ie===0,"data-testid":`workflow-step-move-up-${X}`,title:"Move up",children:t.jsx(hi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>je(Ie),disabled:q||Ie===M.length-1,"data-testid":`workflow-step-move-down-${X}`,title:"Move down",children:t.jsx(mn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Le(X),disabled:q,"data-testid":`workflow-step-remove-${X}`,title:"Remove",children:t.jsx(tn,{})})]})]},X)})]})]})]})]})}const Mh={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 mP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function hP(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 pP(e){return e?new Date(e).toLocaleString():null}function fP(e){const n=e.split(`
676
+ `);return n.length<=1?e:`${n.length} lines`}function Io(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function gP({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.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:a,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 bP({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,x]=i.useState([]),[v,b]=i.useState(!1),y=n.some(w=>w.status==="pending"),{entries:j}=Qg(e,!!l&&y,o);i.useEffect(()=>{let w=!1;return so(o).then(H=>{w||x(H.filter(J=>J.enabled))}).catch(()=>{w||x([])}),()=>{w=!0}},[o]);const C=a??[],A=i.useMemo(()=>g.map(w=>({id:w.id,name:w.name,description:w.description,phase:w.phase||"pre-merge"})),[g]),N=i.useMemo(()=>new Map(A.map(w=>[w.id,w])),[A]),S=w=>{u(H=>({...H,[w]:!H[w]}))},_=w=>{h(H=>{const J=H[w]??"markdown";return{...H,[w]:J==="markdown"?"plain":"markdown"}})},T=w=>{p(w)},M=()=>{p(null)};i.useEffect(()=>{if(!f)return;const w=H=>{H.key==="Escape"&&M()};return document.addEventListener("keydown",w),()=>{document.removeEventListener("keydown",w)}},[f]);const E=i.useCallback((w,H)=>{if(c){if(H){if(C.includes(w)){c(C);return}c([...C,w]);return}c(C.filter(J=>J!==w))}},[c,C]),O=i.useCallback(w=>{if(!c||w<=0)return;const H=[...C];[H[w-1],H[w]]=[H[w],H[w-1]],c(H)},[c,C]),B=i.useCallback(w=>{if(!c||w>=C.length-1)return;const H=[...C];[H[w],H[w+1]]=[H[w+1],H[w]],c(H)},[c,C]),R=i.useCallback(w=>{c&&c(C.filter(H=>H!==w))},[c,C]),P=n.length>0,F=C.length>0;i.useEffect(()=>{r||b(!1)},[r]);const q=i.useMemo(()=>C.map(w=>{const H=N.get(w);return{id:w,name:H?.name||w,description:H?.description||"Step definition not found.",phase:H?.phase||"pre-merge"}}),[C,N]),ee=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:A.map(w=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${w.id}`,children:[t.jsx("input",{type:"checkbox",checked:C.includes(w.id),onChange:H=>E(w.id,H.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[w.name,Io(w.phase,w.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:w.description})]})]},w.id))})]}),C.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:"}),C.map((w,H)=>{const J=N.get(w);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${w}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:J?.name||w}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(H),disabled:H===0,"data-testid":`workflow-step-move-up-${w}`,title:"Move up",children:t.jsx(hi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>B(H),disabled:H===C.length-1,"data-testid":`workflow-step-move-down-${w}`,title:"Move down",children:t.jsx(mn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>R(w),"data-testid":`workflow-step-remove-${w}`,title:"Remove",children:t.jsx(tn,{})})]})]},w)})]})]}),U=()=>{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(!P)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 w=n.filter(D=>D.status==="passed").length,H=n.filter(D=>D.status==="failed").length,J=n.filter(D=>D.status==="skipped").length,fe=n.filter(D=>D.status==="pending").length,de=[`${n.length} step${n.length!==1?"s":""}`];return w>0&&de.push(`${w} passed`),H>0&&de.push(`${H} failed`),J>0&&de.push(`${J} skipped`),fe>0&&de.push(`${fe} 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:de.join(" · ")}),n.map((D,_e)=>{const z=D.phase||"pre-merge",Z=d[D.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${D.status}`,"data-testid":`workflow-result-item-${D.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[D.workflowStepName,Io(z,D.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${D.status}`,"data-testid":`workflow-result-badge-${D.workflowStepId}`,children:mP(D.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[D.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",pP(D.startedAt)]}),D.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:hP(D.startedAt,D.completedAt)})]}),D.status==="pending"&&D.startedAt?t.jsx(gP,{entries:j,startedAt:D.startedAt,stepId:D.workflowStepId}):D.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{className:"workflow-result-toggle",onClick:()=>S(D.workflowStepId),"data-testid":`workflow-result-toggle-${D.workflowStepId}`,children:Z?"Hide output":"Show output"}),!Z&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${D.workflowStepId}`,children:fP(D.output)}),Z&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>_(D.workflowStepId),"data-testid":`workflow-result-mode-toggle-${D.workflowStepId}`,title:(m[D.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[D.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>T(D.workflowStepId),"data-testid":`workflow-result-expand-${D.workflowStepId}`,title:"Expand output",children:t.jsx(_l,{size:12})})]})]}),Z&&t.jsx("div",{className:`workflow-result-output${(m[D.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${D.workflowStepId}`,children:(m[D.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],components:Mh,children:D.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:D.output})})]}):null]},`${D.workflowStepId}-${_e}`)})]})},k=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(w=>!w),"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(ns,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(js,{size:14}),"Edit"]})}):null,I=!s&&!P&&F,$=r&&P;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[I?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:[q.length," step",q.length===1?"":"s"]})]}),k]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:q.map(w=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${w.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[w.name,Io(w.phase,w.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:w.description})]},w.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."}),ee()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),k]}),U(),ee()]}),f&&(()=>{const w=n.find(fe=>fe.workflowStepId===f);if(!w)return null;const H=m[w.workflowStepId]??"markdown",J=w.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:fe=>{fe.target===fe.currentTarget&&M()},"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:w.workflowStepName}),Io(J,w.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>_(w.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:H==="markdown"?"Switch to plain text":"Switch to markdown",children:H==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-output-modal-close",onClick:M,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(tn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${H==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:H==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],components:Mh,children:w.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:w.output})})})]})})})()]})}function xP(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const vP=new Set(["planning","researching","executing","finalizing","merging"]);function yP(e){return e!==void 0&&e!=="online"}function wP({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),ll().then(M=>{o(M)}).catch(M=>{u(Me(M)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(M=>[M.id,M])),[r]),v=i.useMemo(()=>[...r].sort((M,E)=>M.name.localeCompare(E.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,j=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",C=y?x.get(y):void 0,A=C?`${C.name} (${C.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",N=e.column==="in-progress"||vP.has(e.status),S=N||f||l,_=i.useCallback(async M=>{if(M===m)return;const E=e.id,O=m;h(M),p(!0);try{const B=await ci(E,{nodeId:M||null});if(g.current!==E)return;h(B.nodeId??""),a?.(B),s(M?"Node override updated":"Node override cleared","success")}catch(B){if(g.current!==E)return;h(O),s(Me(B)||"Failed to update node override","error")}finally{g.current===E&&p(!1)}},[s,a,m,e.id]),T=i.useCallback(()=>{_("")},[_]);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:[C?t.jsx(ca,{status:C.status,compact:!0}):null,A,yP(C?.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:j})]}),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:xP(b?.unavailableNodePolicy)})]})]}),N&&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"}),N?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:S,onChange:M=>{_(M.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(M=>t.jsxs("option",{value:M.id,title:`Status: ${M.status}`,children:[M.name," (",M.type,") — ",M.status]},M.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):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:N||f,onClick:T,children:"Clear override"})]}):null]})]})}const kP=/^[a-zA-Z0-9_-]{1,64}$/,jP=200;function _h(e){return e?new Date(e).toLocaleString():""}function NP(e,n=jP){return e.length<=n?e:e.substring(0,n)+"…"}function SP({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[x,v]=i.useState(""),[b,y]=i.useState(null),[j,C]=i.useState([]),[A,N]=i.useState(!1),[S,_]=i.useState(!1),[T,M]=i.useState(""),[E,O]=i.useState(""),[B,R]=i.useState(!1),[P,F]=i.useState(null),[q,ee]=i.useState(null),[U,k]=i.useState(!1),I=i.useCallback(async()=>{try{const z=await Nw(e,a);l(z)}catch(z){n(Me(z)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{I()},[I]);async function $(z){u===z.key?(m(null),f(""),g(null),v(""),y(null),C([]),k(!1)):(m(z.key),f(z.content),g(null),v(""),y(null),C([]),k(!1))}async function w(z){if(b===z)y(null),C([]);else{y(z),N(!0);try{const Z=await Sw(e,z,a);C(Z)}catch(Z){n(Me(Z)||"Failed to load revisions","error")}finally{N(!1)}}}function H(){u&&(g(u),v(h))}function J(){g(null),v("")}async function fe(){if(!(!p||!x.trim())){R(!0);try{await $u(e,p,x,{},a),g(null),v(""),await I();const z=o.find(Z=>Z.key===p);z&&f(z.content),n("Document saved","success")}catch(z){n(Me(z)||"Failed to save document","error")}finally{R(!1)}}}async function de(){const z=T.trim(),Z=E.trim();if(!z){n("Document key is required","error");return}if(!kP.test(z)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Z){n("Content is required","error");return}R(!0);try{await $u(e,z,Z,{},a),_(!1),M(""),O(""),await I(),n("Document created","success")}catch(oe){n(Me(oe)||"Failed to create document","error")}finally{R(!1)}}async function D(z){F(z);try{await Cw(e,z,a),ee(null),F(null),u===z&&(m(null),f("")),b===z&&(y(null),C([])),await I(),n("Document deleted","success")}catch(Z){n(Me(Z)||"Failed to delete document","error")}finally{F(null)}}function _e(z){f(z.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),S&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:T,onChange:z=>M(z.target.value),placeholder:"e.g., plan, notes, research",disabled:B}),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:E,onChange:z=>O(z.target.value),rows:6,placeholder:"Enter document content…",disabled:B})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{_(!1),M(""),O("")},disabled:B,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void de(),disabled:B||!T.trim()||!E.trim(),children:B?"Creating…":"Create"})]})]}),o.length===0&&!S?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(z=>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(Vi,{size:14}),t.jsx("span",{className:"task-document-key",children:z.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",z.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:z.author}),t.jsx("span",{className:"task-document-timestamp",children:_h(z.updatedAt||z.createdAt)})]})]}),u===z.key&&p!==z.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:()=>k(Z=>!Z),"aria-label":U?"Switch to plain text":"Switch to markdown","aria-pressed":U,title:U?"Switch to plain text":"Switch to markdown",children:U?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:U?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===z.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),A?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):j.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:j.filter(Z=>Z.revision<z.revision).sort((Z,oe)=>oe.revision-Z.revision).map(Z=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>_e(Z),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Z.revision]}),t.jsx("span",{className:"revision-author",children:Z.author}),t.jsx("span",{className:"revision-timestamp",children:_h(Z.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:NP(Z.content,100)})]},Z.id))})]})]}),p===z.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:Z=>v(Z.target.value),rows:10,disabled:B}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:J,disabled:B,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void fe(),disabled:B||!x.trim(),children:B?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(z),children:u===z.key?t.jsxs(t.Fragment,{children:[t.jsx(hi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(mn,{size:14})," Expand"]})}),u===z.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void w(z.key),children:[t.jsx(Fr,{size:14})," History"]}),r&&p!==z.key&&t.jsx("button",{className:"btn btn-sm",onClick:H,children:"Edit"}),r&&(q===z.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 D(z.key),disabled:P===z.key,children:P===z.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>ee(null),disabled:P===z.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>ee(z.key),children:t.jsx(Sn,{size:14})}))]})]})]},z.key))}),r&&!S&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>_(!0),children:[t.jsx(Nn,{size:14})," New Document"]})]})}function $o(e){return e.toLocaleString()}function Rc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function pr(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),a=Math.round(n%60);return`${s}m ${a}s`}function CP(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 d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=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:a,longestStep:r}}function EP({tokenUsage:e,loading:n,task:s}){const a=Lf(s?.log??[]),r=a.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),d=CP(s?.workflowStepResults??[]),u=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:a.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:pr(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:d.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:pr(d.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:pr(l+d.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} (${pr(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:d.longestStep?`${d.longestStep.name} (${pr(d.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:u>0?`${Math.min((s?.currentStep??0)+1,u)} / ${u}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${Rc(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:$o(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:$o(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:$o(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:$o(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:Rc(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:Rc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const MP=new Set(["planning","researching","executing","finalizing","merging"]);function _P(e,n){return _f(e,n)}function AP(e,n){return Af(e,n)}function PP(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function RP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=PP(n);return a||Pf(e,s)}function TP(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 IP(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/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 $P(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function DP(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(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Ah(e,n){return e.length>n?e.slice(0,n)+"…":e}function Ph(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Tc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Ic(e){return e.trim()}function LP(e){const n=e.trim();return n.length>0?n:void 0}function _i(e){return typeof e=="string"&&Xa.includes(e)?e:Cs}function fr(e){return e==="fast"?"fast":"standard"}function OP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function zP(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const FP=i.lazy(()=>An(()=>import("./AgentDetailView-17J-F0Rl.js").then(e=>e.A),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.AgentDetailView})));function UP(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:OP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:zP(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const $c=200,BP=new Set(["triage","todo"]);function nb({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:x=!1,onRequestClose:v}){const[b,y]=i.useState(p),[j,C]=i.useState(()=>"prompt"in e?e:null),[A,N]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){C(e),N(!1);return}let Q=!1;return N(!0),C(null),Oa(e.id,n).then(We=>{Q||(C(We),N(!1))}).catch(()=>{Q||N(!1)}),()=>{Q=!0}},[e.id,n]);const S=j?{...j,...e,prompt:j.prompt,log:j.log}:{...e,prompt:""},_=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[T,M]=i.useState(null),[E,O]=i.useState(null),B=UP(S,{sourceAgentName:T?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{q(!1)},[e.id]);const[R,P]=i.useState("activity"),[F,q]=i.useState(!1),[ee,U]=i.useState(e.attachments||[]),[k,I]=i.useState(!1),[$,w]=i.useState(e.dependencies||[]),[H,J]=i.useState(!1),[fe,de]=i.useState(""),[D,_e]=i.useState(null),[z,Z]=i.useState([]),[oe,Y]=i.useState(!1),[ae,ce]=i.useState(!1),[te,Re]=i.useState(!1),[be,ke]=i.useState(!1),[Ue,Ge]=i.useState(!1),[qe,Ae]=i.useState(S.prompt||""),[Ee,ie]=i.useState(""),[se,xe]=i.useState(!1),[ne,Fe]=i.useState(""),[Qe,ge]=i.useState(!1),[ze,tt]=i.useState(!1),[pt,ve]=i.useState(e.title||""),[le,Te]=i.useState(e.description||""),[pe,$e]=i.useState(e.dependencies||[]),[st,at]=i.useState(""),[rt,Oe]=i.useState(""),[Be,et]=i.useState(""),[jt,De]=i.useState(""),[vt,Et]=i.useState("default"),[bt,zt]=i.useState(void 0),[qt,It]=i.useState(Cs),[_t,Xt]=i.useState(e.nodeId),[Lt,Ut]=i.useState(fr(e.executionMode)),[cn,Jt]=i.useState(""),[Vt,Kt]=i.useState(e.enabledWorkflowSteps||[]),[rn,fn]=i.useState(e.sourceIssue?.provider??""),[on,gn]=i.useState(e.sourceIssue?.repository??""),[je,Le]=i.useState(e.sourceIssue?.externalIssueId??""),[re,Pe]=i.useState(e.sourceIssue?.url??""),[Se,X]=i.useState([]),[Ie,he]=i.useState(!1),[Ne,Je]=i.useState(_i(e.priority)),[kt,Yt]=i.useState(!1),$t=i.useRef(!1),[Tt,Bt]=i.useState(!1),[jn,Dn]=i.useState(!1),[hn,Ht]=i.useState(!1),yn=i.useRef(null),pn=i.useRef(null),es=i.useRef(null),{getSlotsForId:ye}=Sf(n),Qt=ye("task-detail-tab").map((Q,We)=>({entry:Q,tabId:`plugin-${Q.pluginId}-${We}`})),Cn=typeof b=="string"&&b.startsWith("plugin-")?Qt.find(Q=>Q.tabId===b)??null:null;i.useEffect(()=>($t.current=!0,()=>{$t.current=!1}),[]);const[ue,dt]=i.useState(void 0),[wt,gt]=i.useState([]),[ot,yt]=i.useState(!1),[Ft,Zt]=i.useState(e.enabledWorkflowSteps||[]),Ln=e.column==="in-progress"||MP.has(e.status);i.useEffect(()=>{ve(e.title||""),Te(e.description||""),fn(e.sourceIssue?.provider??""),gn(e.sourceIssue?.repository??""),Le(e.sourceIssue?.externalIssueId??""),Pe(e.sourceIssue?.url??""),Ut(fr(e.executionMode)),Ht(!1),tt(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),i.useEffect(()=>{Zt(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Je(_i(e.priority))},[e.id,e.priority]),i.useEffect(()=>{let Q=!1;return Rl(n).then(We=>{Q||dt(We)}).catch(()=>{}),()=>{Q=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let Q=!1;return yt(!0),rj(e.id,n).then(We=>{Q||gt(We)}).catch(We=>{Q||h(`Failed to load workflow results: ${Me(We)}`,"error")}).finally(()=>{Q||yt(!1)}),()=>{Q=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const Q=n?`?projectId=${encodeURIComponent(n)}`:"",We=xt=>{try{const Gt=JSON.parse(xt.data);Gt.id===e.id&&Array.isArray(Gt.workflowStepResults)&&gt(Gt.workflowStepResults)}catch{}};return fi(`/api/events${Q}`,{events:{"task:updated":We}})},[b,e.id,n]),i.useEffect(()=>{H||de("")},[H]),i.useEffect(()=>{if(!e.assignedAgentId){_e(null);return}const Q=z.find(xt=>xt.id===e.assignedAgentId);if(Q){_e(Q);return}let We=!1;return bd(e.assignedAgentId,n).then(xt=>{We||_e(xt)}).catch(()=>{We||_e(null)}),()=>{We=!0}},[e.assignedAgentId,n,z]),i.useEffect(()=>{if(!e.sourceAgentId){M(null);return}const Q=z.find(xt=>xt.id===e.sourceAgentId);if(Q){M(Q);return}let We=!1;return Promise.resolve(bd(e.sourceAgentId,n)).then(xt=>{We||M(xt??null)}).catch(()=>{We||M(null)}),()=>{We=!0}},[e.sourceAgentId,n,z]),i.useEffect(()=>{Y(!1)},[e.id]),i.useEffect(()=>{if(!(Tt||jn))return;const We=xt=>{const Gt=xt.target,ds=yn.current?.contains(Gt),Xs=es.current?.contains(Gt);!ds&&Tt&&Bt(!1),!Xs&&jn&&Dn(!1)};return document.addEventListener("mousedown",We),()=>document.removeEventListener("mousedown",We)},[Tt,jn]),i.useEffect(()=>{if(!(Tt||jn))return;const We=xt=>{xt.key==="Escape"&&(xt.stopPropagation(),Tt&&Bt(!1),jn&&Dn(!1))};return document.addEventListener("keydown",We),()=>document.removeEventListener("keydown",We)},[Tt,jn]),i.useEffect(()=>{Ge(!1),Ae(S.prompt||""),ie("")},[e.id,S.prompt]);const Wt=BP.has(e.column)&&!Ie,Mt=i.useCallback(()=>{if(!Wt)return;tt(!0),ve(e.title||""),Te(e.description||""),$e(e.dependencies||[]);const Q=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",We=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",xt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";at(Q),Oe(We),et(xt),De(e.thinkingLevel??""),Xt(e.nodeId),Et(Q||We||xt?"custom":"default"),Jt(""),Kt(e.enabledWorkflowSteps||[]),Ut(fr(e.executionMode)),fn(e.sourceIssue?.provider??""),gn(e.sourceIssue?.repository??""),Le(e.sourceIssue?.externalIssueId??""),Pe(e.sourceIssue?.url??""),X([]),zt(e.reviewLevel),It(_i(e.priority))},[Wt,e]),En=i.useCallback(()=>{tt(!1),ve(e.title||""),Te(e.description||""),$e(e.dependencies||[]),Xt(e.nodeId),fn(e.sourceIssue?.provider??""),gn(e.sourceIssue?.repository??""),Le(e.sourceIssue?.externalIssueId??""),Pe(e.sourceIssue?.url??""),It(_i(e.priority)),Ut(fr(e.executionMode)),Se.forEach(Q=>URL.revokeObjectURL(Q.previewUrl)),X([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Se]),Xn=i.useCallback(async()=>{he(!0);try{const Q={},We=pt.trim(),xt=le.trim();We&&We!==(e.title??"")&&(Q.title=We),xt&&xt!==(e.description??"")&&(Q.description=xt),Ph(pe,e.dependencies??[])||(Q.dependencies=pe),Ph(Vt,e.enabledWorkflowSteps??[])||(Q.enabledWorkflowSteps=Vt);const Gt=Tc(st),ds=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";st!==ds&&(Q.modelProvider=Gt?.provider??null,Q.modelId=Gt?.modelId??null);const Xs=Tc(rt),ho=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";rt!==ho&&(Q.validatorModelProvider=Xs?.provider??null,Q.validatorModelId=Xs?.modelId??null);const rr=Tc(Be),po=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Be!==po&&(Q.planningModelProvider=rr?.provider??null,Q.planningModelId=rr?.modelId??null);const fo=e.thinkingLevel??"";jt!==fo&&(Q.thinkingLevel=jt!==""?jt:null),(e.nodeId??void 0)!==_t&&(Q.nodeId=_t??null);const go=e.reviewLevel;bt!==go&&(Q.reviewLevel=bt);const bo=_i(e.priority);qt!==bo&&(Q.priority=qt);const K=fr(e.executionMode);Lt!==K&&(Q.executionMode=Lt==="fast"?"fast":null);const Ce=Ic(rn),Ke=Ic(on),Pt=Ic(je),vn=LP(re);if(Ce.length===0&&Ke.length===0&&Pt.length===0&&!vn)e.sourceIssue&&(Q.sourceIssue=null);else{if(!Ce||!Ke||!Pt){h("Source issue provider, repository, and issue identifier are required","error"),he(!1);return}const Xe=Number.parseInt(Pt,10),nt=e.sourceIssue?.issueNumber??Xe;if(!Number.isFinite(nt)||nt<=0){h("Source issue identifier must be numeric for new metadata","error"),he(!1);return}const At={provider:Ce,repository:Ke,externalIssueId:Pt,issueNumber:nt,...vn?{url:vn}:{}},bn=e.sourceIssue;(!bn||bn.provider!==At.provider||bn.repository!==At.repository||bn.externalIssueId!==At.externalIssueId||bn.issueNumber!==At.issueNumber||(bn.url??void 0)!==At.url)&&(Q.sourceIssue=At)}if(Object.keys(Q).length>0){const Xe=await ci(e.id,Q,n);m?.(Xe)}if(Se.length>0){const Xe=[];for(const nt of Se)try{const At=await Br(e.id,nt.file,n);U(bn=>[...bn,At])}catch{Xe.push(nt.file.name)}Xe.length>0&&h(`Failed to upload: ${Xe.join(", ")}`,"error")}Se.forEach(Xe=>URL.revokeObjectURL(Xe.previewUrl)),X([]),h(`Updated ${e.id}`,"success"),tt(!1)}catch(Q){h(`Failed to update ${e.id}: ${Me(Q)}`,"error")}finally{$t.current&&he(!1)}},[e,pt,le,pe,st,rt,Be,jt,_t,bt,qt,Lt,Vt,rn,on,je,re,Se,h,n,m]),ts=i.useCallback(async Q=>{try{const We=await ci(e.id,{description:Q},n);m?.(We),h("Description saved","success")}catch(We){h(`Failed to save: ${Me(We)}`,"error")}},[e.id,h,n,m]),Ps=i.useCallback(async Q=>{const We=_i(Q),xt=_i(e.priority);if(We===xt){Je(xt);return}const Gt=Ne;Je(We),Yt(!0);try{const ds=await ci(e.id,{priority:We},n);Je(_i(ds.priority)),m?.(ds),h(`Priority updated to ${_i(ds.priority)}`,"success")}catch(ds){Je(Gt),h(`Failed to update ${e.id}: ${Me(ds)}`,"error")}finally{$t.current&&Yt(!1)}},[e.id,e.priority,n,Ne,m,h]),ws=i.useCallback(Q=>{ze&&(Q.key==="Escape"?(Q.preventDefault(),En()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),Xn()))},[ze,En,Xn]);i.useEffect(()=>{if(ze)return document.addEventListener("keydown",ws),()=>document.removeEventListener("keydown",ws)},[ze,ws]);const Bn=i.useRef(null),{nodes:rs}=$l(),{confirm:V}=Gs(),{entries:Ve,loading:Ye,loadMore:mt,hasMore:Ct,total:Rt,loadingMore:dn}=Qg(e.id,b==="logs"&&R==="agent-log",n),Dt=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(x)return;const Q=We=>{We.key==="Escape"&&!ze&&Dt()};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[x,Dt,ze]);const ks=i.useCallback(async Q=>{try{const We=e.steps.some(ds=>ds.status!=="pending"),xt=(Q==="todo"||Q==="triage")&&We;let Gt;if(xt){if(await V({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Gt={preserveProgress:!0};else if(!await V({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,Q,Gt),Dt(),h(`Moved to ${ss[Q]}`,"success")}catch(We){h(Me(We),"error")}},[e.id,e.steps,r,Dt,h,V]),Zn=i.useCallback(async()=>{if(await V({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),Dt(),h(`Deleted ${e.id}`,"info")}catch(We){const xt=DP(We);if(!xt||xt.dependentIds.length===0){h(Me(We),"error");return}const Gt=xt.dependentIds.join(", ");if(!await V({title:"Force Delete Task",message:`${e.id} is a dependency of ${Gt}.
677
+
678
+ Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),Dt(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Xs){h(Me(Xs),"error")}}},[e.id,o,Dt,h,V]),me=i.useCallback(async()=>{await V({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(Dt(),h(`Merging ${e.id}...`,"info"),l(e.id).then(We=>{const xt=We.merged?`Merged ${e.id} (branch: ${We.branch})`:`Closed ${e.id} (${We.error||"no branch to merge"})`;h(xt,"success")}).catch(We=>{h(Me(We),"error")}))},[e.id,l,Dt,h,V]),He=i.useCallback(()=>{c&&(Dt(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Q=>{h(Me(Q),"error")}))},[e.id,c,Dt,h]),lt=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(Dt(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(Q=>{h(Me(Q),"error")}))},[e.id,d,Dt,h]),G=i.useCallback(async()=>{if(!(!u||!await V({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const We=await u(e.id);Dt(),h(`Duplicated ${e.id} → ${We.id}`,"success")}catch(We){h(Me(We),"error")}},[e.id,u,Dt,h,V]),we=i.useCallback(async()=>{try{e.paused?(await hw(e.id,n),h(`Unpaused ${e.id}`,"success")):(await mf(e.id,n),h(`Paused ${e.id}`,"success")),Dt()}catch(Q){h(Me(Q),"error")}},[e.id,e.paused,Dt,h]),it=i.useCallback(async()=>{try{await bw(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),Dt()}catch(Q){h(Me(Q),"error")}},[e.id,Dt,h]),St=i.useCallback(async()=>{if(await V({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await xw(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),Dt()}catch(We){h(Me(We),"error")}},[e.id,Dt,h,V]),Nt=i.useCallback(async()=>{if(await V({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await _w(e.id,n),Dt(),h(`Replanning ${e.id}...`,"info")}catch(We){h(Me(We),"error")}},[e.id,n,Dt,h,V]),Mn=i.useCallback(()=>{xe(!0),Fe("")},[]),nn=i.useCallback(()=>{Bt(!1),Dn(!1)},[]),un=i.useCallback(Q=>{nn(),ks(Q)},[nn]),sn=i.useCallback(Q=>{nn(),Q()},[nn]),Hn=i.useCallback(()=>{nn(),me()},[nn,me]),qn=i.useCallback(()=>{xe(!1),Fe(""),ge(!1)},[]),ls=i.useCallback(async()=>{if(!ne.trim()){h("Please enter feedback describing what needs refinement","error");return}if(ne.length>2e3){h("Feedback must be 2000 characters or less","error");return}ge(!0);try{const Q=await Aw(e.id,ne.trim(),n);h(`Refinement task created: ${Q.id}`,"success"),Dt()}catch(Q){h(Me(Q),"error")}finally{ge(!1)}},[e.id,ne,h,Dt]),Rn=i.useCallback(async Q=>{I(!0);try{const We=await Br(e.id,Q,n);U(xt=>[...xt,We]),h("Screenshot attached","success")}catch(We){h(Me(We),"error")}finally{I(!1)}},[e.id,h]),On=i.useCallback(async Q=>{const We=Q.target.files?.[0];We&&(await Rn(We),Bn.current&&(Bn.current.value=""))},[Rn]);i.useEffect(()=>{const Q=We=>{const xt=We.clipboardData?.items;if(xt)for(let Gt=0;Gt<xt.length;Gt++){const ds=xt[Gt];if(ds.type.startsWith("image/")){const Xs=ds.getAsFile();if(Xs){We.preventDefault(),Rn(Xs);return}}}};return document.addEventListener("paste",Q),()=>document.removeEventListener("paste",Q)},[Rn]);const _n=i.useCallback(Q=>{Q.preventDefault()},[]),cs=i.useCallback(Q=>{Q.preventDefault();const We=Q.dataTransfer.files;for(let xt=0;xt<We.length;xt++){const Gt=We[xt];if(Gt.type.startsWith("image/")){Rn(Gt);return}}},[Rn]),Wn=i.useCallback(async Q=>{try{await ww(e.id,Q,n),U(We=>We.filter(xt=>xt.filename!==Q)),h("Attachment deleted","info")}catch(We){h(Me(We),"error")}},[e.id,h]),Vn=i.useCallback(async Q=>{const We=Ft;Zt(Q);try{const xt=await ci(e.id,{enabledWorkflowSteps:Q},n);h("Workflow steps updated","success"),m?.(xt)}catch(xt){Zt(We),h(`Failed to update workflow steps: ${Me(xt)}`,"error")}},[e.id,n,Ft,m,h]),ms=i.useCallback(async()=>{ce(!0);try{const Q=await fa(void 0,n);Z(Q),Y(!0)}catch(Q){h(`Failed to load agents: ${Me(Q)}`,"error"),Y(!1)}finally{ce(!1)}},[n,h]),Kn=i.useCallback(async Q=>{try{const We=await Wu(e.id,Q,n),xt=z.find(Gt=>Gt.id===Q)??null;_e(xt||(Gt=>Gt?.id===Q?Gt:null)),Y(!1),m?.(We),h("Assigned agent updated","success")}catch(We){h(`Failed to assign agent: ${Me(We)}`,"error")}},[e.id,n,z,m,h]),hs=i.useCallback(async()=>{try{const Q=await Wu(e.id,null,n);_e(null),Y(!1),m?.(Q),h("Agent unassigned","success")}catch(Q){h(`Failed to unassign agent: ${Me(Q)}`,"error")}},[e.id,n,m,h]),Gn=i.useCallback(async Q=>{const We=[...$,Q];w(We);try{await ci(e.id,{dependencies:We},n)}catch(xt){w($),h(Me(xt),"error")}},[e.id,$,h]),Rs=i.useCallback(async(Q,We)=>{Q.stopPropagation();const xt=$.filter(Gt=>Gt!==We);w(xt);try{await ci(e.id,{dependencies:xt},n)}catch(Gt){w($),h(Me(Gt),"error")}},[e.id,$,h]),Ts=i.useCallback(async Q=>{try{const We=await Oa(Q,n);a(We)}catch{h(`Failed to load dependency ${Q}`,"error")}},[a,h]),zi=i.useCallback(async Q=>{Re(!0);try{await ci(S.id,{prompt:Q},n),h("Spec updated","success"),j&&(j.prompt=Q)}catch(We){throw h(Me(We),"error"),We}finally{Re(!1)}},[S,j,h]),Js=i.useCallback(async Q=>{ke(!0);try{await Mw(e.id,Q,n),h("AI revision requested. Task moved to planning.","success"),Dt()}catch(We){const xt=Me(We);xt.includes("done")||xt.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(xt,"error")}finally{ke(!1)}},[e.id,h,Dt]),ai=i.useCallback(()=>{Ge(!0),Ae(S.prompt||""),ie("")},[S.prompt]),Ys=i.useCallback(()=>{Ge(!1),Ae(S.prompt||""),ie("")},[S.prompt]),ct=i.useCallback(async()=>{if(qe===(S.prompt||"")){Ys();return}Ge(!1);try{await zi(qe)}catch(Q){throw Ge(!0),Q}},[qe,S.prompt,zi,Ys]),en=i.useCallback(async()=>{Ee.trim()&&await Js(Ee.trim())},[Ee,Js]),Qs=i.useCallback(Q=>{Q.key==="Escape"?(Q.preventDefault(),Ys()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),ct())},[Ys,ct]),nr=s.filter(Q=>Q.id!==e.id&&!$.includes(Q.id)).sort((Q,We)=>{const xt=We.createdAt.localeCompare(Q.createdAt);if(xt!==0)return xt;const Gt=parseInt(Q.id.slice(Q.id.lastIndexOf("-")+1),10)||0;return(parseInt(We.id.slice(We.id.lastIndexOf("-")+1),10)||0)-Gt}),sr=D?.name??e.assignedAgentId??null,ir=i.useMemo(()=>{const Q=[];return S.modelProvider&&Q.push(S.modelProvider),S.validatorModelProvider&&!Q.includes(S.validatorModelProvider)&&Q.push(S.validatorModelProvider),S.planningModelProvider&&!Q.includes(S.planningModelProvider)&&Q.push(S.planningModelProvider),Q},[S.modelProvider,S.validatorModelProvider,S.planningModelProvider]),ql=xd[e.column]||[],co=["todo","in-progress"],uo=e.column==="in-review"?co:ql,ps=uo[0],gi=uo.slice(1),Is=gi.length>0,ar=i.useCallback(()=>{Bt(!1),pn.current?.focus()},[]),Ji=i.useCallback(Q=>{if(!Is){ps&&un(ps);return}const We=Q.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Q.target instanceof Element&&Q.target.closest(".detail-move-btn__arrow")||We&&Q.clientX>0&&Q.clientX>=We.getBoundingClientRect().left)){Bt(Gt=>!Gt),Dn(!1);return}ps&&un(ps)},[Is,ps,un]),mo=i.useCallback(Q=>{!Is||!(Q.key==="ArrowDown"||Q.altKey&&Q.key==="ArrowDown")||(Q.preventDefault(),Bt(!0),Dn(!1))},[Is]),xa=i.useCallback(Q=>{Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),ar())},[ar]);i.useEffect(()=>{if(!Tt)return;yn.current?.querySelector(".detail-move-menu-item")?.focus()},[Tt]);const Vl={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},va=e.status?Vl[e.status]:void 0;return t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:_n,onDrop:cs,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:ss[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!ze&&Wt&&t.jsx("button",{className:"modal-edit-btn",onClick:Mt,title:"Edit task","aria-label":"Edit task",children:t.jsx(js,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:Dt,"aria-label":"Back to task list",type:"button",children:[t.jsx(ha,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:Dt,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&R==="agent-log"&&!ze?" detail-body--agent-log":""}`,children:[ze?t.jsx("div",{className:"modal-edit-form",children:t.jsx(tb,{mode:"edit",title:pt,onTitleChange:ve,description:le,onDescriptionChange:Te,dependencies:pe,onDependenciesChange:$e,executorModel:st,onExecutorModelChange:at,validatorModel:rt,onValidatorModelChange:Oe,planningModel:Be,onPlanningModelChange:et,thinkingLevel:jt,onThinkingLevelChange:De,presetMode:vt,onPresetModeChange:Et,selectedPresetId:cn,onSelectedPresetIdChange:Jt,selectedWorkflowSteps:Vt,onWorkflowStepsChange:Kt,pendingImages:Se,onImagesChange:X,tasks:s.filter(Q=>Q.id!==e.id),projectId:n,disabled:Ie,addToast:h,isActive:ze,onAutoSaveDescription:ts,reviewLevel:bt,onReviewLevelChange:zt,priority:qt,onPriorityChange:It,nodeId:_t,onNodeIdChange:Xt,nodeOptions:rs,nodeOverrideDisabled:Ln,nodeOverrideDisabledReason:Ln?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Lt,onExecutionModeChange:Ut,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:rn,onChange:Q=>fn(Q.target.value),disabled:Ie,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:on,onChange:Q=>gn(Q.target.value),disabled:Ie,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:je,onChange:Q=>Le(Q.target.value),disabled:Ie,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:re,onChange:Q=>Pe(Q.target.value),disabled:Ie,"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,We=!F&&Q.length>$c;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:We?Q.slice(0,$c)+"…":Q}),Q.length>$c&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>q(!F),children:F?"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("label",{className:`card-priority-badge card-priority-badge--${Ne} detail-priority-chip ${kt?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:Ne,onChange:Q=>{Ps(Q.target.value)},disabled:kt,"aria-label":"Task priority",children:Xa.map(Q=>t.jsx("option",{value:Q,children:Q},Q))})]}),B&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Ks,{"aria-hidden":"true"}),t.jsxs("span",{children:[S.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",B.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>O(B.sourceAgentId),children:B.label}):B.label]}):t.jsxs(t.Fragment,{children:["Created via ",B.label]}),B.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ts(B.parentTaskId),children:B.parentTaskId})]}),B.contextInfo?` (${B.contextInfo})`:""]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!ze&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),Qt.map(({entry:Q,tabId:We})=>t.jsx("button",{className:`detail-tab${b===We?" detail-tab-active":""}`,onClick:()=>y(We),children:Q.slot.label},`plugin-tab-${Q.pluginId}-${We}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(bP,{taskId:e.id,results:wt,loading:ot,enabledWorkflowSteps:Ft,canEdit:Wt,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Vn})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(XA,{task:e,addToast:h,onTaskUpdated:m,settings:ue})}):b==="logs"?t.jsxs("div",{className:`detail-section${R==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${R==="activity"?" log-subview-btn-active":""}`,onClick:()=>P("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${R==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>P("agent-log"),children:"Agent Log"})]}),R==="agent-log"?t.jsx(KA,{entries:Ve,loading:Ye,executorModel:_P(e,ue),validatorModel:AP(e,ue),planningModel:RP(e,Ve,ue),hasMore:Ct,onLoadMore:mt,loadingMore:dn,totalCount:Rt}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),S.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",S.log.length," activity entries."]}):null,S.log&&S.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...S.log].reverse().map((Q,We)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:IP(Q.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Q.action})]}),Q.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Q.outcome})]},We))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(lP,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(sP,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(SP,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:Wt}):Cn?t.jsx("div",{className:"detail-section",children:t.jsx(Hi,{slotId:"task-detail-tab",projectId:n,pluginIds:[Cn.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(EP,{tokenUsage:S.tokenUsage,loading:A,task:S})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(wP,{task:e,settings:ue,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(ji,{remarkPlugins:[Ni],children:e.summary})})]}),t.jsx(aP,{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.provider.toLowerCase()==="github"&&t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub source issue",children:[t.jsx(Ks,{"aria-hidden":"true"}),t.jsx("span",{children:"GitHub"})]}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-link--summary 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":hn,"aria-label":hn?"Collapse source issue details":"Expand source issue details",onClick:()=>Ht(Q=>!Q),children:t.jsx(In,{size:16,className:hn?"detail-source-chevron--expanded":void 0})})]}),hn&&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:[ir.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:ir.map(Q=>t.jsx(Qn,{provider:Q,size:"sm"},Q))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Tn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[sr?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Tn,{size:14}),sr,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void hs(),title:"Unassign agent",children:t.jsx(tn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{oe?Y(!1):ms()},children:"Assign Agent"}),oe&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ae&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ae&&z.filter(Q=>Q.state!=="terminated").map(Q=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Q.id?" selected":""}`,onClick:()=>void Kn(Q.id),children:[t.jsx(Tn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Q.name}),t.jsx("span",{className:"agent-picker-role",children:Q.role})]},Q.id)),!ae&&z.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"}),S.steps&&S.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:S.steps.map((Q,We)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Q.status}`,"data-tooltip":`${Q.name} (${Q.status})`,style:{backgroundColor:TP(Q.status)}},We))}),t.jsxs("span",{className:"step-progress-label",children:[S.steps.filter(Q=>Q.status==="done").length,"/",S.steps.length," step",S.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Ue&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:ai,children:"Edit"})}),Ue?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:qe,onChange:Q=>Ae(Q.target.value),onKeyDown:Qs,disabled:te,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:Ys,disabled:te,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ct(),disabled:qe===(S.prompt||"")||te,children:te?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:Ee,onChange:Q=>ie(Q.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:be,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[Ee.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void en(),disabled:!Ee.trim()||be,children:be?"Requesting…":"Request AI Revision"})]})]})]}):A?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):S.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],children:S.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"}),ee.length>0?t.jsx("div",{className:"detail-attachments-grid",children:ee.map(Q=>{const We=ki(`/api/tasks/${e.id}/attachments/${Q.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:We,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:We,alt:Q.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Q.originalName," (",$P(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:Bn,type:"file",accept:"image/*",onChange:On}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Bn.current?.click(),disabled:k,children:k?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Q=>{const We=s.find(Gt=>Gt.id===Q),xt=We?.title||We?.description||Q;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ts(Q),onKeyDown:Gt=>{(Gt.key==="Enter"||Gt.key===" ")&&(Gt.preventDefault(),Ts(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:Ah(xt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Gt=>Rs(Gt,Q),title:`Remove dependency ${Q}`,children:"×"})]},Q)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{H&&de(""),J(Q=>!Q)},children:"Add Dependency"}),H&&(()=>{const Q=fe.toLowerCase(),We=Q?nr.filter(xt=>xt.id.toLowerCase().includes(Q)||xt.title&&xt.title.toLowerCase().includes(Q)||xt.description&&xt.description.toLowerCase().includes(Q)):nr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:fe,onChange:xt=>de(xt.target.value),onClick:xt=>xt.stopPropagation()}),We.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):We.map(xt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Gn(xt.id),J(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:xt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ah(xt.title||xt.description||xt.id,30)})]},xt.id))]})})()]})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(eP,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:ue?.autoMerge??!1,prAuthAvailable:f??!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:ze?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:En,disabled:Ie,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Xn,disabled:Ie,children:Ie?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&S.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:it,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:St,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!_&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:Zn,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||_||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:es,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{Dn(Q=>!Q),Bt(!1)},"aria-haspopup":"menu","aria-expanded":jn,children:["Actions",t.jsx(mn,{size:12})]}),jn&&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:()=>sn(Zn),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(G),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(Mn),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(Nt),children:"Respecify"}),_&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(He),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>sn(lt),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>sn(we),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:yn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:Ji,onKeyDown:mo,disabled:!ps,"aria-label":ps?`Move to ${ss[ps]}`:void 0,"aria-haspopup":Is?"menu":void 0,"aria-expanded":Is?Tt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ps?ss[ps]:""]}),Is&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(mn,{size:12})})]}),Tt&&Is&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:xa,children:gi.map(Q=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>un(Q),onKeyDown:xa,children:Q==="in-progress"?"Back to In Progress":`Move to ${ss[Q]}`},Q))})]}),va?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:va}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Hn,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:Ji,onKeyDown:mo,disabled:!ps,"aria-label":ps?`Move to ${ss[ps]}`:void 0,"aria-haspopup":Is?"menu":void 0,"aria-expanded":Is?Tt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",ps?ss[ps]:""]}),Is&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(mn,{size:12})})]}),Tt&&Is&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:xa,children:gi.map(Q=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>un(Q),onKeyDown:xa,children:["Move to ",ss[Q]]},Q))})]})})]})}),se&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:qn,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:qn,"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:ne,onChange:Q=>Fe(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:[ne.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ls,disabled:!ne.trim()||Qe,children:Qe?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:qn,disabled:Qe,children:"Cancel"})})]})}),E&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(FP,{agentId:E,projectId:n,onClose:()=>O(null),addToast:h})})]})}function HP({onClose:e,...n}){const s=i.useRef(null);Si(s,!0,"task-detail-modal-size"),Ci(!0);const a=Li(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(nb,{...n,onRequestClose:e})})})}const Do={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Rh=new Set(["planning","researching","executing","finalizing","merging"]),sb=["title","status","column","dependencies","progress"],qP=["title","status","column"];function VP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function WP(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Th(e){try{const n=as("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>sb.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(qP)}function Ih(e){try{const n=as("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function $h(e){try{const n=as("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>aa.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function Dh(e){try{const n=as("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function Lh(e){try{const n=as("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function Oh(e){try{const s=as("kb-dashboard-list-sidebar-width",e);if(!s)return 400;const a=Number(s);if(Number.isFinite(a)&&a>0)return a}catch{}return 400}const gl=280,Id=.65,Lo=16;function $d(e){return Math.max(gl,e*Id)}function Oo(e,n){const s=$d(n);return Math.min(Math.max(e,gl),s)}function KP(e){return e.status==="executing"||e.column==="in-progress"}function zh(e){const n=Df(e);return n.total===0||!KP(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function GP({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:x,onToggleModelFavorite:v,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:j,projectId:C,projectName:A,taskStuckTimeoutMs:N,searchQuery:S="",lastFetchTimeMs:_,prAuthAvailable:T}){const[M,E]=i.useState("id"),[O,B]=i.useState("desc"),[R,P]=i.useState(null),[F,q]=i.useState(null),[ee,U]=i.useState(null),I=Di()==="mobile",{confirm:$}=Gs(),[w,H]=i.useState(()=>Th(C)),[J,fe]=i.useState(()=>Ih(C)),[de,D]=i.useState(()=>$h(C));i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-list-columns",JSON.stringify([...w]),C)},[C,w]),i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-hide-done",J.toString(),C)},[J,C]),i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-list-collapsed",JSON.stringify([...de]),C)},[de,C]);const[_e,z]=i.useState(!1),[Z,oe]=i.useState(!1),[Y,ae]=i.useState(()=>Dh(C)),[ce,te]=i.useState(()=>Lh(C)),[Re,be]=i.useState(null),[ke,Ue]=i.useState(()=>Oh(C)),Ge=i.useRef(null),qe=i.useRef(null);i.useEffect(()=>{H(Th(C)),fe(Ih(C)),D($h(C)),ae(Dh(C));const je=Lh(C);te(je),be(je?e.find(Le=>Le.id===je)??null:null),Ue(Oh(C))},[C,e]),i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-selected-tasks",JSON.stringify([...Y]),C)},[C,Y]),i.useEffect(()=>{if(!(typeof window>"u")){if(ce){xs("kb-dashboard-list-selected-task",ce,C);return}Ua("kb-dashboard-list-selected-task",C)}},[C,ce]),i.useEffect(()=>{if(!ce){be(null);return}const je=e.find(Le=>Le.id===ce);je&&be(Le=>!Le||Le.id!==ce?je:{...Le,...je})},[ce,e]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const je=Ge.current;if(!je)return;const Le=()=>{const Pe=Oo(ke,je.clientWidth);Pe!==ke&&Ue(Pe)};Le();const re=new ResizeObserver(Le);return re.observe(je),()=>re.disconnect()},[I,ke]),i.useEffect(()=>{if(I||typeof ResizeObserver>"u")return;const je=qe.current,Le=Ge.current;if(!je||!Le)return;let re=null,Pe=je.offsetWidth;const Se=new ResizeObserver(()=>{const X=Oo(je.offsetWidth,Le.clientWidth);X!==Pe&&(Pe=X,re&&clearTimeout(re),re=setTimeout(()=>{try{xs("kb-dashboard-list-sidebar-width",String(X),C)}catch{}},200))});return Se.observe(je),()=>{Se.disconnect(),re&&clearTimeout(re)}},[I,C]);const Ae=i.useCallback(()=>{oe(je=>(je&&ae(new Set),!je))},[]),Ee=i.useCallback(je=>{ae(Le=>{const re=new Set(Le);return re.has(je)?re.delete(je):re.add(je),re})},[]),ie=i.useCallback(()=>{ae(new Set)},[]),se=i.useCallback(je=>{H(Le=>{const re=new Set(Le);return re.has(je)?re.size>1&&re.delete(je):re.add(je),re})},[]),xe={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},ne=i.useCallback(je=>{M===je?B(Le=>Le==="asc"?"desc":"asc"):(E(je),B("asc"))},[M]),Fe=i.useCallback(je=>{U(Le=>Le===je?null:je)},[]),Qe=i.useCallback(je=>{D(Le=>{const re=new Set(Le);return re.has(je)?re.delete(je):re.add(je),re})},[]),ge=i.useCallback(()=>{U(null)},[]),ze=i.useMemo(()=>{let je=S?e.filter(Se=>Se.id.toLowerCase().includes(S.toLowerCase())||Se.title&&Se.title.toLowerCase().includes(S.toLowerCase())||Se.description.toLowerCase().includes(S.toLowerCase())):[...e];J&&!ee&&(je=je.filter(Se=>Se.column!=="done"&&Se.column!=="archived"));const re=[...ee?je.filter(Se=>Se.column===ee):je].sort((Se,X)=>{let Ie=0;switch(M){case"id":Ie=Se.id.localeCompare(X.id);break;case"title":Ie=(Se.title||Se.description).localeCompare(X.title||X.description);break;case"status":Ie=(Se.status||"").localeCompare(X.status||"");break;case"column":Ie=Se.column.localeCompare(X.column);break}return O==="asc"?Ie:-Ie}),Pe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return re.forEach(Se=>Pe[Se.column].push(Se)),Pe},[e,S,M,O,J,ee]),tt=i.useMemo(()=>Object.values(ze).reduce((je,Le)=>je+Le.length,0),[ze]),pt=i.useMemo(()=>e.filter(je=>je.column==="done"||je.column==="archived").length,[e]),ve=i.useMemo(()=>J?pt:0,[J,pt]),le=i.useCallback(()=>{const je=Object.values(ze).flat().filter(Le=>Le.column!=="archived").map(Le=>Le.id);ae(Le=>{if(je.every(Pe=>Le.has(Pe))){const Pe=new Set(Le);return je.forEach(Se=>Pe.delete(Se)),Pe}else return new Set([...Le,...je])})},[ze]),Te=i.useMemo(()=>{const je=Object.values(ze).flat().filter(Le=>Le.column!=="archived");return je.length===0?!1:je.every(Le=>Y.has(Le.id))},[ze,Y]),pe=i.useMemo(()=>{const je=Object.values(ze).flat().filter(re=>re.column!=="archived");if(je.length===0)return!1;const Le=je.filter(re=>Y.has(re.id)).length;return Le>0&&Le<je.length},[ze,Y]),[$e,st]=i.useState("__no_change__"),[at,rt]=i.useState("__no_change__"),[Oe,Be]=i.useState("__no_change__"),[et,jt]=i.useState([]),[De,vt]=i.useState(!1),Et=i.useMemo(()=>Oe&&Oe!=="__no_change__"?et.find(je=>je.id===Oe):void 0,[et,Oe]),[bt,zt]=i.useState(!1);i.useEffect(()=>{if(Y.size===0)return;let je=!1;return(async()=>{vt(!0);try{const re=await ll();je||jt(re)}catch(re){console.error("Failed to fetch nodes for bulk edit",re),je||jt([])}finally{je||vt(!1)}})(),()=>{je=!0}},[Y.size]);const qt=i.useCallback(async()=>{if(Y.size===0)return;const je=Array.from(Y).filter(re=>{const Pe=e.find(Se=>Se.id===re);return Pe&&Pe.column!=="archived"});if(je.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Le={taskIds:je};if($e!=="__no_change__")if($e==="")Le.modelProvider=null,Le.modelId=null;else{const re=$e.indexOf("/");re!==-1&&(Le.modelProvider=$e.slice(0,re),Le.modelId=$e.slice(re+1))}if(at!=="__no_change__")if(at==="")Le.validatorModelProvider=null,Le.validatorModelId=null;else{const re=at.indexOf("/");re!==-1&&(Le.validatorModelProvider=at.slice(0,re),Le.validatorModelId=at.slice(re+1))}if(Oe!=="__no_change__"&&(Oe===""?Le.nodeId=null:Le.nodeId=Oe),Object.keys(Le).length===1){d("No changes to apply","info");return}zt(!0);try{const re=await rw(Le.taskIds,Le.modelProvider,Le.modelId,Le.validatorModelProvider,Le.validatorModelId,void 0,void 0,Le.nodeId,C);j&&j(re.updated),d(`Updated ${je.length} task${je.length===1?"":"s"}`,"success"),ie(),st("__no_change__"),rt("__no_change__"),Be("__no_change__")}catch(re){d(Me(re)||"Failed to update models","error")}finally{zt(!1)}},[Y,e,$e,at,Oe,C,d,ie,j]),It=i.useCallback(je=>{if(I){c(je,{origin:"list-mobile"});return}te(je.id),be(je)},[I,c]),_t=i.useRef(null),Xt=i.useRef(null);i.useEffect(()=>()=>{_t.current&&clearTimeout(_t.current)},[]);const Lt=i.useCallback(je=>{if(te(je.id),be(je),"prompt"in je){Xt.current=null,_t.current&&(clearTimeout(_t.current),_t.current=null);return}Xt.current=je.id,_t.current&&clearTimeout(_t.current),_t.current=setTimeout(()=>{_t.current=null,Xt.current===je.id&&Oa(je.id,C).then(re=>{Xt.current===re.id&&be(Pe=>!Pe||Pe.id!==re.id?Pe:{...Pe,...re})}).catch(()=>{})},200)},[C]),Ut=i.useCallback((je,Le)=>{if(Le.paused){je.preventDefault();return}je.dataTransfer.setData("text/plain",Le.id),je.dataTransfer.effectAllowed="move",P(Le.id)},[]),cn=i.useCallback(()=>{P(null),q(null)},[]),Jt=i.useCallback(je=>{if(I)return;je.preventDefault();const Le=Ge.current;if(!Le)return;const re=Le.getBoundingClientRect(),Pe=X=>{const Ie=X.clientX-re.left;Ue(Oo(Ie,re.width))},Se=()=>{window.removeEventListener("mousemove",Pe),window.removeEventListener("mouseup",Se)};window.addEventListener("mousemove",Pe),window.addEventListener("mouseup",Se)},[I]),Vt=i.useCallback(je=>{if(I)return;const Le=Ge.current?.clientWidth??0,re=ke/Id+Lo,Pe=Math.max(Le,re),Se=$d(Pe);if(je.key==="ArrowLeft"||je.key==="ArrowRight"){je.preventDefault();const X=je.key==="ArrowLeft"?-Lo:Lo;Ue(Ie=>Oo(Ie+X,Pe));return}if(je.key==="Home"){je.preventDefault(),Ue(gl);return}je.key==="End"&&(je.preventDefault(),Ue(Se))},[I,ke]),Kt=i.useCallback((je,Le)=>{je.preventDefault(),je.dataTransfer.dropEffect="move",q(Le)},[]),rn=i.useCallback(()=>{q(null)},[]),fn=i.useCallback(async(je,Le)=>{je.preventDefault(),q(null);const re=je.dataTransfer.getData("text/plain");if(re){if(Le==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Se=e.find(he=>he.id===re)?.steps.some(he=>he.status!=="pending")??!1,X=(Le==="todo"||Le==="triage")&&Se;let Ie;if(X){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ie={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(re,Le,Ie)}catch(Pe){d(Me(Pe),"error")}}},[n,d,e,$]),on=je=>M!==je?t.jsx(Zp,{size:14,className:"sort-icon"}):O==="asc"?t.jsx(ia,{size:14,className:"sort-icon active"}):t.jsx(Yr,{size:14,className:"sort-icon active"}),gn=je=>t.jsxs("div",{id:je,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:sb.map(Le=>{const re=w.has(Le),Pe=re&&w.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Pe?" disabled":""}`,title:Pe?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:re,onChange:()=>se(Le),disabled:Pe}),t.jsx("span",{children:xe[Le]})]},Le)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>fe(Le=>!Le),"aria-pressed":J,title:J?"Show done tasks":"Hide done tasks",children:[J?t.jsx(Ja,{size:14}):t.jsx(qd,{size:14}),J?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:aa.map(Le=>{const re=e.filter(Ie=>Ie.column===Le).length,Pe=Le==="done"||Le==="archived",Se=J&&Pe?0:re,X=J&&Pe&&re>0;return t.jsxs("div",{className:`list-drop-zone${F===Le?" drag-over":""}${ee===Le?" active":""}`,onClick:()=>Fe(Le),onDragOver:Ie=>Kt(Ie,Le),onDragLeave:rn,onDrop:Ie=>fn(Ie,Le),"data-column":Le,children:[t.jsx("span",{className:`list-section-dot dot-${Le}`}),t.jsx("span",{className:"drop-zone-label",children:ss[Le]}),t.jsx("span",{className:"drop-zone-count",children:X?`${Se} of ${re}`:re})]},Le)})})]});return t.jsxs("div",{className:"list-view",children:[I&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Ae,"aria-pressed":Z,children:Z?"Done Editing":"Bulk Edit"}),m?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}):null,t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>z(je=>!je),"aria-expanded":_e,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Nu,{size:14}),"View options"]}),t.jsx("div",{className:"list-stats",children:ee?`${tt} of ${e.length} tasks in ${ss[ee]}`:`${tt} of ${e.length} tasks`})]}),_e?t.jsx("div",{className:"list-toolbar-mobile-options",children:gn("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:I?"":"list-split-layout","data-testid":I?void 0:"list-split-layout",ref:Ge,children:[t.jsxs("div",{className:I?"":"list-split-sidebar","data-testid":I?void 0:"list-split-sidebar",ref:qe,style:I?void 0:{width:`${ke}px`},children:[!I&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[ee?`${tt} of ${e.length} tasks in ${ss[ee]}`:`${tt} of ${e.length} tasks`,ve>0&&!ee&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ve," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[m?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}):null,t.jsx("button",{className:"btn btn-sm",onClick:Ae,"aria-pressed":Z,children:Z?"Done Editing":"Bulk Edit"})]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[ee?t.jsx("button",{className:"btn btn-sm",onClick:ge,"aria-label":"Clear column filter",children:`Filter: ${ss[ee]}`}):null,J?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,Z?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,Z&&Y.size>0?t.jsx("button",{className:"btn btn-sm",onClick:ie,children:`${Y.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>z(je=>!je),"aria-expanded":_e,"aria-controls":"list-view-options-panel",children:[t.jsx(Nu,{size:14}),"View options"]}),_e&&gn("list-view-options-panel"),Z&&Y.size>0&&f&&f.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(ys,{models:f,value:$e,onChange:st,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(ys,{models:f,value:at,onChange:rt,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:Oe,onChange:je=>Be(je.target.value),"aria-label":"Node Override",disabled:De,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),et.map(je=>t.jsx("option",{value:je.id,children:`${WP(je.status)} ${je.name||je.id} (${VP(je.status)})`},je.id))]}),Et?t.jsx(ca,{status:Et.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:qt,disabled:bt||$e==="__no_change__"&&at==="__no_change__"&&Oe==="__no_change__",children:bt?"Applying...":"Apply"})]})]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Ff,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:C,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:v})}),tt===0?t.jsx("div",{className:"list-empty",children:S?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:aa.map(je=>{if(ee&&je!==ee||J&&(je==="done"||je==="archived")&&!ee)return null;const Le=ze[je],re=Le.length===0;if(S&&re)return null;const Pe=de.has(je);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>Qe(je),"aria-expanded":!Pe,role:"button",tabIndex:0,onKeyDown:Se=>{(Se.key==="Enter"||Se.key===" ")&&(Se.preventDefault(),Qe(je))},children:[t.jsx(In,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${je}`}),t.jsx("span",{className:"list-section-title",children:ss[je]}),t.jsx("span",{className:"list-section-count",children:Le.length})]}),!Pe&&t.jsx(t.Fragment,{children:re?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Le.map(Se=>{const X=Se.status==="failed",Ie=Se.paused===!0,he=ul(Se,N,_),Ne=!u&&!X&&!Ie&&!he&&(Se.column==="in-progress"||Rh.has(Se.status)),Je=typeof Se.status=="string"&&Se.status.trim().length>0,kt=!!(Se.dependencies&&Se.dependencies.length>0),Yt=zh(Se),$t=Yt.hasProgress,Tt=Z;return t.jsxs("div",{className:`list-card${Ne?" agent-active":""}${Tt?" list-card--selectable":""}`,onClick:()=>It(Se),"data-id":Se.id,children:[Tt&&t.jsx("label",{className:"list-card-checkbox",onClick:Bt=>Bt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:Y.has(Se.id),onChange:Bt=>{Bt.stopPropagation(),Ee(Se.id)},onClick:Bt=>Bt.stopPropagation(),disabled:Se.column==="archived","aria-label":`Select ${Se.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Se.id}),Se.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(is,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),he?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Je?t.jsx("span",{className:`list-status-badge list-status-badge--${Se.column}${X?" failed":""}${Ne?" pulsing":""}`,children:Se.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Se.title||Se.description})}),(kt||$t)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[kt&&t.jsxs("span",{className:"list-dep-badge",title:Se.dependencies.join(", "),children:[t.jsx($a,{size:12})," ",Se.dependencies.length]}),$t&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Yt.percent}%`,backgroundColor:Do[Se.column]}})}),t.jsx("span",{className:"list-progress-label",children:Yt.label})]})]})]},Se.id)})})]},je)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[Z&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Te,ref:je=>{je&&(je.indeterminate=pe)},onChange:le,"aria-label":"Select all visible tasks"})}),w.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("title"),children:["Title ",on("title")]}),w.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("status"),children:["Status ",on("status")]}),w.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>ne("column"),children:["Column ",on("column")]}),w.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),w.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:aa.map(je=>{if(ee&&je!==ee||J&&(je==="done"||je==="archived")&&!ee)return null;const Le=ze[je],re=Le.length===0;if(S&&re)return null;const Pe=de.has(je);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>Qe(je),"aria-expanded":!Pe,children:t.jsxs("th",{colSpan:w.size+(Z?1:0),className:"list-section-cell",children:[t.jsx(In,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${je}`}),t.jsx("span",{className:"list-section-title",children:ss[je]}),t.jsx("span",{className:"list-section-count",children:Le.length})]})}),!Pe&&t.jsx(t.Fragment,{children:re?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:w.size+(Z?1:0),className:"list-empty-cell",children:"No tasks"})}):Le.map(Se=>{const X=Se.status==="failed",Ie=Se.paused===!0,he=ul(Se,N,_),Ne=!u&&!X&&!Ie&&!he&&(Se.column==="in-progress"||Rh.has(Se.status)),Je=R===Se.id;return t.jsxs("tr",{className:`list-row${X?" failed":""}${Ie?" paused":""}${he?" stuck":""}${Ne?" agent-active":""}${Je?" dragging":""}${ce===Se.id?" list-row--selected":""}`,onClick:()=>It(Se),draggable:!Ie,onDragStart:kt=>Ut(kt,Se),onDragEnd:cn,"data-id":Se.id,children:[Z&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:Y.has(Se.id),onChange:kt=>{kt.stopPropagation(),Ee(Se.id)},onClick:kt=>kt.stopPropagation(),disabled:Se.column==="archived","aria-label":`Select ${Se.id}`})}),w.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:Se.id}),t.jsxs("div",{className:"list-title-row",children:[Se.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(is,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Se.title||Se.description})]})]})}),w.has("status")&&t.jsx("td",{className:"list-cell",children:he?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Se.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Se.column}${X?" failed":""}${Ne?" pulsing":""}`,children:Se.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),w.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Do[Se.column]}20`,color:Do[Se.column]},children:ss[Se.column]})}),w.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Se.dependencies&&Se.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Se.dependencies.join(", "),children:[t.jsx($a,{size:12})," ",Se.dependencies.length]}):"-"}),w.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const kt=zh(Se);return kt.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:`${kt.percent}%`,backgroundColor:Do[Se.column]}})}),t.jsx("span",{className:"list-progress-label",children:kt.label})]}):"-"})()})]},Se.id)})})]},je)})})]})]}),!I&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Jt,onKeyDown:Vt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":gl,"aria-valuemax":Math.round($d(Ge.current?.clientWidth??ke/Id+Lo)),"aria-valuenow":Math.round(ke)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:Re?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(nb,{task:Re,projectId:C,tasks:e,embedded:!0,onOpenDetail:Lt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:je=>{be(Le=>!Le||Le.id!==je.id?Le:{...Le,...je})},addToast:d,prAuthAvailable:T})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const JP={active:{label:"Active",color:"var(--success)",icon:Yn},paused:{label:"Paused",color:"var(--warning)",icon:ui},errored:{label:"Error",color:"var(--color-error)",icon:zs},initializing:{label:"Initializing",color:"var(--info)",icon:ft}};function YP(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function QP(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),a=e.slice(-Math.floor(n/2)+2);return`${s}...${a}`}function XP(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,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.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 ZP({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:d=!1}){const[u,m]=i.useState(!1),h=JP[e.status],f=h.icon,p=i.useCallback(()=>{s(e)},[s,e]),g=i.useCallback(C=>{C.stopPropagation(),a(e)},[a,e]),x=i.useCallback(C=>{C.stopPropagation(),r(e)},[r,e]),v=i.useCallback(C=>{if(C.stopPropagation(),!u){m(!0);return}o(e),m(!1)},[u,o,e]),b=e.status==="paused",y=e.status==="errored",j=e.status==="initializing";return t.jsxs("div",{className:`project-card ${d?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(fs,{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:QP(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:j?"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:YP(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:d,title:"Resume project","aria-label":"Resume project",children:[t.jsx(Yn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:d||j,title:j?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:d,title:"Open project","aria-label":"Open project",children:[t.jsx(Qr,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${u?"is-armed":""}`,onClick:v,disabled:d,title:u?"Confirm remove":"Remove project","aria-label":u?"Confirm remove project":"Remove project",children:[t.jsx(Sn,{size:14}),t.jsx("span",{children:u?"Confirm":""})]})]})]})]})}const eR=i.memo(ZP,XP);function tR(){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(fs,{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(qs,{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(Un,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(zs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__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 nR=1e4,Fh=5;function sR(e){const[n,s]=i.useState({}),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(null),d=i.useRef(null),u=i.useRef(!1),m=i.useCallback(async()=>{if(e.length===0){s({}),u.current||(u.current=!0),r(!1);return}d.current&&d.current.abort(),d.current=new AbortController,!u.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=Fh){const x=e.slice(g,g+Fh),v=await Promise.allSettled(x.map(async b=>{try{return await Gu(b)}catch{return null}}));if(x.forEach((b,y)=>{const j=v[y];p[b]=j.status==="fulfilled"?j.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await Gu(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,m(),()=>{d.current&&d.current.abort()}),[m]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},nR),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function iR({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[m,h]=i.useState(null),[f,p]=i.useState("activity"),[g,x]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const B=localStorage.getItem("kb-dashboard-recent-projects");if(B)try{const R=JSON.parse(B);b(R)}catch{}},[]);const[v,b]=i.useState([]),y=i.useMemo(()=>e.map(B=>B.id),[e]),{healthMap:j,loading:C}=sR(y),A=i.useMemo(()=>e.map(B=>({project:B,health:j[B.id]||null})),[e,j]),N=i.useMemo(()=>{let B=[...A];return d!=="all"&&(B=B.filter(({project:R})=>R.status===d)),m!==null&&(B=B.filter(({project:R})=>R.nodeId===m)),B},[A,d,m]),S=i.useMemo(()=>{const B=[...N];return B.sort((R,P)=>{let F=0;switch(f){case"name":F=R.project.name.localeCompare(P.project.name);break;case"activity":{const q=R.project.lastActivityAt||R.health?.lastActivityAt||R.project.updatedAt,ee=P.project.lastActivityAt||P.health?.lastActivityAt||P.project.updatedAt;F=new Date(ee).getTime()-new Date(q).getTime();break}case"status":{const q={errored:0,initializing:1,paused:2,active:3};F=q[R.project.status]-q[P.project.status];break}}return g==="asc"?F:-F}),B},[N,f,g]),_=i.useMemo(()=>{const B=e.length,R=e.filter(I=>I.status==="active").length,P=e.filter(I=>I.status==="errored").length,F=new Set;e.forEach(I=>{I.nodeId&&F.add(I.nodeId)});const q=F.size||(B>0?1:0);let ee=0,U=0,k=0;return Object.values(j).forEach(I=>{I&&(ee+=I.activeTaskCount,U+=I.totalTasksCompleted,k+=I.inFlightAgentCount)}),{totalProjects:B,activeProjects:R,erroredProjects:P,totalNodes:q,totalActiveTasks:ee,totalCompletedTasks:U,totalInFlightAgents:k}},[e,j]),T=i.useMemo(()=>({all:e.length,active:e.filter(B=>B.status==="active").length,paused:e.filter(B=>B.status==="paused").length,errored:e.filter(B=>B.status==="errored").length}),[e]),M=i.useMemo(()=>{const B=new Map;return e.forEach(R=>{const P=R.nodeId,F=B.get(P);if(F)F.count++;else{const ee=c.find(U=>U.id===P)?.name??R._sourceNodeName??"Local";B.set(P,{name:ee,count:1})}}),Array.from(B.entries()).map(([R,{name:P,count:F}])=>({nodeId:R??null,name:P,count:F}))},[e,c]),E=i.useCallback(B=>{const R=[B.id,...v.filter(P=>P!==B.id)].slice(0,3);b(R),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(R)),s(B)},[s,v]);return n||C&&e.length>0&&Object.keys(j).length===0?t.jsx(tR,{}):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:a,children:[t.jsx(Nn,{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(Wi,{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(fs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.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(qs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.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(Un,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),_.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(zs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),_.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ur,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx(Nn,{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 ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:T.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:T.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:T.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${T.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:T.errored})]})]}),M.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Ur,{size:14}),t.jsxs("select",{value:m??"",onChange:B=>{h(B.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),M.map(({nodeId:B,name:R,count:P})=>t.jsxs("option",{value:B??"",children:[R," (",P,")"]},B??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(tl,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:B=>{const[R,P]=B.target.value.split("-");p(R),x(P)},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(Zp,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:S.map(({project:B,health:R})=>{const P=c.find(q=>q.id===B.nodeId),F=P?void 0:B._sourceNodeName;return t.jsx(eR,{project:B,health:R,node:P,nodeNameFallback:F,onSelect:E,onPause:r,onResume:o,onRemove:l},B.id)})}),S.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(tl,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>u("all"),children:"Show All Projects"})]})]})}const yu="kb-planning-last-description",wu="kb-subtask-last-description",ku="kb-mission-last-goal";function aR(e,n){xs(yu,e,n)}function rR(e){return as(yu,e)||""}function Ca(e){Ua(yu,e)}function oR(e,n){xs(wu,e,n)}function lR(e){return as(wu,e)||""}function Dc(e){Ua(wu,e)}function cR(e,n){xs(ku,e,n)}function dR(e){return as(ku,e)||""}function Ui(e){Ua(ku,e)}function uR(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const a=s;if(n.id in a)return a[n.id]}return s}function mR(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(a=>a.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 hR(e){let n=0;const s=[];for(const a of e){if(a.question){n+=1,s.push({...a,questionNumber:n});continue}a.thinkingOutput&&s.push({...a,questionNumber:null})}return s}function ii({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=hR(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,d=!!o.thinkingOutput,u=s[l]??n,m=c?uR(o):void 0,h=o.question&&m!==void 0?mR(o.question,m):"",f=o.response&&typeof o.response=="object"&&!Array.isArray(o.response)?o.response:void 0,p=typeof f?._comment=="string"?f._comment.trim():"";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||"—"}),p&&t.jsxs("p",{className:"conversation-comment",children:["💬 ",p]})]}),d&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{a(g=>({...g,[l]:!u}))},"aria-expanded":u,children:[t.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"}),u?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),u&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Uh="fusion-tab-id";function pR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function ba(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Uh);if(e)return e;const n=pR();return window.sessionStorage.setItem(Uh,n),n}function Bl(e){const n=i.useMemo(()=>ba(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(LN(e,n)).then(m=>{if(u){if(m.acquired){a(!1),o(null);return}a(!0),o(m.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const m=ON(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const m=ki(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:fi("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(zN(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const fR="fusion:ai-session-sync",Bh="fusion:ai-session-sync",gR=3e4,bR=6e4;function xi(){return Date.now()}function xR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Hh(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 vR{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=xR(),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:xi()})}broadcastUpdate(n){const s=n.timestamp??xi();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",a=n.timestamp??xi();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},a),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:a})}broadcastLock(n,s){const a=xi();this.applyTabOwnership(n,s,a),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:a})}broadcastUnlock(n,s){const a=xi();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=xi();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(fR),this.channel.onmessage=s=>{const a=Hh(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Bh||!s.newValue))try{const a=JSON.parse(s.newValue),r=Hh(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=xi();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},gR)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=xi();this.publish({type:"tab:inactive",tabId:a,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 a={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Bh,JSON.stringify(a))}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}}),a=[...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:a,heartbeats:r,timestamp:xi()});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,a=!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)),a&&this.emit()}applyTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(o&&a<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:a}),this.updateHeartbeat(s,a,!1);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:a}),r&&this.emit()}releaseTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||a<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:a}),r&&this.emit()}updateHeartbeat(n,s,a=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),a&&this.emit())}emit(){const n=xi(),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 a=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>bR;a.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:a};for(const r of this.listeners)r()}}const vi=new vR;function tr(){const e=i.useSyncExternalStore(c=>vi.subscribe(c),()=>vi.getSnapshot(),()=>vi.getSnapshot());i.useEffect(()=>{vi.requestSync()},[]);const n=i.useCallback(c=>{vi.broadcastUpdate(c)},[]),s=i.useCallback(c=>{vi.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{vi.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{vi.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{vi.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{vi.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function yR(e,n){return e&&n?`${e}/${n}`:""}function wR(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 kR=["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 jR({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Ci(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,x]=i.useState([]),[v,b]=i.useState(null),[y,j]=i.useState(!1),C=i.useRef(!1),[A,N]=i.useState(""),[S,_]=i.useState(!0),[T,M]=i.useState(!1),[E,O]=i.useState(!1),[B,R]=i.useState(!1),P=i.useRef(null),F=i.useRef(null),q=i.useRef(null),ee=i.useRef(null),[U,k]=i.useState(o??null),I=i.useMemo(()=>ba(),[]),{isLockedByOther:$,takeControl:w,isLoading:H}=Bl(e?U:null),{activeTabMap:J,broadcastUpdate:fe,broadcastCompleted:de,broadcastLock:D,broadcastUnlock:_e,broadcastHeartbeat:z}=tr(),{confirm:Z}=Gs(),[oe,Y]=i.useState(void 0),[ae,ce]=i.useState(void 0),[te,Re]=i.useState([]),[be,ke]=i.useState(!0),[Ue,Ge]=i.useState(null),[qe,Ae]=i.useState([]),[Ee,ie]=i.useState([]),se=yR(oe,ae);i.useEffect(()=>{(async()=>{try{ke(!0);const Be=await Ds();Re(Be.models),Ae(Be.favoriteProviders),ie(Be.favoriteModels)}catch(Be){Ge(Me(Be)||"Failed to load models")}finally{ke(!1)}})()},[]);const xe=i.useCallback(Oe=>{Ae(Be=>{const et=Be,De=et.includes(Oe)?et.filter(vt=>vt!==Oe):[Oe,...et];return Pn({favoriteProviders:De,favoriteModels:Ee}).catch(()=>{Ae(et)}),De})},[Ee]),ne=i.useCallback(Oe=>{ie(Be=>{const et=Be,De=et.includes(Oe)?et.filter(vt=>vt!==Oe):[Oe,...et];return Pn({favoriteProviders:qe,favoriteModels:De}).catch(()=>{ie(et)}),De})},[qe]),Fe=i.useCallback((Oe,Be)=>{if(!Oe||!Be)return"Using default";const et=te.find(jt=>jt.provider===Oe&&jt.id===Be);return et?`${et.provider}/${et.id}`:`${Oe}/${Be}`},[te]),Qe=i.useCallback(Oe=>{F.current?.close();const Be=fN(Oe,a,{onThinking:et=>{N(jt=>jt+et),fe({sessionId:Oe,status:"generating",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:et=>{M(!1),O(!1),Ui(a),u({type:"question",sessionId:Oe,question:et}),N(""),j(!0),fe({sessionId:Oe,status:"awaiting_input",needsInput:!0,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:et=>{M(!1),O(!1),Ui(a),u({type:"summary",sessionId:Oe,summary:et}),b(et),N(""),j(!0),fe({sessionId:Oe,status:"complete",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:et=>{const jt=et||"Session failed while contacting the AI.";M(!1),O(!1),h(null),u({type:"error",sessionId:Oe,errorMessage:jt}),N(""),j(!0),q.current=Oe,fe({sessionId:Oe,status:"error",needsInput:!1,owningTabId:I,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),de({sessionId:Oe,status:"error"})},onComplete:()=>{M(!1),O(!1),q.current=null,de({sessionId:Oe,status:"complete"})},onConnectionStateChange:et=>{M(et==="reconnecting")}});F.current=Be},[de,fe,l,a,I]),ge=i.useCallback(async Oe=>{const Be=Oe??l;if(Be.trim()){h(null),N(""),p([]),x([]),M(!1),u({type:"loading"});try{const{sessionId:et}=await uN(Be.trim(),a,oe&&ae?{modelProvider:oe,modelId:ae}:void 0);q.current=et,k(et),Ui(a),Qe(et),p([])}catch(et){M(!1),h(Me(et)||"Failed to start interview session"),u({type:"initial"}),q.current=null,k(null)}}},[Qe,l,oe,ae,a]);i.useEffect(()=>{e&&d.type==="initial"&&P.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&r&&!C.current&&d.type==="initial"){c(r);const Oe=setTimeout(()=>{C.current=!0,ge(r)},0);return()=>clearTimeout(Oe)}else if(e&&!r&&!C.current&&d.type==="initial"){const Oe=dR(a);Oe&&c(Oe)}},[e,r,d.type,ge]),i.useEffect(()=>{e||(C.current=!1,M(!1),O(!1),k(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Oe=!1;return wi(o).then(Be=>{if(Oe||!Be)return;const et=Fa(Be.conversationHistory);if(x(et),k(Be.id),p(et.map(jt=>jt.response).filter(jt=>!!(jt&&typeof jt=="object"&&!Array.isArray(jt)))),Be.status==="awaiting_input"&&Be.currentQuestion)try{Ui(a);const jt=JSON.parse(Be.currentQuestion);q.current=Be.id,j(!0),u({type:"question",sessionId:Be.id,question:jt})}catch{h("Failed to restore session question.")}else if(Be.status==="complete"&&Be.result)try{Ui(a);const jt=JSON.parse(Be.result);q.current=Be.id,j(!0),b(jt),u({type:"summary",sessionId:Be.id,summary:jt})}catch{h("Failed to restore session result.")}else Be.status==="generating"?(q.current=Be.id,j(!0),Be.thinkingOutput&&N(Be.thinkingOutput),u({type:"loading"}),Qe(Be.id)):Be.status==="error"&&(q.current=Be.id,j(!0),h(null),u({type:"error",sessionId:Be.id,errorMessage:Be.error??"The session encountered an error."}))}).catch(()=>{Oe||h("Failed to resume session.")}),()=>{Oe=!0}},[Qe,e,o,d.type,a]),i.useEffect(()=>{if(!e){ee.current&&(_e(ee.current,I),ee.current=null);return}if(U&&ee.current!==U){ee.current&&_e(ee.current,I),D(U,I),ee.current=U;return}!U&&ee.current&&(_e(ee.current,I),ee.current=null)},[D,_e,e,U,I]),i.useEffect(()=>{if(!e||!U||ee.current!==U)return;z(I);const Oe=setInterval(()=>{z(I)},3e4);return()=>{clearInterval(Oe)}},[z,e,U,I]),i.useEffect(()=>()=>{F.current?.close(),F.current=null,ee.current&&(_e(ee.current,I),ee.current=null)},[_e,I]),i.useEffect(()=>{if(!e)return;const Oe=Be=>{(d.type==="question"||d.type==="summary")&&(Be.preventDefault(),Be.returnValue=""),F.current?.close()};return window.addEventListener("beforeunload",Oe),()=>window.removeEventListener("beforeunload",Oe)},[e,d]);const ze=i.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),tt=i.useCallback(async()=>{if(l&&cR(l,a),!(y&&!await Z({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(F.current?.close(),F.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await kf(d.sessionId,a,I)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),N(""),M(!1),O(!1),j(!1),R(!1),Y(void 0),ce(void 0),q.current=null,k(null),n()}},[l,y,d,n,a,I,Z]);i.useEffect(()=>{if(!e)return;const Oe=Be=>{Be.key==="Escape"&&tt()};return document.addEventListener("keydown",Oe),()=>document.removeEventListener("keydown",Oe)},[e,tt]);const pt=i.useCallback(async Oe=>{if(d.type!=="question")return;const{sessionId:Be}=d;h(null),p(et=>[...et,Oe]),x(et=>[...et,{question:d.question,response:Oe}]),u({type:"loading"}),N("");try{Qe(Be),await mN(Be,Oe,a,I),j(!0)}catch(et){F.current?.close(),F.current=null,h(Me(et)||"Failed to submit response"),u({type:"question",sessionId:Be,question:d.question})}},[d,a,I,Qe]),ve=i.useCallback(async()=>{if(d.type!=="error")return;const Oe=d.sessionId;h(null),O(!0),N(""),u({type:"loading"}),Qe(Oe);try{q.current=Oe,k(Oe),await hN(Oe,a,I)}catch(Be){let et=Be;if((Me(Be)||"").includes("not in an error state"))try{const De=await wi(Oe);if(!De)throw new Error("Failed to refresh interview session.");const vt=Fa(De.conversationHistory);if(x(vt),p(vt.map(Et=>Et.response).filter(Et=>!!(Et&&typeof Et=="object"&&!Array.isArray(Et)))),q.current=De.id,k(De.id),j(!0),De.status==="generating")N(De.thinkingOutput??""),u({type:"loading"}),F.current?.isConnected()||Qe(De.id);else if(De.status==="awaiting_input"){if(!De.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Ui(a);const Et=JSON.parse(De.currentQuestion);u({type:"question",sessionId:De.id,question:Et}),F.current?.isConnected()||Qe(De.id)}else if(De.status==="complete"){if(!De.result)throw new Error("Interview session is complete but has no result.");Ui(a);const Et=JSON.parse(De.result);b(Et),u({type:"summary",sessionId:De.id,summary:Et})}else De.status==="error"&&u({type:"error",sessionId:De.id,errorMessage:De.error??"Retry failed. Please try again."});M(!1);return}catch(De){et=De}F.current?.close(),F.current=null,u({type:"error",sessionId:Oe,errorMessage:Me(et)||"Retry failed. Please try again."}),M(!1)}finally{O(!1)}},[Qe,a,I,d]),le=i.useCallback(async()=>{if(d.type==="summary"){h(null),R(!0);try{const Oe=await pN(d.sessionId,v||void 0,a);s(Oe),Ui(a),F.current?.close(),F.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),N(""),M(!1),O(!1),j(!1),R(!1),q.current=null,k(null),n()}catch(Oe){h(Me(Oe)||"Failed to create mission"),R(!1)}}},[d,v,s,n,a]),Te=()=>d.type==="question"?Math.min(f.length+1,6):6,pe=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",$e=U?J.get(U):null,st=$e&&$e.tabId!==I,at=!!(st&&!$e.stale),rt=$&&(!st||$e.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Oe=>Oe.target===Oe.currentTarget&&tt(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Es,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[pe&&t.jsx("button",{className:"modal-send-to-background",onClick:ze,title:"Send to background","aria-label":"Send to background",children:t.jsx(eo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:tt,"aria-label":"Close",children:t.jsx(tn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),T&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),at&&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.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(vs,{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:P,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:Oe=>c(Oe.target.value),onKeyDown:Oe=>{Oe.key==="Enter"&&!Oe.shiftKey&&l.trim()&&(Oe.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:kR.map((Oe,Be)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Oe),children:Oe.length>45?Oe.slice(0,45)+"...":Oe},Be))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",be&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(ys,{id:"mission-interview-modal-model",label:"Planning Model",value:se,onChange:Oe=>{const{provider:Be,modelId:et}=wR(Oe);Y(Be),ce(et)},models:te,disabled:be,favoriteProviders:qe,onToggleFavorite:xe,favoriteModels:Ee,onToggleModelFavorite:ne}),Ue&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ue," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{ke(!0);const Oe=await Ds();Re(Oe.models),Ae(Oe.favoriteProviders),ie(Oe.favoriteModels),Ge(null)}catch(Oe){Ge(Me(Oe)||"Failed to load models")}finally{ke(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${oe&&ae?"model-badge-custom":"model-badge-default"}`,children:Fe(oe,ae)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ge(),disabled:!l.trim(),children:[t.jsx(Es,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ft,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:A?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>_(!S),type:"button",children:S?"Hide thinking":"Show thinking"}),S&&A&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:A})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{entries:g}),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.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ve(),disabled:E,children:[E?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{className:"icon-ml-6",children:E?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:tt,disabled:E,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(NR,{question:d.question,progress:Te(),historyEntries:g,onSubmit:pt}),d.type==="summary"&&v&&t.jsx(SR,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:le,onStartOver:()=>{u({type:"initial"}),j(!1),b(null),p([]),x([]),k(null),F.current?.close(),F.current=null},isCreating:B}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ml,{size:16}),t.jsx("span",{children:rt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),rt&&t.jsx("button",{type:"button",onClick:()=>{w()},disabled:H,className:"btn btn-primary session-lock-take-control",children:H?"Taking control...":"Take Control"})]})})]})]})}):null}function NR({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{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(ii,{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(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),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:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.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(Un,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(tn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(Qr,{size:16,className:"icon-ml-4"})]})})]})}function SR({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((C,A)=>A))),[d,u]=i.useState(()=>{const C=new Set;return e.milestones.forEach((A,N)=>{A.slices.forEach((S,_)=>C.add(`${N}-${_}`))}),C}),m=C=>{c(A=>{const N=new Set(A);return N.has(C)?N.delete(C):N.add(C),N})},h=C=>{u(A=>{const N=new Set(A);return N.has(C)?N.delete(C):N.add(C),N})},f=(C,A)=>{const N=[...e.milestones];N[C]={...N[C],...A},s({...e,milestones:N})},p=(C,A,N)=>{const S=[...e.milestones],_=[...S[C].slices];_[A]={..._[A],...N},S[C]={...S[C],slices:_},s({...e,milestones:S})},g=(C,A,N,S)=>{const _=[...e.milestones],T=[..._[C].slices],M=[...T[A].features];M[N]={...M[N],...S},T[A]={...T[A],features:M},_[C]={..._[C],slices:T},s({...e,milestones:_})},x=C=>{const A=e.milestones.filter((N,S)=>S!==C);s({...e,milestones:A})},v=(C,A)=>{const N=[...e.milestones];N[C]={...N[C],slices:N[C].slices.filter((S,_)=>_!==A)},s({...e,milestones:N})},b=(C,A,N)=>{const S=[...e.milestones],_=[...S[C].slices];_[A]={..._[A],features:_[A].features.filter((T,M)=>M!==N)},S[C]={...S[C],slices:_},s({...e,milestones:S})},y=(C,A)=>{const N=[...e.milestones],S=[...N[C].slices];S[A]={...S[A],features:[...S[A].features,{title:"New feature",description:""}]},N[C]={...N[C],slices:S},s({...e,milestones:N})},j=e.milestones.reduce((C,A)=>C+A.slices.reduce((N,S)=>N+S.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Un,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",j," 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:C=>s({...e,missionTitle:C.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:C=>s({...e,missionDescription:C.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((C,A)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(A),children:[l.has(A)?t.jsx(mn,{size:16,className:"icon-text-secondary"}):t.jsx(In,{size:16,className:"icon-text-secondary"}),t.jsx(oa,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:C.title,onChange:N=>f(A,{title:N.target.value}),onClick:N=>N.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:N=>{N.stopPropagation(),x(A)},title:"Remove milestone",children:t.jsx(Sn,{size:14,className:"icon-text-secondary"})})]}),l.has(A)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:C.description||"",onChange:N=>f(A,{description:N.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:C.verification||"",onChange:N=>f(A,{verification:N.target.value})})]}),C.slices.map((N,S)=>{const _=`${A}-${S}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(_),children:[d.has(_)?t.jsx(mn,{size:14,className:"icon-text-secondary"}):t.jsx(In,{size:14,className:"icon-text-secondary"}),t.jsx(md,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:N.title,onChange:T=>p(A,S,{title:T.target.value}),onClick:T=>T.stopPropagation()}),C.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:T=>{T.stopPropagation(),v(A,S)},title:"Remove slice",children:t.jsx(Sn,{size:12,className:"icon-text-secondary"})})]}),d.has(_)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:N.verification||"",onChange:T=>p(A,S,{verification:T.target.value})})]}),N.features.map((T,M)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(id,{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:T.title,onChange:E=>g(A,S,M,{title:E.target.value})}),T.description&&t.jsx("p",{className:"roadmap-feature-text",children:T.description}),T.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",T.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(A,S,M),title:"Remove feature",children:t.jsx(Sn,{size:12,className:"icon-text-secondary"})})]},M)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(A,S),children:[t.jsx(Nn,{size:12}),"Add Feature"]})]})]},S)})]})]},A))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(ha,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Un,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function CR({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){Ci(e);const[u,m]=i.useState({type:"initial"}),[h,f]=i.useState(null),[p,g]=i.useState([]),[x,v]=i.useState([]),[b,y]=i.useState(null),[j,C]=i.useState(""),[A,N]=i.useState(!0),[S,_]=i.useState(!1),[T,M]=i.useState(!1),E=i.useRef(null),O=i.useRef(null),B=i.useRef(null),R=i.useRef(null),[P,F]=i.useState(null),q=i.useMemo(()=>ba(),[]);Bl(e?P:null);const{activeTabMap:ee,broadcastUpdate:U,broadcastCompleted:k,broadcastLock:I,broadcastUnlock:$,broadcastHeartbeat:w}=tr(),H=a==="milestone"?gN:wN,J=a==="milestone"?bN:kN,fe=a==="milestone"?xN:jN,de=a==="milestone"?vN:NN,D=a==="milestone"?yN:SN,_e=a==="milestone"?"Milestone":"Slice",z=a==="milestone"?"milestone_interview":"slice_interview",Z=i.useCallback(Ee=>{O.current?.close();const ie=fe(Ee,c,{onThinking:se=>{C(xe=>xe+se),U({sessionId:Ee,status:"generating",needsInput:!1,owningTabId:q,type:z,title:o,projectId:c??null})},onQuestion:se=>{_(!1),oe(),m({type:"question",sessionId:Ee,question:se}),C(""),U({sessionId:Ee,status:"awaiting_input",needsInput:!0,owningTabId:q,type:z,title:o,projectId:c??null})},onSummary:se=>{_(!1),oe(),m({type:"summary",sessionId:Ee,summary:se}),y(se),C(""),U({sessionId:Ee,status:"complete",needsInput:!1,owningTabId:q,type:z,title:o,projectId:c??null})},onError:se=>{const xe=se||"Session failed while contacting the AI.";_(!1),f(null),m({type:"error",sessionId:Ee,errorMessage:xe}),C(""),B.current=Ee,U({sessionId:Ee,status:"error",needsInput:!1,owningTabId:q,type:z,title:o,projectId:c??null}),k({sessionId:Ee,status:"error"})},onComplete:()=>{_(!1),B.current=null,k({sessionId:Ee,status:"complete"})},onConnectionStateChange:se=>{_(se==="reconnecting")}});O.current=ie},[k,U,fe,z,c,q,o]),oe=()=>{y(null),g([]),v([]),C("")},Y=i.useCallback(async()=>{f(null),oe(),_(!1),m({type:"loading"});try{const{sessionId:Ee}=await H(r,c);B.current=Ee,F(Ee),Z(Ee)}catch(Ee){_(!1),f(Me(Ee)||`Failed to start ${_e.toLowerCase()} interview`),m({type:"initial"}),B.current=null,F(null)}},[Z,c,H,r,_e]),ae=i.useCallback(async()=>{f(null),M(!0);try{await D(r,c),s(),m({type:"applied"})}catch(Ee){f(Me(Ee)||`Failed to skip ${_e.toLowerCase()} interview`),M(!1)}},[s,c,D,r,_e]);i.useEffect(()=>{e&&u.type==="initial"&&E.current?.focus()},[e,u.type]),i.useEffect(()=>{if(!e||!d||u.type!=="initial")return;let Ee=!1;return wi(d).then(ie=>{if(Ee||!ie)return;const se=Fa(ie.conversationHistory);if(v(se),F(ie.id),g(se.map(xe=>xe.response).filter(xe=>!!(xe&&typeof xe=="object"&&!Array.isArray(xe)))),ie.status==="awaiting_input"&&ie.currentQuestion)try{const xe=JSON.parse(ie.currentQuestion);B.current=ie.id,m({type:"question",sessionId:ie.id,question:xe})}catch{f("Failed to restore session question.")}else if(ie.status==="complete"&&ie.result)try{const xe=JSON.parse(ie.result);B.current=ie.id,y(xe),m({type:"summary",sessionId:ie.id,summary:xe})}catch{f("Failed to restore session result.")}else ie.status==="generating"?(B.current=ie.id,ie.thinkingOutput&&C(ie.thinkingOutput),m({type:"loading"}),Z(ie.id)):ie.status==="error"&&(B.current=ie.id,f(null),m({type:"error",sessionId:ie.id,errorMessage:ie.error??"The session encountered an error."}))}).catch(()=>{Ee||f("Failed to resume session.")}),()=>{Ee=!0}},[Z,e,d,u.type]),i.useEffect(()=>{e||(_(!1),F(null))},[e]),i.useEffect(()=>{if(!(!e||!P)){if(R.current!==P){R.current&&$(R.current,q),I(P,q),R.current=P;return}!P&&R.current&&($(R.current,q),R.current=null)}},[I,$,e,P,q]),i.useEffect(()=>{if(!e||!P||R.current!==P)return;w(q);const Ee=setInterval(()=>{w(q)},3e4);return()=>{clearInterval(Ee)}},[w,e,P,q]),i.useEffect(()=>()=>{O.current?.close(),O.current=null,R.current&&($(R.current,q),R.current=null)},[$,q]);const ce=i.useCallback(()=>{O.current?.close(),O.current=null,n()},[n]),te=i.useCallback(async()=>{O.current?.close(),O.current=null,oe(),m({type:"initial"}),f(null),B.current=null,F(null),n()},[n]),Re=i.useCallback(async Ee=>{if(u.type!=="question")return;const{sessionId:ie}=u;f(null),g(se=>[...se,Ee]),v(se=>[...se,{question:u.question,response:Ee}]),m({type:"loading"}),C("");try{Z(ie),await J(ie,Ee,c,q)}catch(se){O.current?.close(),O.current=null,f(Me(se)||"Failed to submit response"),m({type:"question",sessionId:ie,question:u.question})}},[Z,c,J,q,u]),be=i.useCallback(async()=>{if(u.type==="summary"){f(null),M(!0);try{await de(u.sessionId,b||void 0,c),s(),m({type:"applied"})}catch(Ee){f(Me(Ee)||"Failed to apply interview results"),M(!1)}}},[de,b,s,c,u]),ke=()=>u.type==="question"?Math.min(p.length+1,6):6,Ue=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Ge=P?ee.get(P):null,Ae=!!(Ge&&Ge.tabId!==q&&!Ge.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ee=>Ee.target===Ee.currentTarget&&te(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(vs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",_e,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ue&&t.jsx("button",{className:"modal-send-to-background",onClick:ce,title:"Send to background","aria-label":"Send to background",children:t.jsx(eo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Close",children:t.jsx(tn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),S&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Ae&&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.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(vs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",_e," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," 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 Y(),children:[t.jsx(vs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ae(),disabled:T,children:[T?t.jsx(ft,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})]})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ft,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:j?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>N(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&j&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:j})})]})]}),u.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(ii,{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:u.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})})]})]})}),u.type==="question"&&t.jsx(ER,{question:u.question,progress:ke(),historyEntries:x,onSubmit:Re}),u.type==="summary"&&b&&t.jsx(MR,{summary:b,historyEntries:x,onSummaryChange:y,onApply:be,onCancel:te,isApplying:T}),u.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(Un,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[_e," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",u.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 ER({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{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(ii,{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(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),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:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.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(Un,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(tn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(Qr,{size:16,className:"icon-ml-4"})]})})]})}function MR({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),m=(h,f)=>{const p={...l,[h]:f};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(ii,{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:()=>u(!d),"aria-expanded":d,children:[d?t.jsx(mn,{size:16}):t.jsx(In,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&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:a,disabled:o,children:[o?t.jsx(ft,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const gr={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)"}},qh={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)"}},Vh={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)"}},zo={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)"}},Fo={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)"}},Uo={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)"}},Wh={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)"}},_R=3;function AR(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Kh({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 Gh(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Lc={title:"",description:"",status:"planning",autopilotEnabled:!1},Oc={title:"",description:"",status:"planning",dependencies:[]},zc={title:"",description:"",status:"pending"},Fc={title:"",description:"",acceptanceCriteria:"",status:"defined"},PR=3600*1e3;function bl(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 a=Math.floor(s/(60*1e3));if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function RR(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=PR,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 TR(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 IR(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 Uc(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 ib=["feature_triaged","feature_completed"],ab=["slice_activated","slice_completed","milestone_completed"],rb=["mission_started","mission_paused","mission_resumed","mission_completed"],ob=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Jh(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return rb.includes(e);case"tasks":return ib.includes(e);case"slices":return ab.includes(e);case"autopilot":return ob.includes(e);default:return!0}}function $R(e){return e==="error"||e==="warning"?"mission-event__type--error":rb.includes(e)?"mission-event__type--state":ib.includes(e)?"mission-event__type--task":ab.includes(e)?"mission-event__type--slice":ob.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function DR(e){return e.replace(/_/g," ")}function LR(e,n){return n?e==="watching"?`Watching since ${bl(n)}`:`Last activation ${bl(n)}`:null}function OR({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,x]=i.useState(null),[v,b]=i.useState(!0),[y,j]=i.useState(!1),C=Di()==="mobile",[A,N]=i.useState(!1),[S,_]=i.useState(null),[T,M]=i.useState(Lc),[E,O]=i.useState(!1),[B,R]=i.useState(new Set),[P,F]=i.useState(new Set),[q,ee]=i.useState(null),[U,k]=i.useState(Oc),[I,$]=i.useState(!1),[w,H]=i.useState(null),[J,fe]=i.useState(zc),[de,D]=i.useState(!1),[_e,z]=i.useState(null),[Z,oe]=i.useState(null),[Y,ae]=i.useState(Fc),[ce,te]=i.useState(!1),[Re,be]=i.useState(null),[ke,Ue]=i.useState(null),[Ge,qe]=i.useState(""),[Ae,Ee]=i.useState(!1),[ie,se]=i.useState([]),[xe,ne]=i.useState(void 0),Fe=xe??c,[Qe,ge]=i.useState(null),[ze,tt]=i.useState(null),[pt,ve]=i.useState(null);i.useEffect(()=>{h&&Fe&&Ee(!0)},[h,Fe]),i.useEffect(()=>{if(!h||Fe)return;let K=!1;return Jd(r).then(Ce=>{if(K)return;const Ke=Ce.filter(Pt=>Pt.type==="mission_interview"&&(Pt.status==="awaiting_input"||Pt.status==="error"));se(Ke)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{K=!0}},[h,r,Fe]),i.useEffect(()=>{if(!h||!u)return;let K=!1;return wi(u).then(Ce=>{if(!(K||!Ce))try{const Ke=JSON.parse(Ce.inputPayload||"{}");Ke.targetId&&Ke.targetType&&ge({type:Ke.targetType,id:Ke.targetId,title:Ke.targetTitle||Ce.title,resumeSessionId:u})}catch{ge({type:"milestone",id:"",title:Ce.title,resumeSessionId:u})}}).catch(Ce=>{K||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{K=!0}},[h,u,m]);const[le,Te]=i.useState(null),[pe,$e]=i.useState(new Map),[st,at]=i.useState(null),[rt,Oe]=i.useState({title:"",assertion:"",status:"pending"}),[Be,et]=i.useState(!1),[jt,De]=i.useState(null),[vt,Et]=i.useState(new Map),[bt,zt]=i.useState(new Set),[qt,It]=i.useState(new Set),[_t,Xt]=i.useState(null),[Lt,Ut]=i.useState(new Map),[cn,Jt]=i.useState(null),[Vt,Kt]=i.useState(null),[rn,fn]=i.useState(!0),[on,gn]=i.useState(new Set),[je,Le]=i.useState(new Map),[re,Pe]=i.useState(null),[Se,X]=i.useState(new Map),[Ie,he]=i.useState(null),[Ne,Je]=i.useState(new Map),[kt,Yt]=i.useState(new Map),[$t,Tt]=i.useState("structure"),[Bt,jn]=i.useState([]),Dn=i.useRef([]),hn=i.useRef([]),Ht=i.useRef(null),yn=i.useRef(null),pn=i.useRef("structure"),es=i.useRef("all"),[ye,ut]=i.useState(!1),[Qt,Cn]=i.useState(0),[ue,dt]=i.useState("all"),[wt,gt]=i.useState(new Set),ot=i.useRef(null),yt=i.useRef(null);hn.current=f,Ht.current=g,yn.current=cn,pn.current=$t,es.current=ue;const Ft=i.useCallback((K="auto")=>{const Ce=yt.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:K});return}const Ke=ot.current;Ke&&(Ke.scrollTop=Ke.scrollHeight)},[]),Zt=i.useCallback(()=>{const K=ot.current;return K?K.scrollHeight-K.scrollTop-K.clientHeight<=100:!0},[]),Ln=i.useCallback(async K=>{if(K.length===0){Yt(new Map);return}const Ce=await Oj(r);Yt(Ke=>{const Pt=new Map(Ke);for(const[vn,an]of Object.entries(Ce))TR(an)&&Pt.set(vn,an);return Pt})},[r]),Wt=i.useCallback(async()=>{try{b(!0);const K=await Tj(r);p(K),Ln(K)}catch(K){a(Me(K)||"Failed to load missions","error")}finally{b(!1)}},[a,r,Ln]),Mt=i.useCallback(async K=>{try{j(!0);const Ce=await wf(K,r);if(x(Ce),Ce.milestones.length>0){const Ke=Ce.milestones[0].id;Jt(Ke),fn(!0),R(new Set([Ke])),Xl(Ke,r).then(Pt=>{$e(vn=>{const an=new Map(vn);return an.set(Ke,Pt),an})}).catch(()=>{}),Zl(Ke,r).then(Pt=>{Ut(vn=>{const an=new Map(vn);return an.set(Ke,Pt),an})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&F(new Set([Ce.milestones[0].slices[0].id]))}else Jt(null),Kt(null)}catch(Ce){a(Me(Ce)||"Failed to load mission details","error")}finally{j(!1)}},[a,r]);i.useEffect(()=>{if(!h||!cn){Kt(null);return}let K=!1;return Kt(null),Yu(cn,r).then(Ce=>{if(!K){if(!Uc(Ce)){Kt(null);return}Kt(Ce),Ut(Ke=>{const Pt=new Map(Ke);return Pt.set(cn,Ce.rollup),Pt})}}).catch(()=>{K||Kt(null)}),()=>{K=!0}},[h,cn,r]),i.useEffect(()=>{fn(!0)},[cn]);const En=i.useCallback(K=>{!K||K!==yn.current||Yu(K,r).then(Ce=>{yn.current!==K||!Uc(Ce)||(Kt(Ce),Ut(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce.rollup),Pt}))}).catch(()=>{})},[r]),Xn=i.useCallback(async(K,Ce)=>{const Ke=Ce?.append??!1,Pt=Ke?Dn.current.length:0;Ke||(ut(!0),gt(new Set));try{const vn=await Lj(K,{limit:50,offset:Pt,eventType:void 0},r),an=vn.events.filter(zn=>Jh(zn.eventType,ue));jn(zn=>{if(!Ke)return an;const Xe=new Set(zn.map(At=>At.id)),nt=[...zn];for(const At of an)Xe.has(At.id)||nt.push(At);return nt}),Cn(vn.total),Ke||requestAnimationFrame(()=>{Ft("auto")})}catch(vn){a(Me(vn)||"Failed to load mission activity","error")}finally{Ke||ut(!1)}},[a,ue,r,Ft]);i.useEffect(()=>{Dn.current=Bt},[Bt]),i.useEffect(()=>{h&&(Wt(),x(null),Jt(null),Kt(null),jn([]),Cn(0),Tt("structure"),dt("all"),gt(new Set))},[h,Wt]);const ts=i.useRef(null);i.useEffect(()=>{h&&d&&ts.current!==d&&f.length>0&&(ts.current=d,Mt(d))},[h,d,f,Mt]),i.useEffect(()=>{h||(ts.current=null)},[h]),i.useEffect(()=>{!h||!g||$t!=="activity"||Xn(g.id)},[$t,h,Xn,g,ue]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const K=new URLSearchParams;r&&K.set("projectId",r);const Ce=`/api/events${K.size>0?`?${K.toString()}`:""}`,Ke=()=>{Ln(hn.current)},Pt=gs=>{Ke();const Jn=gs;if(Jn.data)try{const wn=JSON.parse(Jn.data);wn?.id&&p(Qi=>Qi.map(Zs=>Zs.id===wn.id?{...Zs,...wn}:Zs))}catch{}Ht.current&&Mt(Ht.current.id)},vn=gs=>{Ke(),Ht.current&&Mt(Ht.current.id)},an=()=>{Ke(),Ht.current&&Mt(Ht.current.id)},zn=gs=>{Ke(),Ht.current&&Mt(Ht.current.id)},Xe=gs=>{const Jn=gs;if(Jn.data)try{const wn=JSON.parse(Jn.data);wn&&wn.featureId&&(Js(wn.featureId),ai(wn.featureId),wn.milestoneId&&En(wn.milestoneId))}catch{}},nt=gs=>{const Jn=gs;if(Jn.data)try{const wn=JSON.parse(Jn.data);wn&&wn.featureId&&(Js(wn.featureId),ai(wn.featureId),wn.milestoneId&&En(wn.milestoneId),Ht.current&&Mt(Ht.current.id))}catch{}},At=gs=>{const Jn=gs;if(Jn.data)try{const wn=JSON.parse(Jn.data);wn&&wn.milestoneId&&(_n(wn.milestoneId),En(wn.milestoneId))}catch{}},bn=gs=>{const Jn=gs;if(Jn.data)try{const wn=JSON.parse(Jn.data);wn&&wn.milestoneId&&(On(wn.milestoneId),_n(wn.milestoneId),En(wn.milestoneId))}catch{}};return fi(Ce,{events:{"mission:updated":Pt,"slice:updated":vn,"feature:updated":an,"milestone:updated":zn,"mission:event":gs=>{Ke();const Jn=Ht.current;if(!Jn||pn.current!=="activity")return;const wn=Zt(),Qi=gs;if(Qi.data)try{const Zs=JSON.parse(Qi.data);if(!IR(Zs)||Zs.missionId!==Jn.id||!Jh(Zs.eventType,es.current))return;jn(Mi=>{const Wl=Mi.filter(Kl=>Kl.id!==Zs.id);return[Zs,...Wl].slice(0,100)}),Cn(Mi=>Mi+1),wn&&requestAnimationFrame(()=>{const Mi=ot.current;Mi&&(Mi.scrollTop=0)})}catch{}},"validator-run:started":Xe,"validator-run:completed":nt,"milestone:validation:updated":At,"assertion:created":bn,"assertion:updated":bn,"assertion:deleted":bn,"assertion:linked":bn,"assertion:unlinked":bn,"fix-feature:created":gs=>{const Jn=gs;if(Jn.data)try{const wn=JSON.parse(Jn.data);if(wn&&wn.sourceFeatureId){Js(wn.sourceFeatureId);const Qi=wn?.feature?.sliceId,Zs=Ht.current;if(Qi&&Zs){const Mi=Zs.milestones.find(Wl=>Wl.slices.some(Kl=>Kl.id===Qi));Mi&&En(Mi.id)}Ht.current&&Mt(Ht.current.id)}}catch{}}}})},[h,Zt,Mt,Ln,r,En]);const Ps=i.useCallback(()=>{N(!0),_(null),M(Lc)},[]),ws=i.useCallback(K=>{_(K.id),N(!1),M({title:K.title,description:K.description||"",status:K.status,autopilotEnabled:K.autopilotEnabled??!1})},[]),Bn=i.useCallback(()=>{_(null),N(!1),M(Lc)},[]),rs=i.useCallback(async()=>{if(!T.title.trim()){a("Mission title is required","error");return}try{if(O(!0),A)await Ij({title:T.title.trim(),description:T.description.trim()||void 0,autopilotEnabled:T.autopilotEnabled},r),a("Mission created","success");else if(S){const K={title:T.title.trim(),description:T.description.trim()||void 0,status:T.status,autopilotEnabled:T.autopilotEnabled};T.autopilotEnabled&&(K.autoAdvance=!0),await $j(S,K,r),a("Mission updated","success"),g?.id===S&&await Mt(S)}await Wt(),Bn()}catch(K){a(Me(K)||"Failed to save mission","error")}finally{O(!1)}},[T,A,S,a,Wt,Mt,g,Bn,r]),V=i.useCallback(async K=>{try{await Dj(K,r),a("Mission deleted","success"),g?.id===K&&x(null),await Wt(),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete mission","error")}},[a,Wt,g,r]),Ve=i.useCallback(()=>{$(!0),ee(null),k(Oc)},[]),Ye=i.useCallback(K=>{ee(K.id),$(!1),k({title:K.title,description:K.description||"",status:K.status,dependencies:K.dependencies})},[]),mt=i.useCallback(()=>{ee(null),$(!1),k(Oc)},[]),Ct=i.useCallback(async()=>{if(!U.title.trim()){a("Milestone title is required","error");return}try{O(!0),I&&g?(await zj(g.id,{title:U.title.trim(),description:U.description.trim()||void 0,dependencies:U.dependencies},r),a("Milestone created","success")):q&&(await Fj(q,{title:U.title.trim(),description:U.description.trim()||void 0,status:U.status,dependencies:U.dependencies},r),a("Milestone updated","success")),await Mt(g.id),mt()}catch(K){a(Me(K)||"Failed to save milestone","error")}finally{O(!1)}},[U,I,q,g,a,Mt,mt,T.title,r]),Rt=i.useCallback(async K=>{try{await Uj(K,r),a("Milestone deleted","success"),await Mt(g.id),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete milestone","error")}},[a,Mt,g,r]),dn=i.useCallback(K=>{Jt(K),fn(!0),R(Ce=>{const Ke=new Set(Ce);return!Ke.has(K)?(Ke.add(K),Xl(K,r).then(vn=>{$e(an=>{const zn=new Map(an);return zn.set(K,vn),zn})}).catch(()=>{}),Zl(K,r).then(vn=>{Ut(an=>{const zn=new Map(an);return zn.set(K,vn),zn})}).catch(()=>{})):Ke.delete(K),Ke})},[r]),Dt=i.useCallback(K=>{z(K),D(!0),H(null),fe(zc)},[]),ks=i.useCallback(K=>{H(K.id),D(!1),fe({title:K.title,description:K.description||"",status:K.status})},[]),Zn=i.useCallback(()=>{H(null),D(!1),z(null),fe(zc)},[]),me=i.useCallback(async()=>{if(!J.title.trim()){a("Slice title is required","error");return}try{O(!0),de&&_e?(await Bj(_e,{title:J.title.trim(),description:J.description.trim()||void 0},r),a("Slice created","success")):w&&(await Hj(w,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status},r),a("Slice updated","success")),await Mt(g.id),Zn()}catch(K){a(Me(K)||"Failed to save slice","error")}finally{O(!1)}},[J,de,w,_e,g,a,Mt,Zn,r]),He=i.useCallback(async K=>{try{await qj(K,r),a("Slice deleted","success"),await Mt(g.id),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete slice","error")}},[a,Mt,g,r]),lt=i.useCallback(async K=>{try{await Vj(K,r),a("Slice activated","success"),await Mt(g.id)}catch(Ce){a(Me(Ce)||"Failed to activate slice","error")}},[a,Mt,g,r]),G=i.useCallback(K=>{F(Ce=>{const Ke=new Set(Ce);return Ke.has(K)?Ke.delete(K):Ke.add(K),Ke})},[]),we=i.useCallback(K=>{be(K),te(!0),oe(null),ae(Fc)},[]),it=i.useCallback(K=>{oe(K.id),te(!1),ae({title:K.title,description:K.description||"",acceptanceCriteria:K.acceptanceCriteria||"",status:K.status})},[]),St=i.useCallback(()=>{oe(null),te(!1),be(null),ae(Fc)},[]),Nt=i.useCallback(async()=>{if(!Y.title.trim()){a("Feature title is required","error");return}try{O(!0),ce&&Re?(await Wj(Re,{title:Y.title.trim(),description:Y.description.trim()||void 0,acceptanceCriteria:Y.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):Z&&(await Kj(Z,{title:Y.title.trim(),description:Y.description.trim()||void 0,acceptanceCriteria:Y.acceptanceCriteria.trim()||void 0,status:Y.status},r),a("Feature updated","success")),await Mt(g.id),St()}catch(K){a(Me(K)||"Failed to save feature","error")}finally{O(!1)}},[Y,ce,Z,Re,g,a,Mt,St,r]),Mn=i.useCallback(async K=>{try{await Gj(K,r),a("Feature deleted","success"),await Mt(g.id),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete feature","error")}},[a,Mt,g,r]),nn=i.useCallback(async()=>{if(!ke||!Ge.trim()){a("Task ID is required","error");return}try{await Jj(ke,Ge.trim(),r),a("Feature linked to task","success"),await Mt(g.id),Ue(null),qe("")}catch(K){a(Me(K)||"Failed to link feature to task","error")}},[ke,Ge,a,Mt,g,r]),un=i.useCallback(async K=>{try{await Yj(K,r),a("Feature unlinked from task","success"),await Mt(g.id)}catch(Ce){a(Me(Ce)||"Failed to unlink feature","error")}},[a,Mt,g,r]),sn=i.useCallback(async K=>{try{O(!0),await Qj(K,void 0,void 0,r),a("Feature triaged — task created","success"),await Mt(g.id)}catch(Ce){a(Me(Ce)||"Failed to triage feature","error")}finally{O(!1)}},[a,Mt,g,r]),Hn=i.useCallback(async K=>{ve(K);try{const Ce=await CN(K,r);tt({featureId:K,enrichedDescription:Ce.description})}catch{await sn(K)}finally{ve(null)}},[sn,r]),qn=i.useCallback(async()=>{ze&&(tt(null),await sn(ze.featureId))},[sn,ze]),ls=i.useCallback(()=>{tt(null)},[]),Rn=i.useCallback(async K=>{try{O(!0);const Ce=await Xj(K,r);a(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await Mt(g.id)}catch(Ce){a(Me(Ce)||"Failed to triage slice features","error")}finally{O(!1)}},[a,Mt,g,r]),On=i.useCallback(async K=>{try{const Ce=await Xl(K,r);$e(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch{}},[r]),_n=i.useCallback(async K=>{try{const Ce=await Zl(K,r);Ut(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch{}},[r]),cs=i.useCallback(async K=>{if(!rt.title.trim()||!rt.assertion.trim()){a("Title and assertion text are required","error");return}try{O(!0),await Zj(K,{title:rt.title.trim(),assertion:rt.assertion.trim(),status:rt.status},r),a("Assertion created","success"),await On(K),await _n(K),et(!1),Oe({title:"",assertion:"",status:"pending"})}catch(Ce){a(Me(Ce)||"Failed to create assertion","error")}finally{O(!1)}},[rt,a,On,_n,r]),Wn=i.useCallback(K=>{at(K.id),Oe({title:K.title,assertion:K.assertion,status:K.status})},[]),Vn=i.useCallback(()=>{at(null),et(!1),Oe({title:"",assertion:"",status:"pending"})},[]),ms=i.useCallback(async(K,Ce)=>{if(!rt.title.trim()||!rt.assertion.trim()){a("Title and assertion text are required","error");return}try{O(!0),await eN(K,{title:rt.title.trim(),assertion:rt.assertion.trim(),status:rt.status},r),a("Assertion updated","success"),await On(Ce),await _n(Ce),Vn()}catch(Ke){a(Me(Ke)||"Failed to update assertion","error")}finally{O(!1)}},[rt,a,On,_n,Vn,r]),Kn=i.useCallback(async K=>{try{const Ce=await sN(K,r);Et(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch{}},[r]),hs=i.useCallback(async K=>{const Ce=jt!==K;De(Ke=>Ke===K?null:K),Ce&&await Kn(K)},[jt,Kn]),Gn=i.useCallback(K=>{De(K),Kn(K),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${K}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Kn]),Rs=i.useCallback(async(K,Ce)=>{try{zt(Ke=>new Set(Ke).add(Ce)),await tN(K,Ce,r),a("Feature linked to assertion","success"),await Kn(Ce),Xt(null)}catch(Ke){a(Me(Ke)||"Failed to link feature","error")}finally{zt(Ke=>{const Pt=new Set(Ke);return Pt.delete(Ce),Pt})}},[a,Kn,r]),Ts=i.useCallback(async(K,Ce)=>{const Ke=`${K}-${Ce}`;try{It(Pt=>new Set(Pt).add(Ke)),await nN(K,Ce,r),a("Feature unlinked from assertion","success"),await Kn(Ce)}catch(Pt){a(Me(Pt)||"Failed to unlink feature","error")}finally{It(Pt=>{const vn=new Set(Pt);return vn.delete(Ke),vn})}},[a,Kn,r]),zi=i.useCallback(async K=>{try{gn(Ke=>new Set(Ke).add(K)),await iN(K,r),a("Validation triggered","success");const Ce=await Qu(K,r);Le(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch(Ce){a(Me(Ce)||"Failed to trigger validation","error")}finally{gn(Ce=>{const Ke=new Set(Ce);return Ke.delete(K),Ke})}},[a,r]),Js=i.useCallback(async K=>{try{const Ce=await Qu(K,r);Le(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch{}},[r]),ai=i.useCallback(async K=>{try{const Ce=await aN(K,{limit:10},r);X(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch{}},[r]),Ys=i.useCallback(K=>{const Ce=Ht.current;if(Ce){for(const Ke of Ce.milestones)for(const Pt of Ke.slices)if(Pt.features.find(an=>an.id===K)){R(an=>{const zn=new Set(an);return zn.add(Ke.id),zn}),F(an=>{const zn=new Set(an);return zn.add(Pt.id),zn}),Pe(K),Jt(Ke.id),Js(K),ai(K),requestAnimationFrame(()=>{const an=document.querySelector(`[data-mission-feature-id="${K}"]`);an instanceof HTMLElement&&typeof an.scrollIntoView=="function"&&an.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Js,ai]),ct=i.useCallback(async K=>{try{const Ce=await rN(K,r);Je(Ke=>{const Pt=new Map(Ke);return Pt.set(K,Ce),Pt})}catch{}},[r]),en=i.useCallback(async K=>{re===K?Pe(null):(Pe(K),await Js(K),await ai(K))},[re,Js,ai]),Qs=i.useCallback(async K=>{Ie===K?he(null):(he(K),await ct(K))},[Ie,ct]),nr=i.useCallback(async K=>{try{await oN(K,r),a("Mission resumed","success"),await Mt(K),Wt()}catch(Ce){a(Me(Ce)||"Failed to resume mission","error")}},[a,Mt,Wt,r]),sr=i.useCallback(async K=>{try{const Ke=(await lN(K,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ke} task${Ke!==1?"s":""} paused)`,"success"),await Mt(K),Wt()}catch(Ce){a(Me(Ce)||"Failed to stop mission","error")}},[a,Mt,Wt,r]),ir=i.useCallback(async K=>{try{await cN(K,r),a("Mission started — first slice activated","success"),await Mt(K),Wt()}catch(Ce){a(Me(Ce)||"Failed to start mission","error")}},[a,Mt,Wt,r]),ql=i.useCallback(async(K,Ce)=>{try{await dN(K,{enabled:Ce},r),a(Ce?"Autopilot enabled":"Autopilot disabled","success"),await Mt(K),Wt()}catch(Ke){a(Me(Ke)||"Failed to update autopilot","error")}},[a,Mt,Wt,r]),co=i.useCallback(K=>{Tt("structure"),Jt(null),Kt(null),jn([]),Cn(0),dt("all"),gt(new Set),Mt(K.id)},[Mt]),uo=i.useCallback(()=>{x(null),Jt(null),Kt(null),Tt("structure"),jn([]),Cn(0),dt("all"),gt(new Set),Wt()},[Wt]),ps=Bt.length<Qt,gi=g?.autopilotState??"inactive",Is=gi==="watching"||gi==="activating",ar=LR(gi,g?.lastAutopilotActivityAt),Ji=i.useMemo(()=>!Vt||!cn||!Uc(Vt)?null:Vt.rollup.milestoneId===cn?Vt:null,[cn,Vt]),mo=i.useMemo(()=>{const K=new Map;for(const Ce of Ji?.validationTelemetry.validationRounds??[]){const Ke=K.get(Ce.featureId);(!Ke||Ce.startedAt>Ke.startedAt)&&K.set(Ce.featureId,Ce)}return K},[Ji]),xa=i.useCallback(()=>{!g||ye||!ps||Xn(g.id,{append:!0})},[ye,ps,Xn,g]),Vl=i.useCallback(K=>{gt(Ce=>{const Ke=new Set(Ce);return Ke.has(K)?Ke.delete(K):Ke.add(K),Ke})},[]),va=i.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),rs())},[rs]),Q=i.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),Ct())},[Ct]),We=i.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),me())},[me]),xt=i.useCallback(K=>{K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),Nt())},[Nt]),Gt=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const K=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",K),()=>document.removeEventListener("keydown",K)},[h,s]),!h)return null;const ds=()=>g?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:[Is&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(gr[g.status]||gr.planning).bg,color:(gr[g.status]||gr.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.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:g.autopilotEnabled??!1,onChange:K=>ql(g.id,K.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(is,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Fo[gi]||Fo.inactive).bg,color:(Fo[gi]||Fo.inactive).text},"data-testid":"autopilot-state-badge",children:[Is&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),gi]})]}),ar&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:ar})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>sr(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Bs,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>nr(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(Yn,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ir(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ws(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(js,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Sn,{size:14})})]})]}),S===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:K=>M({...T,title:K.target.value}),onKeyDown:va,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:K=>M({...T,description:K.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:K=>M({...T,status:K.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:T.autopilotEnabled,onChange:K=>M({...T,autopilotEnabled:K.target.checked})}),t.jsx(is,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Bn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${$t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Tt("structure"),role:"tab","aria-selected":$t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${$t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Tt("activity"),role:"tab","aria-selected":$t==="activity","data-testid":"mission-tab-activity",children:["Activity (",Qt,")"]})]}),$t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(K=>{const Ce=Ji?.rollup.milestoneId===K.id?Ji:null,Ke=Ce?.rollup??Lt.get(K.id),Pt=Ce?.validationTelemetry.validationRounds??[],vn=Ce?.fixFeatures??[],an=Wh[Ke?.state??"not_started"]??Wh.not_started,zn=Ke&&(Ke.state==="blocked"||Ke.state==="failed")?Ce?.validationTelemetry.validationRounds.find(Xe=>Xe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>dn(K.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:B.has(K.id)?t.jsx(mn,{size:16}):t.jsx(In,{size:16})}),t.jsx(oa,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:K.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:qh[K.status].bg,color:qh[K.status].text},children:K.status}),t.jsxs("span",{className:"mission-milestone__count",children:[K.slices.length," slices"]}),t.jsx(Kh,{state:AR(K.interviewState)}),Ke&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:an.bg,color:an.text},title:"Validation state",children:Gh(Ke.state)}),Ke.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ke.passedAssertions??0} of ${Ke.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ke.passedAssertions??0)/Ke.totalAssertions*100}%`,backgroundColor:(Ke.passedAssertions??0)===Ke.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),K.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ge({type:"milestone",id:K.id,title:K.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Vi,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Xe=>Xe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Dt(K.id),title:"Add slice",children:t.jsx(Nn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ye(K),title:"Edit milestone",children:t.jsx(js,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"milestone",id:K.id}),title:"Delete milestone",children:t.jsx(Sn,{size:14})})]})]}),B.has(K.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(I||q===K.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:U.title,onChange:Xe=>k({...U,title:Xe.target.value}),onKeyDown:Q,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:Xe=>k({...U,description:Xe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ct,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),q?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:mt,children:"Cancel"})]})]}),Ce&&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:[Ce.validationTelemetry.totalRuns," rounds",Ce.validationTelemetry.lastValidatorStatus?` · Last ${Ce.validationTelemetry.lastValidatorStatus}`:""]})]}),zn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",zn]}),Pt.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>fn(Xe=>!Xe),title:rn?"Hide validation rounds":"Show validation rounds",children:[rn?t.jsx(mn,{size:12}):t.jsx(In,{size:12}),"Validation rounds (",Pt.length,")"]}),rn&&t.jsx("div",{className:"mission-validation-rounds__list",children:Pt.map(Xe=>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--${Xe.validatorStatus}`,children:Xe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Xe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Xe.implementationAttempt," · reviewer #",Xe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Xe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Gn(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):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:"}),Xe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.generatedFixFeatureIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ys(nt),title:`Jump to fix feature ${nt}`,children:nt},`${Xe.roundId}-${nt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Xe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Xe.blockedReason})]},Xe.roundId))})]}),vn.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:vn.map(Xe=>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:()=>Ys(Xe.id),title:`Jump to feature ${Xe.id}`,children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:zo[Xe.status].bg,color:zo[Xe.status].text},children:Xe.status}),Xe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Xe.loopState}`,children:Xe.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:()=>Ys(Xe.sourceFeatureId),title:`Jump to source feature ${Xe.sourceFeatureId}`,children:Xe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Xe.runId})]}),Xe.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:Xe.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Gn(nt),title:`Jump to assertion ${nt}`,children:nt},`${Xe.id}-${nt}`))})]})]},Xe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[K.slices.map(Xe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>G(Xe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:P.has(Xe.id)?t.jsx(mn,{size:16}):t.jsx(In,{size:16})}),t.jsx(md,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vh[Xe.status].bg,color:Vh[Xe.status].text},children:Xe.status}),t.jsxs("span",{className:"mission-slice__count",children:[Xe.features?.length||0," features"]}),t.jsx(Kh,{state:Xe.planState??"not_started"}),Xe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ge({type:"slice",id:Xe.id,title:Xe.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Vi,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:nt=>nt.stopPropagation(),children:[Xe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>lt(Xe.id),title:"Activate slice",children:t.jsx(Yn,{size:14})}),Xe.status==="active"&&Xe.features?.some(nt=>nt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Rn(Xe.id),title:"Triage all features",disabled:E,children:E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>we(Xe.id),title:"Add feature",children:t.jsx(Nn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ks(Xe),title:"Edit slice",children:t.jsx(js,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"slice",id:Xe.id}),title:"Delete slice",children:t.jsx(Sn,{size:14})})]})]}),P.has(Xe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[de&&_e===K.id&&!w&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:J.title,onChange:nt=>fe({...J,title:nt.target.value}),onKeyDown:We,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:nt=>fe({...J,description:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:me,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Zn,children:"Cancel"})]})]}),w===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:J.title,onChange:nt=>fe({...J,title:nt.target.value}),onKeyDown:We,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:nt=>fe({...J,description:nt.target.value}),rows:2}),t.jsxs("select",{value:J.status,onChange:nt=>fe({...J,status:nt.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:me,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Zn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Xe.features?.map(nt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":nt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>en(nt.id),title:re===nt.id?"Collapse details":"Expand to show run history",children:re===nt.id?t.jsx(mn,{size:14}):t.jsx(In,{size:14})}),t.jsx(id,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:nt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:zo[nt.status].bg,color:zo[nt.status].text},children:nt.status}),nt.loopState&&nt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${nt.loopState}`,title:`Loop state: ${nt.loopState}`,children:[nt.loopState==="implementing"&&"⏳",nt.loopState==="validating"&&"🔄",nt.loopState==="needs_fix"&&"🔧",nt.loopState==="passed"&&"✅",nt.loopState==="blocked"&&"🚫"]}),nt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ys(nt.generatedFromFeatureId),title:`Generated from feature: ${nt.generatedFromFeatureId}`,children:"🔗 Fix"}),(nt.loopState==="validating"||nt.loopState==="needs_fix")&&(()=>{const At=je.get(nt.id),bn=mo.get(nt.id),ri=At?.implementationAttemptCount??bn?.implementationAttempt??nt.implementationAttemptCount??0,Yi=At?.retryBudgetRemaining??Math.max(0,_R-ri);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ri," · ",Yi," ",Yi===1?"retry":"retries"," left"]})})(),nt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>zi(nt.id),title:"Validate feature",disabled:on.has(nt.id),children:on.has(nt.id)?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(vs,{size:14})}),nt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(nt.taskId),title:"Click to view task",children:nt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[nt.status==="defined"&&!nt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hn(nt.id),title:"Triage — create task",disabled:E||pt===nt.id,children:pt===nt.id?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(is,{size:14})}),nt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>un(nt.id),title:"Unlink task",children:t.jsx(Eu,{size:14})}):nt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ue(nt.id),title:"Link to task",children:t.jsx($a,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>it(nt),title:"Edit feature",children:t.jsx(js,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"feature",id:nt.id}),title:"Delete feature",children:t.jsx(Sn,{size:14})})]})]}),nt.description&&t.jsx("p",{className:"mission-feature__description",children:nt.description}),nt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",nt.acceptanceCriteria]}),ze?.featureId===nt.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:ze.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:qn,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ls,disabled:E,children:"Cancel"})]})]}),Z===nt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Y.title,onChange:At=>ae({...Y,title:At.target.value}),onKeyDown:xt,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:At=>ae({...Y,description:At.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Y.acceptanceCriteria,onChange:At=>ae({...Y,acceptanceCriteria:At.target.value}),rows:2}),t.jsxs("select",{value:Y.status,onChange:At=>ae({...Y,status:At.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:Nt,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),re===nt.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"})}),(Se.get(nt.id)??[]).map(At=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Qs(At.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${At.status}`,title:At.status,children:At.status}),t.jsx("span",{className:"mission-run__time",children:new Date(At.startedAt).toLocaleString()}),At.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(At.completedAt).getTime()-new Date(At.startedAt).getTime())/1e3),"s"]}),At.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:At.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ie===At.id?"Hide details":"Show details",children:Ie===At.id?t.jsx(mn,{size:12}):t.jsx(In,{size:12})})]}),Ie===At.id&&Ne.get(At.id)&&t.jsxs("div",{className:"mission-run__details",children:[At.summary&&t.jsx("p",{className:"mission-run__summary",children:At.summary}),At.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",At.blockedReason]}),Ne.get(At.id)?.failures&&Ne.get(At.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Ne.get(At.id).failures.map(bn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:bn.message}),bn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",bn.expected]}),bn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",bn.actual]})]},bn.id))]}),(!Ne.get(At.id)?.failures||Ne.get(At.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},At.id)),(!Se.get(nt.id)||Se.get(nt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},nt.id)),ce&&Re===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:Y.title,onChange:nt=>ae({...Y,title:nt.target.value}),onKeyDown:xt,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:nt=>ae({...Y,description:nt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:Y.acceptanceCriteria,onChange:nt=>ae({...Y,acceptanceCriteria:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Nt,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:St,children:"Cancel"})]})]}),!ce&&(!Xe.features||Xe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(id,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Xe.id)),K.slices.length===0&&!de&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(md,{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"}),Ke&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:an.bg,color:an.text},children:Gh(Ke.state)}),Ke&&Ke.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ke.passedAssertions??0} of ${Ke.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ke.passedAssertions??0)/Ke.totalAssertions*100}%`,backgroundColor:(Ke.passedAssertions??0)===Ke.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{et(!0),at(null),Oe({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Nn,{size:14})})]}),Be&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:rt.title,onChange:Xe=>Oe({...rt,title:Xe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:rt.assertion,onChange:Xe=>Oe({...rt,assertion:Xe.target.value}),rows:2}),t.jsxs("select",{value:rt.status,onChange:Xe=>Oe({...rt,status:Xe.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:()=>cs(K.id),disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Vn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(pe.get(K.id))?pe.get(K.id):[]).map(Xe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Xe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:st===Xe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:rt.title,onChange:nt=>Oe({...rt,title:nt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:rt.assertion,onChange:nt=>Oe({...rt,assertion:nt.target.value}),rows:2}),t.jsxs("select",{value:rt.status,onChange:nt=>Oe({...rt,status:nt.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>ms(Xe.id,K.id),disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Vn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Uo[Xe.status]??Uo.pending).bg,color:(Uo[Xe.status]??Uo.pending).text},children:Xe.status}),t.jsx("span",{className:"mission-assertion__title",children:Xe.title}),(()=>{const At=vt.get(Xe.id)?.length??0;return At>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${At} linked feature${At!==1?"s":""}`,children:["(",At," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>hs(Xe.id),title:"Toggle details",children:jt===Xe.id?t.jsx(mn,{size:14}):t.jsx(In,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Wn(Xe),title:"Edit assertion",children:t.jsx(js,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"assertion",id:Xe.id}),title:"Delete assertion",children:t.jsx(Sn,{size:14})})]})}),jt===Xe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Xe.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()=>{jt!==Xe.id&&await hs(Xe.id),Xt(_t===Xe.id?null:Xe.id)},title:"Link a feature",children:[t.jsx($a,{size:12}),"Link Feature"]})]}),_t===Xe.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const nt=new Set((vt.get(Xe.id)??[]).map(bn=>bn.id)),At=[];return g?.milestones.forEach(bn=>bn.slices.forEach(ri=>At.push(...ri.features.filter(Yi=>!nt.has(Yi.id))))),At.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):At.map(bn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Rs(bn.id,Xe.id),disabled:bt.has(Xe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:bn.title}),bt.has(Xe.id)&&t.jsx(ft,{size:12,className:"spinner"})]},bn.id))})()})}),(()=>{const nt=vt.get(Xe.id)??[];return nt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):nt.map(At=>{const bn=`${At.id}-${Xe.id}`,ri=qt.has(bn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:At.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ts(At.id,Xe.id),disabled:ri,title:"Unlink feature",children:ri?t.jsx(ft,{size:12,className:"spinner"}):t.jsx(Eu,{size:12})})]},At.id)})})()]})]})]},Xe.id)),(!pe.get(K.id)||pe.get(K.id)?.length===0)&&!Be&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},K.id)}),g&&!I&&q===null&&t.jsxs("button",{className:"mission-add-btn",onClick:Ve,children:[t.jsx(Nn,{size:16}),"Add Milestone"]}),I&&q===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:U.title,onChange:K=>k({...U,title:K.target.value}),onKeyDown:Q,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:K=>k({...U,description:K.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ct,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:mt,children:"Cancel"})]})]}),g.milestones.length===0&&!I&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(oa,{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:ue,onChange:K=>dt(K.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:[Bt.length," of ",Qt]})]}),!ye&&ps&&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:xa,"data-testid":"mission-activity-load-more",children:"Load more"})}),ye?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(ft,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Bt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(qs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:ot,className:"mission-events","data-testid":"mission-activity-events",children:[Bt.map(K=>{const Ce=!!(K.metadata&&Object.keys(K.metadata).length>0),Ke=wt.has(K.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${$R(K.eventType)}`,children:DR(K.eventType)}),t.jsx("span",{className:"mission-event__time",children:bl(K.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:K.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(K.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Vl(K.id),"data-testid":`mission-event-metadata-${K.id}`,children:[Ke?"Hide":"Show"," metadata"]}),Ke&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(K.metadata,null,2)})]})]},K.id)}),t.jsx("div",{ref:yt})]})]})]}):null,Xs=()=>f.map(K=>{const Ce=K,Ke=g?.id===Ce.id,Pt=gr[Ce.status]||{bg:"",text:""},vn=Ce.summary,an=kt.get(Ce.id),zn=RR(an),Xe=!!(vn&&(vn.totalMilestones>0||vn.totalFeatures>0)),nt=an?.totalTasks??0,At=an?.tasksCompleted??0,bn=an?.tasksFailed??0,ri=an?.estimatedCompletionPercent??vn?.progressPercent??0,Yi=Xe||nt>0||bn>0||!!an?.lastActivityAt,gs=Ce.status==="active"&&(an?.currentMilestoneId||an?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${Ke?"mission-list__item--selected":""}`,onClick:()=>co(K),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(Es,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),K.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(is,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${zn}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${zn}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Pt.bg,color:Pt.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),gs&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",gs]}),Yi&&t.jsxs("div",{className:"mission-list__item-summary",children:[Xe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[vn.completedMilestones,"/",vn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[vn.completedFeatures,"/",vn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[At,"/",nt," tasks"]}),bn>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Jn=>{Jn.stopPropagation(),co(K)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[bn," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",bl(an?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${zn}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${ri}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Jn=>Jn.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>sr(Ce.id),title:"Stop mission",children:t.jsx(Bs,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>nr(Ce.id),title:"Resume mission",children:t.jsx(Yn,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ir(Ce.id),title:"Start mission",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ws(K),title:"Edit mission",children:t.jsx(js,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"mission",id:Ce.id}),title:"Delete mission",children:t.jsx(Sn,{size:14})})]})]},Ce.id)}),ho=({hideBottomButtons:K=!1}={})=>t.jsxs("div",{className:"mission-list",children:[A&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Ce=>M({...T,title:Ce.target.value}),onKeyDown:va,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Ce=>M({...T,description:Ce.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Bn,children:"Cancel"})]})]}),Xs(),S&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Ce=>M({...T,title:Ce.target.value}),onKeyDown:va,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Ce=>M({...T,description:Ce.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:Ce=>M({...T,status:Ce.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:T.autopilotEnabled,onChange:Ce=>M({...T,autopilotEnabled:Ce.target.checked})}),t.jsx(is,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:E,children:[E?t.jsx(ft,{size:14,className:"spinner"}):t.jsx(ns,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Bn,children:"Cancel"})]})]}),f.length===0&&!A&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(Es,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!A&&t.jsxs("div",{className:"mission-list__footer",children:[ie.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(zs,{size:16}),t.jsx("span",{children:ie.length===1?`Resume "${ie[0].title}"?`:`${ie.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:ie.map(Ce=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{ne(Ce.id),Ee(!0),se([])},children:[Ce.status==="error"?t.jsx(os,{size:14}):t.jsx(vs,{size:14}),Ce.status==="error"?"Retry":"Resume"]},Ce.id))})]}),!K&&t.jsxs("div",{className:"mission-list__footer-actions",children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Ee(!0),children:[t.jsx(vs,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:Ps,children:[t.jsx(Nn,{size:16}),"New Mission"]})]})]})]}),rr=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",le?.type,"? This cannot be undone."]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{le&&(le.type==="mission"?await V(le.id):le.type==="milestone"?await Rt(le.id):le.type==="slice"?await He(le.id):le.type==="feature"&&await Mn(le.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Te(null),children:"Cancel"})]})]})}),po=()=>t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:Ge,onChange:K=>qe(K.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(K=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>qe(K.id),children:[K.id,": ",K.title||"Untitled"]},K.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:nn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Ue(null),qe("")},children:"Cancel"})]})]})}),fo=t.jsxs("div",{ref:Gt,className:`mission-manager mission-manager--desktop${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:[g&&t.jsx("button",{className:"mission-manager__back-btn",onClick:uo,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(kl,{size:18})}),t.jsx(Es,{size:18,className:"mission-manager__header-icon"}),t.jsxs("h2",{className:"mission-manager__title","data-testid":"mission-header-title",children:[t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--desktop",children:"Missions"}),t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--mobile",children:g?g.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(tn,{size:18})})]}),C?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ft,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ft,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ds():ho(),le&&rr(),ke&&po()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",children:[t.jsxs("div",{className:"mission-manager__sidebar-header",children:[t.jsx("span",{className:"mission-manager__sidebar-title",children:"Missions"}),t.jsxs("div",{className:"mission-manager__sidebar-actions",children:[t.jsx("button",{className:"mission-add-btn mission-add-btn--sm",onClick:()=>Ee(!0),title:"Plan with AI","aria-label":"Plan with AI",children:t.jsx(vs,{size:14})}),t.jsx("button",{className:"mission-add-btn mission-add-btn--sm",onClick:Ps,title:"New Mission","aria-label":"New Mission",children:t.jsx(Nn,{size:14})})]})]}),t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ft,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):ho({hideBottomButtons:!0})})]}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(ft,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ds():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(Es,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),le&&rr(),ke&&po()]})]})]}),go=t.jsx(jR,{isOpen:Ae,onClose:()=>Ee(!1),onMissionCreated:()=>{Wt(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:Fe}),bo=Qe?t.jsx(CR,{isOpen:!0,onClose:()=>ge(null),onApplied:()=>{ge(null),g&&Mt(g.id)},targetType:Qe.type,targetId:Qe.id,targetTitle:Qe.title,missionContext:g?.title,projectId:r,resumeSessionId:Qe.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[fo,go,bo]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:K=>K.target===K.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:fo}),go,bo]})}const Bo=2e3;function Yh({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,x]=i.useState(!1),[v,b]=i.useState(null),y=d.trim()!==""&&f.trim().length>0&&f.length<=Bo,j=i.useCallback(async()=>{if(!(!y||g)){x(!0),b(null);try{const A=m==="agent"?"user-to-agent":"system";await VN({toId:d.trim(),toType:m,content:f.trim(),type:A,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},a),r()}catch(A){const N=Me(A)||"Failed to send message";b(N),l?.(N,"error")}finally{x(!1)}}},[y,g,d,m,f,n,a,r,l]),C=i.useCallback(A=>{u(A),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(tn,{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:d,onChange:A=>C(A.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(A=>t.jsx("option",{value:A.id,children:A.name||A.id},A.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Tn,{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:f,onChange:A=>p(A.target.value),maxLength:Bo,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>Bo?"over-limit":"",children:[f.length,"/",Bo]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(zs,{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:j,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(sa,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function Ea(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/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 zR(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const a=s?.get(e)?.trim();return a?a===e?`Agent: ${e}`:`Agent: ${a} (${e})`:`Agent: ${e}`}return"System"}function FR(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 Qh(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function UR(e){const n=new Map;for(const s of e){const a=`${s.fromType}:${s.fromId}`,r=n.get(a);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(a,{key:a,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,a)=>new Date(a.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function BR({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[x,v]=i.useState([]),[b,y]=i.useState(!1),[j,C]=i.useState(null),[A,N]=i.useState(null),[S,_]=i.useState(null),[T,M]=i.useState("inbox"),[E,O]=i.useState(null),[B,R]=i.useState([]),P=i.useMemo(()=>new Map(B.map(te=>[te.id,te.name??""])),[B]),F=i.useCallback((te,Re)=>zR(te,Re,P),[P]),ee=Di()==="mobile",U=!ee,k=i.useCallback(async()=>{f(!0);try{const te=await HN({limit:50},e);l(te),m(te.unreadCount),s?.(te.unreadCount)}catch{}finally{f(!1)}},[e,s]),I=i.useCallback(async()=>{f(!0);try{const te=await qN({limit:50},e);d(te)}catch{}finally{f(!1)}},[e]),$=i.useCallback(async te=>{f(!0);try{const Re=await YN(te,e);O(Re)}catch{}finally{f(!1)}},[e]),w=i.useCallback(async()=>{try{const te=await fa(void 0,e);R(te)}catch{}},[e]),H=i.useCallback(async()=>{try{const te=await Nf(e);m(te.unreadCount),s?.(te.unreadCount)}catch{}},[e,s]);i.useEffect(()=>{a==="inbox"?k():a==="outbox"?I():a==="agents"&&w()},[a,k,I,w]),i.useEffect(()=>{S&&$(S)},[S,$]),i.useEffect(()=>{H()},[H]),i.useEffect(()=>{w()},[w]),i.useEffect(()=>{if(typeof EventSource>"u")return;const te=e?`?projectId=${encodeURIComponent(e)}`:"",Re=()=>{H(),a==="inbox"?k():a==="outbox"&&I(),S&&$(S)};return fi(`/api/events${te}`,{events:{"message:sent":Re,"message:received":Re,"message:read":Re,"message:deleted":Re}})},[e,a,S,H,k,I,$]);const J=i.useCallback(async te=>{if(g(te),!te.read)try{const Re=await WN(te.id,e);Re&&l(ke=>ke&&{...ke,messages:ke.messages.map(Ue=>Ue.id===Re.id?Re:Ue),unreadCount:Math.max(0,ke.unreadCount-1)});const be=Math.max(0,u-1);m(be),s?.(be)}catch{}try{const Re=await JN(te.fromId,te.fromType,e);v(Re)}catch{v([te])}},[e,u,s]),fe=i.useCallback(()=>{g(null),v([])},[]),de=i.useCallback(async()=>{try{const te=await KN(e);m(0),s?.(0),l(Re=>Re&&{...Re,messages:Re.messages.map(be=>({...be,read:!0})),unreadCount:0}),n?.(`Marked ${te.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),D=i.useCallback(async te=>{try{await GN(te,e),g(null),v([]),a==="inbox"?k():a==="outbox"?I():S&&$(S),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,S,k,I,$,n]),_e=i.useCallback(te=>{C({id:te.fromId,type:te.fromType}),N({messageId:te.id,preview:Qh(te.content,120)}),y(!0)},[]),z=i.useCallback(()=>{y(!1),C(null),N(null),n?.("Message sent","success"),a==="outbox"?I():a==="agents"&&S&&$(S),H()},[a,I,S,$,n,H]),Z=i.useCallback(()=>{C(a==="agents"&&S?{id:S,type:"agent"}:null),N(null),y(!0)},[a,S]),oe=i.useCallback(()=>{y(!1),C(null),N(null)},[]),Y=()=>!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:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:fe,"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:FR(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Ea(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>_e(p),"data-testid":"mailbox-reply",children:[t.jsx(Ri,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>D(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(Tn,{size:14}):t.jsx(ya,{size:14}),F(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(Tn,{size:14}):t.jsx(ya,{size:14}),F(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(te=>{const Re=te.metadata?.replyTo?.messageId,be=Re?x.find(ke=>ke.id===Re):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${te.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:F(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Ea(te.createdAt)})]}),Re&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${te.id}`,children:["↪ Replying to ",be?Qh(be.content,60):`message ${Re}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:te.content})]},te.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})]})]}),ae=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Bc,{}),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:UR(o.messages).map(te=>t.jsxs("div",{className:`mailbox-conversation-group ${te.unreadCount>0?"unread":""}`,onClick:()=>J(te.latestMessage),"data-testid":`mailbox-conversation-${te.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(Tn,{size:16}):t.jsx(ya,{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:F(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Ea(te.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.latestMessage.content.slice(0,80),te.latestMessage.content.length>80?"…":""]})]}),te.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${te.key}`,children:te.unreadCount>9?"9+":te.unreadCount})]},te.key))})]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Bc,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(sa,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>J(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(Tn,{size:16}):t.jsx(ya,{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: ",F(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Ea(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:B.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Tn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:S??"",onChange:te=>{_(te.target.value||null),M("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),B.map(te=>t.jsx("option",{value:te.id,children:te.name||te.id},te.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Z,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ri,{size:14}),t.jsx("span",{children:"Compose"})]})]}),S&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${T==="inbox"?"active":""}`,onClick:()=>M("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Sr,{size:12}),t.jsx("span",{children:"Inbox"}),E&&E.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:E.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${T==="outbox"?"active":""}`,onClick:()=>M("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(sa,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!S&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Tn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),S&&h&&!E&&t.jsx(Bc,{}),S&&E&&T==="inbox"&&E.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"})]}),S&&E&&T==="outbox"&&E.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(sa,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),S&&E&&T==="inbox"&&E.inbox.map(te=>t.jsxs("div",{className:`mailbox-item ${te.read?"":"unread"}`,onClick:()=>J(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(Tn,{size:16}):t.jsx(ya,{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:F(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Ea(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id)),S&&E&&T==="outbox"&&E.outbox.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>J(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(Tn,{size:16}):t.jsx(ya,{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: ",F(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Ea(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]})]})})]}),ce=()=>b?t.jsx(Yh,{recipient:j,replyContext:A,agents:B,projectId:e,onSend:z,onCancel:oe,addToast:n}):p?Y():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(la,{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(la,{size:18}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Z,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ri,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:de,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(dx,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?k():a==="outbox"?I():S&&$(S)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Sr,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(sa,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Tn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:U?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:ae()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:ce()})]}):t.jsxs(t.Fragment,{children:[Y(),b&&t.jsx(Yh,{recipient:j,replyContext:A,agents:B,projectId:e,onSend:z,onCancel:oe,addToast:n}),!p&&!b&&ae()]})})]})}function Bc(){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))})}const HR=640;function qR({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Ci(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[x,v]=i.useState([]),[b,y]=i.useState(null),[j,C]=i.useState([]),[A,N]=i.useState(null),[S,_]=i.useState(null),[T,M]=i.useState(!1),[E,O]=i.useState([]),[B,R]=i.useState(!1),[P,F]=i.useState(""),q=i.useRef(!1),ee=i.useRef(null);Si(ee,e,"fusion:github-modal-size");const U=Li(n),[k,I]=i.useState(!1),[$,w]=i.useState("list"),H=i.useRef(null),J=new Set;for(const ge of a){const ze=ge.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);ze&&J.add(ze[1]);const tt=ge.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);tt&&J.add(tt[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),y(null),C([]),N(null),g("issues"),_(null),M(!1),O([]),R(!0),F(""),H.current=null,q.current=!0,Qw().then(ge=>{if(q.current)if(O(ge),R(!1),ge.length===1){const ze=ge[0];l(ze.owner),d(ze.repo),F(ze.name)}else ge.length>1&&(l(""),d(""),F(""))}).catch(()=>{q.current&&R(!1)}),()=>{q.current=!1}},[e]);const fe=i.useCallback(ge=>{if(F(ge),ge==="")l(""),d("");else{const ze=E.find(tt=>tt.name===ge);ze&&(l(ze.owner),d(ze.repo))}},[E]),de=i.useCallback(async()=>{if(!o.trim()||!c.trim()){_("Repository must be selected");return}f(!0),_(null),v([]),y(null);try{const ge=u.split(",").map(tt=>tt.trim()).filter(Boolean),ze=await Kw(o.trim(),c.trim(),30,ge.length>0?ge:void 0);v(ze),ze.length===0&&_("No open issues found")}catch(ge){_(Me(ge)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),D=i.useCallback(async()=>{if(!o.trim()||!c.trim()){_("Repository must be selected");return}f(!0),_(null),C([]),N(null);try{const ge=await Jw(o.trim(),c.trim(),30);C(ge),ge.length===0&&_("No open pull requests found")}catch(ge){_(Me(ge)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||T)return;const ge={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};H.current?.owner===ge.owner&&H.current?.repo===ge.repo&&H.current?.labels===ge.labels&&H.current?.tab===ge.tab||(H.current=ge,p==="issues"?de():D())},[o,c,u,p,e,h,T,de,D]),i.useEffect(()=>{if(!e)return;const ge=ze=>{ze.key==="Escape"&&n()};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[e,n]),i.useEffect(()=>{if(!e)return;const ge=()=>{I(window.innerWidth<=HR)};return ge(),window.addEventListener("resize",ge),()=>window.removeEventListener("resize",ge)},[e]);const _e=i.useCallback(ge=>{y(ge),k&&w("preview")},[k]),z=i.useCallback(ge=>{N(ge),k&&w("preview")},[k]),Z=i.useCallback(()=>{w("list")},[]),oe=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;M(!0),_(null);try{const ge=await Gw(o.trim(),c.trim(),b,r);s(ge),y(null),k&&$==="preview"&&w("list")}catch(ge){const ze=Me(ge);ze?.includes("already imported")?_(ze):_(ze||"Failed to import issue")}finally{M(!1)}}else{if(A===null)return;M(!0),_(null);try{const ge=await Yw(o.trim(),c.trim(),A,r);s(ge),N(null),k&&$==="preview"&&w("list")}catch(ge){const ze=Me(ge);ze?.includes("already imported")?_(ze):_(ze||"Failed to import pull request")}finally{M(!1)}}},[p,b,A,o,c,s,k,$]),Y=x.find(ge=>ge.number===b),ae=j.find(ge=>ge.number===A);if(!e)return null;const ce=E.length>0,te=E.length===1,Re=x.filter(ge=>J.has(ge.html_url)).length,be=j.filter(ge=>J.has(ge.html_url)).length,ke=S==="No open issues found",Ue=S==="No open pull requests found",Ge=p==="issues"?ke:Ue,qe=!!S&&!ke&&x.length===0&&!h,Ae=!!S&&!Ue&&j.length===0&&!h,Ee=p==="issues"?qe:Ae,ie=h||x.length>0||ke||qe,se=h||j.length>0||Ue||Ae,xe=p==="issues"?ie:se,ne=!!S&&x.length>0&&!ke,Fe=!!S&&j.length>0&&!Ue,Qe=p==="issues"?ne:Fe;return t.jsx("div",{className:"modal-overlay open",...U,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:ee,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:()=>{g("issues"),N(null)},disabled:h||T,children:[t.jsx(jl,{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:()=>{g("pulls"),y(null)},disabled:h||T,children:[t.jsx(Hs,{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:B?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(ft,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):ce?te?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:E[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[E[0].owner,"/",E[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:P,onChange:ge=>fe(ge.target.value),disabled:h||T,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),E.map(ge=>t.jsxs("option",{value:ge.name,children:[ge.name," (",ge.owner,"/",ge.repo,")"]},ge.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:u,onChange:ge=>m(ge.target.value),onKeyDown:ge=>ge.key==="Enter"&&de(),disabled:h||T||!ce,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?de:D,disabled:h||T||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!B&&!ce&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Qe&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:S}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${k?"mobile":""} ${$==="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:[Re," imported"]})]}),p==="pulls"&&j.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[j.length," pull request",j.length===1?"":"s"]}),t.jsxs("span",{children:[be," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!xe&&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(ft,{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."})]})]}),Ee&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:S})]})}),Ge&&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(ge=>{const ze=J.has(ge.html_url);return t.jsxs("div",{className:`issue-item ${b===ge.number?"selected":""} ${ze?"imported":""}`,onClick:()=>!ze&&_e(ge.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===ge.number,onChange:()=>_e(ge.number),disabled:ze,"aria-label":`Select issue #${ge.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ge.number]}),t.jsx("span",{className:"issue-title",children:ge.title})]}),ge.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ge.labels.map(tt=>t.jsx("span",{className:"label-chip",children:tt.name},tt.name))})]}),ze&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ge.number)})}),p==="pulls"&&j.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:j.map(ge=>{const ze=J.has(ge.html_url);return t.jsxs("div",{className:`issue-item ${A===ge.number?"selected":""} ${ze?"imported":""}`,onClick:()=>!ze&&z(ge.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:A===ge.number,onChange:()=>z(ge.number),disabled:ze,"aria-label":`Select pull request #${ge.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ge.number]}),t.jsx("span",{className:"issue-title",children:ge.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ge.headBranch," → ",ge.baseBranch]})]}),ze&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ge.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${k?"mobile":""} ${$==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[k&&t.jsxs("button",{className:"github-import-back-button",onClick:Z,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(ha,{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"&&Y?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",Y.number]}),t.jsx("div",{className:"preview-title",children:Y.title}),t.jsx("div",{className:"preview-body",children:Y.body?Y.body.slice(0,200)+(Y.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"&&ae?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",ae.number]}),t.jsx("div",{className:"preview-title",children:ae.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",ae.headBranch," → ",ae.baseBranch]}),t.jsx("div",{className:"preview-body",children:ae.body?ae.body.slice(0,200)+(ae.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:T,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:oe,disabled:(p==="issues"?b===null:A===null)||T,children:T?t.jsx(ft,{size:14,className:"spin"}):"Import"})]})]})})}function ni({summary:e,children:n,className:s="",onToggle:a,defaultOpen:r=!1}){const[o,l]=i.useState(r);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const c=!o;l(c),a?.(c)},"aria-expanded":o,type:"button",children:[t.jsx(In,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),o?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const VR=30,WR=16,KR=16;function GR(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Xo=null;function lb(){return Xo===null&&(Xo=window.visualViewport?.height??window.innerHeight),Xo}function JR(e){const n=lb();e>n&&(Xo=e)}function YR(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function QR(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=YR(document.activeElement),s=e.offsetTop;n||JR(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0&&n)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=lb(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=VR&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=WR&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=KR?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Hl({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!GR()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const m=()=>{const h=QR();s(h.overlap),r(h.vvHeight),l(h.vvOffsetTop),d(h.open)};return m(),u.addEventListener("resize",m),u.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}const XR=["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 ZR(e,n){return e&&n?`${e}/${n}`:""}function eT(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 tT({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,x]=i.useState([]),[v,b]=i.useState([]),[y,j]=i.useState(null),C=i.useRef(!1),A=i.useRef(!1),[N,S]=i.useState(""),[_,T]=i.useState(!0),[M,E]=i.useState(!1),[O,B]=i.useState(!1),[R,P]=i.useState(null),[F,q]=i.useState(0),ee=i.useRef(null),U=i.useRef(null),k=i.useRef(null),I=i.useRef(null),$=i.useRef(null),w=i.useRef(null),H=i.useRef(null),[J,fe]=i.useState(c??null),de=i.useMemo(()=>ba(),[]),{isLockedByOther:D,takeControl:_e,isLoading:z}=Bl(e?J:null),{activeTabMap:Z,broadcastUpdate:oe,broadcastCompleted:Y,broadcastLock:ae,broadcastUnlock:ce,broadcastHeartbeat:te}=tr(),[Re,be]=i.useState(void 0),[ke,Ue]=i.useState(void 0),[Ge,qe]=i.useState("medium"),[Ae,Ee]=i.useState(""),[ie,se]=i.useState([]),[xe,ne]=i.useState(!1),[Fe,Qe]=i.useState(null),[ge,ze]=i.useState([]),[tt,pt]=i.useState([]),[ve,le]=i.useState({}),Te=i.useRef(null),[pe,$e]=i.useState([]),[st,at]=i.useState(!1),[rt,Oe]=i.useState(c??null),[Be,et]=i.useState(!!c),[jt,De]=i.useState(null),[vt,Et]=i.useState(!1),bt=i.useRef(!1),zt=i.useRef(null),qt=i.useRef(""),It=i.useRef(null),_t=i.useRef(null);Si(U,e,"fusion:planning-modal-size");const Xt=Di(),{keyboardOverlap:Lt,viewportHeight:Ut,viewportOffsetTop:cn,keyboardOpen:Jt}=Hl({enabled:Xt==="mobile"});Ci(Xt==="mobile"&&e);const Vt=Jt?{"--keyboard-overlap":`${Lt}px`,"--vv-offset-top":`${cn}px`,...Ut!==null?{"--vv-height":`${Ut}px`}:{}}:{};i.useEffect(()=>{qt.current=N},[N]),i.useEffect(()=>{const ue=zt.current;if(!ue)return;ue.scrollHeight-ue.scrollTop-ue.clientHeight<32&&(ue.scrollTop=ue.scrollHeight)},[N]),i.useEffect(()=>{if(m.type!=="loading"){P(null),q(0);return}const ue=Date.now();P(ue),q(0);const dt=setInterval(()=>{q(Math.max(0,Math.floor((Date.now()-ue)/1e3)))},1e3);return()=>clearInterval(dt)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const ue=I.current;if(!ue)return;let dt=!1;const gt=setInterval(async()=>{try{const ot=await wi(ue);if(dt||!ot||I.current!==ue)return;if(ot.status==="awaiting_input"&&ot.currentQuestion){const yt=JSON.parse(ot.currentQuestion);h({type:"question",session:{sessionId:ue,currentQuestion:yt,summary:null}}),S("")}else if(ot.status==="complete"&&ot.result){const yt=JSON.parse(ot.result);h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:yt},summary:yt}),j(yt),S("")}}catch{}},8e3);return()=>{dt=!0,clearInterval(gt)}},[m.type]);const Kt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),j(null),S(""),E(!1),B(!1),be(void 0),Ue(void 0),qe("medium"),Ee(""),I.current=null,fe(null)},[]),rn=ZR(Re,ke),fn=i.useCallback((ue,dt)=>{if(!ue||!dt)return ve.provider&&ve.modelId?`${ve.provider}/${ve.modelId}`:"Using default";const wt=ie.find(gt=>gt.provider===ue&&gt.id===dt);return wt?`${wt.provider}/${wt.id}`:`${ue}/${dt}`},[ie,ve.modelId,ve.provider]),on=i.useCallback(async()=>{ne(!0),Qe(null);try{const ue=await Ds();se(ue.models),ze(ue.favoriteProviders),pt(ue.favoriteModels),le({provider:ue.resolvedPlanningProvider,modelId:ue.resolvedPlanningModelId})}catch(ue){Qe(Me(ue)||"Failed to load models")}finally{ne(!1)}},[]),gn=i.useCallback(ue=>{ze(dt=>{const wt=dt,ot=wt.includes(ue)?wt.filter(yt=>yt!==ue):[ue,...wt];return Pn({favoriteProviders:ot,favoriteModels:tt}).catch(()=>{ze(wt)}),ot})},[tt]),je=i.useCallback(ue=>{pt(dt=>{const wt=dt,ot=wt.includes(ue)?wt.filter(yt=>yt!==ue):[ue,...wt];return Pn({favoriteProviders:ge,favoriteModels:ot}).catch(()=>{pt(wt)}),ot})},[ge]),Le=i.useCallback(ue=>{k.current?.close();const dt=()=>I.current!==ue,wt=Xk(ue,l,{onThinking:gt=>{dt()||(S(ot=>ot+gt),oe({sessionId:ue,status:"generating",needsInput:!1,owningTabId:de,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:gt=>{if(dt())return;E(!1),B(!1),Ca(l);const ot=qt.current.trim();ot&&b(yt=>yt[yt.length-1]?.thinkingOutput===ot?yt:[...yt,{thinkingOutput:ot}]),h({type:"question",session:{sessionId:ue,currentQuestion:gt,summary:null}}),S(""),oe({sessionId:ue,status:"awaiting_input",needsInput:!0,owningTabId:de,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:gt=>{if(dt())return;E(!1),B(!1),Ca(l);const ot=qt.current.trim();ot&&b(yt=>yt[yt.length-1]?.thinkingOutput===ot?yt:[...yt,{thinkingOutput:ot}]),h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:gt},summary:gt}),j(gt),S(""),oe({sessionId:ue,status:"complete",needsInput:!1,owningTabId:de,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:gt=>{const ot=gt||"Session failed while contacting the AI.";E(!0),(async()=>{try{const yt=await wi(ue);if(yt&&(yt.status==="generating"||yt.status==="awaiting_input")){Le(ue);return}}catch{}E(!1),B(!1),p(null),h(yt=>yt.type==="question"||yt.type==="summary"||yt.type==="error"?{type:"error",session:yt.session,errorMessage:ot}:{type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:ot}),S(""),I.current=ue,oe({sessionId:ue,status:"error",needsInput:!1,owningTabId:de,type:"planning",title:d.trim()||void 0,projectId:l??null}),Y({sessionId:ue,status:"error"})})()},onComplete:()=>{E(!1),B(!1),I.current=null,Y({sessionId:ue,status:"complete"})},onConnectionStateChange:gt=>{E(gt==="reconnecting")}});k.current=wt},[Y,oe,d,l,de]),re=i.useCallback(async ue=>{const dt=ue??d;if(dt.trim()){p(null),S(""),b([]),x([]),E(!1),h({type:"loading"});try{const wt=Re&&ke?{planningModelProvider:Re,planningModelId:ke}:void 0,gt=Ae.trim()?Number.parseInt(Ae,10):void 0,ot=$.current,{sessionId:yt}=await Ik(dt.trim(),l,wt,{planningDepth:Ge,customQuestionCount:Number.isInteger(gt)?gt:void 0},ot??void 0);$.current=null,I.current=yt,fe(yt),Oe(yt),Le(yt),x([])}catch(wt){E(!1),p(Me(wt)||"Failed to start planning session"),h({type:"initial"}),I.current=null,fe(null)}}},[Le,Ae,d,Ge,ke,Re,l]);i.useEffect(()=>{e&&m.type==="initial"&&ee.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&on()},[e,on]),i.useEffect(()=>{if(e&&o&&!C.current&&m.type==="initial"){u(o);const ue=setTimeout(()=>{C.current=!0,re(o)},0);return()=>clearTimeout(ue)}else if(e&&!o&&!C.current&&!A.current&&m.type==="initial"){A.current=!0;const ue=rR(l);ue&&u(ue)}},[e,o,m.type,re,l]);const Pe=i.useCallback(async ue=>{k.current?.close(),k.current=null,p(null),S(""),x([]),b([]),j(null),B(!1),h({type:"loading"});try{const dt=await wi(ue);if(!dt){Oe(null),et(!1),h({type:"initial"});return}I.current=ue,fe(ue);const wt=Fa(dt.conversationHistory);if(b(wt),x(wt.map(gt=>gt.response).filter(gt=>!!(gt&&typeof gt=="object"&&!Array.isArray(gt)))),dt.status==="draft"){let gt="",ot,yt;try{const Ft=dt.inputPayload?JSON.parse(dt.inputPayload):null;Ft&&typeof Ft.initialPlan=="string"&&(gt=Ft.initialPlan),Ft&&typeof Ft.modelProvider=="string"&&typeof Ft.modelId=="string"&&(ot=Ft.modelProvider,yt=Ft.modelId)}catch{}u(gt),be(ot),Ue(yt),$.current=ue,_t.current=gt?{sessionId:ue,initialPlan:gt.trim(),modelProvider:ot,modelId:yt}:null,h({type:"initial"})}else if(dt.status==="awaiting_input"&&dt.currentQuestion){Ca(l);const gt=JSON.parse(dt.currentQuestion);if(h({type:"question",session:{sessionId:ue,currentQuestion:gt,summary:null}}),dt.thinkingOutput){const ot=dt.thinkingOutput.trim();ot&&b(yt=>yt[yt.length-1]?.thinkingOutput===ot?yt:[...yt,{thinkingOutput:ot}])}Le(ue)}else if(dt.status==="complete"&&dt.result){Ca(l);const gt=JSON.parse(dt.result);h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:gt},summary:gt}),j(gt)}else dt.status==="generating"?(h({type:"loading"}),dt.thinkingOutput&&S(dt.thinkingOutput),Le(ue)):dt.status==="error"&&h({type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:dt.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Le,l]);i.useEffect(()=>{!e||!c||I.current!==c&&H.current!==c&&(Oe(c),et(!0),Pe(c))},[e,c]),i.useEffect(()=>{e&&rt&&(c&&c===rt||Pe(rt))},[e]);const Se=i.useCallback(async()=>{at(!0);try{const dt=(await Jd(l,{includeCompleted:!0,includeArchived:vt})).filter(wt=>wt.type==="planning").sort((wt,gt)=>Date.parse(gt.updatedAt)-Date.parse(wt.updatedAt));$e(dt)}catch{}finally{at(!1)}},[l,vt]);i.useEffect(()=>{e&&Se()},[e,Se]);const X=i.useRef(!1);i.useEffect(()=>{const ue=X.current&&!st;X.current=st,ue&&Xt==="mobile"&&(Be||c||rt||pe.length>0||et(!0))},[Xt,Be,c,rt,st,pe.length]),i.useEffect(()=>{if(!e)return;const ue=l?`?projectId=${encodeURIComponent(l)}`:"",dt=gt=>{try{const ot=JSON.parse(gt.data);if(ot.type!=="planning")return;$e(yt=>{const Ft=yt.findIndex(Ln=>Ln.id===ot.id);return(Ft>=0?[...yt.slice(0,Ft),ot,...yt.slice(Ft+1)]:[ot,...yt]).sort((Ln,Wt)=>Date.parse(Wt.updatedAt)-Date.parse(Ln.updatedAt))})}catch{}},wt=gt=>{try{const ot=JSON.parse(gt.data);$e(yt=>yt.filter(Ft=>Ft.id!==ot))}catch{}};return fi(`/api/events${ue}`,{events:{"ai_session:updated":dt,"ai_session:deleted":wt},onReconnect:()=>{Se()}})},[e,l,Se]);const Ie=i.useCallback(ue=>{if(rt===ue){et(!0);return}Oe(ue),et(!0),Pe(ue)},[Pe,rt]),he=i.useCallback(()=>{k.current?.close(),k.current=null,$.current=null,w.current&&(clearTimeout(w.current),w.current=null),c&&(H.current=c),Kt(),Oe(null),et(!0)},[Kt,c]),Ne=i.useCallback(()=>{et(!1)},[]),Je=i.useCallback(async(ue,dt)=>{const wt=dt.trim();if(!(!wt||_t.current?.sessionId===ue&&_t.current.initialPlan===wt&&_t.current.modelProvider===Re&&_t.current.modelId===ke))try{await UN(ue,{initialPlan:wt,modelProvider:Re&&ke?Re:void 0,modelId:Re&&ke?ke:void 0},l),_t.current={sessionId:ue,initialPlan:wt,modelProvider:Re,modelId:ke}}catch{}},[ke,Re,l]);i.useEffect(()=>{if(It.current&&(clearTimeout(It.current),It.current=null),!(!e||m.type!=="initial"||!rt))return It.current=setTimeout(()=>{Je(rt,d)},500),()=>{It.current&&(clearTimeout(It.current),It.current=null)}},[d,e,rt,Je,m.type]),i.useEffect(()=>{_t.current=null},[rt]),i.useEffect(()=>()=>{It.current&&(clearTimeout(It.current),It.current=null)},[]);const kt=i.useCallback(async ue=>{const dt=gt=>gt==="generating"||gt==="awaiting_input",wt=pe.find(gt=>gt.id===ue);if(wt&&dt(wt.status))try{await ff(ue,l,de)}catch{}try{await jf(ue)}catch{}Y({sessionId:ue,status:"complete",timestamp:Date.now()}),$e(gt=>gt.filter(ot=>ot.id!==ue)),rt===ue&&(k.current?.close(),k.current=null,Kt(),Oe(null),et(!1)),De(null)},[Y,pe,l,Kt,rt,de]),Yt=i.useCallback(async ue=>{const wt=pe.find(gt=>gt.id===ue)?.archived===!0;try{wt?await DN(ue):await $N(ue)}catch{return}$e(gt=>!wt&&!vt?gt.filter(ot=>ot.id!==ue):gt.map(ot=>ot.id===ue?{...ot,archived:!wt}:ot)),!wt&&rt===ue&&!vt&&(k.current?.close(),k.current=null,Kt(),Oe(null),et(!1))},[pe,Kt,rt,et,vt]);i.useEffect(()=>{e||(C.current=!1,A.current=!1,E(!1),B(!1),fe(null))},[e]),i.useEffect(()=>{if(!e){Te.current&&(ce(Te.current,de),Te.current=null);return}if(J&&Te.current!==J){Te.current&&ce(Te.current,de),ae(J,de),Te.current=J;return}!J&&Te.current&&(ce(Te.current,de),Te.current=null)},[ae,ce,e,J,de]),i.useEffect(()=>{if(!e||!J||Te.current!==J)return;te(de);const ue=setInterval(()=>{te(de)},3e4);return()=>{clearInterval(ue)}},[te,e,J,de]),i.useEffect(()=>()=>{w.current&&(clearTimeout(w.current),w.current=null),k.current?.close(),k.current=null,Te.current&&(ce(Te.current,de),Te.current=null)},[ce,de]),i.useEffect(()=>{if(!e)return;const ue=()=>{k.current?.close(),k.current=null};return window.addEventListener("beforeunload",ue),()=>window.removeEventListener("beforeunload",ue)},[e]);const $t=i.useCallback((ue,dt)=>{It.current&&(clearTimeout(It.current),It.current=null),(async()=>{try{await Je(ue,dt),await BN(ue,l)}catch{}})()},[l,Je]),Tt=i.useCallback(()=>{d&&m.type==="initial"&&aR(d,l);const ue=$.current;ue&&d.trim()&&$t(ue,d),$.current=null,w.current&&(clearTimeout(w.current),w.current=null),k.current?.close(),k.current=null,E(!1),B(!1),n()},[$t,d,n,l,m.type]);i.useEffect(()=>{if(!e)return;const ue=dt=>{dt.key==="Escape"&&Tt()};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[e,Tt]);const Bt=i.useCallback(async ue=>{if(m.type!=="question")return;const{session:dt}=m,wt=dt.sessionId,gt=dt.currentQuestion;if(!gt){p("No active question in session");return}p(null),x(ot=>[...ot,ue]),b(ot=>{const yt=qt.current.trim();let Ft=ot;return yt&&Ft[Ft.length-1]?.thinkingOutput!==yt&&(Ft=[...Ft,{thinkingOutput:yt}]),[...Ft,{question:gt,response:ue}]}),h({type:"loading"}),S("");try{await $k(wt,ue,l,de)}catch(ot){p(Me(ot)||"Failed to submit response"),h({type:"question",session:dt})}},[l,de,m]),jn=i.useCallback(async()=>{const ue=I.current;if(ue){try{await Lk(ue,l,de)}catch{}k.current?.close(),k.current=null,E(!1),B(!1),h({type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),S("")}},[l,de]),Dn=i.useCallback(async()=>{if(m.type!=="error")return;const ue=m.session;p(null),B(!0),S(""),h({type:"loading"}),Le(ue.sessionId);try{I.current=ue.sessionId,fe(ue.sessionId),await Dk(ue.sessionId,l,de)}catch(dt){let wt=dt;if((Me(dt)||"").includes("not in an error state"))try{const ot=await wi(ue.sessionId);if(!ot)throw new Error("Failed to refresh planning session.");if(I.current=ot.id,fe(ot.id),ot.status==="generating")S(ot.thinkingOutput??""),h({type:"loading"});else if(ot.status==="awaiting_input"){if(!ot.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const yt=JSON.parse(ot.currentQuestion);if(Ca(l),h({type:"question",session:{sessionId:ot.id,currentQuestion:yt,summary:null}}),ot.thinkingOutput){const Ft=ot.thinkingOutput.trim();Ft&&b(Zt=>Zt[Zt.length-1]?.thinkingOutput===Ft?Zt:[...Zt,{thinkingOutput:Ft}])}k.current?.isConnected()||Le(ot.id)}else if(ot.status==="complete"){if(!ot.result)throw new Error("Planning session is complete but has no result.");const yt=JSON.parse(ot.result);Ca(l),h({type:"summary",session:{sessionId:ot.id,currentQuestion:null,summary:yt},summary:yt}),j(yt)}else ot.status==="error"&&h({type:"error",session:{sessionId:ot.id,currentQuestion:null,summary:null},errorMessage:ot.error||"Retry failed. Please try again."});E(!1);return}catch(ot){wt=ot}k.current?.close(),k.current=null,h({type:"error",session:ue,errorMessage:Me(wt)||"Retry failed. Please try again."}),E(!1)}finally{B(!1)}},[Le,l,de,m]),hn=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ue=m.session.sessionId,dt=await Ok(ue,y??void 0,l);s(dt),Oe(null),$e(wt=>wt.filter(gt=>gt.id!==ue)),Y({sessionId:ue,status:"complete",timestamp:Date.now()}),Tt()}catch(ue){p(Me(ue)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[Y,y,m,l,s,Tt]),Ht=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ue=await zk(m.session.sessionId,y??void 0,l);fe(ue.sessionId),h({type:"breakdown",sessionId:ue.sessionId,subtasks:ue.subtasks,dirty:!1})}catch(ue){p(Me(ue)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),yn=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const ue=m.sessionId,dt=await Fk(ue,m.subtasks,l);a(dt.tasks),$e(wt=>wt.filter(gt=>gt.id!==ue)),Y({sessionId:ue,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),j(null),S(""),be(void 0),Ue(void 0),qe("medium"),Ee(""),I.current=null,fe(null),Oe(null),n()}catch(ue){p(Me(ue)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[Y,m,a,n,l]),pn=i.useCallback(()=>{if(m.type==="question"&&g.length>0){const ue=g.slice(0,-1);x(ue),h({type:"question",session:m.session})}},[m,g]),es=()=>m.type==="question"?Math.min(g.length+1,3):3,ye=J?Z.get(J):null,ut=ye&&ye.tabId!==de,Qt=!!(ut&&!ye.stale),Cn=D&&(!ut||ye.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:ue=>{bt.current=ue.target===ue.currentTarget},onClick:ue=>{ue.target===ue.currentTarget&&bt.current&&Tt(),bt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:U,style:Vt,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Be&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Ne,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(kl,{size:18})}),t.jsx(pi,{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:Tt,"aria-label":"Close",children:t.jsx(tn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Be?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(rT,{sessions:pe,loading:st,selectedSessionId:rt,pendingDeleteId:jt,showArchived:vt,onToggleShowArchived:()=>Et(ue=>!ue),onArchive:ue=>void Yt(ue),onSelectSession:Ie,onNewSession:he,onRequestDelete:De,onConfirmDelete:ue=>void kt(ue),onCancelDelete:()=>De(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),M&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Qt&&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(vs,{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:ee,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:ue=>{const dt=ue.target.value;u(dt),!($.current||dt.trim().length===0)&&(w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{if($.current)return;const wt=dt.trim();if(!wt)return;Tk(wt,l,Re&&ke?{planningModelProvider:Re,planningModelId:ke}:void 0).then(ot=>{$.current=ot.sessionId,$e(yt=>yt.some(Zt=>Zt.id===ot.sessionId)?yt:[{id:ot.sessionId,type:"planning",status:"draft",title:ot.title,preview:wt.length>80?`${wt.slice(0,79).trimEnd()}…`:wt,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...yt].sort((Zt,Ln)=>Date.parse(Ln.updatedAt)-Date.parse(Zt.updatedAt))),Oe(ot.sessionId)}).catch(()=>{})},300))},onKeyDown:ue=>{ue.key==="Enter"&&!ue.shiftKey&&d.trim()&&(ue.preventDefault(),re())},onBlur:()=>{const ue=$.current;ue&&d.trim()&&$t(ue,d)}})]}),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:XR.map((ue,dt)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(ue),children:ue.length>40?ue.slice(0,40)+"...":ue},dt))})]}),t.jsx(ni,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",children:t.jsxs("div",{className:"planning-advanced-content",children:[t.jsxs("div",{className:"planning-advanced-section planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",xe&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx("p",{className:"planning-advanced-blurb",children:"Selects which model runs the planning interview and writes the final draft."}),t.jsx(ys,{id:"planning-modal-model",label:"Planning Model",value:rn,onChange:ue=>{const{provider:dt,modelId:wt}=eT(ue);be(dt),Ue(wt)},models:ie,disabled:xe,favoriteProviders:ge,onToggleFavorite:gn,favoriteModels:tt,onToggleModelFavorite:je}),Fe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Fe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{on()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Re&&ke?"model-badge-custom":"model-badge-default"}`,children:fn(Re,ke)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(ue=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${Ge===ue.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>qe(ue.value),"aria-pressed":Ge===ue.value,children:ue.label},ue.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:Ae,onChange:ue=>Ee(ue.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>re(),disabled:!d.trim(),children:[t.jsx(pi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ft,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:N?"AI is thinking...":"Generating next question..."}),R&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",F,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>T(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void jn(),children:[t.jsx(jx,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),_&&N&&t.jsx("div",{className:"planning-thinking-output",ref:zt,children:t.jsx("pre",{children:N})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{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 Dn(),disabled:O,children:[O?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{className:"icon-ml-6",children:O?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Tt,disabled:O,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(ft,{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(nT,{question:m.session.currentQuestion,progress:es(),historyEntries:v,onSubmit:Bt,onBack:g.length>0?pn:void 0})}),m.type==="summary"&&y&&t.jsx(sT,{summary:y,historyEntries:v,onSummaryChange:j,tasks:r,onCreateTask:hn,onBreakIntoTasks:Ht,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(aT,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:ue=>h({...m,subtasks:ue,dirty:!0}),onCreateTasks:yn,onBack:()=>{const dt={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:dt,summary:y})}})]}),D&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ml,{size:16}),t.jsx("span",{children:Cn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Cn&&t.jsx("button",{type:"button",onClick:()=>{_e()},disabled:z,className:"btn btn-primary session-lock-take-control",children:z?"Taking control...":"Take Control"})]})})]})]})}):null}function nT({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,m]=i.useState(""),h=i.useCallback(()=>{let p;e.type==="text"?p={[e.id]:c}:e.type==="confirm"?p={[e.id]:o[e.id]===!0}:p=o;const g=u.trim();g.length>0&&(p={...p,_comment:g}),a(p)},[u,e,o,c,a]);i.useEffect(()=>{l({}),d(""),m("")},[e.id]);const f=()=>{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(ii,{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(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),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:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:x=>{const v=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.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(Un,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(tn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:u,onChange:p=>m(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(ha,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!f(),children:["Continue",t.jsx(Qr,{size:16,className:"icon-ml-4"})]})]})]})}function sT({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[m,h]=i.useState(e.suggestedDependencies),f=p=>{const g=m.includes(p)?m.filter(x=>x!==p):[...m,p];h(g),s({...e,suggestedDependencies:g})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(ni,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(ii,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Un,{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:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?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)"})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.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:()=>f(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,g)=>t.jsx("li",{children:p},g))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(ha,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Un,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(El,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Xh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.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),a.add(o),!1};return e.some(o=>r(o.id))}function iT(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function aT({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:a,onCreateTasks:r,onBack:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[m,h]=i.useState(null),f=i.useRef([]),p=i.useMemo(()=>e.length===0||e.some(S=>!S.title.trim())?!0:Xh(e),[e]),g=i.useCallback((S,_)=>{a(e.map(T=>T.id===S?{...T,..._}:T))},[e,a]),x=i.useCallback(()=>{a([...e,iT(e.length+1)])},[e,a]),v=i.useCallback(S=>{a(e.filter(_=>_.id!==S).map(_=>({..._,dependsOn:_.dependsOn.filter(T=>T!==S)})))},[e,a]),b=i.useCallback((S,_)=>{if(_<0||_>=e.length)return;const T=[...e],[M]=T.splice(S,1);T.splice(_,0,M),a(T)},[e,a]),y=i.useCallback(S=>_=>{c(S),_.dataTransfer.setData("text/plain",S),_.dataTransfer.effectAllowed="move"},[]),j=i.useCallback(()=>{c(null),u(null),h(null)},[]),C=i.useCallback(S=>_=>{if(_.preventDefault(),S===l)return;const T=_.currentTarget.getBoundingClientRect(),M=T.top+T.height/2,E=_.clientY<M?"before":"after";u(S),h(E)},[l]),A=i.useCallback(S=>_=>{_.preventDefault();const T=_.dataTransfer.getData("text/plain");if(!T||T===S){j();return}const M=e.findIndex(P=>P.id===T),E=e.findIndex(P=>P.id===S);if(M===-1||E===-1){j();return}const O=[...e],[B]=O.splice(M,1);let R=E;m==="after"&&M<E&&R--,m==="after"&&R++,O.splice(R,0,B),a(O),j()},[e,m,a,j]),N=i.useCallback(S=>{const _=S.currentTarget.getBoundingClientRect(),T=S.clientX,M=S.clientY;(T<_.left||T>_.right||M<_.top||M>_.bottom)&&(u(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(El,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((S,_)=>{const T=l===S.id,M=d===S.id,E=["task-detail-section","subtask-item",T?"subtask-item-dragging":"",M?"subtask-item-drop-target":"",M&&m==="before"?"subtask-item-drop-before":"",M&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:E,"data-testid":`subtask-item-${_}`,draggable:!s,onDragStart:y(S.id),onDragEnd:j,onDragOver:C(S.id),onDrop:A(S.id),onDragLeave:N,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(Cl,{size:16}),t.jsx("strong",{children:S.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(_,_-1),disabled:s||_===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ia,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(_,_+1),disabled:s||_===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Yr,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(S.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:O=>{f.current[_]=O},value:S.title,onChange:O=>g(S.id,{title:O.target.value}),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),_<e.length-1&&f.current[_+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:S.description,onChange:O=>g(S.id,{description:O.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:S.suggestedSize,onChange:O=>g(S.id,{suggestedSize:O.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,_).filter(O=>O.id!==S.id).map(O=>{const B=S.dependsOn.includes(O.id);return t.jsxs("label",{className:`planning-dep-chip ${B?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:B,onChange:()=>{const R=B?S.dependsOn.filter(P=>P!==O.id):[...S.dependsOn,O.id];g(S.id,{dependsOn:R})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:O.id}),t.jsx("span",{className:"planning-dep-title",children:O.title||"Untitled"})]},O.id)}),_===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),_>0&&e.slice(0,_).filter(O=>O.id!==S.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},S.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Nn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Xh(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(ha,{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(ft,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function rT({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,onConfirmDelete:m,onCancelDelete:h}){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:d,type:"button",children:[t.jsx(Ov,{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(f=>{const p=f.id===s,g=a===f.id,x=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${x?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(oT,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(lT,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:cT(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":x?"Unarchive session":"Archive session",title:x?"Unarchive session":"Archive session",children:x?t.jsx(Yb,{size:14}):t.jsx(Jr,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:b=>{b.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(Sn,{size:14})})]})]},f.id)})]}),t.jsx("div",{className:"planning-sidebar-footer",children:t.jsx("a",{href:"#",className:"planning-sidebar-toggle-archived-link",onClick:f=>{f.preventDefault(),o()},"aria-pressed":r,children:r?"Hide archived":"Show archived"})})]})}function oT({status:e}){switch(e){case"generating":return t.jsx(ft,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(ad,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Un,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(zs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Ii,{size:14,className:"planning-sidebar-status-icon"})}}function lT({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 cT(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 a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/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 dT(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Zh(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.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),a.add(o),!1};return e.some(o=>r(o.id))}function uT({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){Ci(e);const[c,d]=i.useState({type:"initial"}),[u,m]=i.useState([]),[h,f]=i.useState([]),[p,g]=i.useState(""),[x,v]=i.useState(!0),[b,y]=i.useState(!1),[j,C]=i.useState(!1),[A,N]=i.useState(s),[S,_]=i.useState(null),[T,M]=i.useState(!1),[E,O]=i.useState(null),[B,R]=i.useState(null),[P,F]=i.useState(null),q=i.useRef(null),ee=i.useRef([]),U=i.useRef(!1),k=i.useRef(null),I=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,$=i.useMemo(()=>ba(),[]),{isLockedByOther:w,takeControl:H,isLoading:J}=Bl(e?I:null),{activeTabMap:fe,broadcastUpdate:de,broadcastCompleted:D,broadcastLock:_e,broadcastUnlock:z,broadcastHeartbeat:Z}=tr(),oe=i.useMemo(()=>u.length===0||u.some(le=>!le.title.trim())?!0:Zh(u),[u]),Y=c.type==="generating"||c.type==="editing"||c.type==="error",ae=I?fe.get(I):null,{confirm:ce}=Gs(),te=ae&&ae.tabId!==$,Re=!!(te&&!ae.stale),be=w&&(!te||ae.stale),ke=i.useCallback(()=>{A&&oR(A,o),q.current?.close(),q.current=null,d({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),C(!1),_(null),M(!1),U.current=!1},[A,o]),Ue=i.useCallback(()=>{q.current?.close(),q.current=null,n()},[n]),Ge=i.useCallback(async()=>{if(!((T||c.type==="editing"||c.type==="creating")&&!await ce({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(I)try{await xf(I,o,$)}catch{}ke(),n()}},[T,n,ke,I,$,c.type,o,ce]),qe=i.useCallback(le=>{q.current?.close(),q.current=pj(le,o,{onThinking:Te=>{g(pe=>pe+Te),de({sessionId:le,status:"generating",needsInput:!1,owningTabId:$,type:"subtask",title:A.trim()||void 0,projectId:o??null})},onSubtasks:Te=>{y(!1),C(!1),Dc(o),m(Te),d({type:"editing",sessionId:le}),M(!1),de({sessionId:le,status:"awaiting_input",needsInput:!0,owningTabId:$,type:"subtask",title:A.trim()||void 0,projectId:o??null})},onError:Te=>{const pe=Te||"Session failed while contacting the AI.";y(!1),C(!1),_(null),d({type:"error",sessionId:le,errorMessage:pe}),de({sessionId:le,status:"error",needsInput:!1,owningTabId:$,type:"subtask",title:A.trim()||void 0,projectId:o??null}),D({sessionId:le,status:"error"})},onComplete:()=>{D({sessionId:le,status:"complete"})},onConnectionStateChange:Te=>{y(Te==="reconnecting")}})},[D,de,A,o,$]),Ae=i.useCallback(async()=>{if(A.trim()){_(null),f([]),g(""),y(!1);try{const{sessionId:le}=await uj(A.trim(),o);d({type:"generating",sessionId:le}),qe(le)}catch(le){_(Me(le)||"Failed to start subtask breakdown"),d({type:"initial"})}}},[qe,A,o]);i.useEffect(()=>{if(!e){ke();return}if(e&&s&&!U.current)N(s),U.current=!0,Ae();else if(e&&!s&&!U.current){const le=lR(o);le&&N(le)}},[e,s,Ae,ke]),i.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const le=await wi(l);if(!le)return;const Te=Fa(le.conversationHistory);if(f(Te),le.status==="generating"||le.status==="awaiting_input")g(le.thinkingOutput??""),d({type:"generating",sessionId:l}),qe(l);else if(le.status==="complete"&&le.result){Dc(o);const pe=JSON.parse(le.result);m(pe),d({type:"editing",sessionId:l})}else le.status==="error"&&(_(null),d({type:"error",sessionId:l,errorMessage:le.error??"Session encountered an error"}))}catch(le){_(Me(le)||"Failed to resume session")}})()},[qe,e,l,c.type,o]),i.useEffect(()=>{if(!e){k.current&&(z(k.current,$),k.current=null);return}if(I&&k.current!==I){k.current&&z(k.current,$),_e(I,$),k.current=I;return}!I&&k.current&&(z(k.current,$),k.current=null)},[_e,z,e,I,$]),i.useEffect(()=>{if(!e||!I||k.current!==I)return;Z($);const le=setInterval(()=>{Z($)},3e4);return()=>{clearInterval(le)}},[Z,e,I,$]),i.useEffect(()=>()=>{q.current?.close(),k.current&&(z(k.current,$),k.current=null)},[z,$]),i.useEffect(()=>{if(!e)return;const le=Te=>{Te.key==="Escape"&&(Te.preventDefault(),Ge())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[e,Ge]);const Ee=i.useCallback((le,Te)=>{m(pe=>pe.map($e=>$e.id===le?{...$e,...Te}:$e)),M(!0)},[]),ie=i.useCallback(()=>{m(le=>[...le,dT(le.length+1)]),M(!0)},[]),se=i.useCallback(le=>{m(Te=>Te.filter(pe=>pe.id!==le).map(pe=>({...pe,dependsOn:pe.dependsOn.filter($e=>$e!==le)}))),M(!0)},[]),xe=i.useCallback(le=>Te=>{O(le),Te.dataTransfer.setData("text/plain",le),Te.dataTransfer.effectAllowed="move"},[]),ne=i.useCallback(()=>{O(null),R(null),F(null)},[]),Fe=i.useCallback(le=>Te=>{if(Te.preventDefault(),le===E)return;const pe=Te.currentTarget.getBoundingClientRect(),$e=pe.top+pe.height/2,st=Te.clientY<$e?"before":"after";R(le),F(st)},[E]),Qe=i.useCallback(le=>Te=>{Te.preventDefault();const pe=Te.dataTransfer.getData("text/plain");if(!pe||pe===le){O(null),R(null),F(null);return}m($e=>{const st=$e.findIndex(et=>et.id===pe),at=$e.findIndex(et=>et.id===le);if(st===-1||at===-1)return $e;const rt=[...$e],[Oe]=rt.splice(st,1);let Be=at;return P==="after"&&st<at&&Be--,P==="after"&&Be++,rt.splice(Be,0,Oe),rt}),M(!0),O(null),R(null),F(null)},[P]),ge=i.useCallback(le=>{const Te=le.currentTarget.getBoundingClientRect(),pe=le.clientX,$e=le.clientY;(pe<Te.left||pe>Te.right||$e<Te.top||$e>Te.bottom)&&(R(null),F(null))},[]),ze=i.useCallback((le,Te)=>{Te<0||Te>=u.length||(m(pe=>{const $e=[...pe],[st]=$e.splice(le,1);return $e.splice(Te,0,st),$e}),M(!0))},[u.length]),tt=i.useCallback(le=>{ee.current[le+1]?.focus()},[]),pt=i.useCallback(async()=>{if(!(!I||oe)){_(null),d({type:"creating",sessionId:I});try{const le=await fj(I,u,r,o);a(le.tasks),ke(),n()}catch(le){_(Me(le)||"Failed to create tasks"),d({type:"editing",sessionId:I})}}},[oe,n,a,r,o,ke,I,u]),ve=i.useCallback(async()=>{if(c.type!=="error")return;const le=c.sessionId;_(null),C(!0),g(""),d({type:"generating",sessionId:le}),qe(le);try{await mj(le,o,$)}catch(Te){let pe=Te;if((Me(Te)||"").includes("not in an error state"))try{const st=await wi(le);if(!st)throw new Error("Failed to refresh subtask session.");if(f(Fa(st.conversationHistory)),st.status==="generating"||st.status==="awaiting_input")g(st.thinkingOutput??""),d({type:"generating",sessionId:st.id}),q.current?.isConnected()||qe(st.id);else if(st.status==="complete"){if(!st.result)throw new Error("Subtask session is complete but has no result.");Dc(o);const at=JSON.parse(st.result);m(at),d({type:"editing",sessionId:st.id}),M(!1)}else st.status==="error"&&d({type:"error",sessionId:st.id,errorMessage:st.error??"Retry failed. Please try again."});y(!1);return}catch(st){pe=st}q.current?.close(),q.current=null,d({type:"error",sessionId:le,errorMessage:Me(pe)||"Retry failed. Please try again."}),y(!1)}finally{C(!1)}},[qe,o,$,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:le=>le.target===le.currentTarget&&void Ge(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(El,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Y&&t.jsx("button",{className:"modal-send-to-background",onClick:Ue,title:"Send to background","aria-label":"Send to background",children:t.jsx(eo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ge(),"aria-label":"Close",children:t.jsx(tn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[S&&t.jsx("div",{className:"form-error planning-error",children:S}),b&&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."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:A})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(ft,{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(ii,{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 ve(),disabled:j,children:[j?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14}),t.jsx("span",{className:"icon-ml-6",children:j?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ge(),disabled:j,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(ii,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Un,{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:[u.map((le,Te)=>{const pe=E===le.id,$e=B===le.id,st=["task-detail-section","subtask-item",pe?"subtask-item-dragging":"",$e?"subtask-item-drop-target":"",$e&&P==="before"?"subtask-item-drop-before":"",$e&&P==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:st,"data-testid":`subtask-item-${Te}`,draggable:c.type!=="creating",onDragStart:xe(le.id),onDragEnd:ne,onDragOver:Fe(le.id),onDrop:Qe(le.id),onDragLeave:ge,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(Cl,{size:16}),t.jsx("strong",{children:le.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ze(Te,Te-1),disabled:c.type==="creating"||Te===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(ia,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ze(Te,Te+1),disabled:c.type==="creating"||Te===u.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Yr,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>se(le.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:at=>{ee.current[Te]=at},value:le.title,onChange:at=>Ee(le.id,{title:at.target.value}),onKeyDown:at=>{at.key==="Enter"&&(at.preventDefault(),tt(Te))},disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:le.description,onChange:at=>Ee(le.id,{description:at.target.value}),disabled:c.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:le.suggestedSize,onChange:at=>Ee(le.id,{suggestedSize:at.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:[u.slice(0,Te).filter(at=>at.id!==le.id).map(at=>{const rt=le.dependsOn.includes(at.id);return t.jsxs("label",{className:`planning-dep-chip ${rt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:rt,onChange:()=>{const Oe=rt?le.dependsOn.filter(Be=>Be!==at.id):[...le.dependsOn,at.id];Ee(le.id,{dependsOn:Oe})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:at.id}),t.jsx("span",{className:"planning-dep-title",children:at.title||"Untitled"})]},at.id)}),Te===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Te>0&&u.slice(0,Te).filter(at=>at.id!==le.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},le.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:ie,disabled:c.type==="creating",children:[t.jsx(Nn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Zh(u)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void Ge(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void pt(),disabled:c.type==="creating"||oe,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),w&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(Ml,{size:16}),t.jsx("span",{children:be?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),be&&t.jsx("button",{type:"button",onClick:()=>{H()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}const mT=5,hT=1e3,pT=45e3;function Ho(){return{scrollback:null,connected:null,data:[]}}function fT(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),x=i.useRef(new Set),v=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Ho()),j=i.useCallback(R=>{p.current.add(R);const P=y.current;return P.data.length>0&&(P.data.forEach(F=>R(F)),P.data=[]),()=>p.current.delete(R)},[]),C=i.useCallback(R=>(g.current.add(R),()=>g.current.delete(R)),[]),A=i.useCallback(R=>{x.current.add(R);const P=y.current;return P.connected&&(R(P.connected),P.connected=null),()=>x.current.delete(R)},[]),N=i.useCallback(R=>{v.current.add(R);const P=y.current;return P.scrollback&&(R(P.scrollback),P.scrollback=null),()=>v.current.delete(R)},[]),S=i.useCallback(R=>(b.current.add(R),()=>b.current.delete(R)),[]),_=i.useCallback(R=>{const P=d.current;P?.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"input",data:R}))},[]),T=i.useCallback((R,P)=>{const F=d.current;F?.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"resize",cols:R,rows:P}))},[]),M=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Ho()},[]),E=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(f.current=!0,d.current.close(),d.current=null),y.current=Ho()},[]),O=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.close()),f.current=!1,a("connecting");const R=r.current;let F=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(F+=`&projectId=${encodeURIComponent(n)}`);const q=new WebSocket(ki(F));d.current=q,q.onopen=()=>{if(r.current!==R){q.close();return}y.current=Ho(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===R&&q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"ping"}))},pT)},q.onmessage=ee=>{if(r.current===R)try{const U=JSON.parse(ee.data),k=y.current;switch(U.type){case"data":U.data&&(p.current.size===0&&k.data.push(U.data),p.current.forEach(I=>I(U.data)));break;case"scrollback":U.data&&(k.scrollback=U.data,v.current.forEach(I=>I(U.data)));break;case"connected":U.shell&&U.cwd&&(k.connected={shell:U.shell,cwd:U.cwd},x.current.forEach(I=>I({shell:U.shell,cwd:U.cwd})));break;case"exit":U.exitCode!==void 0&&g.current.forEach(I=>I(U.exitCode));break;case"ping":q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},q.onclose=ee=>{if(r.current!==R)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(ee.code===4e3||ee.code===4004){a("disconnected"),ee.code===4004&&b.current.forEach(I=>I());return}if(u.current++,u.current>mT){a("disconnected");return}const U=hT*Math.pow(2,u.current-1);a("reconnecting");const k=r.current;m.current=setTimeout(()=>{r.current===k&&(f.current||O())},Math.min(U,16e3))},q.onerror=()=>{}},[e,n]),B=i.useCallback(()=>{u.current=0,E(),O()},[E,O]);return i.useEffect(()=>(c&&(M(),u.current=0,a("disconnected")),e?O():a("disconnected"),E),[e,n,c,O,E,M]),{connectionStatus:s,sendInput:_,resize:T,onData:j,onExit:C,onConnect:A,onScrollback:N,reconnect:B,onSessionInvalid:S}}const cb="kb-terminal-tabs",gT=15e3,bT=15e3;function ep(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function tp(e){if(typeof window>"u")return[];try{const n=as(cb,e);if(n)return JSON.parse(n)}catch{}return[]}function Hc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function np(e,n,s){let a;const r=new Promise((o,l)=>{a=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(a))}function xT(e){const[n,s]=i.useState(()=>tp(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,m]=i.useState(0),h=i.useRef(0);i.useEffect(()=>{h.current+=1,s(tp(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{xs(cb,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let A=!1;const N=h.current;return(async()=>{if(!A)try{const _=await np(rk(e),gT,"listTerminalSessions");if(A||N!==h.current)return;const T=new Set(_.map(M=>M.id));l(!0),s(M=>{if(A||N!==h.current)return M;const O=M.map(P=>({...P,_verified:T.has(P.sessionId)})).filter(P=>P._verified);if(O.length===0)return[];const B=O.map(({_verified:P,...F})=>F);return B.find(P=>P.isActive)?B:B.map((P,F)=>({...P,isActive:F===0}))}),r(!0)}catch(_){if(A||N!==h.current)return;const T=Hc(_);T||console.warn("Failed to validate terminal sessions with server:",_),l(!T),r(!0)}})(),()=>{A=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const A=h.current,N=setTimeout(()=>{np(vo(void 0,void 0,void 0,e),bT,"createTerminalSession").then(S=>{if(A!==h.current)return;const _={id:ep(),sessionId:S.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(T=>T.length>0?T:[...T.map(E=>({...E,isActive:!1})),_]),d(null)}).catch(S=>{if(A!==h.current)return;Hc(S)||console.error(S);const _=S instanceof Error?S.message:typeof S=="string"?S:"Failed to create terminal session";d(_)})},0);return()=>clearTimeout(N)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const A=await vo(void 0,void 0,void 0,e),N={id:ep(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(S=>[...S.map(T=>({...T,isActive:!1})),N]),N},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(A=>{s(N=>{const S=N.find(E=>E.id===A);if(!S)return N;Du(S.sessionId,e).catch(E=>{console.warn(`Failed to kill terminal session ${S.sessionId}:`,E)});const _=N.findIndex(E=>E.id===A),T=S.isActive,M=N.filter(E=>E.id!==A);if(M.length===0)return[];if(T){const E=Math.min(_,M.length-1);return M.map((O,B)=>({...O,isActive:B===E}))}return M})},[]),x=i.useCallback(A=>{s(N=>{let S=!1;const _=N.map(T=>T.id===A?(S=!0,{...T,isActive:!0}):{...T,isActive:!1});return S?_:N})},[]),v=i.useCallback((A,N)=>{s(S=>S.map(_=>_.id===A?{..._,title:N}:_))},[]),b=i.useCallback(async()=>{s(S=>{const _=S.find(T=>T.isActive);return _&&Du(_.sessionId,e).catch(T=>{console.warn(`Failed to kill old session ${_.sessionId}:`,T)}),S});const A=n.find(S=>S.isActive);if(!A)return;const N=await vo(void 0,void 0,void 0,e);s(S=>S.map(_=>_.id===A.id?{..._,sessionId:N.sessionId}:_))},[n]),y=i.useCallback(async()=>{const A=n.find(N=>N.isActive);if(A)try{const N=await vo(void 0,void 0,void 0,e);s(S=>S.map(_=>_.id===A.id?{..._,sessionId:N.sessionId}:_)),d(null)}catch(N){Hc(N)||console.error(N);const S=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(S)}},[n]),j=n.find(A=>A.isActive)??null,C=i.useCallback(()=>{d(null),h.current+=1,m(A=>A+1)},[]);return{tabs:n,activeTab:j,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:C,replaceActiveTabSession:y}}const vT=1e4,yT=[500,1500,3e3],db="kb-terminal-font-size",_r=14,wT=8,kT=32,jT='"Fusion Terminal Nerd Font Symbols", "MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function NT(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 ST(e){return`\x1B${e}`}const CT=[{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 Ar(e){return Math.min(kT,Math.max(wT,e))}function ET(){if(typeof window>"u")return _r;try{const e=window.localStorage.getItem(db);if(!e)return _r;const n=Number.parseInt(e,10);return Number.isFinite(n)?Ar(n):_r}catch{return _r}}function MT(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 _T(e){return new Promise(n=>setTimeout(n,e))}async function AT(e,n=yT){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!MT(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await _T(o)}throw s??new Error("Dynamic import failed")}function sp(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function PT(){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 a=RT()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let qc=null;function RT(){return qc===null&&(qc=window.innerHeight),qc}function TT({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,x]=i.useState(0),[v,b]=i.useState(null),[y,j]=i.useState(()=>ET()),[C,A]=i.useState(!1),[N,S]=i.useState(null),_=i.useRef(null),T=i.useRef(null),M=i.useRef(!1);Si(T,e,"fusion:terminal-modal-size");const E=i.useRef(null),O=i.useRef(null),B=i.useRef(!1),R=i.useRef(!1),P=i.useRef(null),F=i.useRef(()=>{}),q=i.useRef(null),ee=i.useRef(0),U=i.useRef(y),k=i.useRef(null),I=i.useRef(a);ee.current=g,U.current=y;const $=i.useCallback(pe=>{if(pe&&R.current!==pe)return;const $e=O.current,st=E.current,at=P.current;if(!(!$e||!st)&&!(pe&&R.current!==pe))try{$e.fit(),at&&at(st.cols,st.rows)}catch{}},[]);i.useEffect(()=>{e&&p(pe=>pe+1)},[e]),i.useEffect(()=>{if(!e||!sp())return;const pe=window.visualViewport;if(!pe)return;const $e=()=>{const st=PT();x(st),b(pe.height),st>0&&T.current?.scrollIntoView&&T.current.scrollIntoView({block:"end",behavior:"smooth"}),k.current!==null&&(cancelAnimationFrame(k.current),k.current=null);const at=typeof R.current=="string"?R.current:void 0;k.current=requestAnimationFrame(()=>{k.current=null,$(at)})};return $e(),pe.addEventListener("resize",$e),pe.addEventListener("scroll",$e),()=>{pe.removeEventListener("resize",$e),pe.removeEventListener("scroll",$e),k.current!==null&&(cancelAnimationFrame(k.current),k.current=null),x(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const pe=T.current;if(!pe||typeof ResizeObserver>"u")return;let $e=null;const st=new ResizeObserver(()=>{$e!==null&&cancelAnimationFrame($e),$e=requestAnimationFrame(()=>{$e=null;const at=typeof R.current=="string"?R.current:void 0;$(at)})});return st.observe(pe),()=>{st.disconnect(),$e!==null&&cancelAnimationFrame($e)}},[$,e]);const{tabs:w,activeTab:H,isReady:J,bootstrapError:fe,createTab:de,closeTab:D,setActiveTab:_e,updateTabTitle:z,restartActiveTab:Z,retryBootstrap:oe,replaceActiveTabSession:Y}=xT(a),{connectionStatus:ae,sendInput:ce,resize:te,onData:Re,onConnect:be,onExit:ke,onScrollback:Ue,reconnect:Ge,onSessionInvalid:qe}=fT(H?.sessionId??null,a);P.current=te,F.current=ce,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(db,String(y))}catch{}},[y]);const Ae=i.useCallback(()=>{const pe=E.current;if(pe)try{O.current?.fit(),te(pe.cols,pe.rows)}catch{}},[te]);i.useEffect(()=>{if(!e||!J)return;const pe=H?.sessionId;if(!pe)return;const $e=I.current!==a;if($e&&(I.current=a),R.current===pe&&E.current&&!$e)return;E.current&&(R.current!==pe||$e)&&(E.current.dispose(),E.current=null,O.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),u(!1),h(null));let st=!0,at;return(async()=>{const Oe=AT(()=>Promise.all([An(()=>import("./vendor-xterm-DzcZoU0P.js").then(De=>De.x),__vite__mapDeps([4,1,5])),An(()=>import("./addon-fit-C7jRorKK.js").then(De=>De.a),__vite__mapDeps([6,1])),An(()=>import("./addon-web-links-CkJwd4cQ.js").then(De=>De.a),__vite__mapDeps([7,1]))])),Be=new Promise((De,vt)=>{at=setTimeout(()=>{vt(new Error("xterm initialization timed out"))},vT)});let et,jt;try{const[{Terminal:De},{FitAddon:vt},{WebLinksAddon:Et}]=await Promise.race([Oe,Be]);if(!st||!_.current||E.current)return;et=new De({cursorBlink:!0,cursorStyle:"block",fontSize:U.current,fontFamily:jT,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}),jt=new vt,et.loadAddon(jt);const bt=new Et;if(et.loadAddon(bt),!sp())try{const{WebglAddon:It}=await An(async()=>{const{WebglAddon:Xt}=await import("./addon-webgl-BjvOw43o.js").then(Lt=>Lt.a);return{WebglAddon:Xt}},__vite__mapDeps([8,1])),_t=new It;_t.onContextLoss(()=>{_t.dispose()}),et.loadAddon(_t)}catch{}et.open(_.current),at&&clearTimeout(at);const zt=_.current?.querySelector(".xterm-helper-textarea");if(zt&&zt.focus(),_.current)try{_.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{jt.fit();const It=_.current?.querySelector(".xterm-helper-textarea");It&&It.focus()},50),E.current=et,O.current=jt,R.current=pe,ee.current>0&&(k.current!==null&&(cancelAnimationFrame(k.current),k.current=null),k.current=requestAnimationFrame(()=>{k.current=null,$(pe)})),et.onData(It=>{R.current===pe&&F.current(It)});const qt=()=>{if(R.current===pe&&O.current&&E.current)try{O.current.fit();const{cols:It,rows:_t}=E.current;P.current?.(It,_t)}catch{}};window.addEventListener("resize",qt),q.current&&window.removeEventListener("resize",q.current),q.current=qt,u(!0),h(null)}catch(De){if(at&&clearTimeout(at),!st)return;const vt=De instanceof Error?De.message:"xterm initialization failed";h(vt)}})(),()=>{st=!1,at&&clearTimeout(at)}},[$,e,J,H?.sessionId,a]),i.useEffect(()=>{e||(E.current&&(E.current.dispose(),E.current=null),O.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),u(!1),h(null),B.current=!1,o(null),c(null),A(!1),S(null))},[e]),i.useEffect(()=>{if(!d||!E.current||!H)return;const pe=H.sessionId,$e=Be=>{R.current===pe&&E.current?.write(Be)},st=Re(Be=>{$e(Be)}),at=Ue(Be=>{$e(Be)}),rt=be(Be=>{z(H.id,Xd(Be.shell)||Be.shell)}),Oe=ke(Be=>{R.current===pe&&(c(Be),E.current?.write(`\r
679
+ \x1B[33m[Process exited with code ${Be}]\x1B[0m\r
680
+ `))});return()=>{st(),at(),rt(),Oe()}},[d,H?.sessionId,H?.id,H,ae,Re,Ue,be,ke,z]),i.useEffect(()=>{ae==="connected"&&s&&B.current!==s&&H&&(B.current=s,setTimeout(()=>{ce(s+`
681
+ `)},500))},[ae,s,ce,H,f]),i.useEffect(()=>{if(!d||!E.current)return;E.current.options.fontSize=y,k.current!==null&&(cancelAnimationFrame(k.current),k.current=null);const pe=requestAnimationFrame(()=>{k.current=null,Ae()});return k.current=pe,()=>{k.current===pe&&(cancelAnimationFrame(pe),k.current=null)}},[y,d,Ae]),i.useEffect(()=>{if(!e)return;const pe=$e=>{if(!(!$e.ctrlKey&&!$e.metaKey)){if($e.code==="Equal"||$e.code==="NumpadAdd"){$e.preventDefault(),j(st=>Ar(st+1));return}if($e.code==="Minus"||$e.code==="NumpadSubtract"){$e.preventDefault(),j(st=>Ar(st-1));return}if($e.code==="Digit0"||$e.code==="Numpad0"){$e.preventDefault(),j(_r);return}}};return window.addEventListener("keydown",pe),()=>window.removeEventListener("keydown",pe)},[e,Ae]),i.useEffect(()=>{if(!e)return;const pe=$e=>{$e.key==="Escape"&&n()};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[e,n]),i.useEffect(()=>{ae==="connected"&&E.current&&setTimeout(()=>{if(!E.current||!_.current)return;const pe=_.current.querySelector(".xterm-helper-textarea");pe&&pe.focus();try{_.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[ae]);const Ee=i.useCallback(()=>{if(!_.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;E.current?.focus();const $e=_.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 st=$e.value.length;$e.setSelectionRange(st,st)},[]);i.useEffect(()=>qe(()=>{E.current?.clear(),c(null),B.current=!1,E.current&&(E.current.dispose(),E.current=null),O.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),u(!1),h(null),Y().catch($e=>{console.error("Failed to replace invalid terminal session:",$e)})}),[qe,Y]);const ie=i.useCallback(pe=>{pe.target===pe.currentTarget&&(M.current=!0)},[]),se=i.useCallback(pe=>{M.current&&pe.target===pe.currentTarget&&n(),M.current=!1},[n]),xe=i.useCallback(()=>{E.current?.clear()},[]),ne=i.useCallback(async()=>{E.current?.clear(),c(null),B.current=!1;try{await Z()}catch(pe){o(Me(pe)||"Failed to restart terminal session")}},[Z]),Fe=i.useCallback(()=>{E.current&&(E.current.dispose(),E.current=null),O.current=null,R.current=!1,q.current&&(window.removeEventListener("resize",q.current),q.current=null),h(null),u(!1)},[]),Qe=i.useCallback(()=>{window.location.reload()},[]),ge=i.useCallback(()=>{j(pe=>Ar(pe+1))},[]),ze=i.useCallback(()=>{j(pe=>Ar(pe-1))},[]),tt=i.useCallback(pe=>{S($e=>$e===pe?null:pe)},[]),pt=i.useCallback(pe=>{if(N==="ctrl"){ce(NT(pe)),S(null);return}if(N==="alt"){ce(ST(pe)),S(null);return}ce(pe)},[ce,N]),ve=i.useCallback(pe=>{ce(pe),S(null)},[ce]);if(!e)return null;const le=()=>{switch(ae){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=!J||!H&&!fe;return t.jsx("div",{className:"modal-overlay open",onMouseDown:ie,onMouseUp:se,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:T,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}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:[w.map(pe=>t.jsxs("div",{className:`terminal-tab ${pe.isActive?"terminal-tab--active":""}`,onClick:()=>_e(pe.id),title:pe.title,role:"tab","aria-selected":pe.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:pe.title}),w.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:$e=>{$e.stopPropagation(),D(pe.id)},title:"Close tab",children:"×"})]},pe.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:de,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Ti,{size:16}),le()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[ae==="disconnected"&&H&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Ge,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(os,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:ne,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(os,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:xe,"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 terminal-clear-btn--shortcut",onClick:()=>A(pe=>!pe),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":C,children:[t.jsx(kv,{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(tn,{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&&!fe&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),fe&&!H&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",fe]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:oe,"data-testid":"terminal-retry-btn",children:[t.jsx(os,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Qe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(os,{size:14}),"Refresh page"]})]})]})}),m&&H&&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:Fe,"data-testid":"terminal-reinit-btn",children:[t.jsx(os,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Qe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(os,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:_,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Ee,onTouchStart:Ee},H?.sessionId)]}),C&&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 ${N==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>tt("ctrl"),"aria-pressed":N==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>tt("alt"),"aria-pressed":N==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ve("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ve(" "),children:"Tab"})]}),CT.map(pe=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>pt(pe.key),title:pe.description,children:pe.label},pe.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${ae}`,children:[ae==="connected"&&"Connected",ae==="connecting"&&"Connecting...",ae==="reconnecting"&&"Reconnecting...",ae==="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:ze,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Bv,{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:ge,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Nn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const br={name:"",command:""};function ip(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function IT(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function $T({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Ci(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(br),[x,v]=i.useState(!1),[b,y]=i.useState(null),[j,C]=i.useState(null),A=Li(n),N=i.useCallback(async()=>{try{d(!0);const F=await qr(a);l(F)}catch(F){s(Me(F)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&N()},[e,N]);const S=i.useCallback(()=>{m(!0),f(null),g(br),C(null)},[]),_=i.useCallback((F,q)=>{f(F),m(!1),g({name:F,command:q}),C(null)},[]),T=i.useCallback(()=>{f(null),m(!1),g(br),C(null)},[]),M=i.useCallback(F=>{g(q=>({...q,name:F})),F&&!ip(F)?C("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):C(null)},[]),E=i.useCallback(async()=>{const F=p.name.trim(),q=p.command.trim();if(!F){s("Script name is required","error");return}if(!ip(F)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!q){s("Script command is required","error");return}v(!0);try{await cj(F,q,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(br),C(null),await N()}catch(ee){const U=Me(ee);U?.includes("already exists")?s("A script with this name already exists","error"):s(U||"Failed to save script","error")}finally{v(!1)}},[p,h,s,N,a]),O=i.useCallback(async F=>{try{await dj(F,a),s("Script deleted","success"),y(null),h===F&&(f(null),g(br)),await N()}catch(q){s(Me(q)||"Failed to delete script","error")}},[h,s,N,a]),B=i.useCallback((F,q)=>{r&&r(F,q)},[r]);if(!e)return null;const R=u||h!==null,P=Object.entries(o).map(([F,q])=>({name:F,command:q}));return t.jsx("div",{className:"modal-overlay open",...A,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Ti,{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(ft,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):R?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:F=>M(F.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:j?"var(--color-error)":void 0}}),j&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:j}),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=>g(q=>({...q,command:F.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:T,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:E,disabled:x||!!j,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(ft,{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:P.length===0?"No scripts defined":`${P.length} script${P.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:S,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Nn,{size:14}),"Add Script"]})]}),P.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(Ti,{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:P.map(F=>t.jsx("div",{className:"script-card","data-testid":`script-${F.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:F.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:F.command,children:IT(F.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:()=>B(F.name,F.command),title:"Run script","aria-label":`Run ${F.name}`,"data-testid":`run-script-${F.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Yn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>_(F.name,F.command),title:"Edit","aria-label":`Edit ${F.name}`,"data-testid":`edit-script-${F.name}`,children:t.jsx(Nn,{size:14,style:{transform:"rotate(45deg)"}})}),b===F.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>O(F.name),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,"data-testid":`confirm-delete-script-${F.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-${F.name}`,children:t.jsx(tn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(F.name),title:"Delete","aria-label":`Delete ${F.name}`,"data-testid":`delete-script-${F.name}`,children:t.jsx(Sn,{size:14})})]})]})},F.name))})]})})]})})}function DT(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(x=>x+1)},[]),g=i.useCallback(x=>{l(x),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){d(!0),m(null);try{const b=await Nk(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Me(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function LT(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(null),v=i.useCallback(j=>{o(j),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let j=!1;async function C(){h(!0),x(null);try{const A=await Sk(e,n,a);j||(o(A.content),c(A.content),u(A.mtime))}catch(A){j||(x(Me(A)||"Failed to load file"),o(""),c(""),u(null))}finally{j||h(!1)}}return C(),()=>{j=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const j=await Ck(e,n,r,a);c(r),u(j.mtime)}catch(j){throw x(Me(j)||"Failed to save file"),j}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const OT=1e4;function zT(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function FT(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function UT(e){const[n,s]=i.useState("Project Root"),[a,r]=i.useState([]),[o,l]=i.useState(!0),[c,d]=i.useState(null);return i.useEffect(()=>{let u=!1;async function m(){try{const f=await jk(e);if(u)return;s(zT(f.project)),r(f.tasks.map(FT)),d(null)}catch(f){u||d(Me(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},OT);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function BT(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function HT(e){return e?new Date(e).toLocaleDateString():""}function ap(e,n){return u1(e,n)}const xr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Vc={type:null,entry:null,entryFullPath:""},qT=200,VT=500,rp=10;function WT({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,x=f?.offsetLeft??0,v=f?.offsetTop??0,b=8;let y=e-x,j=n-v;y+h.width>p-b&&(y=p-b-h.width),j+h.height>g-b&&(j=g-b-h.height),y<b&&(y=b),j<b&&(j=b),c({x:y+x,y:j+v})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:ra,disabled:!1},{id:"move",label:"Move",icon:Vv,disabled:!1},{id:"rename",label:"Rename",icon:js,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:Jr,disabled:!1}]:[{id:"download",label:"Download",icon:Ix,disabled:!1}],{id:"divider",label:"",icon:ra,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:u.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:()=>a(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 KT({type:e,entry:n,entryFullPath:s,onConfirm:a,onCancel:r,loading:o,error:l}){const c=i.useRef(null),d=e==="rename"?n.name:"",[u,m]=i.useState(d);i.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),i.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&u.trim()&&a(u.trim()),g.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:g=>g.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:()=>a(""),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:g=>g.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:u,onChange:g=>m(g.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:()=>a(u.trim()),disabled:o||!u.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function GT({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[m,h]=i.useState(xr),[f,p]=i.useState(Vc),[g,x]=i.useState(!1),[v,b]=i.useState(null),[y,j]=i.useState(!1),[C,A]=i.useState(null),N=i.useRef(null),S=i.useRef(null),_=i.useRef(null),T=i.useRef(!1),M=i.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),S.current!==null&&(window.clearTimeout(S.current),S.current=null)},[]),E=i.useCallback(()=>{M(),_.current=null,j(!1),A(null)},[M]);i.useEffect(()=>()=>{M()},[M]);const O=i.useCallback((I,$,w,H)=>{h({visible:!0,x:I,y:$,entry:w,entryFullPath:H})},[]),B=i.useCallback((I,$,w)=>{if(I.touches.length!==1)return;const H=I.touches[0];H&&(E(),_.current={x:H.clientX,y:H.clientY},S.current=window.setTimeout(()=>{j(!0),A(w)},qT),N.current=window.setTimeout(()=>{const J=_.current;J&&(T.current=!0,j(!1),A(null),M(),O(J.x,J.y,$,w))},VT))},[E,M,O]),R=i.useCallback(I=>{const $=_.current,w=I.touches[0];!$||!w||(Math.abs(w.clientX-$.x)>rp||Math.abs(w.clientY-$.y)>rp)&&E()},[E]),P=i.useCallback(()=>{E()},[E]);i.useEffect(()=>{if(!m.visible)return;const I=document.querySelector(".file-browser-list"),$=()=>{T.current=!1,E(),h(xr)};return I?.addEventListener("scroll",$),()=>I?.removeEventListener("scroll",$)},[E,m.visible]),i.useEffect(()=>{if(!m.visible)return;const I=$=>{$.key==="Escape"&&(T.current=!1,h(xr))};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[m.visible]);const F=i.useCallback((I,$)=>{I.preventDefault(),I.stopPropagation(),E(),T.current=!1,O(I.clientX,I.clientY,$,ap(n,$.name))},[E,n,O]),q=i.useCallback(I=>{if(!m.entry)return;T.current=!1;const $=m.entry,w=m.entryFullPath;if(h(xr),I==="download"){if(!c)return;const H=pf(c,w,u);window.open(ki(H),"_blank");return}if(I==="download-zip"){if(!c)return;const H=Rk(c,w,u);window.open(ki(H),"_blank");return}p({type:I,entry:$,entryFullPath:w}),b(null)},[m,c,u]),ee=i.useCallback(async I=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await Mk(c,f.entryFullPath,I,u);break;case"move":await _k(c,f.entryFullPath,I,u);break;case"rename":await Pk(c,f.entryFullPath,I,u);break;case"delete":await Ak(c,f.entryFullPath,u);break}p(Vc),d?.()}catch($){b(Me($)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),U=i.useCallback(()=>{p(Vc),b(null)},[]),k=i.useCallback((I,$)=>{if(T.current){T.current=!1;return}m.visible||(I.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(ft,{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:()=>{a(m1(n))},children:[t.jsx(In,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Qa(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(I=>{const $=ap(n,I.name),w=y&&C===$;return t.jsxs("div",{className:`file-node file-node--${I.type} ${w?"file-node--long-pressing":""}`,onClick:()=>k(I,$),onContextMenu:H=>F(H,I),onTouchStart:H=>B(H,I,$),onTouchMove:R,onTouchEnd:P,onTouchCancel:P,children:[t.jsx("div",{className:"file-node-icon",children:I.type==="directory"?t.jsx(fs,{size:16}):t.jsx(sf,{size:16})}),t.jsx("div",{className:"file-node-name",children:I.name}),I.type==="file"&&I.size!==void 0&&t.jsx("div",{className:"file-node-size",children:BT(I.size)}),I.mtime&&t.jsx("div",{className:"file-node-time",children:HT(I.mtime)})]},I.name)})}),m.visible&&m.entry&&t.jsx(WT,{x:m.x,y:m.y,entry:m.entry,onAction:q,onClose:()=>{T.current=!1,h(xr)}}),f.type&&f.entry&&t.jsx(KT,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:ee,onCancel:U,loading:g,error:v})]})}function JT(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function YT({content:e,onChange:n,readOnly:s,filePath:a}){const[r,o]=i.useState(!1),[l,c]=i.useState(!0),d=JT(a),u=d&&(s?!0:r),m=i.useCallback(()=>{o(!1)},[]),h=i.useCallback(()=>{o(!0)},[]),f=i.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[d?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 ${u?"":"btn-primary"}`,onClick:m,disabled:!u,"aria-label":"Edit mode",children:[t.jsx(nf,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:h,disabled:u,"aria-label":"Preview mode",children:[t.jsx(Ja,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(sl,{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:f,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(sl,{size:14})})]}),u?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ji,{remarkPlugins:[Ni],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":a?`Editor for ${a}`:"File editor"})]})}function QT(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function XT({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.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(Su,{size:14}):t.jsx(ld,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(mn,{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:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Su,{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:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(ld,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:QT(c.title)})]},c.id))]})]})]})}const ZT=768,eI=280,qo=180,Vo=500,op="fusion:file-browser-sidebar-width",ub=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),tI=new Set([...ub,".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 lp(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return tI.has(n)}function nI(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ub.has(n)}function sI({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=UT(a),l=i.useRef(null);Si(l,!0,"fusion:files-modal-size");const c=Li(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[v,b]=i.useState(eI),{entries:y,currentPath:j,setPath:C,loading:A,error:N,refresh:S}=DT(d,!0,a),{content:_,setContent:T,originalContent:M,loading:E,saving:O,error:B,save:R,hasChanges:P,mtime:F}=LT(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const D=()=>{p(window.innerWidth<=ZT)};return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const D=localStorage.getItem(op);if(!D)return;const _e=Number.parseInt(D,10);if(!Number.isNaN(_e)){const z=Math.max(qo,Math.min(Vo,_e));b(z)}}catch{}},[]),i.useEffect(()=>{const D=_e=>{_e.key==="Escape"&&n(),(_e.metaKey||_e.ctrlKey)&&_e.key==="s"&&(_e.preventDefault(),P&&!O&&R())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[n,P,O,R]);const q=i.useCallback(D=>{h(D),f&&x("editor")},[f]),ee=i.useCallback(()=>{x("list")},[]),U=i.useCallback(()=>{T(M)},[M,T]),k=i.useCallback(D=>{u(D),h(null),x("list"),s?.(D)},[s]),I=i.useCallback(D=>{try{localStorage.setItem(op,String(D))}catch{}},[]),$=i.useCallback(D=>{if(f)return;D.preventDefault(),D.stopPropagation();const _e=D.currentTarget;typeof _e.setPointerCapture=="function"&&_e.setPointerCapture(D.pointerId);const z=D.clientX,Z=v;let oe=Z;document.body.style.userSelect="none";const Y=ce=>{const te=ce.clientX-z,Re=Math.max(qo,Math.min(Vo,Z+te));oe=Re,b(Re)},ae=ce=>{typeof _e.releasePointerCapture=="function"&&_e.releasePointerCapture(ce.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",ae),I(oe)};document.addEventListener("pointermove",Y),document.addEventListener("pointerup",ae)},[f,I,v]),w=i.useCallback(D=>{if(f)return;const _e=20;if(D.key!=="ArrowLeft"&&D.key!=="ArrowRight")return;D.preventDefault();const z=D.key==="ArrowLeft"?-_e:_e,Z=Math.max(qo,Math.min(Vo,v+z));b(Z),I(Z)},[f,I,v]),J=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(D=>D.id===d)?.id??d,[d,o])}`,fe=i.useMemo(()=>!m||!nI(m)?null:pf(d,m,a),[m,d,a]),de=D=>{const _e=new Blob([D]).size;return _e<1024?`${_e} B`:`${(_e/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(fs,{size:18}),t.jsx("span",{children:J}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(XT,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:k}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(tn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${f?"mobile":""} ${g==="list"?"active":""}`,style:f?void 0:{width:`${v}px`},children:t.jsx(GT,{entries:y,currentPath:j,onSelectFile:q,onNavigate:C,loading:A,error:N,onRetry:S,workspace:d,onRefresh:S,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":qo,"aria-valuemax":Vo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:$,onKeyDown:w}),t.jsx("div",{className:`file-browser-content ${f?"mobile":""} ${g==="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:[f&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:ee,"aria-label":"Back to file list",children:[t.jsx(ha,{size:16}),t.jsx("span",{children:"Back"})]}),m,lp(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Zx,{size:12}),"Binary file — read only"]}),F&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(F).toLocaleString()]}),E&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!fe&&P&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:U,disabled:O,children:[t.jsx(iy,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void R(),disabled:O,children:[t.jsx(cf,{size:14}),O?"Saving...":"Save"]})]})})]}),B&&!fe&&t.jsx("div",{className:"file-browser-error-banner",children:B}),fe?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:fe,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(YT,{content:_,onChange:T,filePath:m,readOnly:lp(m)})}),!fe&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:de(_)}),P&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(fs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function iI(e){const{items:n,...s}=e;return s}function cp(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function aI(e={}){const{projectId:n,addToast:s}=e,[a,r]=i.useState([]),[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(null),[p,g]=i.useState([]),x=i.useRef(h);x.current=h,i.useEffect(()=>{let _=!1;async function T(){d(!0),m(null);try{const M=await EN(n);if(_)return;g(M),r(M.map(iI));const E=x.current&&M.some(O=>O.id===x.current)?x.current:M[0]?.id??null;f(E),l(E?M.find(O=>O.id===E)?.items??[]:[])}catch(M){if(_)return;g([]),r([]),l([]),f(null),m(M instanceof Error?M.message:"Failed to load todo lists")}finally{_||d(!1)}}return T(),()=>{_=!0}},[n]),i.useEffect(()=>{if(!h){l([]);return}const _=p.find(T=>T.id===h);l(_?.items??[])},[p,h]);const v=i.useCallback(async _=>{const T=a,M=p,E=new Date().toISOString(),O={id:cp("temp-list"),projectId:n??"",title:_,createdAt:E,updatedAt:E};m(null),r(B=>[...B,O]),g(B=>[...B,{...O,items:[]}]);try{const B=await MN(_,n);r(R=>R.map(P=>P.id===O.id?B:P)),g(R=>R.map(P=>P.id===O.id?{...B,items:[]}:P)),x.current||f(B.id)}catch(B){r(T),g(M),m(B instanceof Error?B.message:"Failed to create list"),s?.("Failed to create todo list","error")}},[s,p,a,n]),b=i.useCallback(async(_,T)=>{const M=a,E=p;m(null),r(O=>O.map(B=>B.id===_?{...B,title:T}:B)),g(O=>O.map(B=>B.id===_?{...B,title:T}:B));try{const O=await _N(_,T,n);r(B=>B.map(R=>R.id===_?O:R)),g(B=>B.map(R=>R.id===_?{...O,items:R.items}:R))}catch(O){r(M),g(E),m(O instanceof Error?O.message:"Failed to rename list"),s?.("Failed to rename todo list","error")}},[s,p,a,n]),y=i.useCallback(async _=>{const T=a,M=p,E=x.current,O=E===_?a.find(B=>B.id!==_)?.id??null:E;m(null),r(B=>B.filter(R=>R.id!==_)),g(B=>B.filter(R=>R.id!==_)),E===_&&f(O);try{await AN(_,n)}catch(B){r(T),g(M),f(E),m(B instanceof Error?B.message:"Failed to delete list"),s?.("Failed to delete todo list","error")}},[s,p,a,n]),j=i.useCallback(async _=>{const T=x.current;if(!T)return;const M=o,E=p,O=new Date().toISOString(),B=o.reduce((P,F)=>Math.max(P,F.sortOrder),-1),R={id:cp("temp-item"),listId:T,text:_,completed:!1,completedAt:null,createdAt:O,updatedAt:O,sortOrder:B+1};m(null),l(P=>[...P,R]),g(P=>P.map(F=>F.id===T?{...F,items:[...F.items,R]}:F));try{const P=await PN(T,_,n);l(F=>F.map(q=>q.id===R.id?P:q)),g(F=>F.map(q=>q.id===T?{...q,items:q.items.map(ee=>ee.id===R.id?P:ee)}:q))}catch(P){l(M),g(E),m(P instanceof Error?P.message:"Failed to create item"),s?.("Failed to create todo item","error")}},[s,o,p,n]),C=i.useCallback(async(_,T)=>{const M=o.find(P=>P.id===_);if(!M)return;const E=o,O=p,B=T.completed??M.completed,R={...M,...T,completed:B,completedAt:B?M.completedAt??new Date().toISOString():null,updatedAt:new Date().toISOString()};m(null),l(P=>P.map(F=>F.id===_?R:F)),g(P=>P.map(F=>F.id===R.listId?{...F,items:F.items.map(q=>q.id===_?R:q)}:F));try{const P=await RN(_,T,n);l(F=>F.map(q=>q.id===_?P:q)),g(F=>F.map(q=>q.id===P.listId?{...q,items:q.items.map(ee=>ee.id===_?P:ee)}:q))}catch(P){l(E),g(O),m(P instanceof Error?P.message:"Failed to update item"),s?.("Failed to update todo item","error")}},[s,o,p,n]),A=i.useCallback(async _=>{const T=o.find(M=>M.id===_);T&&await C(_,{completed:!T.completed})},[o,C]),N=i.useCallback(async _=>{const T=o,M=p;m(null),l(E=>E.filter(O=>O.id!==_)),g(E=>E.map(O=>({...O,items:O.items.filter(B=>B.id!==_)})));try{await TN(_,n)}catch(E){l(T),g(M),m(E instanceof Error?E.message:"Failed to delete item"),s?.("Failed to delete todo item","error")}},[s,o,p,n]),S=i.useCallback(async _=>{const T=x.current;if(!T)return;const M=o,E=p,O=new Map(o.map(R=>[R.id,R])),B=_.map((R,P)=>{const F=O.get(R);return F?{...F,sortOrder:P}:null}).filter(R=>R!==null);m(null),l(B),g(R=>R.map(P=>P.id===T?{...P,items:B}:P));try{await IN(T,_,n)}catch(R){l(M),g(E),m(R instanceof Error?R.message:"Failed to reorder items"),s?.("Failed to reorder todo items","error")}},[s,o,p,n]);return{lists:a,items:o,loading:c,error:u,selectedListId:h,setSelectedListId:f,createList:v,renameList:b,deleteList:y,createItem:j,updateItem:C,toggleItem:A,deleteItem:N,reorderItems:S}}function rI(e){return[...e].sort((n,s)=>n.sortOrder-s.sortOrder)}function mb({projectId:e,addToast:n,onPlanningMode:s,onTaskCreated:a}){const{lists:r,items:o,loading:l,error:c,selectedListId:d,setSelectedListId:u,createList:m,renameList:h,deleteList:f,createItem:p,updateItem:g,toggleItem:x,deleteItem:v,reorderItems:b}=aI({projectId:e,addToast:(ie,se)=>{if(se==="success"||se==="error"||se==="info"||se===void 0){n(ie,se);return}n(ie,"info")}}),[y,j]=i.useState(null),[C,A]=i.useState(""),[N,S]=i.useState(null),[_,T]=i.useState(""),[M,E]=i.useState(""),[O,B]=i.useState(!1),[R,P]=i.useState(""),[F,q]=i.useState([]),[ee,U]=i.useState(!1),[k,I]=i.useState(!1),[$,w]=i.useState(null),H=i.useRef(null),{confirm:J}=Gs(),fe=i.useMemo(()=>r.find(ie=>ie.id===d)??null,[r,d]),de=i.useMemo(()=>rI(o.filter(ie=>ie.listId===d)),[o,d]);function D(){j(null),A(""),E(""),B(!1)}function _e(){S(null),T(""),P("")}function z(ie){D(),_e(),u(ie)}const Z=i.useCallback(async()=>{U(!0);try{const ie=await fa(void 0,e);q(ie),I(!0)}catch(ie){n(`Failed to load agents: ${Me(ie)}`,"error"),I(!1),w(null)}finally{U(!1)}},[e,n]);i.useEffect(()=>{j(null),A(""),E(""),B(!1),S(null),T(""),P(""),I(!1),w(null)},[d]),i.useEffect(()=>{if(!k)return;const ie=se=>{H.current&&!H.current.contains(se.target)&&(I(!1),w(null))};return document.addEventListener("mousedown",ie),()=>{document.removeEventListener("mousedown",ie)}},[k]);function oe(ie){_e(),j(ie.id),A(ie.title),B(!1)}async function Y(){if(!y)return;const ie=C.trim();if(!ie){j(null),A("");return}await h(y,ie),j(null),A("")}function ae(){j(null),A("")}function ce(ie){D(),S(ie.id),T(ie.text)}async function te(){if(!N)return;const ie=_.trim();if(!ie){S(null),T("");return}await g(N,{text:ie}),S(null),T("")}function Re(){S(null),T("")}async function be(){const ie=M.trim();ie&&(await m(ie),E(""),B(!1))}async function ke(){if(!d)return;const ie=R.trim();ie&&(await p(ie),P(""))}async function Ue(ie){await J({title:"Delete List",message:"Delete this list and all its items?",danger:!0})&&await f(ie)}async function Ge(ie){await v(ie)}async function qe(ie,se){const xe=de.map(Qe=>Qe.id),ne=xe.findIndex(Qe=>Qe===ie);if(ne<0)return;const Fe=se==="up"?ne-1:ne+1;Fe<0||Fe>=xe.length||([xe[ne],xe[Fe]]=[xe[Fe],xe[ne]],await b(xe))}const Ae=i.useCallback(async ie=>{try{const se={description:ie.text,column:"triage",source:{sourceType:"dashboard_ui"}},xe=await rl(se,e);a?.(xe),n(`Created ${xe.id} from todo`,"success")}catch(se){n(`Failed to create task: ${Me(se)}`,"error")}},[e,n,a]),Ee=i.useCallback(async(ie,se)=>{try{const xe={description:ie.text,column:"triage",assignedAgentId:se,source:{sourceType:"dashboard_ui"}},ne=await rl(xe,e);a?.(ne);const Qe=F.find(ge=>ge.id===se)?.name??se;n(`Created ${ne.id} and assigned to ${Qe}`,"success"),I(!1),w(null)}catch(xe){n(`Failed to create and assign task: ${Me(xe)}`,"error")}},[e,n,F,a]);return l?t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-loading",children:[t.jsx(ft,{className:"todo-loading-icon","aria-hidden":"true"}),t.jsx("p",{children:"Loading todos..."})]})}):t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-view-layout",children:[t.jsxs("aside",{className:"todo-view-sidebar","aria-label":"Todo lists sidebar",children:[t.jsxs("div",{className:"todo-sidebar-header",children:[t.jsx("h3",{className:"todo-sidebar-title",children:"Lists"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-add-list-btn",onClick:()=>{_e(),B(!0),j(null)},"aria-label":"Add list","data-testid":"add-list-button",children:t.jsx(Nn,{})})]}),O&&t.jsxs("div",{className:"todo-list-item",children:[t.jsx("input",{className:"input todo-inline-edit-input",placeholder:"New list title",value:M,onChange:ie=>E(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&be(),ie.key==="Escape"&&(E(""),B(!1))},autoFocus:!0,"data-testid":"new-list-input"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{be()},"aria-label":"Save list",children:t.jsx(ns,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{E(""),B(!1)},"aria-label":"Cancel list",children:t.jsx(tn,{})})]}),r.length===0&&!O?t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(cd,{"aria-hidden":"true"}),t.jsx("p",{children:"No todo lists yet. Create one to get started."}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{_e(),B(!0)},children:"Create List"})]}):t.jsx("div",{className:"todo-list-items",role:"list","aria-label":"Todo lists",children:r.map(ie=>{const se=ie.id===d,xe=ie.id===y;return t.jsx("div",{className:`todo-list-item${se?" todo-list-item--active":""}`,role:"listitem",children:xe?t.jsxs(t.Fragment,{children:[t.jsx("input",{className:"input todo-inline-edit-input",value:C,onChange:ne=>A(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&Y(),ne.key==="Escape"&&ae()},autoFocus:!0,"data-testid":`rename-list-input-${ie.id}`}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{Y()},"aria-label":"Save list rename",children:t.jsx(ns,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:ae,"aria-label":"Cancel list rename",children:t.jsx(tn,{})})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"todo-list-select-btn",onClick:()=>z(ie.id),"aria-label":`Select list ${ie.title}`,"aria-current":se?"true":void 0,"data-testid":`todo-list-${ie.id}`,children:t.jsx("span",{className:"todo-list-item-name",children:ie.title})}),t.jsxs("div",{className:"todo-list-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{oe(ie)},"aria-label":`Rename ${ie.title}`,"data-testid":`rename-list-button-${ie.id}`,children:t.jsx(js,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Ue(ie.id)},"aria-label":`Delete ${ie.title}`,"data-testid":`delete-list-button-${ie.id}`,children:t.jsx(Sn,{})})]})]})},ie.id)})})]}),t.jsxs("section",{className:"todo-view-main","aria-label":"Todo items",children:[c&&t.jsxs("div",{className:"todo-error-banner",role:"alert",children:[t.jsx("span",{className:"todo-error-message",children:c}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>window.location.reload(),children:"Retry"})]}),fe?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"todo-items-header",children:t.jsx("h3",{children:fe.title})}),t.jsxs("div",{className:"todo-add-item-row",children:[t.jsx("input",{className:"input",placeholder:"Add a todo item",value:R,onChange:ie=>P(ie.target.value),onKeyDown:ie=>{ie.key==="Enter"&&ke(),ie.key==="Escape"&&P("")},"data-testid":"new-item-input"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>{ke()},children:"Add"})]}),de.length===0?t.jsx("div",{className:"todo-empty-state",children:t.jsx("p",{children:"No items in this list. Add one above."})}):t.jsx("div",{className:"todo-items-list",children:de.map((ie,se)=>{const xe=ie.id===N;return t.jsxs("div",{className:"todo-item","data-testid":`todo-item-${ie.id}`,children:[t.jsxs("div",{className:"todo-item-main-row",children:[t.jsx("input",{type:"checkbox",checked:ie.completed,onChange:()=>{x(ie.id)},className:"todo-item-checkbox","aria-label":`Toggle ${ie.text}`,"data-testid":`toggle-item-${ie.id}`}),xe?t.jsx("input",{className:"input todo-inline-edit-input",value:_,onChange:ne=>T(ne.target.value),onKeyDown:ne=>{ne.key==="Enter"&&te(),ne.key==="Escape"&&Re()},autoFocus:!0,"data-testid":`edit-item-input-${ie.id}`}):t.jsx("button",{type:"button",className:`todo-item-text${ie.completed?" todo-item-text--completed":""}`,onClick:()=>ce(ie),children:ie.text})]}),t.jsx("div",{className:"todo-item-actions","data-testid":`todo-item-actions-${ie.id}`,children:xe?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{te()},"aria-label":"Save item edit",children:t.jsx(ns,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:Re,"aria-label":"Cancel item edit",children:t.jsx(tn,{})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"todo-item-reorder-btns",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{qe(ie.id,"up")},disabled:se===0,"aria-label":`Move ${ie.text} up`,"data-testid":`move-up-${ie.id}`,children:t.jsx(hi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{qe(ie.id,"down")},disabled:se===de.length-1,"aria-label":`Move ${ie.text} down`,"data-testid":`move-down-${ie.id}`,children:t.jsx(mn,{})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{s?.(ie.text)},"aria-label":`Start planning from ${ie.text}`,"data-testid":`planning-from-${ie.id}`,children:t.jsx(pi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{Ae(ie)},"aria-label":`Create task from ${ie.text}`,"data-testid":`create-task-from-${ie.id}`,children:t.jsx(yx,{})}),t.jsxs("div",{className:"todo-agent-picker-trigger",ref:$===ie.id?H:void 0,children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{w(ie.id),Z()},"aria-label":`Assign ${ie.text} to agent`,"data-testid":`assign-agent-for-${ie.id}`,children:t.jsx(Tn,{})}),k&&$===ie.id&&t.jsx("div",{className:"todo-agent-picker-dropdown",onMouseDown:ne=>{ne.preventDefault()},children:ee?t.jsx("div",{className:"todo-agent-picker-loading",children:"Loading agents..."}):F.filter(ne=>ne.state!=="terminated").length>0?F.filter(ne=>ne.state!=="terminated").map(ne=>t.jsxs("button",{type:"button",className:"todo-agent-picker-item",onClick:()=>{Ee(ie,ne.id)},children:[t.jsx(Tn,{}),t.jsx("span",{children:ne.name}),t.jsx("span",{className:"todo-agent-picker-role",children:ne.role})]},ne.id)):t.jsx("div",{className:"todo-agent-picker-empty",children:"No agents available"})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>ce(ie),"aria-label":`Edit ${ie.text}`,"data-testid":`edit-item-${ie.id}`,children:t.jsx(js,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Ge(ie.id)},"aria-label":`Delete ${ie.text}`,"data-testid":`delete-item-${ie.id}`,children:t.jsx(Sn,{})})]})})]},ie.id)})})]}):t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(cd,{"aria-hidden":"true"}),t.jsx("p",{children:"Select a list from the sidebar"})]})]})]})})}const hb=Object.freeze(Object.defineProperty({__proto__:null,TodoView:mb},Symbol.toStringTag,{value:"Module"}));function oI({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Li(e),l=Di()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Hl({enabled:l});Ci(l);const h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(cd,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(tn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(mb,{projectId:n,addToast:s,onPlanningMode:a,onClose:e})})]})})}function lI(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await Pw();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:Me(m)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function cI(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;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"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function dI(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const pb="kb-usage-hidden-windows",fb="kb-usage-modal-size",gb="kb-usage-provider-order";function dp(e){const n=as(fb,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function up(e){const n=as(pb,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function uI(e,n){xs(pb,JSON.stringify(e),n)}function mp(e){const n=as(gb,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function hp(e,n){xs(gb,JSON.stringify(e),n)}function bb(e,n,s){return s[e]?.includes(n)??!1}function mI({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=dI(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`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&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),j=b%24;y>0&&j>0?u=`resets in ${y}d ${j}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=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:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Ja,{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:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:cI(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Al,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(Cy,{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(Un,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function hI(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 pI({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:x,onMoveUp:v,onMoveDown:b}){const y=s[e.name]?.length??0,j=()=>{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${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Qn,{provider:hI(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>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 (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(hi,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!x,"aria-label":`Move ${e.name} down`,children:t.jsx(mn,{size:14})})]}),j(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(Cl,{size:16})})]})]}),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,A)=>{const N=bb(e.name,C.label,s);return t.jsx(mI,{window:C,viewMode:n,isHidden:N,onToggleHidden:()=>a(e.name,C.label)},`${e.name}-${C.label}-${A}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function fI(){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 gI({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=lI({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,v]=i.useState("used"),[b,y]=i.useState(()=>up(s)),[j,C]=i.useState(()=>mp(s)),[A,N]=i.useState(null),[S,_]=i.useState(null),[T,M]=i.useState(null),E=i.useRef(null),O=i.useRef(null),B=i.useRef(e),R=i.useRef(!1),[P,F]=i.useState(()=>dp(s));i.useEffect(()=>{F(dp(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const be=O.current;if(!be||typeof ResizeObserver>"u")return;let ke=null;const Ue=new ResizeObserver(Ge=>{const qe=Ge[0];if(!qe)return;const{width:Ae,height:Ee}=qe.contentRect;Ae<=0||Ee<=0||(ke&&clearTimeout(ke),ke=setTimeout(()=>{xs(fb,JSON.stringify({width:Math.round(Ae),height:Math.round(Ee)}),s)},250))});return Ue.observe(be),()=>{ke&&clearTimeout(ke),Ue.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(R.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(R.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const be=window.matchMedia?.("(pointer: coarse)"),ke=()=>{f(window.innerWidth>=769),g(be?.matches??!1)};return ke(),window.addEventListener("resize",ke),be?.addEventListener?.("change",ke),()=>{window.removeEventListener("resize",ke),be?.removeEventListener?.("change",ke)}},[]),i.useEffect(()=>{!B.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),B.current=e},[e,c,d]),i.useEffect(()=>{const be=as("kb-usage-view-mode",s);if(be==="used"||be==="remaining"){v(be);return}v("used")},[s]);const q=i.useCallback(be=>{v(be),xs("kb-usage-view-mode",be,s)},[s]);i.useEffect(()=>{y(up(s)),C(mp(s))},[s]),i.useEffect(()=>{uI(b,s)},[b,s]);const ee=i.useCallback((be,ke)=>{y(Ue=>{if(bb(be,ke,Ue)){const Ge=(Ue[be]??[]).filter(qe=>qe!==ke);if(Ge.length===0){const{[be]:qe,...Ae}=Ue;return Ae}return{...Ue,[be]:Ge}}return{...Ue,[be]:[...Ue[be]??[],ke]}})},[]),U=i.useCallback(be=>{y(ke=>{if(!ke[be])return ke;const{[be]:Ue,...Ge}=ke;return Ge})},[]),k=i.useCallback(be=>{if(j.length===0)return be;const ke=new Map(be.map(Ge=>[Ge.name,Ge])),Ue=[];for(const Ge of j){const qe=ke.get(Ge);qe&&(Ue.push(qe),ke.delete(Ge))}return[...Ue,...ke.values()]},[j]),I=i.useCallback((be,ke)=>{be.dataTransfer.effectAllowed="move",be.dataTransfer.setData("text/plain",ke),N(ke)},[]),$=i.useCallback((be,ke)=>{if(!A||A===ke)return;be.preventDefault(),be.dataTransfer.dropEffect="move";const{top:Ue,height:Ge}=be.currentTarget.getBoundingClientRect(),qe=Ue+Ge/2,Ae=be.clientY<qe?"before":"after";_(ke),M(Ae)},[A]),w=i.useCallback((be,ke)=>{be.preventDefault();const Ue=A??be.dataTransfer.getData("text/plain");if(!Ue||Ue===ke){_(null),M(null);return}const qe=k(r).map(ie=>ie.name).filter(ie=>ie!==Ue),Ae=qe.indexOf(ke);if(Ae<0){_(null),M(null);return}const Ee=T==="after"?Ae+1:Ae;qe.splice(Ee,0,Ue),hp(qe,s),C(qe),_(null),M(null)},[A,T,s,r,k]),H=i.useCallback(()=>{N(null),_(null),M(null)},[]),J=i.useCallback((be,ke)=>{const Ue=k(r).map(ie=>ie.name),Ge=Ue.indexOf(be),qe=Ge+ke;if(Ge<0||qe<0||qe>=Ue.length)return;const Ae=[...Ue],[Ee]=Ae.splice(Ge,1);Ae.splice(qe,0,Ee),hp(Ae,s),C(Ae)},[s,r,k]),fe=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const be=ke=>{ke.key==="Escape"&&n()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,n]);const de=i.useCallback(be=>{be.target===be.currentTarget&&n()},[n]);if(!e)return null;const D=!!(a&&h),_e=8,z=12,oe=P?.width??420,Y=D?Math.min((a?.bottom??0)+_e,window.innerHeight-z):void 0,ae=D?Math.max(8,(a?.right??0)-oe):void 0,ce=h&&P?{width:P.width,height:P.height}:{},te=k(r),Re=t.jsxs("div",{ref:O,className:`usage-modal${D?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:D?{position:"fixed",top:Y,left:ae,...ce}:ce,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(qs,{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 ${x==="used"?"active":""}`,onClick:()=>q("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>q("remaining"),"aria-pressed":x==="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(tn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:E,children:(o||!R.current&&!l)&&r.length===0?t.jsx(fI,{}):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:fe,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:te.map((be,ke)=>t.jsx(pI,{provider:be,viewMode:x,hiddenWindows:b,onToggleWindow:ee,onShowAllHidden:U,isDragging:A===be.name,isDragOver:S===be.name,dragOverPosition:S===be.name?T:null,onDragStart:Ue=>I(Ue,be.name),onDragOver:Ue=>$(Ue,be.name),onDragLeave:()=>{S===be.name&&(_(null),M(null))},onDrop:Ue=>w(Ue,be.name),onDragEnd:H,isTouchReorderMode:p,canMoveUp:ke>0,canMoveDown:ke<te.length-1,onMoveUp:()=>J(be.name,-1),onMoveDown:()=>J(be.name,1)},be.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:fe,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(os,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return D?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),Re]}):t.jsx("div",{className:"modal-overlay open",onClick:de,"data-testid":"usage-modal-overlay",children:Re})}function xb(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),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function xl(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);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 a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const bI={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},vb={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},xI={cron:ef,webhook:df,api:tf,manual:is},vI={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},yI={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function wI({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(Un,{size:12}):t.jsx(Xr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:xb(n)})]})}function kI({result:e,index:n}){const[s,a]=i.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:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${xl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Un,{size:12}):t.jsx(Xr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:xl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:vb[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:xb(r)}),s?t.jsx(hi,{size:12}):t.jsx(mn,{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 jI({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=Gs(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=bI[e.trigger.type],f=xI[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(f,{size:10}),vb[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(Nl,{size:10}):t.jsx(fs,{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:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(ft,{className:"spinner"}):t.jsx(Yn,{})}),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(ui,{}):t.jsx(Yn,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(js,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Sn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(oa,{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(Ii,{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:vI[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:yI[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:xl(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:xl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(wI,{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:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(hi,{size:12}):t.jsx(mn,{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((g,x)=>t.jsx(kI,{result:g,index:x},`${g.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function NI({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Ti,{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(_v,{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(vs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Wc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function SI(e){return e==="command"?{id:Wc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Wc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Wc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function CI({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[x,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[j,C]=i.useState(e.taskColumn??"triage"),[A,N]=i.useState(e.timeoutMs),[S,_]=i.useState(e.continueOnFailure??!1),[T,M]=i.useState({}),[E,O]=i.useState([]),[B,R]=i.useState(!1),[P,F]=i.useState(null);i.useEffect(()=>{let I=!1;return R(!0),F(null),Ds().then($=>{I||O($.models)}).catch($=>{I||F($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{I||R(!1)}),()=>{I=!0}},[]);const q=i.useCallback(()=>{const I={};return a.trim()||(I.name="Step name is required"),o==="command"&&!c.trim()&&(I.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(I.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(I.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(I.modelProvider="Both model provider and model ID must be set together"),A!==void 0&&A<1e3&&(I.timeoutMs="Timeout must be at least 1 second (1000ms)"),M(I),Object.keys(I).length===0},[a,o,c,u,b,h,p,A]),ee=h&&p?`${h}/${p}`:"",U=i.useCallback(I=>{if(!I)f(""),g("");else{const $=I.indexOf("/");$!==-1&&(f(I.slice(0,$)),g(I.slice($+1)))}},[]),k=i.useCallback(()=>{if(!q())return;const I={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.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"?j:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:A||void 0,continueOnFailure:S};o!=="ai-prompt"&&delete I.prompt,o!=="create-task"&&(delete I.taskTitle,delete I.taskDescription,delete I.taskColumn),n(I)},[q,n,e,a,o,c,u,x,b,j,h,p,A,S]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:I=>r(I.target.value),"aria-invalid":!!T.name}),T.name&&t.jsx("small",{className:"field-error",children:T.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:I=>l(I.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:I=>d(I.target.value),rows:2,"aria-invalid":!!T.command}),T.command&&t.jsx("small",{className:"field-error",children:T.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:u,onChange:I=>m(I.target.value),rows:3,"aria-invalid":!!T.prompt}),T.prompt&&t.jsx("small",{className:"field-error",children:T.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(ys,{id:`step-model-${e.id}`,label:"Model",models:E,value:ee,onChange:U,placeholder:"Use default",disabled:B}),P&&t.jsx("small",{className:"field-error",children:P}),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:I=>v(I.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:I=>y(I.target.value),rows:4,"aria-invalid":!!T.taskDescription}),T.taskDescription&&t.jsx("small",{className:"field-error",children:T.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:j,onChange:I=>C(I.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(ys,{id:`step-task-model-${e.id}`,label:"Model",models:E,value:ee,onChange:U,placeholder:"Use default",disabled:B}),P&&t.jsx("small",{className:"field-error",children:P}),T.modelProvider&&t.jsx("small",{className:"field-error",children:T.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:A??"",onChange:I=>N(I.target.value?Number(I.target.value):void 0),"aria-invalid":!!T.timeoutMs}),T.timeoutMs&&t.jsx("small",{className:"field-error",children:T.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:S,onChange:I=>_(I.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:k,children:"Save Step"})]})]})}function EI({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const m=SI(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u: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((u,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(CI,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(Cl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(NI,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.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(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(hi,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(mn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(js,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(Sn,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Nn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Nn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Nn,{size:14}),"Add Create Task Step"]})]})]})}const yb={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},MI={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function _I(e){const n=e.trim();for(const[s,a]of Object.entries(yb))if(a===n)return s;return"custom"}function AI(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function PI(e,n,s,a,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:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function RI(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 TI=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],II=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function pp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function fp({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?RI(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,x]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":_I(c.cronExpression)),[y,j]=i.useState(c.webhookPath),[C,A]=i.useState(c.webhookSecret),[N,S]=i.useState(c.endpoint),[_,T]=i.useState(e?.executionPolicy??"queue"),[M,E]=i.useState(e?.catchUpPolicy??"run_one"),[O,B]=i.useState(e?.enabled??!0),R=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,P=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[F,q]=i.useState(e?.steps&&e.steps.length>0&&!R&&!P?"advanced":"simple"),[ee,U]=i.useState(()=>R?"ai-prompt":P?"create-task":"command"),[k,I]=i.useState(e?.command??""),[$,w]=i.useState(e?.steps??[]),[H,J]=i.useState(!1),[fe,de]=i.useState(e?.timeoutMs??3e5),[D,_e]=i.useState(R?e.steps?.[0]?.prompt??"":""),[z,Z]=i.useState(P?e.steps?.[0]?.taskTitle??"":""),[oe,Y]=i.useState(P?e.steps?.[0]?.taskDescription??"":""),[ae,ce]=i.useState(P?e.steps?.[0]?.taskColumn??"triage":"triage"),[te,Re]=i.useState(R||P?e.steps?.[0]?.modelProvider??"":""),[be,ke]=i.useState(R||P?e.steps?.[0]?.modelId??"":""),[Ue,Ge]=i.useState([]),[qe,Ae]=i.useState(!1),[Ee,ie]=i.useState(null),[se,xe]=i.useState(a??"global"),[ne,Fe]=i.useState({}),[Qe,ge]=i.useState(!1),ze=i.useRef(!0);i.useEffect(()=>()=>{ze.current=!1},[]),i.useEffect(()=>{a&&xe(a)},[a]),i.useEffect(()=>{let De=!1;return Ae(!0),ie(null),Ds().then(vt=>{De||Ge(vt.models)}).catch(vt=>{De||ie(vt instanceof Error?vt.message:"Failed to load models")}).finally(()=>{De||Ae(!1)}),()=>{De=!0}},[]);const tt=te&&be?`${te}/${be}`:"",pt=i.useCallback(De=>{if(!De){Re(""),ke("");return}const vt=De.indexOf("/");vt!==-1&&(Re(De.slice(0,vt)),ke(De.slice(vt+1)))},[]),ve=i.useCallback(()=>{const De={};if(d.trim()||(De.name="Name is required"),se==="project"&&!r&&(De.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?AI(g)||(De.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):De.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(De.webhookPath="Webhook path is required"),f==="api"&&!N.trim()&&(De.endpoint="API endpoint is required"),F==="simple")ee==="command"&&!k.trim()&&(De.command="Command is required"),ee==="ai-prompt"&&!D.trim()&&(De.prompt="Prompt is required"),ee==="create-task"&&!oe.trim()&&(De.taskDescription="Task description is required"),(te.trim()&&!be.trim()||!te.trim()&&be.trim())&&(De.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(De.steps="At least one step is required"),H&&(De.stepsEditing="Please save or cancel all step edits before saving the routine");const vt=[];$.forEach((Et,bt)=>{Et.name?.trim()||vt.push(`Step ${bt+1}: Name is required`),Et.type==="command"&&!Et.command?.trim()&&vt.push(`Step ${bt+1}: Command is required`),Et.type==="ai-prompt"&&!Et.prompt?.trim()&&vt.push(`Step ${bt+1}: Prompt is required`),Et.type==="create-task"&&!Et.taskDescription?.trim()&&vt.push(`Step ${bt+1}: Task description is required`)}),vt.length>0&&(De.steps=vt.join("; "))}return fe<1e3&&(De.timeoutMs="Timeout must be at least 1 second (1000ms)"),Fe(De),Object.keys(De).length===0},[d,f,g,v,y,N,se,r,F,ee,k,D,oe,te,be,$,H,fe]),le=i.useCallback(async De=>{if(De.preventDefault(),!!ve()){ge(!0);try{let vt=e?.scope??se??(r?"project":"global");vt==="project"&&!r&&(vt="global");const Et=PI(f,g,y,C,N);let bt,zt;F==="simple"?ee==="command"?bt=k.trim()||void 0:ee==="ai-prompt"?zt=[{id:pp(),type:"ai-prompt",name:d.trim(),prompt:D.trim(),modelProvider:te.trim()||void 0,modelId:be.trim()||void 0}]:zt=[{id:pp(),type:"create-task",name:d.trim(),taskTitle:z.trim()||void 0,taskDescription:oe.trim(),taskColumn:ae,modelProvider:te.trim()||void 0,modelId:be.trim()||void 0}]:zt=$;const qt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Et,command:bt,steps:zt,timeoutMs:fe,executionPolicy:_,catchUpPolicy:M,enabled:O,scope:vt};await n(qt)}finally{ze.current&&ge(!1)}}},[ve,n,d,m,f,g,y,C,N,F,ee,k,D,te,be,z,oe,ae,$,fe,_,M,O,se,r,e?.scope,e?.agentId]),Te="routine-name-error",pe="routine-cron-error",$e="routine-webhook-error",st="routine-endpoint-error",at="routine-command-error",rt="routine-prompt-error",Oe="routine-task-description-error",Be="routine-model-error",et="routine-timeout-error",jt=i.useCallback(De=>{b(De),De!=="custom"&&x(yb[De])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:le,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:d,onChange:De=>u(De.target.value),"aria-invalid":!!ne.name,"aria-describedby":ne.name?Te:void 0}),ne.name&&t.jsx("small",{id:Te,className:"field-error",children:ne.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:De=>h(De.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="global"?" active":""}`,onClick:()=>{xe("global"),o?.("global")},role:"radio","aria-checked":se==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Nl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="project"?" active":""}`,onClick:()=>{xe("project"),o?.("project")},role:"radio","aria-checked":se==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(fs,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":se==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),ne.scope&&t.jsx("small",{className:"field-error",children:ne.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${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(ef,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(df,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(tf,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(is,{size:14}),"Manual"]})]})]}),f==="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:De=>jt(De.target.value),children:Object.entries(MI).map(([De,vt])=>t.jsx("option",{value:De,children:vt},De))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:De=>x(De.target.value),disabled:v!=="custom","aria-invalid":!!ne.cronExpression,"aria-describedby":ne.cronExpression?pe:void 0}),ne.cronExpression?t.jsx("small",{id:pe,className:"field-error",children:ne.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: ${g}`})]}),f==="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:De=>j(De.target.value),"aria-invalid":!!ne.webhookPath,"aria-describedby":ne.webhookPath?$e:void 0}),ne.webhookPath?t.jsx("small",{id:$e,className:"field-error",children:ne.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:C,onChange:De=>A(De.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:N,onChange:De=>S(De.target.value),"aria-invalid":!!ne.endpoint,"aria-describedby":ne.endpoint?st:void 0}),ne.endpoint?t.jsx("small",{id:st,className:"field-error",children:ne.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="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${F==="simple"?" active":""}`,onClick:()=>q("simple"),role:"radio","aria-checked":F==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${F==="advanced"?" active":""}`,onClick:()=>q("advanced"),role:"radio","aria-checked":F==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:F==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),F==="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${ee==="command"?" active":""}`,onClick:()=>U("command"),role:"radio","aria-checked":ee==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ee==="ai-prompt"?" active":""}`,onClick:()=>U("ai-prompt"),role:"radio","aria-checked":ee==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ee==="create-task"?" active":""}`,onClick:()=>U("create-task"),role:"radio","aria-checked":ee==="create-task",children:"Create Task"})]})]}),ee==="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:k,onChange:De=>I(De.target.value),"aria-invalid":!!ne.command,"aria-describedby":ne.command?at:void 0}),ne.command?t.jsx("small",{id:at,className:"field-error",children:ne.command}):t.jsx("small",{children:"Shell command to execute."})]}):ee==="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:D,onChange:De=>_e(De.target.value),rows:3,"aria-invalid":!!ne.prompt,"aria-describedby":ne.prompt?rt:void 0}),ne.prompt?t.jsx("small",{id:rt,className:"field-error",children:ne.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(ys,{id:"routine-model",label:"Model",models:Ue,value:tt,onChange:pt,placeholder:"Use default",disabled:qe}),Ee&&t.jsx("small",{className:"field-error",children:Ee}),ne.model&&t.jsx("small",{id:Be,className:"field-error",children:ne.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:z,onChange:De=>Z(De.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:oe,onChange:De=>Y(De.target.value),rows:4,"aria-invalid":!!ne.taskDescription,"aria-describedby":ne.taskDescription?Oe:void 0}),ne.taskDescription?t.jsx("small",{id:Oe,className:"field-error",children:ne.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:ae,onChange:De=>ce(De.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(ys,{id:"routine-task-model",label:"Executor Model",models:Ue,value:tt,onChange:pt,placeholder:"Use default",disabled:qe}),Ee&&t.jsx("small",{className:"field-error",children:Ee}),ne.model&&t.jsx("small",{id:Be,className:"field-error",children:ne.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(EI,{steps:$,onChange:w,onEditingChange:J}),ne.steps&&t.jsx("small",{className:"field-error",children:ne.steps}),ne.stepsEditing&&t.jsx("small",{className:"field-error",children:ne.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:fe,onChange:De=>de(Number(De.target.value)),"aria-invalid":!!ne.timeoutMs,"aria-describedby":ne.timeoutMs?et:void 0}),ne.timeoutMs?t.jsx("small",{id:et,className:"field-error",children:ne.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:_,onChange:De=>T(De.target.value),children:TI.map(De=>t.jsx("option",{value:De.value,children:De.label},De.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:M,onChange:De=>E(De.target.value),children:II.map(De=>t.jsx("option",{value:De.value,children:De.label},De.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:O,onChange:De=>B(De.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:Qe,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Qe,children:Qe?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const $I=3e4;function DI({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),x=i.useRef(null);Si(x,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const R=await Zk(v);l(R),g(P=>{const F={...P};for(const q of R){const ee=F[q.id];if(!ee||!q.lastRunResult)continue;const U=q.lastRunResult;U.success===ee.success&&(U.output||"")===ee.output&&(U.error||"")===(ee.error||"")&&delete F[q.id]}return F})}catch(R){n(Me(R)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const R=setInterval(()=>{b()},$I);return()=>clearInterval(R)},[b]),i.useEffect(()=>{const R=P=>{P.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[e,c]);const y=Li(e),j=i.useCallback(async R=>{try{await ej(R,v),n("Routine created","success"),d("list"),await b()}catch(P){n(Me(P)||"Failed to create routine","error")}},[n,b,v]),C=i.useCallback(R=>{m(R),d("edit")},[]),A=i.useCallback(async R=>{if(u)try{await Bu(u.id,R,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(P){n(Me(P)||"Failed to update routine","error")}},[u,n,b,v]),N=i.useCallback(async R=>{try{await tj(R.id,v),n(`Deleted "${R.name}"`,"success"),await b()}catch(P){n(Me(P)||"Failed to delete routine","error")}},[n,b,v]),S=i.useCallback(async R=>{f(R.id);try{const{result:P}=await nj(R.id,v);g(F=>({...F,[R.id]:{output:P.output||"",error:P.error,success:P.success}})),P.success?n(`"${R.name}" completed successfully`,"success"):n(`"${R.name}" failed: ${P.error||"Unknown error"}`,"error"),await b()}catch(P){n(Me(P)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),_=i.useCallback(async R=>{try{await Bu(R.id,{enabled:!R.enabled},v),n(`"${R.name}" ${R.enabled?"disabled":"enabled"}`,"success"),await b()}catch(P){n(Me(P)||"Failed to toggle routine","error")}},[n,b,v]),T=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const M=i.useCallback(R=>{r(R),d("list"),m(void 0),g({})},[]),E=()=>c==="create"?t.jsx(fp,{onSubmit:j,onCancel:T,scope:a,projectId:s}):c==="edit"&&u?t.jsx(fp,{routine:u,onSubmit:A,onCancel:T,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(is,{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:()=>d("create"),children:[t.jsx(Nn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(R=>t.jsx(jI,{routine:R,onEdit:C,onDelete:N,onRun:S,onToggle:_,running:h===R.id,lastRunOutput:p[R.id]??null},R.id))}),O=()=>E(),B=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(is,{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(tn,{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${a==="global"?" active":""}`,onClick:()=>M("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(Nl,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>M("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(fs,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(is,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:B&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(Nn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:O()})]})})}const LI=3e4,Dd=new Map,Kc=new Map;function gp(e){return e??"default"}function bp(e){const n=Dd.get(e);return n?Date.now()>=n.expiresAt?(Dd.delete(e),null):n:null}function OI(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function zI(e){const n=Kc.get(e);if(n)return n;const s=Hr().then(({providers:a,ghCli:r})=>{const l={...OI(a,r),ghCli:r,expiresAt:Date.now()+LI};return Dd.set(e,l),l}).finally(()=>{Kc.delete(e)});return Kc.set(e,s),s}function wb(e){const n=gp(e),s=bp(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=gp(e),p=bp(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const v=await zI(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function kb({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(tn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" 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${a?" 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 FI({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=Gs();Ci(e);const[u,m]=i.useState(""),[h,f]=i.useState([]),[p,g]=i.useState([]),[x,v]=i.useState(!1),[b,y]=i.useState(""),[j,C]=i.useState(""),[A,N]=i.useState(""),[S,_]=i.useState(""),[T,M]=i.useState(""),[E,O]=i.useState("default"),[B,R]=i.useState(!1),[P,F]=i.useState([]),[q,ee]=i.useState(!1),[U,k]=i.useState(void 0),[I,$]=i.useState(Cs),[w,H]=i.useState(void 0),[J,fe]=i.useState(null),[de,D]=i.useState([]),[_e,z]=i.useState(!1),[Z,oe]=i.useState(!1),Y=i.useRef(null),[ae,ce]=i.useState(!1),[te,Re]=i.useState(""),be=i.useRef(null),{hasAiProvider:ke,hasGithub:Ue,loading:Ge}=wb(s),{nodes:qe}=$l(),Ae=i.useCallback(ve=>{ee(!0),F(ve)},[]),Ee=i.useCallback(()=>{ee(!1)},[]),ie=i.useCallback(async()=>{if(de.length>0){z(!0);return}oe(!0);try{const ve=await fa(void 0,s);D(ve),z(!0)}catch(ve){const le=Me(ve);o(le?`Failed to load agents: ${le}`:"Failed to load agents","error"),z(!1)}finally{oe(!1)}},[de.length,s,o]);i.useEffect(()=>{if(!_e)return;const ve=le=>{Y.current&&!Y.current.contains(le.target)&&z(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[_e]),i.useEffect(()=>{if(!ae)return;const ve=le=>{be.current&&!be.current.contains(le.target)&&(ce(!1),Re(""))};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[ae]);const se=a.filter(ve=>!h.includes(ve.id)).sort((ve,le)=>{const Te=le.createdAt.localeCompare(ve.createdAt);if(Te!==0)return Te;const pe=parseInt(ve.id.slice(ve.id.lastIndexOf("-")+1),10)||0;return(parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0)-pe}),xe=te?se.filter(ve=>ve.id.toLowerCase().includes(te.toLowerCase())||ve.title&&ve.title.toLowerCase().includes(te.toLowerCase())||ve.description&&ve.description.toLowerCase().includes(te.toLowerCase())):se,ne=(ve,le)=>ve.length>le?ve.slice(0,le)+"…":ve;i.useEffect(()=>{const ve=u.trim()!==""||h.length>0||p.length>0||b!==""||j!==""||A!==""||S!==""||P.length>0||J!==null||U!==void 0||I!==Cs||w!==void 0;R(ve)},[u,h,p,b,j,A,S,P,J,U,I,w]);const Fe=i.useCallback(async()=>{B&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ve=>URL.revokeObjectURL(ve.previewUrl)),g([]),m(""),f([]),y(""),C(""),N(""),_(""),M(""),O("default"),F([]),ee(!1),fe(null),z(!1),k(void 0),$(Cs),H(void 0),R(!1),n())},[B,n,p,d]),Qe=i.useCallback(async()=>{const ve=u.trim();if(!(!ve||x)){v(!0);try{const le=b.indexOf("/"),Te=j.indexOf("/"),pe=A.indexOf("/"),$e=await r({title:void 0,description:ve,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:q?P.length>0?P:[]:void 0,...J?{assignedAgentId:J}:{},modelPresetId:E==="preset"&&T||void 0,modelProvider:b&&le!==-1?b.slice(0,le):void 0,modelId:b&&le!==-1?b.slice(le+1):void 0,validatorModelProvider:j&&Te!==-1?j.slice(0,Te):void 0,validatorModelId:j&&Te!==-1?j.slice(Te+1):void 0,planningModelProvider:A&&pe!==-1?A.slice(0,pe):void 0,planningModelId:A&&pe!==-1?A.slice(pe+1):void 0,thinkingLevel:S!==""?S:void 0,reviewLevel:U,priority:I,nodeId:w});if(p.length>0){const st=[];for(const at of p)try{await Br($e.id,at.file,s)}catch{st.push(at.file.name)}st.length>0&&o(`Failed to upload: ${st.join(", ")}`,"error")}p.forEach(st=>URL.revokeObjectURL(st.previewUrl)),g([]),m(""),f([]),y(""),C(""),N(""),_(""),M(""),O("default"),F([]),ee(!1),fe(null),z(!1),k(void 0),$(Cs),H(void 0),o(`Created ${$e.id}`,"success"),n()}catch(le){o(Me(le)||"Failed to create task","error")}finally{v(!1)}}},[u,h,p,b,j,A,S,x,r,o,n,s,E,T,P,q,J,U,I,w]),ge=i.useCallback(ve=>{ve.key==="Escape"&&(ve.preventDefault(),Fe())},[Fe]),tt=(J?de.find(ve=>ve.id===J):void 0)?.name??J,pt=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:be,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ce(ve=>!ve),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),ae&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:te,onChange:ve=>Re(ve.target.value),onClick:ve=>ve.stopPropagation()}),xe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):xe.map(ve=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ve.id)?" selected":""}`,onClick:()=>{f(h.includes(ve.id)?h.filter(le=>le!==ve.id):[...h,ve.id]),ce(!1),Re("")},onMouseDown:le=>le.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ve.id}),t.jsx("span",{className:"dep-dropdown-title",children:ne(ve.title||ve.description||ve.id,30)})]},ve.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ve=>t.jsxs("span",{className:"dep-chip",children:[ve,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(le=>le!==ve)),disabled:x,children:"×"})]},ve))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Y,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{_e?z(!1):ie()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(Tn,{size:12,style:{verticalAlign:"middle"}}),tt?` ${tt}`:" Assign agent"]}),_e&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ve=>ve.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Z&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Z&&de.filter(ve=>ve.state!=="terminated").map(ve=>t.jsxs("div",{className:`dep-dropdown-item${J===ve.id?" selected":""}`,onMouseDown:le=>le.preventDefault(),onClick:()=>{fe(ve.id===J?null:ve.id),z(!1)},"data-testid":`agent-option-${ve.id}`,children:[t.jsx(Tn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ve.role}),t.jsx("span",{className:"dep-dropdown-title",children:ve.name})]},ve.id)),!Z&&de.filter(ve=>ve.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),J&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ve=>ve.preventDefault(),onClick:()=>{fe(null),z(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Fe,onKeyDown:ge,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ve=>ve.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Fe,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Ge&&t.jsx(kb,{hasAiProvider:ke,hasGithub:Ue}),t.jsx(tb,{mode:"create",description:u,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:b,onExecutorModelChange:y,validatorModel:j,onValidatorModelChange:C,presetMode:E,onPresetModeChange:O,selectedPresetId:T,onSelectedPresetIdChange:M,selectedWorkflowSteps:P,onWorkflowStepsChange:Ae,onDefaultOnApplied:Ee,pendingImages:p,onImagesChange:g,tasks:a,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Fe,planningModel:A,onPlanningModelChange:N,thinkingLevel:S,onThinkingLevelChange:_,reviewLevel:U,onReviewLevelChange:k,priority:I,onPriorityChange:$,nodeId:w,onNodeIdChange:H,nodeOptions:qe,renderBelowPrimary:pt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Fe,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Qe,disabled:!u.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function li(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 xp(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function UI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function BI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function HI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function Gc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function qI(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function VI({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[x,v]=i.useState(!1),[b,y]=i.useState(null),[j,C]=i.useState(null),[A,N]=i.useState(null),S=i.useCallback(async H=>{l(!0);try{const J=await Mj(s);r(J),d(null),N(Date.now()),H?.preserveKillResult||y(null)}catch(J){d(J instanceof Error?J.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;S();const H=window.setInterval(()=>{S()},5e3);return()=>{window.clearInterval(H)}},[e,S]),i.useEffect(()=>{if(!e)return;(async()=>{try{const J=await pa();m(J.vitestAutoKillEnabled??!0),f(J.vitestKillThresholdPct??90),C(null)}catch(J){C(J instanceof Error?J.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const H=J=>{J.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const _=i.useMemo(()=>{if(!a)return[];const H=a.systemStats,J=Gc(UI(H.heapUsed,H.heapLimit)),fe=Gc(BI(H.rss,H.systemTotalMem));return[{label:"RSS",value:li(H.rss),detail:xp(H.rss,H.systemTotalMem),className:fe},{label:"Heap Used",value:li(H.heapUsed),detail:`of ${li(H.heapTotal)}`,className:J},{label:"Heap Limit",value:li(H.heapLimit),detail:"V8 limit"},{label:"External",value:li(H.external)},{label:"Array Buffers",value:li(H.arrayBuffers)}]},[a]),T=i.useCallback(async H=>{m(H);try{await Pn({vitestAutoKillEnabled:H}),C(null)}catch(J){C(J instanceof Error?J.message:"Failed to save vitest settings")}},[]),M=i.useCallback(async H=>{const J=Math.min(99,Math.max(50,Number.isFinite(H)?Math.round(H):90));f(J);try{await Pn({vitestKillThresholdPct:J}),C(null)}catch(fe){C(fe instanceof Error?fe.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async()=>{if(!p){if(!x){v(!0);return}g(!0);try{const H=await _j(s);y(H),v(!1),await S({preserveKillResult:!0})}catch(H){d(H instanceof Error?H.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,S,s]);if(!e)return null;const O=a?.systemStats,B=o&&!!a,R=A?`Updated ${new Date(A).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",P=a?.taskStats,F=O?O.systemTotalMem-O.systemFreeMem:0,q=O?HI(F,O.systemTotalMem):"normal",ee=O?Gc(q):"",U=O&&Number.isFinite(O.systemTotalMem)&&O.systemTotalMem>0?Math.max(0,Math.min(100,F/O.systemTotalMem*100)):0,k=O?`System memory used: ${U.toFixed(1)}% (${li(F)} of ${li(O.systemTotalMem)})`:"System memory usage unavailable",I=a?.vitestProcessCount,$=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":"",w=qI(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:H=>{H.target===H.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(Da,{}),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:R})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void S(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(os,{size:16,className:B?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(tn,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&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:_.map(H=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${H.className}`.trim(),children:H.value}),H.detail?t.jsx("span",{className:"system-stats-modal__detail",children:H.detail}):null]})]},H.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:O?.loadAvg.map(H=>H.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:O?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:O?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:O?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:O?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ee}`.trim(),children:O?li(F):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:O?`${xp(F,O.systemTotalMem)} of ${li(O.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${q}`,role:"progressbar","aria-valuenow":Math.round(U),"aria-valuemin":0,"aria-valuemax":100,"aria-label":k,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${q}`,style:{width:`${U}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:O?li(O.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:P?.total??0})]}),Object.entries(P?.byColumn??{}).map(([H,J])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H}),t.jsx("dd",{children:J})]},H))]})]}),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:P?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:P?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:P?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:P?.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(hy,{}),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:I??"—"})]})}),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 E(),disabled:p||I===0,children:[t.jsx(by,{}),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:u,onChange:H=>{T(H.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:H=>{const J=Number.parseInt(H.target.value,10);M(Number.isNaN(J)?90:J)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:H=>{const J=Number.parseInt(H.target.value,10);M(Number.isNaN(J)?90:J)},onBlur:()=>{M(h)}})]})]}),b&&t.jsxs("p",{className:$,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",w]}),j&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:j})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const WI=5e3;function KI(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),x=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let j;o?j=await Ju({limit:a,projectId:n,type:s}):j=(await Hu({limit:a,type:s,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),c(j),p(j.length===a),j.length>0&&(x.current=j[j.length-1].timestamp)}catch(j){h(j instanceof Error?j.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let j;o?j=await Ju({limit:a,projectId:n,type:s,since:x.current}):j=(await Hu({limit:a,type:s,since:x.current,projectId:n})).map(A=>({...A,projectId:n??"",projectName:""})),c(C=>[...C,...j]),p(j.length===a),j.length>0&&(x.current=j[j.length-1].timestamp)}catch(j){h(j instanceof Error?j.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},WI),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:b}}const Jc={"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"},GI={"task:created":t.jsx(Nn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Qr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(os,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(tn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Un,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Xr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Rr,{size:14,className:"activity-icon settings"})};function JI(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/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 YI({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:j,refresh:C,hasMore:A}=KI({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),N=b.map(E=>({id:E.id,timestamp:E.timestamp,type:E.type,taskId:E.taskId,taskTitle:E.taskTitle,details:E.details,metadata:E.metadata,projectId:E.projectId,projectName:E.projectName})),S=async()=>{try{await sj(),C(),p(!1)}catch{p(!1)}},_=E=>{a&&a(E)},T=E=>{h(E),l?.(E==="all"?void 0:E)};i.useEffect(()=>{if(!e)return;const E=O=>{O.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,n,f]);const M=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:E=>{E.target===E.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(Fr,{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(fs,{size:14}),t.jsxs("select",{value:m,onChange:E=>T(E.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(E=>t.jsx("option",{value:E.id,children:E.name},E.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(tl,{size:14}),t.jsxs("select",{value:d,onChange:E=>u(E.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Jc).map(([E,O])=>t.jsx("option",{value:E,children:O},E))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>C(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14})}),N.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Sn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),M&&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(E=>E.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Jc[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[j&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(zs,{size:16}),t.jsx("span",{children:j})]}),N.length===0&&!y&&!j&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Fr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:M?"No activity matches the current filters":"No activity recorded yet"}),M&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:N.map(E=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:GI[E.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:Jc[E.type]}),t.jsx("span",{className:"activity-log-entry-time",children:JI(E.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[E.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>_(E.taskId),"data-testid":"activity-task-link",children:E.taskId}),E.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:E.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:E.details})]}),E.metadata&&Object.keys(E.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof E.metadata.from=="string"&&typeof E.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[E.metadata.from," → ",E.metadata.to]}),typeof E.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${E.metadata.merged?"success":"error"}`,children:E.metadata.merged?"Merged":"Not merged"})]})]})]},E.id))}),A&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:C,"data-testid":"activity-load-more",children:"Load More"}),y&&N.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(ft,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:S,children:"Clear Log"})]})]})})]})}):null}const vr=[{id:"status",label:"Status",icon:lf},{id:"changes",label:"Changes",icon:od},{id:"commits",label:"Commits",icon:Zr},{id:"branches",label:"Branches",icon:Ks},{id:"worktrees",label:"Worktrees",icon:fv},{id:"stashes",label:"Stashes",icon:Jr},{id:"remotes",label:"Remotes",icon:af}];function vp({status:e}){switch(e){case"added":case"untracked":return t.jsx(Gx,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(nf,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Vx,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Vi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Yx,{size:14,className:"gm-file-icon"})}}function yp({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 QI(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function qa(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/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 XI({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=Gs(),[l,c]=i.useState("status"),[d,u]=i.useState(!1),[m,h]=i.useState(null),f=i.useRef(null);Si(f,e,"fusion:git-modal-size");const p=Li(n),g=QI(a),[x,v]=i.useState(null),[b,y]=i.useState([]),[j,C]=i.useState(new Set),[A,N]=i.useState(""),[S,_]=i.useState(!1),[T,M]=i.useState(null),[E,O]=i.useState(!1),[B,R]=i.useState(null),[P,F]=i.useState(null),q=i.useRef(0),[ee,U]=i.useState([]),[k,I]=i.useState(null),[$,w]=i.useState(null),[H,J]=i.useState(!1),[fe,de]=i.useState(20),[D,_e]=i.useState(""),[z,Z]=i.useState([]),[oe,Y]=i.useState(""),[ae,ce]=i.useState(""),[te,Re]=i.useState(""),[be,ke]=i.useState(null),[Ue,Ge]=i.useState([]),[qe,Ae]=i.useState(!1),[Ee,ie]=i.useState(null),[se,xe]=i.useState(null),[ne,Fe]=i.useState(!1),[Qe,ge]=i.useState([]),[ze,tt]=i.useState([]),[pt,ve]=i.useState(""),[le,Te]=i.useState(null),[pe,$e]=i.useState(null),[st,at]=i.useState(null),rt=i.useCallback(async()=>{if(e){u(!0),h(null);try{switch(l){case"status":{const re=await oi(r);v(re);break}case"changes":{const[re,Pe]=await Promise.all([oi(r),wa(r)]);v(re),y(Pe),C(new Set),F(null),M(null),R(null);break}case"commits":{const re=await ok(fe,r);U(re);break}case"branches":{const[re,Pe]=await Promise.all([or(r),oi(r)]);Z(re),v(Pe);break}case"worktrees":{const re=await uk(r);ge(re);break}case"stashes":{const re=await yo(r);tt(re);break}case"remotes":{const re=await oi(r);v(re);break}}}catch(re){h(Me(re)||"Failed to fetch git data"),a(Me(re)||"Failed to fetch git data","error")}finally{u(!1)}}},[l,e,fe,a,r]);i.useEffect(()=>{e&&rt()},[rt,e]),i.useEffect(()=>{if(!e)return;const re=Pe=>{if(Pe.key==="Escape"){n();return}if((Pe.key==="ArrowUp"||Pe.key==="ArrowDown")&&Pe.altKey){Pe.preventDefault();const Se=vr.findIndex(X=>X.id===l);Pe.key==="ArrowUp"&&Se>0?c(vr[Se-1].id):Pe.key==="ArrowDown"&&Se<vr.length-1&&c(vr[Se+1].id)}};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[e,n,l]);const Oe=i.useCallback(async re=>{try{await Ou(re,r),a(`Staged ${re.length} file(s)`,"success");const Pe=await wa(r);y(Pe),C(new Set),F(null),M(null),R(null)}catch(Pe){a(Me(Pe)||"Failed to stage files","error")}},[a,r]),Be=i.useCallback(async re=>{try{await wk(re,r),a(`Unstaged ${re.length} file(s)`,"success");const Pe=await wa(r);y(Pe),C(new Set),F(null),M(null),R(null)}catch(Pe){a(Me(Pe)||"Failed to unstage files","error")}},[a,r]),et=i.useCallback(async re=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${re.length} file(s)? This cannot be undone.`,danger:!0}))try{await kk(re,r),a(`Discarded changes to ${re.length} file(s)`,"success");const[Se,X]=await Promise.all([wa(r),oi(r)]);y(Se),v(X),C(new Set),F(null),M(null),R(null)}catch(Se){a(Me(Se)||"Failed to discard changes","error")}},[a,r,o]),jt=i.useCallback(async re=>{if(re.preventDefault(),!!A.trim()){_(!0);try{const Pe=await zu(A.trim(),r);a(`Committed: ${Pe.hash}`,"success"),N("");const[Se,X]=await Promise.all([wa(r),oi(r)]);y(Se),v(X),F(null),M(null),R(null)}catch(Pe){a(Me(Pe)||"Failed to commit","error")}finally{_(!1)}}},[A,a,r]),De=i.useCallback(async()=>{if(A.trim()){_(!0);try{const re=b.filter(Ie=>!Ie.staged).map(Ie=>Ie.file);re.length>0&&await Ou(re,r);const Pe=await zu(A.trim(),r);a(`Committed: ${Pe.hash}`,"success"),N("");const[Se,X]=await Promise.all([wa(r),oi(r)]);y(Se),v(X),F(null),M(null),R(null)}catch(re){a(Me(re)||"Failed to commit","error")}finally{_(!1)}}},[A,b,a,r]),vt=i.useCallback(async(re,Pe)=>{F({file:re,staged:Pe}),O(!0),R(null);const Se=q.current+1;q.current=Se;try{const X=await yk(re,Pe,r);if(q.current!==Se)return;M(X)}catch(X){if(q.current!==Se)return;const Ie=Me(X)||"Failed to load file diff";M(null),R(Ie),a(Ie,"error")}finally{q.current===Se&&O(!1)}},[a,r]),Et=i.useCallback(re=>{C(Pe=>{const Se=new Set(Pe);return Se.has(re)?Se.delete(re):Se.add(re),Se})},[]),bt=i.useCallback(async re=>{if(k===re){I(null),w(null);return}I(re),J(!0);try{const Pe=await ol(re,r);w(Pe)}catch(Pe){a(Me(Pe)||"Failed to load diff","error"),w(null)}finally{J(!1)}},[k,a,r]),zt=i.useCallback(()=>{de(re=>Math.min(re+20,100))},[]),qt=i.useMemo(()=>{if(!D.trim())return ee;const re=D.toLowerCase();return ee.filter(Pe=>Pe.message.toLowerCase().includes(re)||Pe.author.toLowerCase().includes(re)||Pe.shortHash.toLowerCase().includes(re))},[ee,D]),It=i.useCallback(async re=>{if(re.preventDefault(),!!oe.trim()){u(!0);try{await mk(oe.trim(),ae.trim()||void 0,r),a(`Created branch ${oe}`,"success"),Y(""),ce("");const Pe=await or(r);Z(Pe)}catch(Pe){a(Me(Pe)||"Failed to create branch","error")}finally{u(!1)}}},[oe,ae,a,r]),_t=i.useCallback(async re=>{u(!0);try{await hk(re,r),a(`Switched to ${re}`,"success");const[Pe,Se]=await Promise.all([oi(r),or(r)]);v(Pe),Z(Se)}catch(Pe){a(Me(Pe)||"Failed to checkout branch","error")}finally{u(!1)}},[a,r]),Xt=i.useCallback(async re=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${re}"?`,danger:!0})){u(!0);try{await Lu(re,void 0,r),a(`Deleted branch ${re}`,"success");const Se=await or(r);Z(Se)}catch(Se){if(Me(Se).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Lu(re,!0,r),a(`Force deleted branch ${re}`,"success");const Ie=await or(r);Z(Ie)}catch(Ie){a(Me(Ie)||"Failed to delete branch","error")}}else a(Me(Se)||"Failed to delete branch","error")}finally{u(!1)}}},[a,r,o]),Lt=i.useMemo(()=>{if(!te.trim())return z;const re=te.toLowerCase();return z.filter(Pe=>Pe.name.toLowerCase().includes(re))},[z,te]),Ut=i.useCallback(async re=>{if(be===re){ke(null),Ge([]),ie(null),xe(null);return}ke(re),Ge([]),ie(null),xe(null),Ae(!0);try{const Pe=await dk(re,10,r);Ge(Pe)}catch{Ge([])}finally{Ae(!1)}},[be,r]),cn=i.useCallback(async re=>{if(Ee===re){ie(null),xe(null);return}ie(re),xe(null),Fe(!0);try{const Pe=await ol(re,r);xe(Pe)}catch{xe(null)}finally{Fe(!1)}},[Ee,r]),Jt=i.useCallback(()=>{ke(null),Ge([]),ie(null),xe(null)},[]),Vt=i.useCallback(async re=>{re.preventDefault(),Te("create");try{await bk(pt.trim()||void 0,r),a("Changes stashed","success"),ve("");const Pe=await yo(r);tt(Pe)}catch(Pe){a(Me(Pe)||"Failed to stash changes","error")}finally{Te(null)}},[pt,a,r]),Kt=i.useCallback(async(re,Pe=!1)=>{Te(`apply-${re}`);try{await xk(re,Pe,r),a(Pe?"Stash popped":"Stash applied","success");const Se=await yo(r);tt(Se)}catch(Se){a(Me(Se)||"Failed to apply stash","error")}finally{Te(null)}},[a,r]),rn=i.useCallback(async re=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${re}}? This cannot be undone.`,danger:!0})){Te(`drop-${re}`);try{await vk(re,r),a("Stash dropped","success");const Se=await yo(r);tt(Se)}catch(Se){a(Me(Se)||"Failed to drop stash","error")}finally{Te(null)}}},[a,r,o]),fn=i.useCallback(async()=>{$e("fetch");try{const re=await pk(void 0,r);at(re),a(re.message||"Fetch completed",re.fetched?"success":"info");const Pe=await oi(r);v(Pe)}catch(re){a(Me(re)||"Fetch failed","error")}finally{$e(null)}},[a,r]),on=i.useCallback(async()=>{$e("pull");try{const re=await fk(r);at(re),re.conflict?a("Merge conflict detected. Resolve manually.","error"):a(re.message||"Pull completed","success");const Pe=await oi(r);v(Pe)}catch(re){a(Me(re)||"Pull failed","error")}finally{$e(null)}},[a,r]),gn=i.useCallback(async()=>{$e("push");try{const re=await gk(r);at(re),a(re.message||"Push completed","success");const Pe=await oi(r);v(Pe)}catch(re){a(Me(re)||"Push failed","error")}finally{$e(null)}},[a,r]),je=i.useMemo(()=>b.filter(re=>re.staged),[b]),Le=i.useMemo(()=>b.filter(re=>!re.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:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(ld,{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:rt,disabled:d,title:"Refresh",children:t.jsx(os,{size:14,className:d?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(tn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:vr.map(re=>{const Pe=re.icon;return t.jsxs("button",{role:"tab","aria-selected":l===re.id,className:`gm-nav-item${l===re.id?" active":""}`,onClick:()=>c(re.id),children:[t.jsx(Pe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:re.label})]},re.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(ft,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!d&&t.jsxs("div",{className:"gm-error",children:[t.jsx(zs,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:rt,children:"Retry"})]}),l==="status"&&!d&&x&&t.jsx(ZI,{status:x,copyToClipboard:g}),l==="changes"&&!d&&t.jsx(e4,{status:x,stagedFiles:je,unstagedFiles:Le,selectedFiles:j,toggleFileSelection:Et,onStageFiles:Oe,onUnstageFiles:Be,onDiscardChanges:et,onSelectDiffFile:vt,selectedDiffTarget:P,changeDiff:T,loadingChangeDiff:E,changeDiffError:B,commitMessage:A,setCommitMessage:N,onCommit:jt,onStageAllAndCommit:De,committing:S}),l==="commits"&&!d&&t.jsx(t4,{commits:qt,commitSearch:D,setCommitSearch:_e,selectedCommit:k,commitDiff:$,loadingDiff:H,onCommitClick:bt,onLoadMore:zt,canLoadMore:ee.length>=fe&&fe<100,copyToClipboard:g}),l==="branches"&&!d&&t.jsx(n4,{branches:Lt,branchSearch:te,setBranchSearch:Re,newBranchName:oe,setNewBranchName:Y,branchBase:ae,setBranchBase:ce,onCreateBranch:It,onCheckoutBranch:_t,onDeleteBranch:Xt,loading:d,allBranches:z,selectedBranch:be,branchCommits:Ue,loadingBranchCommits:qe,expandedBranchCommit:Ee,branchCommitDiff:se,loadingBranchCommitDiff:ne,onSelectBranch:Ut,onBranchCommitClick:cn,onCloseBranchDetails:Jt}),l==="worktrees"&&!d&&t.jsx(s4,{worktrees:Qe}),l==="stashes"&&!d&&t.jsx(i4,{stashes:ze,stashMessage:pt,setStashMessage:ve,onCreateStash:Vt,onApplyStash:Kt,onDropStash:rn,stashLoading:le}),l==="remotes"&&!d&&t.jsx(a4,{status:x,remoteLoading:pe,lastRemoteResult:st,onFetch:fn,onPull:on,onPush:gn,addToast:a,projectId:r,copyToClipboard:g})]})]})]})}):null}function ZI({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(Ks,{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(ra,{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(zs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Un,{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(ia,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Yr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Un,{size:12}),"Up to date"]})]})]})]})]})}function e4({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(C=>a.has(`unstaged:${C.file}`)),j=n.filter(C=>a.has(`staged:${C.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(Ks,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(C=>C.file)),title:"Stage selected",children:[t.jsx(Nn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(C=>C.file)),title:"Discard selected",children:t.jsx(Xr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(C=>C.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(C=>{const A=u?.file===C.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${A?" active":""}`,onClick:()=>d(C.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),d(C.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${C.file}`),onChange:()=>r(`unstaged:${C.file}`)})}),t.jsx(vp,{status:C.status}),t.jsx("span",{className:"gm-file-name",title:C.file,children:t.jsx("bdo",{dir:"ltr",children:C.file})}),t.jsx(yp,{status:C.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([C.file])},title:"Stage file",children:t.jsx(Nn,{size:12})})]},`unstaged:${C.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:[j.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(j.map(C=>C.file)),title:"Unstage selected",children:["Unstage (",j.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(C=>C.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(C=>{const A=u?.file===C.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${A?" active":""}`,onClick:()=>d(C.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),d(C.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${C.file}`),onChange:()=>r(`staged:${C.file}`)})}),t.jsx(vp,{status:C.status}),t.jsx("span",{className:"gm-file-name",title:C.file,children:t.jsx("bdo",{dir:"ltr",children:C.file})}),t.jsx(yp,{status:C.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([C.file])},title:"Unstage file",children:t.jsx(tn,{size:12})})]},`staged:${C.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(od,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ft,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(od,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:C=>g(C.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(ft,{size:14,className:"spin"}):t.jsx(sa,{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 t4({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){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(Pi,{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:qa(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:()=>u(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(ra,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ft,{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))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function n4({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:j,onCloseBranchDetails:C}){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(Pi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:A=>s(A.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:A=>r(A.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:A=>l(A.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(A=>t.jsx("option",{value:A.name,children:A.name},A.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(Nn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(A=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${A.isCurrent?" current":""}${f===A.name?" selected":""}`,onClick:()=>y(A.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[A.isCurrent&&t.jsx(ns,{size:14,className:"gm-current-icon"}),A.name]}),A.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",A.remote]}),A.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:qa(A.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!A.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),d(A.name)},disabled:m,title:"Checkout",children:t.jsx(Ks,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),u(A.name)},disabled:m,title:"Delete",children:t.jsx(Sn,{size:14})})]})})]}),f===A.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Zr,{size:14}),"Commits on ",A.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:C,title:"Close","data-testid":"close-branch-details",children:t.jsx(tn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(ft,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(N=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>j(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),t.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:N.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:qa(N.date)}),N.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===N.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ft,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},N.hash))})]})]},A.name))})]})}function s4({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:Xd(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Ks,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function i4({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,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:a,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(ft,{size:14,className:"spin"}):t.jsx(Jr,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Ks,{size:12}),c.branch]}),t.jsx("span",{children:qa(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(ft,{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(ft,{size:14,className:"spin"}):t.jsx(Sn,{size:14})})]})]},c.index))})]})}function a4({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=ne=>{try{return new URL(ne).hostname}catch{return ne.replace(/^git@/,"").split(":")[0]||ne}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[v,b]=i.useState(""),[y,j]=i.useState(""),[C,A]=i.useState(null),[N,S]=i.useState(""),[_,T]=i.useState(""),[M,E]=i.useState(!1),[O,B]=i.useState([]),[R,P]=i.useState(!1),[F,q]=i.useState(null),[ee,U]=i.useState([]),[k,I]=i.useState(!1),[$,w]=i.useState(null),H=m.find(ne=>ne.name===F),[J,fe]=i.useState(null),[de,D]=i.useState(null),[_e,z]=i.useState(!1),[Z,oe]=i.useState(null),[Y,ae]=i.useState(null),[ce,te]=i.useState(!1);i.useEffect(()=>{Re()},[]),i.useEffect(()=>{e&&e.ahead>0?be():e&&e.ahead===0&&B([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!F&&q(m[0].name)},[m]),i.useEffect(()=>{F?ke(F):(U([]),w(null))},[F]),i.useEffect(()=>{F&&!m.find(ne=>ne.name===F)&&q(m.length>0?m[0].name:null)},[m,F]);const Re=async()=>{p(!0);try{const ne=await Xw(c);h(ne)}catch(ne){l(Me(ne)||"Failed to load remotes","error")}finally{p(!1)}},be=async()=>{P(!0);try{const ne=await lk(c);B(ne)}catch{B([])}finally{P(!1)}},ke=async ne=>{I(!0),w(null);try{const Fe=await ck(ne,void 0,10,c);U(Fe)}catch(Fe){w(Me(Fe)||"Failed to load remote commits"),U([])}finally{I(!1)}},Ue=Gs(),Ge=async ne=>{if(ne.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await Zw(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),j(""),E(!1),await Re()}catch(Fe){l(Me(Fe)||"Failed to add remote","error")}finally{x(null)}}},qe=async ne=>{if(await Ue.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${ne}'?`,danger:!0})){x(`remove-${ne}`);try{await ek(ne,c),l(`Remote '${ne}' removed`,"success"),await Re()}catch(Qe){l(Me(Qe)||"Failed to remove remote","error")}finally{x(null)}}},Ae=async ne=>{if(_.trim()){x(`rename-${ne}`);try{await tk(ne,_.trim(),c),l(`Remote renamed to '${_.trim()}'`,"success"),A(null),T(""),await Re()}catch(Fe){l(Me(Fe)||"Failed to rename remote","error")}finally{x(null)}}},Ee=async ne=>{if(N.trim()){x(`url-${ne}`);try{await nk(ne,N.trim(),c),l("Remote URL updated","success"),A(null),S(""),await Re()}catch(Fe){l(Me(Fe)||"Failed to update remote URL","error")}finally{x(null)}}},ie=i.useCallback(async(ne,Fe)=>{if(Fe==="ahead"){if(J===ne){fe(null),D(null);return}fe(ne),D(null),z(!0);try{const Qe=await ol(ne);D(Qe)}catch{D(null)}finally{z(!1)}}else{if(Z===ne){oe(null),ae(null);return}oe(ne),ae(null),te(!0);try{const Qe=await ol(ne);ae(Qe)}catch{ae(null)}finally{te(!1)}}},[J,Z]),se=ne=>{A(`url-${ne.name}`),S(ne.pushUrl||ne.fetchUrl)},xe=ne=>{A(`name-${ne.name}`),T(ne.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:()=>E(!M),disabled:g!==null,title:M?"Cancel":"Add Remote",children:M?t.jsx(tn,{size:14}):t.jsx(Nn,{size:14})})]}),M&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ge,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:ne=>b(ne.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:ne=>j(ne.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(ft,{size:12,className:"spin"}):t.jsx(Nn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ft,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(ne=>t.jsxs("div",{className:`gm-remote-selector-item${F===ne.name?" selected":""}`,onClick:()=>q(ne.name),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),q(ne.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:ne.name}),ne.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:ne.fetchUrl,children:u(ne.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Fe=>{Fe.stopPropagation(),qe(ne.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Sn,{size:14})})]},ne.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[F&&H?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:F}),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("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(ia,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(Yr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(ft,{size:14,className:"spin"}):t.jsx(os,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(ft,{size:14,className:"spin"}):t.jsx(Hs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(ft,{size:14,className:"spin"}):t.jsx(ia,{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:"}),C===`url-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:ne=>S(ne.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ee(F),disabled:g===`url-${F}`,children:g===`url-${F}`?t.jsx(ft,{size:12,className:"spin"}):t.jsx(ns,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),S("")},title:"Cancel",children:t.jsx(tn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:H.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:H.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(H.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ra,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>se(H),disabled:g!==null,title:"Edit remote URL",children:t.jsx(js,{size:14})})]})]})]}),H.pushUrl&&H.pushUrl!==H.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:H.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:H.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(H.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ra,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:C===`name-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:_,onChange:ne=>T(ne.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ae(F),disabled:g===`rename-${F}`,children:g===`rename-${F}`?t.jsx(ft,{size:12,className:"spin"}):t.jsx(ns,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{A(null),T("")},title:"Cancel",children:t.jsx(tn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>xe(H),disabled:g!==null,title:"Edit remote name",children:t.jsx(js,{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(ia,{size:14}),"Commits to Push (",e.ahead,")"]})}),R?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ft,{size:14,className:"spin"}),"Loading..."]}):O.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:O.map(ne=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ie(ne.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),ie(ne.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:ne.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ne.message,children:ne.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ne.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:qa(ne.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:J===ne.hash?t.jsx(mn,{size:14}):t.jsx(In,{size:14})})]}),J===ne.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:_e?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ft,{size:16,className:"spin"}),"Loading diff..."]}):de?t.jsxs(t.Fragment,{children:[ne.message&&t.jsx("div",{className:"gm-commit-message-full",children:ne.message}),de.stat&&t.jsx("pre",{className:"gm-diff-stat",children:de.stat}),t.jsx("pre",{className:"gm-diff-patch",children:de.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ne.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(lf,{size:14}),"Recent commits on ",F]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ft,{size:14,className:"spin"}),"Loading commits..."]}):$?t.jsxs("div",{className:"gm-error",children:[t.jsx(zs,{size:14}),$]}):ee.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",F,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:ee.map(ne=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ie(ne.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Fe=>{(Fe.key==="Enter"||Fe.key===" ")&&(Fe.preventDefault(),ie(ne.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:ne.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ne.message,children:ne.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ne.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:qa(ne.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Z===ne.hash?t.jsx(mn,{size:14}):t.jsx(In,{size:14})})]}),Z===ne.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ce?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ft,{size:16,className:"spin"}),"Loading diff..."]}):Y?t.jsxs(t.Fragment,{children:[ne.message&&t.jsx("div",{className:"gm-commit-message-full",children:ne.message}),Y.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Y.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Y.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ne.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 yr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function r4(e,n){return e&&n?`${e}/${n}`:""}function o4(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 l4(e){switch(e){case"file-text":return Vi;case"check-circle":return Un;case"shield":return fy;case"zap":return is;case"eye":return Ja;case"globe":return Nl;case"layout-grid":return Wi;default:return Un}}function c4(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 d4({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(!0),[m,h]=i.useState(!0),[f,p]=i.useState("my-steps"),[g,x]=i.useState(null),[v,b]=i.useState(!1),[y,j]=i.useState(yr),[C,A]=i.useState(!1),[N,S]=i.useState(!1),[_,T]=i.useState(null),[M,E]=i.useState(null),[O,B]=i.useState({}),[R,P]=i.useState([]),F=i.useRef(null);Si(F,e,"fusion:workflow-steps-modal-size");const q=i.useCallback(async()=>{try{u(!0);const z=await so(a);o(z)}catch(z){s(Me(z)||"Failed to load workflow steps","error")}finally{u(!1)}},[s,a]),ee=i.useCallback(async()=>{try{const z=await qr(a);B(z||{})}catch{}},[a]),U=i.useCallback(async()=>{try{const z=await Ds();P(z.models||[])}catch{}},[]),k=i.useCallback(async()=>{try{h(!0);const z=await oj();c(z.templates)}catch(z){s(Me(z)||"Failed to load templates","error")}finally{h(!1)}},[s]);i.useEffect(()=>{e&&(q(),k(),ee(),U())},[e,q,k,ee,U]);const I=i.useCallback(()=>{b(!0),x(null),j(yr)},[]),$=i.useCallback(z=>{x(z.id),b(!1),j({name:z.name,description:z.description,mode:z.mode||"prompt",phase:z.phase||"pre-merge",prompt:z.prompt,scriptName:z.scriptName||"",enabled:z.enabled,defaultOn:z.defaultOn||!1,modelProvider:z.modelProvider||"",modelId:z.modelId||""})},[]),w=i.useCallback(()=>{x(null),b(!1),j(yr)},[]),H=i.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}A(!0);try{const z=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 Z={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,...z};await qu(Z,a),s("Workflow step created","success")}else g&&(await ij(g,{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,...z},a),s("Workflow step updated","success"));b(!1),x(null),j(yr),await q()}catch(z){s(Me(z)||"Failed to save workflow step","error")}finally{A(!1)}},[y,v,g,s,q]),J=i.useCallback(async z=>{try{await aj(z,a),s("Workflow step deleted","success"),T(null),g===z&&(x(null),j(yr)),await q()}catch(Z){s(Me(Z)||"Failed to delete workflow step","error")}},[g,s,q]),fe=i.useCallback(async()=>{if(!(!g&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}A(!0);try{const z=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},Z={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...z},oe=await qu(Z,a);b(!1),x(oe.id),S(!0);const Y=await Vu(oe.id,a);j(ae=>({...ae,prompt:Y.prompt})),s("Prompt refined with AI","success"),await q()}catch(z){s(Me(z)||"Failed to refine prompt","error")}finally{A(!1),S(!1)}return}if(g){S(!0);try{const z=await Vu(g,a);j(Z=>({...Z,prompt:z.prompt})),s("Prompt refined with AI","success"),await q()}catch(z){s(Me(z)||"Failed to refine prompt","error")}finally{S(!1)}}}},[g,v,y,s,q]),de=i.useCallback(async z=>{E(z.id);try{await lj(z.id,a),s(`Added ${z.name} workflow step`,"success"),await q(),p("my-steps")}catch(Z){const oe=Me(Z);oe?.includes("already exists")?s(`A workflow step named '${z.name}' already exists`,"error"):s(oe||"Failed to add workflow step from template","error")}finally{E(null)}},[s,q]),D=Li(n);if(!e)return null;const _e=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...D,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:F,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:d?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!_e&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${f==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(ix,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${f==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Wi,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!_e&&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(z=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${z.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:z.name}),t.jsx("span",{className:`wfm-badge ${z.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:z.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(z.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(z.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(z.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(z.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),z.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:z.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>$(z),title:"Edit","aria-label":`Edit ${z.name}`,children:t.jsx(js,{size:14})}),_===z.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>J(z.id),title:"Confirm delete","aria-label":`Confirm delete ${z.name}`,children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>T(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(tn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>T(z.id),title:"Delete","aria-label":`Delete ${z.name}`,children:t.jsx(Sn,{size:14})})]})]})},z.id))})]}),f==="templates"&&!_e&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(ft,{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(z=>{const Z=l4(z.icon),oe=c4(z.category),Y=M===z.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${z.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(Z,{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:z.name}),t.jsx("span",{className:oe,children:z.category})]}),t.jsx("div",{className:"wfm-template-desc",children:z.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>de(z),disabled:Y,"data-testid":`add-template-${z.id}`,children:Y?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Nn,{size:12}),"Add"]})})]})]})},z.id)})})}),_e&&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:z=>j(Z=>({...Z,name:z.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:z=>j(Z=>({...Z,description:z.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:()=>j(z=>({...z,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ri,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(z=>({...z,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Ti,{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:()=>j(z=>({...z,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:()=>j(z=>({...z,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:fe,disabled:!y.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?t.jsx(ft,{size:12,className:"spin"}):t.jsx(vs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:z=>j(Z=>({...Z,prompt:z.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:()=>j(z=>({...z,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(tn,{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(ys,{models:R,value:r4(y.modelProvider,y.modelId),onChange:z=>{const Z=o4(z);j(oe=>({...oe,modelProvider:Z.provider,modelId:Z.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(O).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:z=>j(Z=>({...Z,scriptName:z.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(O).map(([z,Z])=>t.jsxs("option",{value:z,children:[z," (",Z,")"]},z))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:z=>j(Z=>({...Z,enabled:z.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:z=>j(Z=>({...Z,defaultOn:z.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:w,disabled:C,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:H,disabled:C||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:C?"Saving...":v?"Create":"Save"})]})]})]})]})}),!_e&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:I,"data-testid":"add-workflow-step",children:[t.jsx(Nn,{size:14}),"Add Workflow Step"]})})]})})}const u4=36e5,m4=3e5,Yc=[{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 h4(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 p4(e){return typeof e!="number"||!Number.isFinite(e)?u4:Math.max(m4,Math.round(e))}function l3(e){if(Yc.some(s=>s.value===e))return[...Yc];const n={value:e,label:`${h4(e)} (custom)`};return[...Yc,n].sort((s,a)=>s.value-a.value)}const f4=4,g4=5*6e4;function b4(e){const n=p4(e?.heartbeatIntervalMs);return Math.max(n*f4,g4)}function wp(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function x4(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 v4(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=x4(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(Bs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:a??"Error",icon:t.jsx(qs,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(ui,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(qs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(ui,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Tn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=b4(o);if(u>m){const h=`No heartbeat for ${wp(u)} (threshold: ${wp(m)})`;return{label:"Unresponsive",icon:t.jsx(qs,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(bv,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const wr=[{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 y4({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,x]=i.useState("all"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=as("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=as("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{xs("fn-agent-view",v,a)},[a,v]);const[y,j]=i.useState(null),C=i.useRef(null),[A,N]=i.useState(new Set),[S,_]=i.useState(new Map),{confirm:T}=Gs(),M=i.useMemo(()=>S.size===0?r:r.map($=>{const w=S.get($.id);return w?{...$,state:w}:$}),[r,S]),E=i.useMemo(()=>g==="all"?M.filter($=>$.state!=="terminated"):M,[M,g]),O=i.useCallback(async()=>{c(!0);try{const w=await fa(g!=="all"?{state:g}:void 0,a);o(w)}catch($){s(`Failed to load agents: ${Me($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&O()},[e,O]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{O()},3e4);return()=>{clearInterval($)}},[e,O]);const B=async()=>{if(m.trim())try{await bj({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),O()}catch($){s(`Failed to create agent: ${Me($)}`,"error")}},R=async($,w)=>{if(!A.has($)){N(H=>new Set(H).add($)),_(H=>{const J=new Map(H);return J.set($,w),J});try{await vj($,w,a),s(`Agent state updated to ${w}`,"success"),await O(),_(H=>{const J=new Map(H);return J.delete($),J})}catch(H){_(J=>{const fe=new Map(J);return fe.delete($),fe}),s(`Failed to update state: ${Me(H)}`,"error")}finally{N(H=>{const J=new Set(H);return J.delete($),J})}}},P=async($,w)=>{if(await T({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await yj($,a),s(`Agent "${w}" deleted`,"success"),O()}catch(J){s(`Failed to delete agent: ${Me(J)}`,"error")}},F=async($,w)=>{const H=r.find(J=>J.id===$);if(H){if(H.role===w){j(null);return}try{await xj($,{role:w},a),s(`Agent role updated to ${wr.find(J=>J.value===w)?.label??w}`,"success"),j(null),O()}catch(J){s(`Failed to update role: ${Me(J)}`,"error")}}},q=($,w)=>{$.key==="Escape"&&j(null)},ee=$=>wr.find(w=>w.value===$)?.label??$,U=$=>wr.find(w=>w.value===$)?.icon??"◆",k=$=>v4($),I=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>$.target===$.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(Tn,{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(Wi,{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(dd,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void O(),title:"Refresh",disabled:l,children:t.jsx(os,{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(tl,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>x($.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:()=>u(!d),children:[t.jsx(Nn,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&B(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:wr.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void B(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:E.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Tn,{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"?E.map($=>{const w=k($),H=I(w);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:U($.role)}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":H,title:w.reason??w.label,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Activate",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:t.jsx(Sn,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:t.jsx(ui,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Bs,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Resume",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Bs,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:t.jsx(ui,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Bs,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Retry",children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:t.jsx(Bs,{size:14})})]}),$.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:t.jsx(Sn,{size:14})})]})]},$.id)}):E.map($=>{const w=k($),H=I(w);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:C,className:"select agent-role-select",value:$.role,onChange:J=>void F($.id,J.target.value),onKeyDown:J=>q(J,$.id),onBlur:()=>j(null),autoFocus:!0,children:wr.map(J=>t.jsxs("option",{value:J.value,children:[J.icon," ",J.label]},J.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>j($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:J=>{(J.key==="Enter"||J.key===" ")&&j($.id)},children:U($.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":H,title:w.reason??w.label,children:[w.icon,!w.stateDerived&&` ${w.label}`]}),t.jsx("span",{className:"badge text-secondary",children:ee($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Activate",children:[t.jsx(Yn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:[t.jsx(Sn,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:[t.jsx(ui,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Bs,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Resume",children:[t.jsx(Yn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Bs,{size:14})," Stop"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"paused"),disabled:A.has($.id),title:"Pause",children:[t.jsx(ui,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Bs,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Retry",children:[t.jsx(Yn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R($.id,"terminated"),disabled:A.has($.id),title:"Stop",children:[t.jsx(Bs,{size:14})," Stop"]})]}),$.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void R($.id,"active"),disabled:A.has($.id),title:"Start",children:[t.jsx(Yn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P($.id,$.name),title:"Delete",children:[t.jsx(Sn,{size:14})," Delete"]})]})]})]},$.id)})})]})]})}):null}function w4({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await Rw();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await Dw(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.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(ft,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!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(Qn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(k4,{status:a,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(kp,{status:a,authenticated:e}),c&&t.jsx(jp,{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(Qn,{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(kp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(jp,{action:c})]})}function k4({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&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 kp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ft,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?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 jp({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 j4({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await $w();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await Lw(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"droid"})," CLI. Uses your existing Factory AI 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(ft,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`droid` binary not detected on PATH — install Droid 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":"droid-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Qn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(N4,{status:a,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(Np,{status:a,authenticated:e}),c&&t.jsx(Sp,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"droid-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(Qn,{provider:"droid-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Factory AI — via Droid CLI"}),x,t.jsx(Np,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Sp,{action:c})]})}function N4({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&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 Np({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ft,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?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:"droid"})," ",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??"`droid` not found on PATH"]})}function Sp({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"?"Factory AI (via Droid CLI) models are now visible in the model picker.":"Factory AI (via Droid CLI) models are hidden from the model picker.",e.restartRequired?" Restart required: restart your active CLI/chat session for routing changes to take effect.":""]})}function S4(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"),a=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(a);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Qc({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=S4(e),o=i.useRef(null),l=i.useCallback(()=>{a(!0),setTimeout(()=>a(!1),2e3)},[]),c=i.useCallback(async()=>{const d=r??e;try{await navigator.clipboard.writeText(d),l()}catch{}},[r,e,l]);return i.useEffect(()=>{const d=o.current===null&&r!==null;if(o.current=r,!d)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((d,u,m)=>t.jsxs("span",{children:[d,u<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(ns,{size:12}):t.jsx(ra,{size:12})})]})]},u))}):e})}function C4({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){return t.jsxs("div",{className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{className:"form-input oauth-manual-code__input",value:e,onChange:u=>n(u.target.value),placeholder:r,rows:3,spellCheck:!1,disabled:l}),t.jsx("div",{className:"oauth-manual-code__actions",children:t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:l,children:c})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const E4=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),M4=/^[a-z][a-z0-9-]*$/,Cp=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Ep(){return{id:"",name:"",reasoning:!1}}function _4({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,x]=i.useState(e?.apiKey??""),[v,b]=i.useState(e?.models?.length?e.models:[Ep()]),[y,j]=i.useState(null),C=v.length>1,A=i.useMemo(()=>y??r??null,[y,r]);function N(M,E){b(O=>O.map((B,R)=>R===M?{...B,...E}:B))}function S(M){b(E=>E.length<=1?E:E.filter((O,B)=>B!==M))}function _(){if(!l.trim())return"Provider ID is required.";if(!M4.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&E4.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const M=new URL(m.trim());if(M.protocol!=="http:"&&M.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Cp.includes(f)?v.length===0?"At least one model is required.":v.some(M=>!M.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function T(M){M.preventDefault();const E=_();j(E),!E&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(O=>({id:O.id.trim(),name:O.name?.trim()||void 0,reasoning:!!O.reasoning,contextWindow:O.contextWindow,maxTokens:O.maxTokens}))})}return t.jsxs("form",{onSubmit:T,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:M=>c(M.target.value),disabled:o||a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:d,onChange:M=>u(M.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:M=>h(M.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:M=>p(M.target.value),disabled:a,children:Cp.map(M=>t.jsx("option",{value:M,children:M},M))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:M=>x(M.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((M,E)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${E+1}`,placeholder:"Model ID",value:M.id,onChange:O=>N(E,{id:O.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${E+1}`,placeholder:"Display name",value:M.name??"",onChange:O=>N(E,{name:O.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!M.reasoning,onChange:O=>N(E,{reasoning:O.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${E+1}`,placeholder:"Context window",type:"number",value:M.contextWindow??"",onChange:O=>N(E,{contextWindow:O.target.value?Number(O.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${E+1}`,placeholder:"Max tokens",type:"number",value:M.maxTokens??"",onChange:O=>N(E,{maxTokens:O.target.value?Number(O.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>S(E),disabled:a||!C,"aria-label":`Remove model ${E+1}`,children:"×"})]},`${E}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(M=>[...M,Ep()]),disabled:a,children:"+ Add model"})]}),A?t.jsx("div",{className:"form-error",children:A}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const A4=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function P4(e){return!A4.has(e)}function Mp(e){return e.filter(n=>P4(n.id))}const ma="fusion_model_onboarding_state",Va=[],Wa=[],vl=!1,yl=!1,Ka={},R4=void 0,Bi=["ai-setup","github","project-setup","first-task"],T4={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Ws(){if(typeof window>"u")return null;try{const e=localStorage.getItem(ma);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?I4(n):null}catch{return null}}function I4(e){const n=e.postOnboardingDismissedAt??R4;return{...e,completedSteps:e.completedSteps??Va,skippedSteps:e.skippedSteps??Wa,dismissed:e.dismissed??vl,completed:e.completed??yl,stepData:e.stepData??Ka,...n?{postOnboardingDismissedAt:n}:{}}}function Wo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Va,skippedSteps:Wa,dismissed:vl,completed:yl,stepData:Ka};try{localStorage.setItem(ma,JSON.stringify(s))}catch{}return}try{const s=Ws(),a=new Date().toISOString(),r=n.completed??yl;let o=n.dismissed??vl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Va,c=n.skippedSteps??s?.skippedSteps??Wa,d={...s?.stepData??Ka};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(d[m]={...d[m]??{},...h});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(ma,JSON.stringify(u))}catch{}}}function $4(e){if(!(typeof window>"u"))try{const n=Ws(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Va,skippedSteps:[e],dismissed:vl,completed:yl,stepData:Ka};localStorage.setItem(ma,JSON.stringify(o));return}const a=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:a,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(ma,JSON.stringify(r))}catch{}}function _p(){if(!(typeof window>"u"))try{const e=Ws(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Va,skippedSteps:Wa,dismissed:!1,completed:!0,stepData:Ka};localStorage.setItem(ma,JSON.stringify(s))}catch{}}function Ga(){const e=Ws();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function D4(){if(!(typeof window>"u"))try{const e=Ws(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Va,skippedSteps:Wa,dismissed:!1,completed:!1,stepData:Ka,postOnboardingDismissedAt:n};localStorage.setItem(ma,JSON.stringify(s))}catch{}}function jb(){const e=Ws();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function L4(){const e=Ws();return!e||Ga()?!1:e.currentStep!=="complete"}function O4(){const e=Ws();if(!e||Ga()||e.currentStep==="complete")return null;const n=e.currentStep,s=T4[n]??U4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function z4(){const e=Ws();return e?e.skippedSteps:Wa}function F4(e){const n=Ws();return!n||!n.stepData?null:n.stepData[e]??null}function U4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Nb="fusion_onboarding_events",Ap="fusion_onboarding_session_id",B4=200,H4=50;function ti(e,n={}){if(!(typeof window>"u"))try{const s=V4(),a=G4(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:q4()},o=K4([...s,r]);W4(o)}catch{}}function q4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Ap);if(e)return e;const n=Pp();return sessionStorage.setItem(Ap,n),n}catch{return Pp()}}function Pp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function V4(){try{const e=localStorage.getItem(Nb);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(J4):[]}catch{return[]}}function W4(e){try{localStorage.setItem(Nb,JSON.stringify(e))}catch{}}function K4(e){const n=[...e];for(;n.length>B4;)n.splice(0,H4);return n}function G4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function J4(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 Y4=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),Q4={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"}}},Sb={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:"..."}},X4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Rp={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 Ld(e){if(Rp[e])return Rp[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 Xc=["anthropic","openai","google","gemini","ollama"],Z4=["anthropic","claude-cli","droid-cli","openai-codex","gemini","minimax","kimi","zai"],e$={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},t$={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Od(e){return e$[e]??e}function Tp(e){const n=Od(e),s=Z4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function Ip(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Tp(e.id),a=Tp(n.id);if(s!==a)return s-a;const r=Od(e.id),o=Od(n.id);if(r!==o)return r.localeCompare(o);const l=t$[r];if(l){const d=l.indexOf(e.id),u=l.indexOf(n.id);if(d!==u)return(d===-1?Number.POSITIVE_INFINITY:d)-(u===-1?Number.POSITIVE_INFINITY:u)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function n$(e,n){const s=n.trim();if(!s)return"API key is required";const a=Sb[e]??X4;return a.pattern.test(s)?null:`${Ld(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const Cb={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"},s$={description:"AI provider — connect to start using AI models",apiKeyInfo:Cb};function zd(e){return Q4[e]??s$}function i$(e){return zd(e.id).apiKeyInfo??Cb}function a$({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 a=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:a}),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 r$({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const m=`onboarding-apikey-input-${e.id}`,h=a||!s.trim(),f=Sb[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.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:()=>u(e.id),disabled:a,children:a?"Removing…":"Remove Key"}),t.jsx(ni,{summary:"Advanced setup details",children:g}),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"&&d(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:a?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(ni,{summary:"Advanced setup details",children:g})]})}const o$=150;function l$({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Ws(),u=d?.currentStep,m=u==="complete"?"ai-setup":Bi.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??z4(),[p,g]=i.useState(!0),[x,v]=i.useState(m),[b,y]=i.useState(h),[j,C]=i.useState(f),[A,N]=i.useState(!1),[S,_]=i.useState(""),[T,M]=i.useState(!1),[E,O]=i.useState(null),[B,R]=i.useState(null),[P,F]=i.useState([]),[q,ee]=i.useState(void 0),[U,k]=i.useState(!0),[I,$]=i.useState(null),[w,H]=i.useState({}),[J,fe]=i.useState({}),[de,D]=i.useState({}),[_e,z]=i.useState(null),[Z,oe]=i.useState([]),[Y,ae]=i.useState(""),[ce,te]=i.useState(!1),[Re,be]=i.useState({}),[ke,Ue]=i.useState({}),[Ge,qe]=i.useState({}),[Ae,Ee]=i.useState([]),[ie,se]=i.useState(!1),[xe,ne]=i.useState(!1),[Fe,Qe]=i.useState(),ge=i.useRef({}),ze=i.useRef(null),tt=i.useRef(null),pt=i.useRef(null),[ve,le]=i.useState({}),[Te,pe]=i.useState(()=>Ws()?.stepData?.github?.skipped===!0),$e=i.useRef(0),st=i.useRef(l),at=i.useRef(!1),rt=d?.currentStep,Oe=!!d&&d.currentStep!=="complete";Si(tt,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const V=ze.current;V&&(V.scrollTop=0)},[x]);const[Be,et]=i.useState(()=>Ws()?.stepData?.["ai-setup"]?.skippedProviders??{}),jt=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],De=jt.findIndex(V=>V.key===x),vt=x==="complete"?jt.length:De;i.useEffect(()=>{x!=="complete"&&Wo(x,{completedSteps:b,skippedSteps:j})},[x,b,j]),i.useEffect(()=>{at.current||(at.current=!0,ti("onboarding:wizard-opened",{source:Oe?"resume":"initial",resumedFromStep:rt}))},[Oe,rt]),i.useEffect(()=>{const V=st.current!=null,Ve=l!=null;!V&&Ve&&N(!0),Ve||N(!1),st.current=l},[l]);const Et=i.useRef(m);i.useEffect(()=>{if(Et.current==="ai-setup"&&x!=="ai-setup"&&!P.some(Ve=>Ve.id!=="github"&&Ve.authenticated)){const Ve={};for(const Ye of P)Ye.id!=="github"&&!Ye.authenticated&&!Be[Ye.id]&&(Ve[Ye.id]=!0);if(Object.keys(Ve).length>0){const Ye={...Be,...Ve};et(Ye),Wo(x,{stepData:{"ai-setup":{skippedProviders:Ye}}})}}Et.current=x},[x,P,Be]);const bt=i.useCallback(async()=>{try{const{providers:V,ghCli:Ve}=await Hr(),Ye=Mp(V);F(Ye),ee(Ve),H(mt=>{const Ct={};for(const[Rt,dn]of Object.entries(mt)){const Dt=Ye.find(ks=>ks.id===Rt);Dt&&!Dt.authenticated&&Dt.loginInProgress&&(Ct[Rt]=dn)}return Object.keys(Ct).length===Object.keys(mt).length?mt:Ct}),le(mt=>{let Ct=!1;const Rt={...mt};for(const[dn,Dt]of Object.entries(mt)){if(Dt!=="pending")continue;Ye.find(Zn=>Zn.id===dn)?.loginInProgress||(delete Rt[dn],Ct=!0)}return Ct?Rt:mt}),et(mt=>{const Ct={...mt};for(const Rt of Ye)Rt.authenticated&&Ct[Rt.id]&&delete Ct[Rt.id];return Object.keys(Ct).length===Object.keys(mt).length?mt:Ct})}catch{}},[]),zt=i.useCallback(async()=>{try{const V=await Ow();Ee((V.providers??[]).map(Y4))}catch{}},[]),qt=i.useCallback(async V=>{ne(!0),Qe(void 0);try{await Fw(V),await zt(),await Ds().then(Ve=>oe(Ve.models??[])),se(!1)}catch(Ve){Qe(Me(Ve)||"Failed to create custom provider")}finally{ne(!1)}},[zt]),It=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&zt(),It.current&&bt(),It.current=x!=="ai-setup"},[x,bt,zt]),i.useEffect(()=>{if(!P.some(Ye=>Ye.loginInProgress))return;const Ve=setInterval(()=>{bt()},2e3);return()=>clearInterval(Ve)},[P,bt]);const _t=P.find(V=>V.id==="github"),Xt=!!_t,Lt=_t?.authenticated??!1,Ut=_t?.loginInProgress??!1,cn=q?.authenticated??!1,Jt=Lt||cn,Vt=!Lt&&cn,Kt=i.useCallback(V=>{if(V.authenticated)return"connected";const Ve=ve?.[V.id];return Ve==="timeout"||Ve==="failed"?"retry":Be[V.id]?"skipped":"not-connected"},[ve,Be]);function rn({status:V}){const Ve={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:mt}=Ve[V];return t.jsx("span",{"data-testid":"provider-status-badge",className:mt,"data-status":V,children:Ye})}const fn=i.useCallback(()=>{if(Jt)return"connected";const V=ve.github;return V==="pending"?"pending":V==="failed"||V==="timeout"?"failed":Te?"skipped":"not-connected"},[Jt,ve,Te]);function on({status:V}){const Ve={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:mt}=Ve[V];return t.jsx("span",{"data-testid":"github-status-badge",className:mt,"data-status":V,children:Ye})}const gn=i.useCallback(async()=>{try{const V=await Ds();oe(V.models)}catch{}},[]),je=i.useCallback(async()=>{try{const V=await pa();if(V.defaultProvider&&V.defaultModelId){const Ve=`${V.defaultProvider}/${V.defaultModelId}`;ae(Ve)}}catch{}},[]);i.useEffect(()=>{Promise.all([bt(),gn(),je()]).finally(()=>k(!1))},[bt,gn,je]),i.useEffect(()=>{const V=F4("ai-setup");if(V?.loginOutcomes){const Ve=V.loginOutcomes,Ye={};for(const[mt,Ct]of Object.entries(Ve))Ct!=="pending"&&(Ye[mt]=Ct);Object.keys(Ye).length>0&&le(Ye)}},[]);const Le=i.useCallback((V,Ve)=>{Wo(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[V]:Ve}}}})},[x,b]);i.useEffect(()=>{const V=Object.entries(ve).filter(([Ve,Ye])=>Ye!=="pending");for(const[Ve,Ye]of V)Le(Ve,Ye)},[ve,Le]),i.useEffect(()=>()=>{pt.current&&clearInterval(pt.current),Object.values(ge.current).forEach(clearTimeout),ge.current={}},[]);const re=i.useCallback(V=>{pe(V),Wo(x,{completedSteps:b,stepData:{github:{skipped:V}}})},[x,b]),Pe=i.useCallback(V=>V==="complete"?-1:Bi.indexOf(V),[]),Se=i.useCallback(()=>{y(Ve=>[...new Set([...Ve,x])]),C(Ve=>Ve.filter(Ye=>Ye!==x)),ti("onboarding:step-completed",{step:x}),x==="github"&&!Lt&&re(!1);const V=Pe(x);V>=0&&V<Bi.length-1&&v(Bi[V+1])},[x,Lt,re,Pe]),X=i.useCallback(()=>{C(Ve=>[...new Set([...Ve,x])]),$4(x),ti("onboarding:step-skipped",{step:x}),x==="github"&&!Lt&&re(!0);const V=Pe(x);V>=0&&V<Bi.length-1&&v(Bi[V+1])},[x,Lt,re,Pe]),Ie=i.useCallback(()=>{const V=x;y(Ye=>Ye.filter(mt=>mt!==V)),C(Ye=>Ye.filter(mt=>mt!==V)),V==="github"&&!Lt&&re(!1);const Ve=Pe(x);Ve>0&&v(Bi[Ve-1])},[x,Lt,re,Pe]),he=i.useCallback(()=>{X()},[X]),Ne=i.useCallback(async V=>{le(Ye=>{const mt=Ye[V];if(mt&&mt!=="pending"){const{[V]:Ct,...Rt}=Ye;return Rt}return Ye});const Ve=()=>{H(Ye=>{if(!(V in Ye))return Ye;const mt={...Ye};return delete mt[V],mt}),fe(Ye=>{if(!(V in Ye))return Ye;const mt={...Ye};return delete mt[V],mt}),D(Ye=>{if(!(V in Ye))return Ye;const mt={...Ye};return delete mt[V],mt})};Ve(),le(Ye=>({...Ye,[V]:"pending"})),$(V),$e.current=0;try{const{url:Ye,instructions:mt,manualCode:Ct}=await Uw(V);mt?.trim()&&H(Rt=>({...Rt,[V]:mt})),Ct&&fe(Rt=>({...Rt,[V]:Ct})),window.open(ki(Ye),"_blank"),pt.current=setInterval(async()=>{if($e.current++,$e.current>=o$){pt.current&&(clearInterval(pt.current),pt.current=null),$(null),le(Rt=>({...Rt,[V]:"timeout"})),Ve(),n("Login timed out. Please try again.","warning");return}try{const{providers:Rt,ghCli:dn}=await Hr(),Dt=Mp(Rt);F(Dt),ee(dn);const ks=Dt.find(Zn=>Zn.id===V);if(ks?.authenticated){pt.current&&(clearInterval(pt.current),pt.current=null),$(null),le(Zn=>({...Zn,[V]:"success"})),Ve(),V==="github"&&re(!1),n("Login successful","success");return}ks?.loginInProgress||(pt.current&&(clearInterval(pt.current),pt.current=null),$(null),le(Zn=>({...Zn,[V]:"failed"})),Ve(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(Ye){Ye instanceof Error&&Ye.message.includes("already in progress")||Ye&&typeof Ye=="object"&&"status"in Ye&&Ye.status===409?(n("Login already in progress. Cancel it to retry.","warning"),le(Ct=>({...Ct,[V]:"pending"})),bt()):(n(Ye instanceof Error?Ye.message:"Login failed","error"),le(Ct=>({...Ct,[V]:"failed"}))),$(null),Ve()}},[n,bt,re]),Je=i.useCallback(async V=>{const Ve=de[V]?.trim();if(!Ve){n("Paste the full redirect URL or authorization code first.","warning");return}z(V);try{(await Bw(V,Ve)).submitted?(D(mt=>{if(!(V in mt))return mt;const Ct={...mt};return delete Ct[V],Ct}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Ye){n(Me(Ye)||"Failed to submit authorization code","error")}finally{z(null)}},[n,de]),kt=i.useCallback(async V=>{pt.current&&(clearInterval(pt.current),pt.current=null),$(V),$e.current=0,F(Ve=>Ve.map(Ye=>Ye.id===V?{...Ye,loginInProgress:!1}:Ye)),le(Ve=>({...Ve,[V]:"cancelled"}));try{await qw(V),await bt().catch(()=>{}),n("Login cancelled","success")}catch(Ve){n(Me(Ve)||"Failed to cancel login","error")}finally{$(null),H(Ve=>{if(!(V in Ve))return Ve;const Ye={...Ve};return delete Ye[V],Ye}),fe(Ve=>{if(!(V in Ve))return Ve;const Ye={...Ve};return delete Ye[V],Ye}),D(Ve=>{if(!(V in Ve))return Ve;const Ye={...Ve};return delete Ye[V],Ye}),z(Ve=>Ve===V?null:Ve)}},[n,bt]),Yt=i.useCallback((V,Ve)=>{be(mt=>({...mt,[V]:Ve}));const Ye=ge.current[V];Ye&&(clearTimeout(Ye),delete ge.current[V]),Ue(mt=>{if(!mt[V])return mt;const Ct={...mt};return delete Ct[V],Ct}),qe(mt=>{if(!mt[V])return mt;const Ct={...mt};return delete Ct[V],Ct})},[]),$t=i.useCallback(()=>{const V=ze.current;if(!V)return;const Ve=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof V.scrollTo=="function"){V.scrollTo({top:0,behavior:Ve?"auto":"smooth"});return}}catch{}V.scrollTop=0},[]),Tt=i.useCallback(async(V,Ve)=>{const Ye=(Ve??Re[V]??"").trim(),mt=n$(V,Ye);if(mt){Ue(Rt=>({...Rt,[V]:mt}));return}const Ct=ge.current[V];Ct&&(clearTimeout(Ct),delete ge.current[V]),$(V),Ue(Rt=>{const dn={...Rt};return delete dn[V],dn}),qe(Rt=>{if(!Rt[V])return Rt;const dn={...Rt};return delete dn[V],dn});try{await Vw(V,Ye),await bt(),$t(),be(Rt=>{const dn={...Rt};return delete dn[V],dn}),Ue(Rt=>{if(!Rt[V])return Rt;const dn={...Rt};return delete dn[V],dn}),qe(Rt=>({...Rt,[V]:"✓ Key saved"})),ge.current[V]=setTimeout(()=>{qe(Rt=>{if(!Rt[V])return Rt;const dn={...Rt};return delete dn[V],dn}),delete ge.current[V]},3e3),n("API key saved","success")}catch(Rt){const dn=Rt instanceof TypeError&&Rt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Rt instanceof Error?Rt.message:"Failed to save API key";Ue(Dt=>({...Dt,[V]:dn})),qe(Dt=>{if(!Dt[V])return Dt;const ks={...Dt};return delete ks[V],ks}),n(dn,"error")}finally{$(null)}},[Re,n,bt,$t]),Bt=i.useCallback(async V=>{$(V);try{await Ww(V),await bt(),n("API key removed","success")}catch(Ve){n(Ve instanceof Error?Ve.message:"Failed to clear API key","error")}finally{$(null)}},[n,bt]),jn=i.useCallback(async V=>{$(V);try{await Hw(V),await bt(),n("Logged out","success")}catch(Ve){n(Ve instanceof Error?Ve.message:"Logout failed","error")}finally{$(null)}},[n,bt]),Dn=i.useCallback(V=>{ae(V)},[]),hn=i.useCallback(async()=>{try{const V={modelOnboardingComplete:!0};if(Y){const Ve=Y.indexOf("/"),Ye=Ve!==-1?Y.slice(0,Ve):void 0,mt=Ve!==-1?Y.slice(Ve+1):Y,Ct=Z.find(Rt=>Rt.id===mt);Ct?(V.defaultProvider=Ct.provider,V.defaultModelId=Ct.id):Ye&&mt&&(V.defaultProvider=Ye,V.defaultModelId=mt)}await Pn(V),_p()}catch{}},[Y,Z,Pn,_p]),Ht=i.useCallback(async()=>{const V=[...new Set([...b,"first-task"])];te(!0);try{await hn(),ti("onboarding:completed",{completedSteps:V,skippedSteps:j}),y(V),C(Ve=>Ve.filter(Ye=>Ye!=="first-task")),v("complete")}finally{te(!1)}},[hn,b,j]),yn=i.useCallback(async()=>{if(!s)return;const V=S.trim();if(!V){O("Please enter a task description.");return}O(null),M(!0);let Ve=!1;try{const Ye=await rl({description:V,source:{sourceType:"dashboard_ui"}},s);R(Ye),N(!0),ti("onboarding:first-task-created",{taskId:Ye?.id}),n("Task created","success"),Ve=!0}catch(Ye){const mt=Ye instanceof Error?Ye.message:"Something went wrong creating your task. Please try again.";O(mt),n(mt,"error")}finally{M(!1)}Ve&&hn()},[s,S,n,hn]),pn=i.useCallback(async()=>{te(!0);try{await hn()}finally{te(!1)}ti("onboarding:open-new-task",{}),r?.()},[hn,r]),es=i.useCallback(async()=>{if(Jt){te(!0);try{await hn()}finally{te(!1)}g(!1),e(),ti("onboarding:open-github-import",{}),o?.()}},[hn,Jt,e,o]),ye=i.useCallback(async()=>{ti("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:j}),te(!0);try{await Pn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,j,e]),ut=i.useCallback(()=>{ti("onboarding:finished",{}),g(!1),e()},[e]),Qt=i.useCallback(()=>{const V=l??B;V&&(hn(),c?.(V),e())},[l,B,hn,c,e]),Cn=i.useCallback(()=>{hn(),e()},[hn,e]);if(!p)return null;const ue=fn(),dt=P.filter(V=>V.id!=="github"),wt=[...dt].sort(Ip),gt=wt.some(V=>!V.type||V.type==="oauth"),ot=wt.some(V=>V.type==="api_key"),yt=dt.filter(V=>V.authenticated),Ft=yt.length>0,Zt=!!s,Ln=x==="github"&&!Ft,Wt=(()=>{if(!Y)return"";const V=Y.indexOf("/"),Ve=V===-1?void 0:Y.slice(0,V),Ye=V===-1?Y:Y.slice(V+1),mt=Z.find(Ct=>Ct.id===Ye&&(!Ve||Ct.provider===Ve));return mt?.name?mt.name:Ve?`${Ld(Ve)} ${Ye}`:Y})(),Mt=[];if(Zt?Mt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Mt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Ft){const V=Ld(yt[0]?.id??"");Mt.push({label:"AI Provider",status:"connected",detail:`${V} connected — AI agents can work on tasks`})}else dt.length>0&&dt.some(V=>Be[V.id])?Mt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Mt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Jt?Mt.push({label:"GitHub",status:"connected",detail:Vt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Xt||Te?Mt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Mt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Wt&&Mt.push({label:"Default Model",status:"connected",detail:Wt});const En=l??B,Xn=En?.description?.split(`
682
+ `)[0]?.trim()||En?.title||"",ts=new Set(Xc),Ps=wt.filter(V=>ts.has(V.id)).sort((V,Ve)=>{const Ye=Xc.indexOf(V.id),mt=Xc.indexOf(Ve.id);return Ye!==mt?Ye-mt:Ip(V,Ve)}),ws=wt.filter(V=>V.authenticated&&!ts.has(V.id)),Bn=wt.filter(V=>!V.authenticated&&!ts.has(V.id)),rs=V=>{if(V.id==="droid-cli"&&V.type==="cli")return t.jsx(j4,{authenticated:V.authenticated,onToggled:()=>{bt()}},V.id);if(V.id==="claude-cli"&&V.type==="cli")return t.jsx(w4,{authenticated:V.authenticated,onToggled:()=>{bt()}},V.id);if(V.type==="api_key"){const Ve=zd(V.id),Ye=i$(V);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${V.id}`,className:`onboarding-provider-card${V.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${V.id}`,"aria-hidden":"true",children:t.jsx(Qn,{provider:V.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(rf,{size:14,className:"onboarding-provider-key-icon"}),V.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Ve.description}),t.jsx(rn,{status:Kt(V)}),V.authenticated&&V.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",V.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(r$,{provider:V,apiKeyInfo:Ye,inputValue:Re[V.id]??"",isSaving:I===V.id,error:ke[V.id],success:Ge[V.id],isConnected:V.authenticated,onInputChange:Yt,onSave:Tt,onClear:Bt})})]},V.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${V.id}`,className:`onboarding-provider-card${V.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${V.id}`,"aria-hidden":"true",children:t.jsx(Qn,{provider:V.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:V.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:zd(V.id).description}),t.jsx(rn,{status:Kt(V)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:I===V.id?V.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void kt(V.id),children:"Cancel"})]}):V.loginInProgress?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void kt(V.id),children:"Cancel"})]}):V.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>jn(V.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Ne(V.id),children:"Login"})}),(I===V.id||V.loginInProgress)&&w[V.id]&&t.jsx(Qc,{instructions:w[V.id],"data-testid":`onboarding-login-instructions-${V.id}`}),(I===V.id||V.loginInProgress)&&J[V.id]&&t.jsx(C4,{value:de[V.id]??"",onChange:Ve=>D(Ye=>({...Ye,[V.id]:Ve})),onSubmit:()=>void Je(V.id),prompt:J[V.id].prompt,placeholder:J[V.id].placeholder,helpText:J[V.id].helpText,disabled:_e===V.id,submitLabel:_e===V.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${V.id}`}),ve[V.id]==="timeout"&&I!==V.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),ve[V.id]==="failed"&&I!==V.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},V.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:tt,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(is,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Hs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Cu,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Cu,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Un,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ye,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(tn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:jt.map((V,Ve)=>{const Ye=vt>Ve,mt=b.includes(V.key)&&Ye,Ct=j.includes(V.key)&&!b.includes(V.key)&&Ye,Rt=mt||Ct;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Ve>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Ve<=vt?"done":""}`}),Rt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===V.key?"active":""} ${mt?"done":""} ${Ct?"skipped":""}`,onClick:()=>v(V.key),"aria-label":`Go back to ${V.label}`,title:`Review ${V.label}`,children:[t.jsx("span",{className:"step-number",children:mt?t.jsx(Un,{size:14}):Ct?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ve+1}),t.jsx("span",{className:"step-label",children:V.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===V.key?"active":""} ${mt?"done":""} ${Ct?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:mt?t.jsx(Un,{size:14}):Ct?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ve+1}),t.jsx("span",{className:"step-label",children:V.label})]})]},V.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:ze,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."}),!U&&P.length>0&&(()=>{const V=P.filter(Rt=>Rt.id!=="github"&&Rt.authenticated).length,Ve=P.filter(Rt=>Rt.id!=="github").length,Ye=Object.keys(Be).filter(Rt=>!P.find(dn=>dn.id===Rt)?.authenticated).length;if(Ve===0)return null;let mt="onboarding-provider-summary",Ct="";return V>0?(mt+=" onboarding-provider-summary--connected",Ct=`✓ ${V} of ${Ve} provider${Ve!==1?"s":""} connected`):Ye>0?(mt+=" onboarding-provider-summary--skipped",Ct=`${Ye} provider${Ye!==1?"s":""} skipped`):(mt+=" onboarding-provider-summary--none",Ct="No providers connected yet"),t.jsx("div",{className:mt,"data-testid":"provider-summary",children:Ct})})(),t.jsx(Hi,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ni,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),P.length>0&&!P.some(V=>V.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),U?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(ft,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):P.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.jsx(Hi,{slotId:"onboarding-provider-card",projectId:s}),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"}),Ps.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ps.map(V=>rs(V))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ws.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:ws.map(V=>rs(V))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(ni,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Z.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(ys,{models:Z,value:Y,onChange:Dn,placeholder:"Select a default model…",label:"Default model"})}),Y&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(V=>V.id===Y)?.name??Y]})})]}),t.jsx(ni,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Bn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Bn.map(V=>rs(V))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Ae.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Ae.map(V=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Qn,{provider:V.id,size:"sm"}),t.jsx("span",{children:V.name||V.id})]},V.id))}):null,ie?t.jsx(_4,{onSave:qt,onCancel:()=>{se(!1),Qe(void 0)},saving:xe,error:Fe}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>se(!0),children:"Add custom provider"})]})}),gt&&t.jsx(ni,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),ot&&t.jsx(ni,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(Hi,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Jt?t.jsx("p",{className:"model-onboarding-description",children:Vt?"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."}),!Jt&&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"})]})}),Ln&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(ni,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),Xt?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(Hs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(on,{status:ue})})]}),Lt&&(I==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>jn("github"),children:"Disconnect"}))]}),(ue==="not-connected"||ue==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[I==="github"||Ut?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:()=>void kt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Ne("github"),children:[t.jsx(Hs,{size:16}),"Connect"]}),(I==="github"||Ut)&&w.github&&t.jsx(Qc,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),ue==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Vt?"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."}),ue==="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:()=>Ne("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:he,children:"Skip for now"})]})]}),ue==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),ue==="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:()=>Ne("github"),children:"Connect anyway"})})]}),ue==="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(Qn,{provider:"github",size:"lg"})}),Vt?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:Vt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Vt&&(I==="github"||Ut?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(ft,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Ne("github"),children:[t.jsx(Qn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Vt&&(I==="github"||Ut)&&w.github&&t.jsx(Qc,{instructions:w.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."}),Zt?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:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(ni,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),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."}),A&&En?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Un,{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:En.id}),Xn&&t.jsx("p",{className:"onboarding-task-created__description",children:Xn}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:Qt,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Cn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Zt?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:S,onChange:V=>{_(V.target.value),O(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:yn,disabled:T,"data-testid":"onboarding-first-task-submit",children:T?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),E&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:E}),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:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(a$,{items:Mt}),Zt&&t.jsxs(t.Fragment,{children:[t.jsx(ni,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:pn,disabled:ce,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Nn,{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${Jt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:es,disabled:ce||!Jt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Hs,{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"}),!Jt&&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(Un,{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:ye,disabled:ce,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:X,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Se,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ie,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:X,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Se,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ie,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Se,disabled:!Zt,children:"Next →"})]}),x==="first-task"&&!A&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Ie,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Ht,disabled:ce,children:ce?t.jsxs(t.Fragment,{children:[t.jsx(ft,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:ut,children:[t.jsx(Un,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Eb({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 c$=i.lazy(()=>An(()=>import("./SetupWizardModal-Bhumd4Rf.js"),__vite__mapDeps([9,1,10,11,12,4,5,13])).then(e=>({default:e.SetupWizardModal}))),d$=i.lazy(()=>An(()=>import("./SettingsModal-D0kuJpBA.js"),__vite__mapDeps([14,1,15,16,17,2,4,5,18])).then(e=>({default:e.SettingsModal})));function u$(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{An(()=>import("./SettingsModal-D0kuJpBA.js"),__vite__mapDeps([14,1,15,16,17,2,4,5,18]))},{timeout:1500})}function m$({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[x,v]=i.useState(null),b=c.detailTask?(()=>{const S=n.find(_=>_.id===c.detailTask?.id);return S?"prompt"in c.detailTask?{...c.detailTask,...S,prompt:c.detailTask.prompt,log:c.detailTask.log}:S:c.detailTask})():null,y=p??c.closeSettings,j=i.useCallback(()=>{c.openNewTask()},[c]),C=i.useCallback(()=>{c.openGitHubImport()},[c]),A=i.useCallback(S=>{v(null),c.closeModelOnboarding(),c.openDetailTask(S)},[c]),N=i.useCallback(async S=>{const _=await u.handleModalCreate(S);return c.modelOnboardingOpen&&v(_),_},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{u$()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Xi,{children:t.jsx(HP,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Xi,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(d$,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(qR,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Xi,{children:t.jsx(tT,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Xi,{children:t.jsx(uT,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(TT,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx($T,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(sI,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(oI,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(gI,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(VI,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(DI,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Xi,{children:t.jsx(FI,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:N,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(YI,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:S=>{const _=n.find(T=>T.id===S);_&&c.openDetailTask(_)}}),t.jsx(Xi,{children:t.jsx(XI,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Xi,{children:t.jsx(d4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(y4,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(c$,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(l$,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:j,onOpenGitHubImport:C,firstCreatedTask:x,onViewTask:A}),t.jsx(Eb,{toasts:o,onRemove:l})]})}function h$({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 Fd=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function p$(e,n){if(n==="ready")return"done";const s=Fd.findIndex(r=>r.id===n),a=Fd.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function f$({stage:e}){const[n]=i.useState(()=>$y());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:Fd.map(s=>{const a=p$(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(ft,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const g$=5e3;function b$(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function x$(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,ul(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function v$(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const v=await Ej(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},g$),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=x$(e,s,a),g=b$(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const y$={planning:pi,subtask:oa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},w$={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function k$({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=Gs(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=tr(),g=i.useMemo(()=>ba(),[]);if(i.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]),i.useEffect(()=>{const b=new Set,y=new Map;for(const j of e){const C=p.get(j.id),A=[j.status,j.updatedAt,C?.tabId??j.lockedByTab??"",C?.stale?"stale":"fresh"].join("|"),N=h.current.get(j.id);N&&N!==A&&b.add(j.id),y.set(j.id,A)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.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(ft,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(ad,{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=y$[b.type],j=b.status==="generating",C=b.status==="awaiting_input",A=b.status==="error",N=p.get(b.id),S=N?.tabId??b.lockedByTab??null,_=!!(S&&S!==g&&!N?.stale),T=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${T?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:T?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:T?"translateY(-1px)":void 0},onClick:async()=>{_&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[A?t.jsx(zs,{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:[A?"Failed":w$[b.type],j&&" — generating...",C&&!_&&" — needs input",C&&_&&" — active in another tab"]})]}),j&&t.jsx(ft,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),C&&!_&&t.jsx(ad,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),C&&_&&t.jsx(Ml,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:M=>{M.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(tn,{size:12})})]},b.id)})})]})]})}function j$(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/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 N$(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:Yn};case"paused":return{label:"Paused",color:"var(--triage)",icon:ui};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:is}}}function S$({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m}){const{stats:h,loading:f,error:p}=v$(e,n,s,d),[g,x]=i.useState(!1),v=i.useMemo(()=>N$(h.executorState),[h.executorState]),b=i.useMemo(()=>j$(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(Al,{size:14}),p]})}):f&&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:[a&&a.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(k$,{sessions:a,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})]}),u&&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${g?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(j=>!j),"aria-label":g?"Hide project directory":"Show project directory","aria-expanded":g,"data-testid":"executor-project-path-toggle",title:g?"Hide project directory":"Show project directory",children:t.jsx(fs,{size:12,"aria-hidden":"true"})}),g&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:u,"data-testid":"executor-project-path-link",children:u})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Ii,{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 C$={planning:pi,subtask:oa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},E$={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Mb="fusion:session-banner-dismissed";function Pr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function M$(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Mb);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:Pr(r);s.set(a,o)}return s}catch{return new Map}}function _$(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Mb,JSON.stringify(n))}catch{}}const Ai=M$();function A$({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{_$(Ai),o(g=>g+1)};i.useEffect(()=>{if(Ai.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let x=!1;for(const[v,b]of Ai){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Ai.delete(v),x=!0;continue}Pr(y.updatedAt)>b&&(Ai.delete(v),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=Ai.get(g.id);return x===void 0?!0:Pr(g.updatedAt)>x}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{Ai.set(g.id,Math.max(Pr(g.updatedAt),Date.now())),l()},f=g=>{Ai.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Ai.set(x.id,Math.max(Pr(x.updatedAt),g));l(),a()};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(zs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(tn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const x=C$[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(zs,{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:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":E$[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(tn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const _b="fusion:cli-binary-banner-dismissed";function P$(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(_b)==="1"}catch{return!1}}function R$(){if(!(typeof window>"u"))try{window.localStorage.setItem(_b,"1")}catch{}}function T$({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>P$()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let h=!1;return Tw().then(f=>{h||s(f)}).catch(()=>{}),()=>{h=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const h=await Iw();s({binary:h.binary,expectedVersion:h.expectedVersion,state:h.state,install:h.install}),h.installResult.success||d(h.installResult.permissionsHint||h.installResult.stderr||`Install failed (exit ${h.installResult.exitCode??"n/a"})`)}catch(h){d(h instanceof Error?h.message:String(h))}finally{l(!1)}},[]),m=i.useCallback(()=>{R$(),r(!0)},[]);return a||!n||n.state==="installed"||n.state==="skipped"?null:t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:"Install the Fusion CLI"}),t.jsxs("div",{className:"cli-binary-banner__text",children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?"Installing…":"Install with npm"}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(tn,{size:16})})]})}function I$({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(tn,{size:16,"aria-hidden":"true"})})]})}function $$({onResume:e}){const n=O4();if(!n)return null;const s=n.completedSteps.length,a=Bi.length,r=s>0?`${s} of ${a} 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(vs,{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:()=>{ti("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(Yn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function D$({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ga(),a=jb(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[j,C]=await Promise.all([Hr(),pa()]);if(b)return;const A=j.providers??[],N=A.find(E=>E.id==="github"),_=!A.some(E=>E.id!=="github"&&E.authenticated),T=!C.defaultProvider&&!C.defaultModelId,M=N?!N.authenticated:!1;h({needsAiProvider:_,needsDefaultModel:T,needsGitHub:M})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{D4(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),v=i.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:is}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:rf}),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:Hs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||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(pi,{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.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children: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(Hi,{slotId:"post-onboarding-recommendation"})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(tn,{size:16,"aria-hidden":!0})})]})}function L$({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 Zc(e){return e>99?"99+":String(e)}function O$({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,onOpenGitManager:m,onOpenWorkflowSteps:h,onOpenSchedules:f,onOpenScripts:p,onToggleTerminal:g,onOpenFiles:x,onOpenTodos:v,todosOpen:b=!1,onOpenGitHubImport:y,onOpenPlanning:j,onResumePlanning:C,activePlanningSessionCount:A=0,onOpenUsage:N,onRunScript:S,projectId:_,onViewAllProjects:T,showSkillsTab:M,experimentalFeatures:E,onOpenNodes:O,pluginDashboardViews:B=[]}){const R=Di(),[P,F]=i.useState(!1),[q,ee]=i.useState(!1),[U,k]=i.useState({}),[I,$]=i.useState(!1),w=i.useMemo(()=>Object.entries(U).sort(([Ae],[Ee])=>Ae.localeCompare(Ee)),[U]);i.useEffect(()=>{if(!q)return;let Ae=!1;return $(!0),qr(_).then(Ee=>{Ae||k(Ee)}).catch(()=>{Ae||k({})}).finally(()=>{Ae||$(!1)}),()=>{Ae=!0}},[q,_]);const H=i.useCallback(()=>F(!1),[]),J=i.useCallback(Ae=>{H(),Ae?.()},[H]);if(i.useEffect(()=>{if(!P)return;const Ae=Ee=>{Ee.key==="Escape"&&F(!1)};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[P]),R!=="mobile"||a||r)return null;const fe=A>0&&C?C:j,de=B.some(Ae=>Ae.pluginId==="fusion-plugin-roadmap"),D=!!E?.roadmap&&!de,_e=!!M,z=!!E?.todoView,Z=D&&(!_e||e==="roadmaps"),oe=_e&&(!D||e!=="roadmaps"),Y=_e&&!oe,ae=Ae=>Ae.pluginId==="fusion-plugin-dependency-graph"&&Ae.view.viewId==="graph",ce=B.filter(Ae=>Ae.view.placement==="primary").sort((Ae,Ee)=>(Ae.view.order??Number.MAX_SAFE_INTEGER)-(Ee.view.order??Number.MAX_SAFE_INTEGER)),te=B.find(ae)??null,ke=(te?[te,...ce.filter(Ae=>!ae(Ae))]:ce).slice(0,1),Ue=new Set(ke.map(Ae=>`${Ae.pluginId}:${Ae.view.viewId}`)),Ge=B.filter(Ae=>!Ue.has(`${Ae.pluginId}:${Ae.view.viewId}`)).sort((Ae,Ee)=>(Ae.view.order??Number.MAX_SAFE_INTEGER)-(Ee.view.order??Number.MAX_SAFE_INTEGER)),qe=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||b&&z||e==="roadmaps"&&!Z||e==="skills"&&!oe||e.startsWith("plugin:")&&!ke.some(Ae=>Ir(Ae.pluginId,Ae.view.viewId)===e);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(Wi,{}),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(Tn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(Es,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(Ri,{}),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(la,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Zc(u)})]}),oe&&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(is,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),Z&&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(ud,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),ke.map(Ae=>{const Ee=Ir(Ae.pluginId,Ae.view.viewId),ie=cl(Ae.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Ee?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${Ae.pluginId}-${Ae.view.viewId}`,role:"tab","aria-selected":e===Ee,onClick:()=>n(Ee),children:[t.jsx(ie,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:Ae.view.label})]},`${Ae.pluginId}:${Ae.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${qe?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>F(Ae=>!Ae),children:[t.jsx(rd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:H}),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:()=>J(d),children:[t.jsx(la,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Zc(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>J(l),children:[t.jsx(qs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>J(c),children:[t.jsx(Da,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>J(m),children:[t.jsx(Ks,{}),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:()=>J(g),children:[t.jsx(Ti,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>ee(Ae=>!Ae),"aria-expanded":q,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(In,{size:14,className:`mobile-more-chevron${q?" mobile-more-chevron--open":""}`})})]}),q&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(ft,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):w.length>0?t.jsxs(t.Fragment,{children:[w.map(([Ae,Ee])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${Ae}`,onClick:()=>{S&&S(Ae,Ee),H(),ee(!1)},children:[t.jsx(Yn,{}),t.jsx("span",{children:Ae})]},Ae)),p&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{H(),ee(!1),p()},children:[t.jsx(di,{}),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:()=>{H(),ee(!1),p()},children:[t.jsx(di,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>J(x),children:[t.jsx(fs,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>J(fe),children:[t.jsx(pi,{}),t.jsx("span",{children:"Planning"}),A>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Zc(A)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>J(h),children:[t.jsx(il,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>J(f),children:[t.jsx(Ii,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>J(y),children:[t.jsx(L$,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>J(N),children:[t.jsx(qs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>J(T),children:[t.jsx(Sl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>J(()=>n("documents")),children:[t.jsx(Vi,{}),t.jsx("span",{children:"Documents"})]}),Y&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>J(()=>n("skills")),children:[t.jsx(is,{}),t.jsx("span",{children:"Skills"})]}),D&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>J(()=>n("roadmaps")),children:[t.jsx(ud,{}),t.jsx("span",{children:"Roadmaps"})]}),E?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>J(()=>n("research")),children:[t.jsx(Pi,{}),t.jsx("span",{children:"Research"})]}),E?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>J(()=>n("insights")),children:[t.jsx(vs,{}),t.jsx("span",{children:"Insights"})]}),E?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>J(()=>n("memory")),children:[t.jsx(zr,{}),t.jsx("span",{children:"Memory"})]}),E?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{J(()=>n("dev-server"))},children:[t.jsx(Da,{}),t.jsx("span",{children:"Dev Server"})]}),E?.nodesView&&O&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>J(O),children:[t.jsx(Kv,{}),t.jsx("span",{children:"Nodes"})]}),z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>J(()=>v?.()),children:[t.jsx(nl,{}),t.jsx("span",{children:"Todos"})]}),Ge.map(Ae=>{const Ee=Ir(Ae.pluginId,Ae.view.viewId),ie=cl(Ae.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${Ae.pluginId}-${Ae.view.viewId}`,onClick:()=>J(()=>n(Ee)),children:[t.jsx(ie,{}),t.jsx("span",{children:Ae.view.label})]},`${Ae.pluginId}:${Ae.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>J(o),children:[t.jsx(Rr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function z$({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below"}){const l=i.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(d=>d.name.toLowerCase().includes(c)):e},[e,n]);return a?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,d)=>t.jsxs("button",{type:"button",className:`agent-mention-item${d===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:u=>u.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":d===s,children:[t.jsx(Tn,{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 Ra="__fn_agent__";function Ab(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Ko(e,n,s){const a=typeof e=="string"?e.trim():"",r=Ab(n,s),o=a||(r.modelProvider&&r.modelId?Ra:"");return o?{agentId:o,...r}:null}function Go(e,n,s){const a=Ab(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function F$(e){const n=typeof e=="string"?e.trim():"",s=n.indexOf("/");return!n||s<=0||s>=n.length-1?{}:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function U$(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,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(a=>a!==null);return s.length>0?s:void 0}function B$(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,a=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!a||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:a,fallbackModel:r,triggerPoint:o}}function ed(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:U$(e.metadata),fallbackInfo:B$(e.metadata),createdAt:e.createdAt}}function H$(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(""),[v,b]=i.useState(""),[y,j]=i.useState([]),[C,A]=i.useState(""),N=i.useRef(null),S=i.useRef(!1),_=i.useRef(null),T=i.useRef(""),M=i.useRef(f);M.current=f;const E=i.useRef(null),O=i.useRef(""),B=i.useRef(null);i.useEffect(()=>{T.current=C},[C]);const R=i.useCallback(async()=>{c(!0);try{const de=await Xu(e);o(de.sessions)}catch(de){console.error("[useQuickChat] Failed to refresh sessions:",de)}finally{c(!1)}},[e]),P=i.useCallback(async de=>{const D={agentId:de.agentId};return de.modelProvider&&de.modelId&&(D.modelProvider=de.modelProvider,D.modelId=de.modelId),(await t1(D,e)).session},[e]),F=i.useCallback(async(de,D,_e)=>{const z=Ko(de,D,_e);if(!z)return;const Z=Go(z.agentId,z.modelProvider,z.modelId);c(!0);try{const{session:oe}=await e1({agentId:z.agentId,modelProvider:z.modelProvider,modelId:z.modelId},e);if(oe)a(oe),O.current=Z,oe.isGenerating&&(p(!0),x(""));else{const Y=await P(z);a(Y),O.current=Z}}catch(oe){console.error("[useQuickChat] Failed to initialize session:",oe),n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,P]),q=i.useCallback(async()=>{if(s){h(!0);try{const de=await ec(s.id,{limit:50},e);u(de.messages.map(ed))}catch(de){console.error("[useQuickChat] Failed to load messages:",de)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?q():u([])},[s,q]),i.useEffect(()=>{if(!f||N.current||!s)return;const de=setInterval(async()=>{if(!M.current||N.current||!s){clearInterval(de);return}try{if(!(await n1(s.id,e)).session.isGenerating){clearInterval(de);const _e=await ec(s.id,{limit:50},e);u(_e.messages.map(ed)),x(""),b(""),j([]),p(!1)}}catch{}},3e3);return()=>clearInterval(de)},[f,s,e]);const ee=i.useCallback(async()=>{if(s){h(!0);try{const de=await ec(s.id,{limit:50},e);u(de.messages.map(ed))}catch(de){console.error("[useQuickChat] Failed to reload messages:",de)}finally{h(!1)}}},[s,e]),U=i.useCallback(()=>{_.current?.(),_.current=null,T.current="",A(""),x(""),b(""),j([]),p(!1)},[]),k=i.useCallback(async(de,D,_e)=>{const z=Ko(de,D,_e);if(!z)return;const Z=Go(z.agentId,z.modelProvider,z.modelId);B.current=z;const oe=Z===O.current&&s;if(oe||(N.current&&(N.current.close(),N.current=null),U()),oe){await ee();return}a(null),u([]),O.current=Z,await F(z.agentId,z.modelProvider,z.modelId)},[s,F,ee,U]),I=i.useCallback(async de=>{const D=Ko(de.agentId,de.modelProvider??void 0,de.modelId??void 0);D&&(B.current=D,O.current=Go(D.agentId,D.modelProvider,D.modelId),N.current&&(N.current.close(),N.current=null),U(),a(de))},[U]),$=i.useCallback(async(de,D)=>{await k(Ra,de,D)},[k]),w=i.useCallback(async(de,D,_e)=>{const Z=Ko(de??"",D,_e)??B.current;if(!Z)return;B.current=Z;const oe=Go(Z.agentId,Z.modelProvider,Z.modelId);N.current&&(N.current.close(),N.current=null),U(),u([]),a(null),c(!0);try{const Y=await P(Z);a(Y),O.current=oe;const ae=await Xu(e);o(ae.sessions)}catch(Y){console.error("[useQuickChat] Failed to start a fresh session:",Y),n?.("Failed to start a new chat","error")}finally{c(!1)}},[n,P,e,U]),H=i.useCallback(()=>{s&&(S.current=!0,_.current?.(),_.current=null,N.current?.close(),N.current=null,s1(s.id,e).catch(()=>{}),p(!1),x(""),b(""),j([]))},[s,e]),J=i.useCallback(()=>{T.current="",A("")},[]),fe=i.useCallback((de,D)=>{if(!s||!de.trim()&&(!D||D.length===0))return Promise.resolve();if(f)return D&&D.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(T.current=de,A(de),Promise.resolve());const _e=new Promise((z,Z)=>{E.current={resolve:z,reject:Z},S.current=!1,N.current&&(N.current.close(),N.current=null);const Y={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:de,createdAt:new Date().toISOString()};u(Ee=>[...Ee,Y]),x(""),b(""),j([]),p(!0);let ae="",ce="",te=[],Re,be=null,ke=null;const Ue=()=>{be=null,x(ae)},Ge=()=>{ke=null,b(ce)},qe=()=>{be!==null&&(cancelAnimationFrame(be),be=null),ke!==null&&(cancelAnimationFrame(ke),ke=null)};_.current=qe;const Ae={onThinking:Ee=>{ce+=Ee,ke===null&&(ke=requestAnimationFrame(Ge))},onText:Ee=>{ae+=Ee,be===null&&(be=requestAnimationFrame(Ue))},onToolStart:Ee=>{te=[...te,{toolName:Ee.toolName,args:Ee.args,isError:!1,status:"running"}],j(te)},onToolEnd:Ee=>{const ie=[...te];for(let se=ie.length-1;se>=0;se--){const xe=ie[se];if(xe?.toolName===Ee.toolName&&xe.status==="running"){ie[se]={...xe,status:"completed",isError:Ee.isError,result:Ee.result},te=ie,j(ie);return}}te=[...ie,{toolName:Ee.toolName,isError:Ee.isError,result:Ee.result,status:"completed"}],j(te)},onFallback:Ee=>{Re=Ee;const ie=F$(Ee.fallbackModel);o(se=>se.map(xe=>xe.id===s.id?{...xe,...ie}:xe)),a(se=>se&&se.id===s.id?{...se,...ie}:se),n?.(`Primary model unavailable. Switched to fallback ${Ee.fallbackModel}.`,"warning")},onDone:Ee=>{qe();const ie={id:Ee.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:ae,thinkingOutput:ce||void 0,toolCalls:te.length>0?te:void 0,fallbackInfo:Re,createdAt:new Date().toISOString()};u(xe=>[...xe,ie]),x(""),b(""),j([]),p(!1),N.current=null,E.current?.resolve(),E.current=null;const se=T.current.trim();se&&(T.current="",A(""),fe(se))},onError:Ee=>{if(qe(),x(""),b(""),j([]),p(!1),N.current=null,console.error("[useQuickChat] Stream error:",Ee),n?.(typeof Ee=="string"&&Ee.trim()?Ee:"Failed to get response","error"),E.current?.reject(new Error(typeof Ee=="string"?Ee:"Failed to get response")),E.current=null,!S.current){const ie=T.current.trim();ie&&(T.current="",A(""),fe(ie))}ee()}};N.current=i1(s.id,de,Ae,D,e)});return _e.catch(()=>{}),_e},[s,f,e,n,ee]);return i.useEffect(()=>()=>{N.current&&(N.current.close(),N.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:C,sendMessage:fe,stopStreaming:H,clearPendingMessage:J,switchSession:k,selectSession:I,startModelChat:$,startFreshSession:w,refreshSessions:R,loadMessages:q,reloadMessages:ee}),[s,r,l,d,m,f,g,v,y,C,fe,H,J,k,I,$,w,R,q,ee])}function q$(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async f=>{c(!0);try{const p=n?.filterState,g=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await fa({...g,...f,includeEphemeral:f?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());a(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const f=await wj(e);o(f)}catch(f){console.error("Failed to load agent stats:",f)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{d(),u()};return fi(`/api/events${f}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,d,u]);const m=n?.showSystemAgents??!1,h=s.filter(f=>f.state!=="active"&&f.state!=="running"?!1:m||!B1(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:d,loadStats:u}}function V$({visible:e,position:n,files:s,selectedIndex:a,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 d=d1(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(sf,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const W$=200;function K$(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),x=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=i.useCallback((N,S)=>{if(S<0||S>N.length){r(!1);return}const _=T=>/[a-zA-Z0-9/_.-]/.test(T);for(let T=S-1;T>=0;T--){if(N[T]==="#")if(T===0){const M=N.slice(T+1,S);d(T),l(M),g(0),r(!0);return}else{const M=N[T-1];if(/[\s,.;:!?'"()[\]{}]/.test(M)){const E=N.slice(T+1,S);d(T),l(E),g(0),r(!0);return}r(!1);return}if(!_(N[T])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),j=i.useCallback(async N=>{if(!N.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const S=await Ek(N,s,n);m(S.files),g(0)}catch(S){S.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{j(o)},W$),()=>{x.current&&clearTimeout(x.current)}},[o,a,j]);const C=i.useCallback((N,S)=>{if(!a||c<0)return S;const _=S.slice(0,c),T=S.slice(c+1),M=T.match(/[\s]|$/),E=M?M.index:T.length,O=T.slice(E);return`${_}#${N.path}${O}`},[a,c]),A=i.useCallback((N,S)=>{if(!a||u.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),g(_=>Math.min(_+1,u.length-1)),!0;case"ArrowUp":return N.preventDefault(),g(_=>Math.max(_-1,0)),!0;case"Enter":case"Tab":return u[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:C,dismissMention:y,handleKeyDown:A}}function G$(e){return`${e.name?.trim()||e.id} (${e.role})`}function kr(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 J$(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 Zo(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function Y$(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${Zo(r,50)}`}).join(", ")}function Q$(e){if(e===void 0)return null;if(typeof e=="string")return Zo(e,200);try{return Zo(JSON.stringify(e),200)}catch{return Zo(String(e),200)}}function Pb(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",x=f.status==="completed"&&f.isError,v=Y$(f.args),b=Q$(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,j=n?null:y,C=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),j&&t.jsx("span",{className:"chat-tool-call-preview",title:j,children:j}),t.jsx("span",{className:"chat-tool-call-status-text",children:C})]}),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})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Mu,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"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(Mu,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Rb={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 $p(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function X$(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Jo={width:320,height:400},Z$=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"]),eD=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function tD(e){return e.type.startsWith("image/")}function nD(e){if(Z$.has(e.type))return!0;const n=e.name.toLowerCase();return eD.some(s=>n.endsWith(s))}const Ma={width:280,height:260},Ss=768,_a=8;function sD(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();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 a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=n??i.useRef(!1),m=i.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,j=window.innerWidth>768?s():0,C=window.innerWidth-v-b,A=window.innerHeight-v-b-y-j;return{x:Math.max(b,Math.min(C,x.x)),y:Math.max(b,Math.min(A,x.y))}},[s]),h=i.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),f=i.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),d.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},u.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=i.useCallback(x=>{if(!d.current||!l)return;const v=x.clientX-d.current.pointerX,b=x.clientY-d.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(u.current=!0),u.current){const y=d.current.x-v,j=d.current.y-b,C=m({x:y,y:j});o(C)}},[l,m]),g=i.useCallback(x=>{if(!d.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="",!u.current){d.current=null;return}h(r),d.current=null,u.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:f,handlePointerMove:p,handlePointerUp:g}}function iD(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Ss,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(Ma.width,window.innerWidth-p-_a),v=Math.max(Ma.height,window.innerHeight-g-_a);return{width:Math.max(Ma.width,Math.min(x,f.width)),height:Math.max(Ma.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ss)return Jo;try{const f=localStorage.getItem(a);if(!f)return Jo;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Jo:{width:p.width,height:p.height}}catch{return Jo}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const j=y.clientX-x.pointerX,C=y.clientY-x.pointerY;let A=x.width,N=x.height,S=x.anchorRight,_=x.anchorBottom;if(p.includes("w")&&(A=x.width-j),p.includes("e")){const R=j;A=x.width+R,S=x.anchorRight-R}if(p.includes("n")&&(N=x.height-C),p.includes("s")){const R=C;N=x.height+R,_=x.anchorBottom-R}const T=n+S,M=s+_,E=o({width:A,height:N},T,M),O=Math.max(_a-n,Math.min(window.innerWidth-n-Ma.width-_a,S)),B=Math.max(_a-s,Math.min(window.innerHeight-s-Ma.height-_a,_));d(E),m({right:O,bottom:B})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Dp=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,onToggleRender:r}){const o=n.role==="user",l=i.useMemo(()=>{if(!o)return null;const d=n.content,u=/@([\w-]+)/g,m=[];let h=0,f=u.exec(d);for(;f;){const[p,g=""]=f,x=f.index;x>h&&m.push(d.slice(h,x));const v=g.replace(/_/g," ").toLowerCase(),b=a.get(v);b?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",b.name.replace(/\s+/g,"_")]},`${b.id}-${x}`)):m.push(p),h=x+p.length,f=u.exec(d)}return h<d.length&&m.push(d.slice(h)),m.length===0?d:m},[o,n.content,a]),c=i.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ji,{remarkPlugins:[Ni],components:Rb,children:n.content})}),[o,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${o?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[o?t.jsx("p",{children:l}):t.jsxs(t.Fragment,{children:[c,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>r(n.id),children:s?t.jsx(qd,{size:14}):t.jsx(Ja,{size:14})})]}),Pb(n.toolCalls,!0)]})});function aD({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=q$(e),[m,h]=i.useState(!1),f=a!==void 0,p=f?a:m,g=f?me=>{r?.(typeof me=="function"?me(p):me)}:h;Hl({enabled:p});const x=Di(),[v,b]=i.useState("agent"),[y,j]=i.useState(""),[C,A]=i.useState(!1),[N,S]=i.useState("model"),[_,T]=i.useState(""),[M,E]=i.useState(""),[O,B]=i.useState([]),[R,P]=i.useState(!1),[F,q]=i.useState(""),[ee,U]=i.useState(""),[k,I]=i.useState(""),[$,w]=i.useState([]),[H,J]=i.useState(!1),[fe,de]=i.useState(!1),[D,_e]=i.useState(""),[z,Z]=i.useState(0),[oe,Y]=i.useState(""),[ae,ce]=i.useState(!1),[te,Re]=i.useState(0),[be,ke]=i.useState(-1),[Ue,Ge]=i.useState(()=>new Set),[qe,Ae]=i.useState(!1),[Ee,ie]=i.useState([]),[se,xe]=i.useState(!1),[,ne]=i.useState(!1),[Fe,Qe]=i.useState({top:0,left:0}),ge=K$({projectId:e}),ze=i.useCallback(me=>{if(!me||!ge.mentionActive)return;const He=me.getBoundingClientRect();Qe({top:He.top-260,left:He.left+8})},[ge.mentionActive]),tt=i.useRef(!1),pt=i.useRef(!1),ve=i.useRef(""),le=i.useRef(0),Te=i.useRef(null),pe=i.useRef(null),$e=i.useRef(0),{position:st,isDragging:at,handlePointerDown:rt,handlePointerMove:Oe,handlePointerUp:Be}=sD(e,tt),et=st.y+60,{panelSize:jt,anchorOffset:De,handleResizeStart:vt}=iD(e,st.x,et),Et=typeof window<"u"&&window.innerWidth>Ss,{activeSession:bt,messages:zt,isStreaming:qt,streamingText:It,streamingThinking:_t,streamingToolCalls:Xt,sessions:Lt,sessionsLoading:Ut,messagesLoading:cn,sendMessage:Jt,stopStreaming:Vt,pendingMessage:Kt,clearPendingMessage:rn,switchSession:fn,selectSession:on,startModelChat:gn,startFreshSession:je,refreshSessions:Le}=H$(e,n),re=i.useRef(null),Pe=i.useRef(null),Se=i.useRef(null),X=i.useRef(null),Ie=i.useRef(null),he=i.useRef([]),Ne=i.useRef(!1),Je=i.useRef(!1),kt=i.useRef(!1),Yt=i.useRef(null),$t=i.useRef(!1);i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>Ss)return;const me=window.scrollY,He=document.documentElement,lt=document.body,G={htmlOverflow:He.style.overflow,bodyOverflow:lt.style.overflow};return window.scrollTo(0,0),He.style.overflow="hidden",lt.style.overflow="hidden",()=>{He.style.overflow=G.htmlOverflow,lt.style.overflow=G.bodyOverflow,window.scrollTo(0,me)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const me=re.current;if(!me)return;const He=window.visualViewport,lt=()=>{$t.current||(me.style.setProperty("--vv-height",`${He.height}px`),me.style.setProperty("--vv-offset-top",`${He.offsetTop||0}px`))};return lt(),He.addEventListener("resize",lt),He.addEventListener("scroll",lt),()=>{He.removeEventListener("resize",lt),He.removeEventListener("scroll",lt)}},[p]);const Tt=F||ee,Bt=i.useMemo(()=>kr(Tt),[Tt]),jn=i.useMemo(()=>v==="model"&&bt?.modelProvider&&bt?.modelId?`${bt.modelProvider}/${bt.modelId}`:Tt,[bt?.modelId,bt?.modelProvider,v,Tt]),Dn=i.useMemo(()=>kr(jn),[jn]),hn=i.useMemo(()=>O.find(me=>`${me.provider}/${me.id}`===jn)??null,[jn,O]),Ht=i.useMemo(()=>J$(hn,Dn),[hn,Dn]),yn=i.useMemo(()=>v==="model"?Bt?`${Ra}::${Bt.modelProvider}/${Bt.modelId}`:"":y?`${y}::`:"",[v,y,Bt]),es=!(v==="agent"?!!y:!!Bt)||!bt;i.useEffect(()=>{if(u.length===0){j(""),b("model");return}u.some(He=>He.id===y)||j(u[0]?.id??"")},[u,y]),i.useEffect(()=>{!p||pt.current||(pt.current=!0,P(!0),Ds().then(me=>{const He=me.models??[];if(B(He),F||He.length===0)return;const lt=me.defaultProvider,G=me.defaultModelId;if(lt&&G){const it=`${lt}/${G}`;if(He.some(Nt=>`${Nt.provider}/${Nt.id}`===it)){U(it),q(it),b("model");return}}U("");const we=He[0];we&&q(`${we.provider}/${we.id}`)}).catch(me=>{console.error("[QuickChatFAB] Failed to load models:",me),B([]),U("")}).finally(()=>{P(!1)}))},[p,u.length,F]),i.useEffect(()=>{!p||!e||(J(!0),ZN(e).then(me=>{w(me)}).catch(()=>{w([])}).finally(()=>{J(!1)}))},[p,e]),i.useEffect(()=>{p&&Le()},[p,Le]),i.useEffect(()=>{if(!p){ve.current="";return}if(!yn){ve.current="";return}const me=yn===ve.current&&!bt&&!Ut;if(!(yn===ve.current&&!me)){if(ve.current=yn,v==="model"&&Bt){gn(Bt.modelProvider,Bt.modelId);return}v==="agent"&&y&&fn(y)}},[p,v,Bt,y,yn,bt,Ut,gn,fn]),i.useEffect(()=>{p||(ce(!1),Y(""),ke(-1),de(!1),_e(""),Z(0),he.current.forEach(me=>{me.previewUrl&&URL.revokeObjectURL(me.previewUrl)}),ie([]))},[p]),i.useEffect(()=>{he.current=Ee},[Ee]),i.useEffect(()=>{if(!p){Ne.current=!1;return}typeof window>"u"||(Ne.current=window.innerWidth<=Ss)},[p]),i.useEffect(()=>{if(!p||es||!Ne.current)return;const me=X.current;if(!me)return;const He=document.activeElement,lt=He?re.current?.contains(He):!1,G=He===document.body,we=He===Yt.current;if(!lt&&!G&&!we){Ne.current=!1;return}if(we){me.focus({preventScroll:!0}),Ne.current=!1;return}const it=requestAnimationFrame(()=>{me.focus(),Ne.current=!1});return()=>cancelAnimationFrame(it)},[p,es]),i.useEffect(()=>()=>{he.current.forEach(me=>{me.previewUrl&&URL.revokeObjectURL(me.previewUrl)})},[]);const ye=i.useCallback(()=>{A(!0),S("model"),T(u[0]?.id??""),E(F||ee||"")},[u,ee,F]),ut=i.useMemo(()=>u.find(me=>me.id===y)??null,[u,y]),Qt=i.useMemo(()=>{const me=D.trim().toLowerCase();return(me?$.filter(lt=>lt.name.toLowerCase().includes(me)):$).slice(0,10)},[$,D]),Cn=i.useMemo(()=>{const me=oe.trim().toLowerCase();return me?u.filter(He=>He.name.toLowerCase().includes(me)):u},[u,oe]),ue=i.useMemo(()=>{const me=new Map;for(const He of u)me.set(He.name.toLowerCase(),He);return me},[u]);i.useEffect(()=>{Z(0)},[Qt]),i.useEffect(()=>{Re(0)},[oe,ae]),i.useEffect(()=>()=>{Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),pe.current!==null&&(window.clearTimeout(pe.current),pe.current=null)},[]),i.useEffect(()=>{if(!p)return;const me=lt=>{const G=lt.target;re.current?.contains(G)||Pe.current?.contains(G)||G.closest(".model-combobox-dropdown--portal")||g(!1)},He=lt=>{lt.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",me),document.addEventListener("keydown",He),()=>{document.removeEventListener("mousedown",me),document.removeEventListener("keydown",He)}},[p,g]),i.useEffect(()=>{if(!p)return;const me=Se.current;me&&(me.scrollTop=me.scrollHeight)},[zt,It,_t,qt,p]);const dt=i.useMemo(()=>{const me=new Map(u.map(lt=>[lt.id,lt.name?.trim()||lt.id])),He=new Map(O.map(lt=>[`${lt.provider}/${lt.id}`,lt.name?.trim()||""]));return Lt.map((lt,G)=>{const we=lt.title?.trim()||`Session ${G+1}`;let it=null;if(lt.agentId&&lt.agentId!==Ra)it=me.get(lt.agentId)||lt.agentId;else if(lt.modelProvider&&lt.modelId){const St=`${lt.modelProvider}/${lt.modelId}`,Nt=He.get(St);it=Nt?`${Nt} [${St}]`:St}return{id:lt.id,label:it?`${we} — ${it}`:we}})},[u,O,Lt]),wt=i.useMemo(()=>v==="agent"?ut?`Message ${ut.name||ut.id}`:"Select an agent to start chatting":Ht?`Message ${Ht}`:"Select a model to start chatting",[v,ut,Ht]),gt=i.useCallback(me=>{const He=Lt.find(lt=>lt.id===me);He&&(He.modelProvider&&He.modelId?(b("model"),q(`${He.modelProvider}/${He.modelId}`)):(b("agent"),j(He.agentId)),on(He))},[on,Lt]),ot=i.useCallback(async()=>{if(!Ut){if(N==="agent"){if(!_)return;b("agent"),j(_),await je(_)}else{const me=kr(M||F||ee);if(!me)return;b("model"),q(`${me.modelProvider}/${me.modelId}`),await je(Ra,me.modelProvider,me.modelId)}await Le(),A(!1),S("model")}},[ee,_,N,M,Le,F,Ut,je]),yt=Kt.length>50?`${Kt.slice(0,50)}…`:Kt,Ft=i.useCallback(me=>{if(!me||me.length===0)return;const He=[];for(let lt=0;lt<me.length;lt+=1){const G=me[lt];nD(G)&&He.push({file:G,previewUrl:tD(G)?URL.createObjectURL(G):""})}He.length>0&&ie(lt=>[...lt,...He])},[]),Zt=i.useCallback(me=>{ie(He=>{const lt=He[me];return lt?.previewUrl&&URL.revokeObjectURL(lt.previewUrl),He.filter((G,we)=>we!==me)})},[]),Ln=i.useCallback(me=>{Ft(me.clipboardData?.files)},[Ft]),Wt=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ss)return;const me=X.current;!me||me.disabled||me.focus({preventScroll:!0})},[]),Mt=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ss||(kt.current=!0)},[]),En=i.useCallback(async()=>{const me=k.trim(),He=he.current;if(!(!me&&He.length===0)&&!es){if(I(""),ce(!1),Y(""),ke(-1),me==="/help"){Ae(!0),Wt(),kt.current=!1;return}if(me==="/clear"){Vt(),rn(),He.forEach(lt=>{lt.previewUrl&&URL.revokeObjectURL(lt.previewUrl)}),ie(lt=>lt.filter(G=>!He.includes(G)));try{if(v==="model"){const lt=kr(Tt);if(!lt)return;await je(Ra,lt.modelProvider,lt.modelId)}else y&&await je(y)}catch{n("Failed to clear conversation","error")}finally{Wt(),kt.current=!1}return}try{Ae(!1),await Jt(me,He.map(lt=>lt.file)),He.forEach(lt=>{lt.previewUrl&&URL.revokeObjectURL(lt.previewUrl)}),ie(lt=>lt.filter(G=>!He.includes(G)))}catch{}finally{Wt(),kt.current=!1}}},[n,v,rn,Wt,es,k,Tt,y,Jt,je,Vt]),Xn=i.useCallback(me=>{me.preventDefault(),$e.current+=1,xe(!0)},[]),ts=i.useCallback(me=>{me.preventDefault(),me.dataTransfer.dropEffect="copy",xe(!0)},[]),Ps=i.useCallback(me=>{me.preventDefault(),$e.current=Math.max(0,$e.current-1),$e.current===0&&xe(!1)},[]),ws=i.useCallback(me=>{me.preventDefault(),$e.current=0,xe(!1),Ft(me.dataTransfer?.files)},[Ft]),Bn=i.useCallback((me,He)=>{const lt=X$(me,He);if(lt){ce(!0),Y(lt.filter),ke(lt.start);return}ce(!1),Y(""),ke(-1)},[]),rs=i.useCallback(me=>{I(He=>{const lt=$p(He);if(!lt)return He;const G=`/skill:${me.name} `,we=He.slice(0,lt.start)+G+He.slice(lt.end);return window.requestAnimationFrame(()=>{X.current&&X.current.focus()}),we}),de(!1),_e(""),Z(0)},[]),V=i.useCallback(me=>{const He=X.current;if(!He||be<0)return;const lt=He.selectionStart??le.current,G=He.selectionEnd??lt,we=Math.max(lt,G),it=Math.min(be,we),Nt=`${`@${me.name.replace(/\s+/g,"_")}`} `,Mn=k.slice(0,it)+Nt+k.slice(we),nn=it+Nt.length;I(Mn),ce(!1),Y(""),Re(0),ke(-1),window.requestAnimationFrame(()=>{X.current&&(X.current.focus(),X.current.setSelectionRange(nn,nn))})},[be,k]),Ve=i.useCallback(me=>{const He=me.target.value,lt=me.target.selectionStart??He.length;le.current=lt,I(He),qe&&He.trim().length>0&&Ae(!1),Bn(He,lt);const G=$p(He);G?(de(!0),_e(G.filter)):(de(!1),_e("")),ge.detectMention(He,lt),ne(ge.mentionActive),ge.mentionActive&&ze(me.target)},[qe,Bn,ge,ze]),Ye=i.useCallback(()=>{if(kt.current){window.requestAnimationFrame(()=>{Wt()});return}typeof window<"u"&&window.innerWidth<=Ss&&re.current&&($t.current=!0,re.current.style.removeProperty("--vv-height"),re.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{$t.current=!1},450)),Te.current!==null&&window.clearTimeout(Te.current),Te.current=window.setTimeout(()=>{ce(!1),Y(""),ke(-1),ne(!1),ge.dismissMention(),Te.current=null},120),pe.current!==null&&window.clearTimeout(pe.current),pe.current=window.setTimeout(()=>{de(!1),pe.current=null},120)},[ge,Wt]),mt=i.useCallback(()=>{$t.current=!1,Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),pe.current!==null&&(window.clearTimeout(pe.current),pe.current=null)},[]),Ct=i.useCallback(me=>{const He=me.currentTarget,lt=He.selectionStart??He.value.length;le.current=lt,Bn(He.value,lt),ge.detectMention(He.value,lt),ne(ge.mentionActive),ge.mentionActive&&ze(He)},[Bn,ge,ze]),Rt=i.useCallback(me=>{me.key!=="Escape"&&Ct(me)},[Ct]),dn=i.useCallback(me=>{Ge(He=>{const lt=new Set(He);return lt.has(me)?lt.delete(me):lt.add(me),lt})},[]),Dt=i.useCallback((me,He=!1)=>He?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:me}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ji,{remarkPlugins:[Ni],components:Rb,children:me})}),[]),ks=i.useCallback(me=>{if(le.current=me.currentTarget.selectionStart??le.current,ge.mentionActive&&ge.files.length>0){if(ge.handleKeyDown(me,k),me.key==="Enter"||me.key==="Tab"){const He=ge.files[ge.selectedIndex];if(He){const lt=ge.selectFile(He,k);I(lt),ge.dismissMention(),ne(!1)}}return}if(ae&&me.key==="ArrowDown"){me.preventDefault(),Cn.length>0&&Re(He=>(He+1)%Cn.length);return}if(ae&&me.key==="ArrowUp"){me.preventDefault(),Cn.length>0&&Re(He=>He===0?Cn.length-1:He-1);return}if(ae&&me.key==="Enter"){me.preventDefault();const He=Cn[te]??Cn[0];He&&V(He);return}if(ae&&me.key==="Escape"){me.preventDefault(),me.stopPropagation(),ce(!1),Y(""),ke(-1);return}if(fe&&Qt.length>0&&me.key==="ArrowDown"){me.preventDefault(),Z(He=>(He+1)%Qt.length);return}if(fe&&Qt.length>0&&me.key==="ArrowUp"){me.preventDefault(),Z(He=>He===0?Qt.length-1:He-1);return}if(fe&&(me.key==="Enter"||me.key==="Tab")){me.preventDefault();const He=Qt[z]??Qt[0];He&&rs(He);return}if(fe&&me.key==="Escape"){me.preventDefault(),de(!1),_e("");return}me.key!=="Enter"||me.shiftKey||(me.preventDefault(),En())},[ae,Cn,te,V,En,ge,k,fe,Qt,z,rs]),Zn=i.useCallback(()=>{if(tt.current){tt.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=Ss&&Yt.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Yt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Pe,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":at?"true":"false",style:{right:st.x,bottom:st.y},onPointerDown:rt,onPointerMove:Oe,onPointerUp:Be,onClick:Zn,children:t.jsx(Ri,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:re,"data-testid":"quick-chat-panel",style:{...Et?{right:st.x+De.right,bottom:et+De.bottom,width:jt.width,height:jt.height}:{}},children:[Et&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:vt,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:vt,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:vt,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:vt,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:vt,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:vt,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:vt,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:vt,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"}),v==="model"&&Ht&&(()=>{const me=hn?.provider??Dn?.modelProvider??"";return x==="mobile"&&Ht.length>12&&me?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Ht,"aria-label":Ht,children:t.jsx(Qn,{provider:me,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Ht,children:Ht})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:ye,disabled:Ut,children:t.jsx(Nn,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>g(!1),children:t.jsx(tn,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:bt?.id??"",onChange:me=>gt(me.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Ut?"Loading sessions…":"Select a session"}),dt.map(me=>t.jsx("option",{value:me.id,children:me.label},me.id))]})]}),C&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${N==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>S("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${N==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>S("agent"),children:"Agent"})]}),N==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:me=>T(me.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(me=>t.jsx("option",{value:me.id,children:G$(me)},me.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(ys,{id:"quick-chat-new-model-select",models:O,value:M,onChange:E,label:"Select model override",placeholder:R?"Loading models…":"Select a model",disabled:R||O.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{A(!1),S("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void ot(),disabled:Ut||(N==="agent"?!_:!kr(M||F||ee)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Se,"data-testid":"quick-chat-messages",children:Ut?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):qt?t.jsxs(t.Fragment,{children:[zt.map(me=>t.jsx(Dp,{message:me,forcePlain:me.role!=="user"&&Ue.has(me.id),mentionAgentsByName:ue,onToggleRender:dn},me.id)),qe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Dt("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),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:[It?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Dt(It,Ue.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Ue.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Ue.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>dn("__streaming__"),children:Ue.has("__streaming__")?t.jsx(qd,{size:14}):t.jsx(Ja,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:_t?"Thinking…":"Connecting…"}),Pb(Xt,!0),_t&&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:_t})]})]})]}):cn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):zt.length===0&&!It&&!_t&&!qt&&!qe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[zt.map(me=>t.jsx(Dp,{message:me,forcePlain:me.role!=="user"&&Ue.has(me.id),mentionAgentsByName:ue,onToggleRender:dn},me.id)),qe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Dt("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),Ee.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Ee.map((me,He)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${He}`,children:[me.previewUrl?t.jsx("img",{src:me.previewUrl,alt:me.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:me.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${He}`,"aria-label":`Remove ${me.file.name}`,onClick:()=>Zt(He),children:"×"})]},`${me.file.name}-${He}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${se?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Xn,onDragOver:ts,onDragLeave:Ps,onDrop:ws,children:[t.jsx("input",{ref:Ie,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:me=>{Ft(me.target.files),me.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Ie.current?.click(),children:t.jsx(of,{size:16})}),t.jsx("input",{ref:X,type:"text",value:k,onChange:Ve,onKeyDown:ks,onKeyUp:Rt,onClick:Ct,onBlur:Ye,onFocus:mt,onPaste:Ln,onTouchStart:me=>{typeof window>"u"||window.innerWidth>Ss||document.activeElement!==me.currentTarget&&(me.preventDefault(),me.currentTarget.focus({preventScroll:!0}))},placeholder:wt,disabled:es,"data-testid":"quick-chat-input"}),qt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:me=>{typeof window>"u"||window.innerWidth>Ss||(me.preventDefault(),me.pointerType&&me.pointerType!=="mouse"&&(Je.current=!0,Vt()))},onTouchStart:me=>{typeof window>"u"||window.innerWidth>Ss||(me.preventDefault(),Je.current=!0,Vt())},onMouseDown:me=>{typeof window>"u"||window.innerWidth>Ss||me.preventDefault()},onClick:()=>{if(Je.current){Je.current=!1;return}Vt()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Bs,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:me=>{typeof window>"u"||window.innerWidth>Ss||(me.preventDefault(),me.pointerType&&me.pointerType!=="mouse"&&(Je.current=!0,Mt(),Wt(),En()))},onTouchStart:me=>{typeof window>"u"||window.innerWidth>Ss||(me.preventDefault(),Je.current=!0,Mt(),Wt(),En())},onMouseDown:me=>{typeof window>"u"||window.innerWidth>Ss||me.preventDefault()},onClick:()=>{if(Je.current){Je.current=!1;return}En()},disabled:es||k.trim().length===0&&Ee.length===0,"data-testid":"quick-chat-send",children:t.jsx(sa,{size:16})})]}),t.jsx(z$,{agents:u,filter:oe,highlightedIndex:te,visible:ae,onSelect:V,position:"above"}),t.jsx(V$,{visible:ge.mentionActive&&!ae,position:Fe,files:ge.files,selectedIndex:ge.selectedIndex,onSelect:me=>{const He=ge.selectFile(me,k);I(He),ge.dismissMention(),ne(!1),X.current?.focus()},loading:ge.loading}),fe&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:H?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Qt.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:D?"No skills found":"No skills available"}):Qt.map((me,He)=>t.jsxs("button",{type:"button",role:"option","aria-selected":He===z,className:`chat-skill-menu-item${He===z?" chat-skill-menu-item--highlighted":""}`,onMouseDown:lt=>lt.preventDefault(),onMouseEnter:()=>Z(He),onClick:()=>rs(me),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:me.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:me.relativePath,children:me.relativePath})]},me.id))}),Kt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${yt}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:rn,children:"×"})]})]})})]})]})}function jr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Lp(e){return e.status==="generating"||e.status==="awaiting_input"}function Nr(e){return e==="complete"||e==="error"}function rD(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=tr(),u=i.useCallback(()=>{Jd(e).then(p=>{const g=p.filter(v=>{const b=jr(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 g)x.set(v.id,jr(v.updatedAt));a.current=x,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!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=a.current.get(v.sessionId)??0;if(b<y)continue;const j=r.current.get(v.sessionId);if(j!==void 0&&b<=j)continue;if(j!==void 0&&b>j&&!Nr(v.status)&&r.current.delete(v.sessionId),Nr(v.status)){x.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const C=x.get(v.sessionId),A=v.type??C?.type,N=v.title??C?.title;if(!C&&(!A||!N))continue;const S={id:v.sessionId,type:A??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??C?.projectId??e??null,lockedByTab:v.owningTabId??C?.lockedByTab??null,updatedAt:v.updatedAt??C?.updatedAt??new Date(b).toISOString()},_=x.get(v.sessionId);(!_||_.status!==S.status||_.title!==S.title||_.type!==S.type||_.projectId!==S.projectId||_.lockedByTab!==S.lockedByTab||_.updatedAt!==S.updatedAt)&&(x.set(v.sessionId,S),a.current.set(v.sessionId,b),g=!0)}return g?[...x.values()].sort((v,b)=>jr(b.updatedAt)-jr(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=jr(b.updatedAt)||Date.now();s(j=>{const C=a.current.get(b.id)??0;if(y<C)return j;const A=r.current.get(b.id);if(A!==void 0&&y<=A)return j;if(A!==void 0&&y>A&&!Nr(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),Nr(b.status))return j.filter(S=>S.id!==b.id);const N=j.findIndex(S=>S.id===b.id);if(N>=0){const S=[...j];return S[N]=b,S}return Lp(b)?[b,...j]:j}),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),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(j=>j.filter(C=>C.id!==b))}catch{}};return fi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(j=>j.id===p)?.type,v=ba();let b=!1;if(x==="planning")try{await ff(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await xf(p,e,v)}catch(j){b=!0,j instanceof Error&&j.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await kf(p,e,v)}catch(j){b=!0,j instanceof Error&&j.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),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await jf(p)}catch{}s(j=>j.filter(C=>C.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Lp(p)),[n]),f=i.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:f,dismissSession:m,refresh:u}}const wl="fusion:hide-session-banners",Ud="fusion:session-banner-pref-changed";function oD(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(wl)==="1"}catch{return!1}}function lD(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===wl&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Ud,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Ud,s)}}function c3(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(wl,"1"):window.localStorage.removeItem(wl),window.dispatchEvent(new Event(Ud))}catch{}}function cD(){return i.useSyncExternalStore(lD,oD,()=>!1)}function bs(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 Op(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function dD(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function td(e,n){if(Op(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return dD(e,n);const a=Op(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function uD(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),x=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=i.useCallback(async ee=>{const U=++m.current,k=n,I=ee?.searchQueryOverride??f.current,$=ee?.includeArchivedOverride??d.current;try{const w=await aw(void 0,void 0,k,I,$);if(m.current!==U||n!==k)return;o(w.map(bs)),g.current=Date.now()}catch{if(m.current!==U||n!==k)return;if(ee?.clearOnError){o([]);return}o(w=>w)}},[n]);p.current=y;const j=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),C=i.useRef(s);i.useEffect(()=>{if(s===void 0&&C.current===void 0)return;C.current=s;const ee=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(ee)},[s]),i.useEffect(()=>{y({clearOnError:!0});const ee=()=>{if(document.visibilityState!=="visible")return;const U=Date.now();U-h.current<b||(h.current=U,y())};return document.addEventListener("visibilitychange",ee),()=>{document.removeEventListener("visibilitychange",ee)}},[y]),i.useEffect(()=>{if(a===!1)return;const ee=x.current,U=n?`?projectId=${encodeURIComponent(n)}`:"",k=()=>x.current!==ee;let I=!0;const $=D=>{if(k())return;const _e=bs(JSON.parse(D.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(z=>{const Z=z.findIndex(ce=>ce.id===_e.id);if(Z===-1)return[...z,_e];const oe=z[Z],Y=td(oe,_e);if(Y===oe)return z;const ae=[...z];return ae[Z]=Y,ae}),g.current=Date.now()},w=D=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:_e,to:z}=JSON.parse(D.data),Z=bs(_e);o(oe=>oe.map(Y=>Y.id===Z.id?{...Z,column:z}:Y)),g.current=Date.now()},H=D=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const _e=bs(JSON.parse(D.data));o(z=>z.map(Z=>Z.id!==_e.id?Z:td(Z,_e))),g.current=Date.now()},J=D=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const _e=bs(JSON.parse(D.data));o(z=>z.filter(Z=>Z.id!==_e.id))},fe=D=>{if(k())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:_e}=JSON.parse(D.data),z=bs(_e);o(Z=>Z.map(oe=>oe.id===z.id?{...z,column:"done"}:oe))},de=fi(`/api/events${U}`,{events:{"task:created":$,"task:moved":w,"task:updated":H,"task:deleted":J,"task:merged":fe},onReconnect:()=>{I&&(k()||p.current())}});return()=>{I=!1,de()}},[n,a]);const A=i.useCallback(async ee=>{const U=bs(await rl(ee,n));return o(k=>k.some(I=>I.id===U.id)?k:[...k,U]),U},[n]),N=i.useCallback(async(ee,U,k)=>bs(await ow(ee,U,n,k)),[n]),S=i.useCallback(async ee=>bs(await mf(ee,n)),[n]),_=i.useCallback(async ee=>bs(await lw(ee,n)),[n]),T=i.useCallback(async ee=>cw(ee,n),[n]),M=i.useCallback(async ee=>bs(await dw(ee,n)),[n]),E=i.useCallback(async ee=>bs(await uw(ee,n)),[n]),O=i.useCallback(async ee=>{const U=bs(await mw(ee,n));return o(k=>k.some(I=>I.id===U.id)?k:[...k,U]),U},[n]),B=i.useCallback(async(ee,U)=>{const k=u.current.find($=>$.id===ee),I=k?{...k,...U,updatedAt:new Date().toISOString()}:void 0;I&&o($=>$.map(w=>w.id===ee?I:w));try{const $=bs(await ci(ee,U,n));return o(w=>w.map(H=>H.id===ee?$:H)),$}catch($){throw k&&o(w=>w.map(H=>H.id===ee?k:H)),$}},[n]),R=i.useCallback(async ee=>{const U=bs(await pw(ee,n));return o(k=>k.map(I=>I.id===ee?U:I)),U},[n]),P=i.useCallback(async ee=>{const U=bs(await fw(ee,n));return o(k=>k.map(I=>I.id===ee?U:I)),U},[n]),F=i.useCallback(async()=>{const U=(await gw(n)).map(bs);return o(k=>k.map(I=>U.find(w=>w.id===I.id)||I)),U},[n]),q=i.useCallback(ee=>{if(ee.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const U=ee.map(bs);o(k=>{let I=k;for(const $ of U){const w=I.findIndex(fe=>fe.id===$.id);if(w===-1){I===k&&(I=[...k]),I.push($);continue}const H=I[w],J=td(H,$);J!==H&&(I===k&&(I=[...k]),I[w]=J)}return I}),g.current=Date.now()},[]);return{tasks:r,createTask:A,moveTask:N,pauseTask:S,deleteTask:_,mergeTask:T,retryTask:M,resetTask:E,duplicateTask:O,updateTask:B,archiveTask:R,unarchiveTask:P,archiveAllDone:F,loadArchivedTasks:j,includeArchived:l,ingestCreatedTasks:q,lastFetchTimeMs:g.current}}const mD=5e3,hD=1e3;function pD(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await Ku();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const x=performance.now();try{const v=await Ku(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),Tr("[useProjects]",y),f||(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}`),Tr("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<hD||(c.current=x,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},mD),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await Cj(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await Rj(f,p);return n(x=>x.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await vf(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const fD="kb-dashboard-current-project";function gD(e){return e??"local"}function bD(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=gD(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await pa();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const v=u.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(fD);if(b){const y=JSON.parse(b);y?.id&&e.some(C=>C.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await Pn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Pn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,Pn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Pn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Tb=i.createContext(null);function xD({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),el.createElement(Tb.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function vD(){const e=i.useContext(Tb);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Ib="kb-dashboard-theme-mode",$b="kb-dashboard-color-theme",Db="kb-dashboard-font-scale-pct",Bd=100,yD=85,wD=125,Lb=[...F1],Hd="theme-data",nd="theme-data.css";function kD(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${nd}`:e.replace(/\/[^/]+$/,`/${nd}`):`/${nd}`}const Os=typeof window<"u",jD=Os?i.useLayoutEffect:i.useEffect;function Ob(e){return e==="dark"||e==="light"||e==="system"}function zp(){if(!Os)return"dark";try{const e=localStorage.getItem(Ib);if(Ob(e))return e}catch{}return"dark"}function Fp(){if(!Os)return"default";try{const e=localStorage.getItem($b);if(e&&Lb.includes(e))return e}catch{}return"default"}function Up(e){if(Os)try{localStorage.setItem(Ib,e)}catch{}}function Bp(e){if(Os)try{localStorage.setItem($b,e)}catch{}}function Gr(e){return typeof e!="number"||!Number.isFinite(e)?Bd:Math.min(wD,Math.max(yD,Math.round(e)))}function Hp(){if(!Os)return Bd;try{const e=Number(localStorage.getItem(Db));return Gr(e)}catch{return Bd}}function qp(e){if(Os)try{localStorage.setItem(Db,String(Gr(e)))}catch{}}function ND(e,n){return e==="system"?n?"dark":"light":e}function SD(e,n,s,a){if(!Os)return;const r=ND(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Gr(s)}%`}function Vp(){if(!Os)return;const e=kD(),n=document.getElementById(Hd);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=Hd,document.head.appendChild(s)}function Wp(){if(!Os)return;const e=document.getElementById(Hd);e&&e.remove()}function CD(){const[e,n]=i.useState(()=>zp()),[s,a]=i.useState(()=>Fp()),[r,o]=i.useState(()=>Hp()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Os?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),x=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Os||!l)return;let j=!1;return pa().then(C=>{if(!j&&(Ob(C.themeMode)&&!p.current&&(m.current!==C.themeMode&&(m.current=C.themeMode,n(C.themeMode)),zp()!==C.themeMode&&Up(C.themeMode)),C.colorTheme&&Lb.includes(C.colorTheme)&&!g.current&&(h.current!==C.colorTheme&&(h.current=C.colorTheme,a(C.colorTheme)),Fp()!==C.colorTheme&&Bp(C.colorTheme)),!x.current)){const A=Gr(C.dashboardFontScalePct);f.current!==A&&(f.current=A,o(A)),Hp()!==A&&qp(A)}}).catch(C=>{console.warn("[useTheme] Failed to hydrate theme from global settings",C)}).finally(()=>{j||c(!1)}),()=>{j=!0}},[l]),i.useEffect(()=>{if(!Os)return;const j=window.matchMedia("(prefers-color-scheme: dark)"),C=A=>{u(A.matches)};return j.addEventListener("change",C),()=>j.removeEventListener("change",C)},[]),jD(()=>{SD(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Os||l||(s!=="default"?Vp():Wp())},[s,l]);const v=i.useCallback(j=>{p.current=!0,m.current=j,n(j),Up(j),Pn({themeMode:j}).catch(C=>{console.warn("[useTheme] Failed to persist themeMode to global settings",C)})},[]),b=i.useCallback(j=>{g.current=!0,h.current=j,a(j),Bp(j),j!=="default"?Vp():Wp(),Pn({colorTheme:j}).catch(C=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",C)})},[]),y=i.useCallback(j=>{const C=Gr(j);x.current=!0,f.current=C,o(C),qp(C),Pn({dashboardFontScalePct:C}).catch(A=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",A)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function ED(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(void 0),[v,b]=i.useState(null),[y,j]=i.useState("definition"),[C,A]=i.useState(null),[N,S]=i.useState(!1),[_,T]=i.useState(void 0),[M,E]=i.useState(!1),[O,B]=i.useState(!1),[R,P]=i.useState(!1),[F,q]=i.useState(null),[ee,U]=i.useState(!1),[k,I]=i.useState(!1),[$,w]=i.useState(void 0),[H,J]=i.useState(!1),[fe,de]=i.useState(!1),[D,_e]=i.useState("project"),[z,Z]=i.useState(!1),[oe,Y]=i.useState(!1),[ae,ce]=i.useState(!1),[te,Re]=i.useState(!1),[be,ke]=i.useState(!1),[Ue,Ge]=i.useState(!1),[qe,Ae]=i.useState(!1),Ee=!!(v||N||s||r||m||k||H||fe||z||oe||ae||be||te||R||ee||M||O||Ue||qe),ie=i.useCallback(()=>a(!0),[]),se=i.useCallback(()=>a(!1),[]),xe=i.useCallback(()=>o(!0),[]),ne=i.useCallback(Ne=>{c(Ne),o(!0)},[]),Fe=i.useCallback(()=>{const Ne=n[0];Ne&&(u(Ne.id),o(!0))},[n]),Qe=i.useCallback(Ne=>{u(Ne),o(!0)},[]),ge=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),ze=i.useCallback(Ne=>{p(Ne),h(!0)},[]),tt=i.useCallback(Ne=>{x(Ne),h(!0)},[]),pt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),ve=i.useCallback((Ne,Je="definition",kt)=>{b(Ne),j(Je),A(kt?.origin??null)},[]),le=i.useCallback(Ne=>{b(Ne),j("changes"),A(null)},[]),Te=i.useCallback(Ne=>{b(Je=>Je&&{...Je,...Ne})},[]),pe=i.useCallback(()=>{b(null),A(null)},[]),$e=i.useCallback(Ne=>{T(Ne),S(!0)},[]),st=i.useCallback(()=>{S(!1),T(void 0)},[]),at=i.useCallback(()=>E(!0),[]),rt=i.useCallback(()=>E(!1),[]),Oe=i.useCallback(()=>B(!0),[]),Be=i.useCallback(()=>B(!1),[]),et=i.useCallback(Ne=>{q(Ne??null),P(!0)},[]),jt=i.useCallback(()=>{P(!1),q(null)},[]),De=i.useCallback(()=>U(!0),[]),vt=i.useCallback(()=>U(!1),[]),Et=i.useCallback(()=>{I(Ne=>!Ne)},[]),bt=i.useCallback(()=>{I(!1),w(void 0)},[]),zt=i.useCallback(()=>J(!0),[]),qt=i.useCallback(()=>J(!1),[]),It=i.useCallback(()=>de(!0),[]),_t=i.useCallback(()=>de(!1),[]),Xt=i.useCallback(Ne=>{_e(Ne)},[]),Lt=i.useCallback(()=>Z(!0),[]),Ut=i.useCallback(()=>Z(!1),[]),cn=i.useCallback(()=>Y(!0),[]),Jt=i.useCallback(()=>Y(!1),[]),Vt=i.useCallback(()=>ce(!0),[]),Kt=i.useCallback(()=>ce(!1),[]),rn=i.useCallback(()=>Re(!0),[]),fn=i.useCallback(()=>Re(!1),[]),on=i.useCallback(()=>ke(!0),[]),gn=i.useCallback(()=>ke(!1),[]),je=i.useCallback(async(Ne,Je)=>{ke(!1),w(Je),I(!0)},[]),Le=i.useCallback(()=>Ge(!0),[]),re=i.useCallback(()=>Ge(!1),[]),Pe=i.useCallback(()=>Ae(!0),[]),Se=i.useCallback(()=>Ae(!1),[]),X=i.useCallback((Ne,Je)=>{Je(`Created ${Ne.id} from planning mode`,"success"),o(!1),c(null)},[]),Ie=i.useCallback((Ne,Je)=>{const kt=Ne.map(Yt=>Yt.id).join(", ");Je(`Created ${kt} from planning mode`,"success"),o(!1),c(null)},[]),he=i.useCallback((Ne,Je)=>{const kt=Ne.map(Yt=>Yt.id).join(", ");Je(`Created ${kt} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:C,settingsOpen:N,settingsInitialSection:_,schedulesOpen:M,githubImportOpen:O,usageOpen:R,usageAnchorRect:F,systemStatsOpen:ee,terminalOpen:k,terminalInitialCommand:$,filesOpen:H,todosOpen:fe,fileBrowserWorkspace:D,activityLogOpen:z,gitManagerOpen:oe,workflowStepsOpen:ae,agentsOpen:te,scriptsOpen:be,setupWizardOpen:Ue,modelOnboardingOpen:qe,anyModalOpen:Ee,openNewTask:ie,closeNewTask:se,openPlanning:xe,openPlanningWithInitialPlan:ne,resumePlanning:Fe,openPlanningWithSession:Qe,closePlanning:ge,openSubtaskBreakdown:ze,openSubtaskWithSession:tt,closeSubtask:pt,openDetailTask:ve,openDetailWithChangesTab:le,updateDetailTask:Te,closeDetailTask:pe,openSettings:$e,closeSettings:st,openSchedules:at,closeSchedules:rt,openGitHubImport:Oe,closeGitHubImport:Be,openUsage:et,closeUsage:jt,openSystemStats:De,closeSystemStats:vt,toggleTerminal:Et,closeTerminal:bt,openFiles:zt,closeFiles:qt,openTodos:It,closeTodos:_t,setFileWorkspace:Xt,openActivityLog:Lt,closeActivityLog:Ut,openGitManager:cn,closeGitManager:Jt,openWorkflowSteps:Vt,closeWorkflowSteps:Kt,openAgents:rn,closeAgents:fn,openScripts:on,closeScripts:gn,runScript:je,openSetupWizard:Le,closeSetupWizard:re,openModelOnboarding:Pe,closeModelOnboarding:Se,onPlanningTaskCreated:X,onPlanningTasksCreated:Ie,onSubtaskTasksCreated:he}}function MD(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(!1),[x,v]=i.useState(!1),[b,y]=i.useState(!1),[j,C]=i.useState({}),[A,N]=i.useState(!1),[S,_]=i.useState(!1),[T,M]=i.useState(!1),[E,O]=i.useState(!1),[B,R]=i.useState(!1),[P,F]=i.useState(!0),q=i.useCallback(async()=>{const[w,H]=await Promise.allSettled([vw(e),Rl(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),H.status==="fulfilled"){const J=H.value;l(!!J.autoMerge),d(!!J.globalPause),m(!!J.enginePaused),v(!!J.prAuthAvailable),f(J.taskStuckTimeoutMs),g(J.showQuickChatFAB===!0),C(J.experimentalFeatures??{});const fe=J.experimentalFeatures??{};N(fe.insights===!0),_(fe.roadmap===!0),M(fe.memoryView===!0),O(fe.devServerView===!0||fe.devServer===!0),R(fe.todoView===!0);const de=J.autoReloadOnVersionChange!==!1;F(de),Jl(de)}y(!0)},[e]);i.useEffect(()=>{y(!1),C({}),N(!1),_(!1),M(!1),O(!1),R(!1),q()},[q]);const ee=i.useCallback(async()=>{const w=!o;l(w);try{await xo({autoMerge:w},e)}catch{l(!w)}},[o,e]),U=i.useCallback(async()=>{const w=!c;d(w);try{await xo({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{d(!w)}},[c,e]),k=i.useCallback(async()=>{const w=!u;m(w);try{await xo({enginePaused:w},e)}catch{m(!w)}},[u,e]),I=i.useCallback(async()=>{const w=!p;g(w);try{await xo({showQuickChatFAB:w},e)}catch{g(!w)}},[p,e]),$=i.useCallback(async()=>{const w=!P;F(w),Jl(w);try{await Pn({autoReloadOnVersionChange:w})}catch{F(!w),Jl(!w)}},[P]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:j,insightsEnabled:A,roadmapEnabled:S,memoryEnabled:T,devServerEnabled:E,todosEnabled:B,autoReloadOnVersionChange:P,toggleAutoMerge:ee,toggleGlobalPause:U,toggleEnginePause:k,toggleShowQuickChatFAB:I,toggleAutoReloadOnVersionChange:$,refresh:q}}function _D(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(null);return i.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||a)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(u.current)return;u.current=!0,Oa(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}d()},[d])}}function AD(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ds().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await Pn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await Pn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function PD({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Hr().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return pa().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Ga()?l=!0:!u&&!Ga()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ti("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ti("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Kp="kb-update-banner-dismissed";function RD(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const h=sessionStorage.getItem(Kp)==="true";u(h);let f=!1;return yw().then(p=>{f||p.disabled||(a(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=i.useCallback(()=>{u(!0),sessionStorage.setItem(Kp,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const TD=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function ID(e){return e!==null&&TD.includes(e)}function $D(e){return e!==null&&/^plugin:[^:]+:.+$/u.test(e)}function Gp(e){return ID(e)||$D(e)}function DD(e){return e==="devserver"?"dev-server":e}function LD(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=as("kb-dashboard-task-view");return Gp(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=as("kb-dashboard-task-view",r?.id);if(Gp(b)){const y=!g.current&&b==="devserver";p(y?"devserver":DD(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{xs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const x=i.useCallback(b=>{p(b)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),j=b[(y+1)%b.length];u(j)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function OD(e){const{enabled:n}=e,s=i.useRef([]),a=i.useRef(!1),r=i.useRef(n);r.current=n;const o=i.useCallback(c=>{if(!r.current||a.current)return;const d=s.current[s.current.length-1];if(d){const h=d.type==="modal"?d.close:d.revert,f=c.type==="modal"?c.close:c.revert;if(h===f)return}s.current.push(c);const u=s.current.length,m=typeof window<"u"&&window.history.state?window.history.state:{};window.history.pushState({...m,navIndex:u},"")},[]),l=i.useCallback(c=>{if(!r.current||s.current.length===0)return;s.current[s.current.length-1]=c;const d=s.current.length,u=typeof window<"u"&&window.history.state?window.history.state:{};window.history.replaceState({...u,navIndex:d},"")},[]);return i.useEffect(()=>{if(typeof window>"u")return;const c=d=>{if(!r.current)return;const u=d.state?.navIndex??0,m=s.current.length;if(u>=m)return;const h=m-u;if(!(h<=0)){a.current=!0;try{for(let f=0;f<h;f++){const p=s.current.pop();p&&(p.type==="modal"?p.close():p.revert())}}finally{a.current=!1}}};return window.addEventListener("popstate",c),()=>{window.removeEventListener("popstate",c)}},[]),{pushNav:o,replaceCurrent:l}}const Jp=new Map,zD=6e4;function FD(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1);return i.useEffect(()=>{const d=e??"default";let u=!1;async function m(){const h=Jp.get(d);if(h&&Date.now()<h.expiresAt){if(u)return;s(h.views),r(!1);return}c.current||r(!0),l(null);try{const f=await XN(e);if(u)return;Jp.set(d,{views:f,expiresAt:Date.now()+zD}),s(f)}catch(f){if(u)return;l(f instanceof Error?f.message:"Failed to fetch plugin dashboard views")}finally{u||(r(!1),c.current=!0)}}return m(),()=>{u=!0}},[e]),i.useMemo(()=>({views:n,loading:a,error:o}),[n,a,o])}function UD({taskView:e,context:n}){const s=S1(e);if(!s)return null;const a=C1(s.pluginId,s.viewId);return a?t.jsx(a,{context:n}):t.jsx(t.Fragment,{children:E1({pluginId:s.pluginId,viewId:s.viewId})})}function BD(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(_=>{n(_),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(_=>{h(),n(_),a("project"),d(`Project ${_.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),j=i.useCallback(async _=>{try{await Aj(_.id),d(`Project ${_.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${_.name}`,"error")}},[d,o]),C=i.useCallback(async _=>{try{await Pj(_.id),d(`Project ${_.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${_.name}`,"error")}},[d,o]),A=i.useCallback(async _=>{try{await vf(_.id),d(`Project ${_.name} removed`,"success"),r?.id===_.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${_.name}`,"error")}},[r,s,a,d,o]),N=i.useCallback(async _=>{try{await l(_)}catch{d("Failed to update favorites","error")}},[l,d]),S=i.useCallback(async _=>{try{await c(_)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:j,handleResumeProject:C,handleRemoveProject:A,handleToggleFavorite:N,handleToggleModelFavorite:S}}function HD(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function qD(e){return Tl("/health",{nodeId:e})}async function VD(e){return Tl("/projects",{nodeId:e})}async function WD(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Tl(`/tasks?${a.toString()}`,{nodeId:e})}async function KD(e,n){return Tl(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function d3(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function u3(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function m3(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function h3(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function GD(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),x=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[qD(e),VD(e)];s&&(y.push(WD(e,s,a)),y.push(KD(e,s)));const j=await Promise.allSettled(y);if(b.signal.aborted)return;const C=j[0],A=j[1];if(C.status==="rejected"){p(`Failed to fetch node health: ${C.reason}`),h(!1);return}if(u(C.value),A.status==="rejected"){p(`Failed to fetch projects: ${A.reason}`),h(!1);return}if(o(A.value),s&&j[2]){const N=j[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const v=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function JD(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return fi(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:a}}const YD="fusion-dashboard-current-node",zb=i.createContext(null);function QD({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let m=!1;async function h(){try{const f=await pa();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(YD);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await Pn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,Pn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Pn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Pn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(zb.Provider,{value:u,children:e})}function XD(){const e=i.useContext(zb);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function ZD({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(Gy(l),window.location.reload())},[n]),o=i.useCallback(()=>{Jy(),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:a,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 eL=200,tL=i.lazy(()=>An(()=>import("./AgentsView-sbBkb7Wd.js"),__vite__mapDeps([19,1,0,2,3,20,11,4,5,21])).then(e=>({default:e.AgentsView}))),nL=i.lazy(()=>An(()=>import("./DocumentsView-BHpDsIIt.js"),__vite__mapDeps([22,1,4,5,23])).then(e=>({default:e.DocumentsView}))),sL=i.lazy(()=>An(()=>import("./InsightsView-Bxu0TJkt.js"),__vite__mapDeps([24,1,17,4,5,25])).then(e=>({default:e.InsightsView}))),iL=i.lazy(()=>An(()=>import("./ResearchView-Dsa6Gykl.js"),__vite__mapDeps([26,1,4,5,27])).then(e=>({default:e.ResearchView}))),aL=i.lazy(()=>An(()=>import("./NodesView-CO9_4hCr.js"),__vite__mapDeps([28,1,20,4,5,29])).then(e=>({default:e.NodesView}))),rL=i.lazy(()=>An(()=>import("./ChatView-BR5cvK_B.js"),__vite__mapDeps([30,1,4,5])).then(e=>({default:e.ChatView}))),oL=i.lazy(()=>An(()=>import("./RoadmapsView-jHTOK0RQ.js"),__vite__mapDeps([31,1,4,5,32])).then(e=>({default:e.RoadmapsView}))),lL=i.lazy(()=>An(()=>import("./SkillsView-MHweJTz4.js"),__vite__mapDeps([33,1,4,5,34])).then(e=>({default:e.SkillsView}))),cL=i.lazy(()=>An(()=>import("./MemoryView-CmnzZorw.js"),__vite__mapDeps([35,1,15,16,4,5,36])).then(e=>({default:e.MemoryView}))),dL=i.lazy(()=>An(()=>import("./DevServerView-GFFVXHVP.js"),__vite__mapDeps([37,1,4,5,38])).then(e=>({default:e.DevServerView})));i.lazy(()=>An(()=>Promise.resolve().then(()=>hb),void 0).then(e=>({default:e.TodoView})));function uL(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{An(()=>import("./AgentsView-sbBkb7Wd.js"),__vite__mapDeps([19,1,0,2,3,20,11,4,5,21])),An(()=>import("./DocumentsView-BHpDsIIt.js"),__vite__mapDeps([22,1,4,5,23])),An(()=>import("./InsightsView-Bxu0TJkt.js"),__vite__mapDeps([24,1,17,4,5,25])),An(()=>import("./ResearchView-Dsa6Gykl.js"),__vite__mapDeps([26,1,4,5,27])),An(()=>import("./NodesView-CO9_4hCr.js"),__vite__mapDeps([28,1,20,4,5,29])),An(()=>import("./ChatView-BR5cvK_B.js"),__vite__mapDeps([30,1,4,5])),An(()=>import("./RoadmapsView-jHTOK0RQ.js"),__vite__mapDeps([31,1,4,5,32])),An(()=>import("./SkillsView-MHweJTz4.js"),__vite__mapDeps([33,1,4,5,34])),An(()=>import("./MemoryView-CmnzZorw.js"),__vite__mapDeps([35,1,15,16,4,5,36])),An(()=>import("./DevServerView-GFFVXHVP.js"),__vite__mapDeps([37,1,4,5,38])),An(()=>Promise.resolve().then(()=>hb),void 0)})}const sd="kb-setup-warning-dismissed";function mL(){const{toasts:e,addToast:n,removeToast:s}=vD(),a=typeof window<"u"&&!!window.electronAPI;i.useEffect(()=>{uL()},[]);const{projects:r,loading:o,error:l,refresh:c}=pD(),{nodes:d}=$l(),{currentNode:u,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=XD(),{currentProject:g,setCurrentProject:x,clearCurrentProject:v,loading:b}=bD(r,{nodeId:m}),{hasAiProvider:y,hasGithub:j,loading:C,hasWarnings:A}=wb(g?.id),{updateAvailable:N,latestVersion:S,currentVersion:_,dismissed:T,dismiss:M}=RD();i.useEffect(()=>{if(m&&!u&&d.length>0){const ct=d.find(en=>en.id===m);if(ct){f(ct);return}}m&&d.length>0&&(d.some(en=>en.id===m)||p())},[m,u,d,f,p]);const[E,O]=i.useState(""),B=GD(m,{projectId:g?.id,searchQuery:E||void 0});JD(m);const R=h&&B.projects.length>0?B.projects:r,{themeMode:P,colorTheme:F,dashboardFontScalePct:q,setThemeMode:ee,setColorTheme:U,setDashboardFontScalePct:k}=CD(),{sessions:I,generating:$,needsInput:w,planningSessions:H,dismissSession:J}=rD(g?.id),fe=I.filter(ct=>ct.status==="awaiting_input"||ct.status==="error"),de=cD(),D=ED({projectId:g?.id,planningSessions:H}),z=Di()==="mobile",{pushNav:Z,replaceCurrent:oe}=OD({enabled:z}),{viewMode:Y,setViewMode:ae,taskView:ce,handleChangeTaskView:te}=LD({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:g,projectsLength:r.length,setupWizardOpen:D.setupWizardOpen,openSetupWizard:D.openSetupWizard,themeMode:P,setThemeMode:ee}),{views:Re}=FD(g?.id),be=i.useCallback(ct=>{ct==="missions"&&(_t(void 0),Lt(void 0),cn(void 0));const en=ce;te(ct),en!==ct&&Z({type:"view",revert:()=>te(en)})},[te,ce,Z]),ke=ce==="board"||ce==="list",{tasks:Ue,createTask:Ge,moveTask:qe,pauseTask:Ae,deleteTask:Ee,mergeTask:ie,retryTask:se,resetTask:xe,updateTask:ne,duplicateTask:Fe,archiveTask:Qe,unarchiveTask:ge,archiveAllDone:ze,loadArchivedTasks:tt,ingestCreatedTasks:pt,lastFetchTimeMs:ve}=uD({...g?{projectId:g.id}:{},searchQuery:E||void 0,sseEnabled:ke}),[le,Te]=i.useState(!1),[pe,$e]=i.useState(0),st=i.useRef(performance.now()),at=i.useRef(!1),rt=i.useRef(!1),Oe=i.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);i.useEffect(()=>{if(!o&&!at.current){at.current=!0;const ct=`projects loaded at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${ct}`),Tr("[App]",ct)}if(!b&&!rt.current){rt.current=!0;const ct=`current-project resolved at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${ct}`),Tr("[App]",ct)}},[o,b]),i.useEffect(()=>{if(le||o||b)return;const ct=performance.now(),en=window.setTimeout(()=>{const Qs=`dashboard ready at ${Math.round(performance.now()-st.current)}ms from mount (settle delay=${Math.round(performance.now()-ct)}ms)`;console.log(`[App] ${Qs}`),Tr("[App]",Qs),Te(!0)},eL);return()=>{window.clearTimeout(en)}},[le,o,b]);const{keyboardOpen:Be}=Hl({enabled:z}),et=z&&Be&&!D.anyModalOpen;Ci(et);const[jt,De]=i.useState(0),vt=i.useCallback(()=>{Nf(g?.id).then(ct=>{De(ct.unreadCount)}).catch(ct=>{console.warn("[App] Failed to fetch mailbox unread count:",ct)})},[g?.id]);i.useEffect(()=>{vt();const ct=new URLSearchParams;g?.id&&ct.set("projectId",g.id);const en=ct.size>0?`?${ct.toString()}`:"";return fi(`/api/events${en}`,{events:{"message:sent":vt,"message:received":vt,"message:read":vt,"message:deleted":vt}})},[g?.id,vt]);const[Et,bt]=i.useState(!1),[zt,qt]=i.useState(!1),[It,_t]=i.useState(void 0),[Xt,Lt]=i.useState(void 0),[Ut,cn]=i.useState(void 0),[Jt,Vt]=i.useState(!1),[Kt,rn]=i.useState(!1),[fn,on]=i.useState(()=>as(sd,g?.id)==="true");i.useEffect(()=>{on(as(sd,g?.id)==="true")},[g?.id]),i.useEffect(()=>{const ct=()=>{rn(!0)};return window.addEventListener(fd,ct),()=>{window.removeEventListener(fd,ct)}},[]);const gn=i.useCallback(()=>{xs(sd,"true",g?.id),on(!0)},[g?.id]),{maxConcurrent:je,autoMerge:Le,globalPaused:re,enginePaused:Pe,taskStuckTimeoutMs:Se,showQuickChatFAB:X,prAuthAvailable:Ie,settingsLoaded:he,experimentalFeatures:Ne,insightsEnabled:Je,roadmapEnabled:kt,memoryEnabled:Yt,devServerEnabled:$t,todosEnabled:Tt,toggleAutoMerge:Bt,toggleGlobalPause:jn,toggleEnginePause:Dn,refresh:hn}=MD(g?.id),Ht=Ne.skillsView===!0,yn=Ne.nodesView===!0,pn=Ne.researchView===!0,es=Ne.agentOnboarding===!0,ye=!0,ut=i.useCallback(()=>{D.closeSettings(),$e(ct=>ct+1),hn()},[D,hn]);i.useEffect(()=>{he&&(ce==="skills"&&!Ht&&te("board"),ce==="insights"&&!Je&&te("board"),ce==="roadmaps"&&!kt&&te("board"),ce==="memory"&&!Yt&&te("board"),(ce==="devserver"||ce==="dev-server")&&!$t&&te("board"),ce==="research"&&!pn&&te("board"))},[ce,he,Ht,Je,kt,te,ye,Yt,$t,pn]),i.useEffect(()=>{Et&&!yn&&bt(!1)},[Et,yn]);const{availableModels:Qt,favoriteProviders:Cn,favoriteModels:ue,toggleFavoriteProvider:dt,toggleFavoriteModel:wt}=AD();PD({projectId:g?.id,setupWizardOpen:D.setupWizardOpen,openModelOnboarding:D.openModelOnboarding,openSettings:D.openSettings});const{handleSelectProject:gt,handleViewAllProjects:ot,handleOpenSettings:yt,handleAddProject:Ft,handleSetupComplete:Zt,handleModelOnboardingComplete:Ln,handlePauseProject:Wt,handleResumeProject:Mt,handleRemoveProject:En,handleToggleFavorite:Xn,handleToggleModelFavorite:ts}=BD({setCurrentProject:x,clearCurrentProject:v,setViewMode:ae,currentProject:g,refreshProjects:c,toggleFavoriteProvider:dt,toggleFavoriteModel:wt,addToast:n,openSettings:D.openSettings,openSetupWizard:D.openSetupWizard,closeSetupWizard:D.closeSetupWizard,closeModelOnboarding:D.closeModelOnboarding}),{handleDetailClose:Ps}=_D({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:x,addToast:n,openTaskDetail:D.openDetailTask,closeTaskDetail:D.closeDetailTask}),ws=i.useCallback(async({insightId:ct,title:en,description:Qs})=>{await Ge({title:en,description:Qs,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:ct}}})},[Ge]),{handleBoardQuickCreate:Bn,handleModalCreate:rs,handlePlanningTaskCreated:V,handlePlanningTasksCreated:Ve,handleSubtaskTasksCreated:Ye,handleGitHubImport:mt}=HD({createTask:Ge,ingestCreatedTasks:pt,onPlanningTaskCreated:D.onPlanningTaskCreated,onPlanningTasksCreated:D.onPlanningTasksCreated,onSubtaskTasksCreated:D.onSubtaskTasksCreated,addToast:n}),Ct=i.useCallback((ct,en)=>{en==="changes"?D.openDetailWithChangesTab(ct):D.openDetailTask(ct,en),Z({type:"modal",close:D.closeDetailTask})},[D,Z]),Rt=i.useCallback(async ct=>{try{const en=await Oa(ct,g?.id);D.openDetailTask(en,"logs"),Z({type:"modal",close:D.closeDetailTask})}catch(en){n(`Failed to open task logs: ${en.message}`,"error")}},[D,g?.id,n,Z]),[dn,Dt]=i.useState([]);i.useEffect(()=>{let ct=!1;return so(g?.id).then(en=>{ct||Dt(en)}).catch(()=>{ct||Dt([])}),()=>{ct=!0}},[g?.id]);const ks=i.useMemo(()=>new Map(dn.map(ct=>[ct.id,ct.name])),[dn]),Zn=i.useCallback(()=>{yn&&bt(ct=>!ct)},[yn]),me=i.useCallback(()=>{yn&&(Et?bt(!1):(bt(!0),Z({type:"view",revert:()=>bt(!1)})))},[yn,Et,Z]),He=i.useCallback((ct,en,Qs)=>{D.openDetailTask(ct,en,Qs),Z({type:"modal",close:D.closeDetailTask})},[D,Z]),lt=i.useCallback(ct=>{D.openSettings(ct),Z({type:"modal",close:ut})},[D,Z,ut]),G=i.useCallback(()=>{D.openNewTask(),Z({type:"modal",close:D.closeNewTask})},[D,Z]),we=i.useCallback(()=>{D.openPlanning(),Z({type:"modal",close:D.closePlanning})},[D,Z]),it=i.useCallback(ct=>{D.openPlanningWithInitialPlan(ct),Z({type:"modal",close:D.closePlanning})},[D,Z]),St=i.useCallback(()=>{D.resumePlanning(),Z({type:"modal",close:D.closePlanning})},[D,Z]),Nt=i.useCallback(ct=>{D.openSubtaskBreakdown(ct),Z({type:"modal",close:D.closeSubtask})},[D,Z]),Mn=i.useCallback(()=>{D.openGitHubImport(),Z({type:"modal",close:D.closeGitHubImport})},[D,Z]),nn=i.useCallback(()=>{D.terminalOpen?D.toggleTerminal():(D.toggleTerminal(),Z({type:"modal",close:D.closeTerminal}))},[D,Z]),un=i.useCallback(()=>{D.openFiles(),Z({type:"modal",close:D.closeFiles})},[D,Z]),sn=i.useCallback(()=>{D.openTodos(),Z({type:"modal",close:D.closeTodos})},[D,Z]),Hn=i.useCallback(()=>{D.openActivityLog(),Z({type:"modal",close:D.closeActivityLog})},[D,Z]),qn=i.useCallback(()=>{D.openGitManager(),Z({type:"modal",close:D.closeGitManager})},[D,Z]),ls=i.useCallback(()=>{D.openSystemStats(),Z({type:"modal",close:D.closeSystemStats})},[D,Z]),Rn=i.useCallback(()=>{D.openSchedules(),Z({type:"modal",close:D.closeSchedules})},[D,Z]),On=i.useCallback(()=>{D.openScripts(),Z({type:"modal",close:D.closeScripts})},[D,Z]),_n=i.useCallback(()=>{D.openWorkflowSteps(),Z({type:"modal",close:D.closeWorkflowSteps})},[D,Z]),cs=i.useCallback(ct=>{D.openUsage(ct),Z({type:"modal",close:D.closeUsage})},[D,Z]),Wn=i.useCallback(async(ct,en)=>{await D.runScript(ct,en),oe({type:"modal",close:D.closeTerminal})},[D,oe]),Vn=i.useCallback(()=>{D.closeSettings(),D.openModelOnboarding(),oe({type:"modal",close:D.closeModelOnboarding})},[D,oe]),ms=i.useCallback(()=>{D.setFileWorkspace("project"),D.openFiles()},[D]),Kn=i.useCallback(async()=>{qt(!0);try{await c()}finally{qt(!1)}},[c]),hs=i.useCallback(ct=>{Lt(ct),_t(void 0),te("missions")},[te]),Gn=i.useCallback(ct=>{ct.type==="planning"?D.openPlanningWithSession(ct.id):ct.type==="subtask"?D.openSubtaskWithSession(ct.id):ct.type==="mission_interview"?(Lt(void 0),_t(ct.id),cn(void 0),te("missions")):(ct.type==="milestone_interview"||ct.type==="slice_interview")&&(_t(void 0),Lt(void 0),cn(ct.id),te("missions"))},[te,D]),Rs=i.useCallback(()=>{},[]),Ts=i.useCallback(()=>{},[]),zi=!o&&!b&&r.length===0&&!g&&!!l,Js=()=>zi?t.jsx(h$,{errorMessage:l??"Failed to fetch projects",isRetrying:zt,onRetry:Kn}):Et?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(aL,{addToast:n,onClose:()=>bt(!1)})})})}):Y==="overview"?t.jsx(Ns,{children:t.jsx(iR,{projects:r,loading:o,onSelectProject:gt,onAddProject:Ft,onPauseProject:Wt,onResumeProject:Mt,onRemoveProject:En,nodes:d})}):ce.startsWith("plugin:")?t.jsx(Ns,{children:t.jsx(UD,{taskView:ce,context:{projectId:g?.id,tasks:h&&B.tasks.length>0?B.tasks:Ue,workflowSteps:dn,openTaskDetail:z?(ct,en)=>He(ct,en):(ct,en)=>D.openDetailTask(ct,en),renderTaskCard:ct=>t.jsx(Vr,{task:ct,projectId:g?.id,onOpenDetail:z?en=>He(en):en=>D.openDetailTask(en),addToast:n,workflowStepNameLookup:ks})}})}):ce==="skills"?!he||!Ht?null:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(lL,{addToast:n,projectId:g?.id,onClose:()=>te("board")})})}):ce==="chat"?t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(rL,{addToast:n,projectId:g?.id})})}):ce==="mailbox"?t.jsx(Ns,{children:t.jsx(BR,{projectId:g?.id,addToast:n,onUnreadCountChange:De})}):ce==="roadmaps"?!he||!kt?null:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(oL,{addToast:n,projectId:g?.id})})}):ce==="missions"?t.jsx(Ns,{children:t.jsx(OR,{isInline:!0,isOpen:!0,onClose:()=>{Lt(void 0),_t(void 0),cn(void 0),te("board")},addToast:n,projectId:g?.id,onSelectTask:ct=>{const en=Ue.find(Qs=>Qs.id===ct);en&&(z?He:D.openDetailTask)(en)},availableTasks:Ue.map(ct=>({id:ct.id,title:ct.title})),resumeSessionId:It,targetMissionId:Xt,milestoneSliceResumeSessionId:Ut,onMilestoneSliceResumeFetchError:()=>cn(void 0)})}):ce==="agents"&&ye?t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(tL,{addToast:n,projectId:g?.id,onOpenTaskLogs:Rt,agentOnboardingEnabled:es})})}):ce==="documents"?t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(nL,{projectId:g?.id,addToast:n,onOpenDetail:z?He:D.openDetailTask})})}):ce==="insights"?!he||!Je?null:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(sL,{projectId:g?.id,addToast:n,onClose:()=>te("board"),onCreateTask:ws})})}):ce==="research"?!he||!pn?null:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(iL,{projectId:g?.id,addToast:n,onOpenSettings:ct=>D.openSettings(ct),readinessVersion:pe})})}):ce==="memory"?!he||!Yt?null:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(cL,{addToast:n,projectId:g?.id})})}):ce==="devserver"||ce==="dev-server"?!he||!$t?null:t.jsx(Ns,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(dL,{addToast:n,projectId:g?.id})})}):ce==="board"?t.jsx(Ns,{children:t.jsx(o0,{tasks:h&&B.tasks.length>0?B.tasks:Ue,projectId:g?.id,maxConcurrent:je,onMoveTask:qe,onPauseTask:Ae,onOpenDetail:z?He:D.openDetailTask,addToast:n,onQuickCreate:Bn,onNewTask:z?G:D.openNewTask,onPlanningMode:z?it:D.openPlanningWithInitialPlan,onSubtaskBreakdown:z?Nt:D.openSubtaskBreakdown,autoMerge:Le,onToggleAutoMerge:Bt,globalPaused:re,onUpdateTask:ne,onRetryTask:se,onArchiveTask:Qe,onUnarchiveTask:ge,onDeleteTask:Ee,onArchiveAllDone:ze,onLoadArchivedTasks:tt,searchQuery:E,availableModels:Qt,onOpenDetailWithTab:Ct,favoriteProviders:Cn,favoriteModels:ue,onToggleFavorite:Xn,onToggleModelFavorite:ts,taskStuckTimeoutMs:Se,onOpenMission:hs,lastFetchTimeMs:ve})}):t.jsx(Ns,{children:t.jsx(GP,{tasks:h&&B.tasks.length>0?B.tasks:Ue,projectId:g?.id,onMoveTask:qe,onRetryTask:se,onDeleteTask:Ee,onMergeTask:ie,onResetTask:xe,onDuplicateTask:Fe,onOpenDetail:z?(ct,en)=>He(ct,void 0,en):(ct,en)=>D.openDetailTask(ct,void 0,en),addToast:n,globalPaused:re,onNewTask:z?G:D.openNewTask,onQuickCreate:Bn,onPlanningMode:z?it:D.openPlanningWithInitialPlan,onSubtaskBreakdown:z?Nt:D.openSubtaskBreakdown,availableModels:Qt,favoriteProviders:Cn,favoriteModels:ue,onToggleFavorite:Xn,onToggleModelFavorite:ts,taskStuckTimeoutMs:Se,searchQuery:E,lastFetchTimeMs:ve,prAuthAvailable:Ie})});if(!le)return t.jsxs(t.Fragment,{children:[t.jsx(f$,{stage:Oe}),t.jsx(Eb,{toasts:e,onRemove:s})]});const ai=!D.modelOnboardingOpen&&L4(),Ys=!D.modelOnboardingOpen&&!ai&&Ga()&&!jb();return t.jsxs(t.Fragment,{children:[t.jsx(P1,{isElectron:a,onOpenSettings:z?lt:yt,onOpenGitHubImport:z?Mn:D.openGitHubImport,onOpenPlanning:z?we:D.openPlanning,onResumePlanning:z?St:D.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:z?cs:D.openUsage,onOpenActivityLog:z?Hn:D.openActivityLog,onOpenSystemStats:z?ls:D.openSystemStats,onOpenMailbox:()=>be("mailbox"),mailboxUnreadCount:jt,onOpenSchedules:z?Rn:D.openSchedules,onOpenGitManager:z?qn:D.openGitManager,onOpenNodes:z?me:Zn,showNodesButton:yn,onOpenWorkflowSteps:z?_n:D.openWorkflowSteps,onOpenScripts:z?On:D.openScripts,onRunScript:z?Wn:D.runScript,onToggleTerminal:z?nn:D.toggleTerminal,onOpenFiles:z?un:D.openFiles,filesOpen:D.filesOpen,onOpenTodos:z?sn:D.openTodos,todosOpen:D.todosOpen,todosEnabled:Tt,globalPaused:re,enginePaused:Pe,onToggleGlobalPause:jn,onToggleEnginePause:Dn,view:ce,onChangeView:Y==="project"&&g?be:void 0,showSkillsTab:Ht,showAgentsTab:ye,searchQuery:E,onSearchChange:O,projects:R,currentProject:g,onSelectProject:gt,onViewAllProjects:ot,projectId:g?.id,mobileNavEnabled:z,availableNodes:d,currentNode:u,onSelectNode:ct=>{ct===null?p():f(ct)},isRemote:h,experimentalFeatures:{insights:Je,roadmap:kt,memoryView:Yt,devServer:$t,devServerView:$t,researchView:pn},pluginDashboardViews:Re}),Y==="project"&&g&&!Et&&ce!=="missions"&&!D.isPlanningOpen&&!de&&t.jsx(A$,{sessions:fe,onResumeSession:Gn,onDismissSession:Rs,onDismissAll:Ts}),Y==="project"&&g&&t.jsx(T$,{onOpenSettings:()=>D.openSettings("general")}),Y==="project"&&g&&ai&&t.jsx($$,{onResume:D.openModelOnboarding}),Y==="project"&&g&&Ys&&t.jsx(D$,{onOpenModelOnboarding:D.openModelOnboarding,onOpenSettings:ct=>D.openSettings(ct)}),Y==="project"&&g&&N&&S&&_&&!T&&t.jsx(I$,{latestVersion:S,currentVersion:_,onDismiss:M}),Y==="project"&&g&&!C&&A&&!fn&&t.jsx(kb,{hasAiProvider:y,hasGithub:j,onDismiss:gn}),t.jsx("div",{className:`project-content${Y==="project"&&g?" project-content--with-footer":""}${z&&!et?" project-content--with-mobile-nav":""}`,children:Js()}),Y==="project"&&g&&!Et&&t.jsx(S$,{tasks:h&&B.tasks.length>0?B.tasks:Ue,projectId:g.id,taskStuckTimeoutMs:Se,backgroundSessions:I,backgroundGenerating:$,backgroundNeedsInput:w,onOpenBackgroundSession:Gn,onDismissBackgroundSession:J,lastFetchTimeMs:ve,currentProjectPath:g.path,onOpenProjectDirectory:ms}),t.jsx(O$,{view:ce,onChangeView:Y==="project"&&g?be:()=>{},footerVisible:Y==="project"&&!!g,modalOpen:D.anyModalOpen,keyboardOpen:et,onOpenSettings:z?lt:yt,onOpenActivityLog:z?Hn:D.openActivityLog,onOpenSystemStats:z?ls:D.openSystemStats,onOpenMailbox:()=>be("mailbox"),onOpenNodes:z?me:Zn,mailboxUnreadCount:jt,onOpenGitManager:z?qn:D.openGitManager,onOpenWorkflowSteps:z?_n:D.openWorkflowSteps,onOpenSchedules:z?Rn:D.openSchedules,onOpenScripts:z?On:D.openScripts,onToggleTerminal:z?nn:D.toggleTerminal,onOpenFiles:z?un:D.openFiles,onOpenTodos:z?sn:D.openTodos,todosOpen:D.todosOpen,onOpenGitHubImport:z?Mn:D.openGitHubImport,onOpenPlanning:z?we:D.openPlanning,onResumePlanning:z?St:D.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:z?()=>cs(null):()=>D.openUsage(null),onViewAllProjects:ot,onRunScript:z?Wn:D.runScript,projectId:g?.id,showSkillsTab:Ht,experimentalFeatures:{insights:Je,roadmap:kt,memoryView:Yt,devServer:$t,devServerView:$t,todoView:Tt,researchView:pn,nodesView:yn},pluginDashboardViews:Re}),Y==="project"&&g&&ce!=="chat"&&ce!=="mailbox"&&ce!=="insights"&&ce!=="devserver"&&ce!=="dev-server"&&!ce.startsWith("plugin:")&&t.jsx(aD,{projectId:g.id,addToast:n,showFAB:X,open:Jt,onOpenChange:Vt,favoriteProviders:Cn,favoriteModels:ue,onToggleFavorite:Xn,onToggleModelFavorite:ts}),t.jsx(m$,{projectId:g?.id,tasks:Ue,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:D,projectActions:{handleAddProject:Ft,handleSetupComplete:Zt,handleModelOnboardingComplete:Ln},taskHandlers:{handleModalCreate:rs,handlePlanningTaskCreated:V,handlePlanningTasksCreated:Ve,handleSubtaskTasksCreated:Ye,handleGitHubImport:mt},taskOperations:{moveTask:qe,deleteTask:Ee,mergeTask:ie,retryTask:se,resetTask:xe,duplicateTask:Fe},deepLink:{handleDetailClose:Ps},settings:{prAuthAvailable:Ie,themeMode:P,colorTheme:F,dashboardFontScalePct:q,setThemeMode:ee,setColorTheme:U,setDashboardFontScalePct:k},onSettingsClose:ut,onReopenOnboarding:z?Vn:()=>{D.closeSettings(),D.openModelOnboarding()}}),t.jsx(ZD,{open:Kt})]})}function hL(){return t.jsx(xD,{children:t.jsx(QD,{children:t.jsx(V1,{children:t.jsx(mL,{})})})})}function Fb(e){e.postMessage({type:"SKIP_WAITING"})}function Yp(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&Fb(e)})}function pL(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,Wd("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&Fb(n.waiting),n.installing&&Yp(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&Yp(s)})}).catch(n=>{console.log("SW registration failed:",n)})}nw();Uy();Ub.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(By,{children:t.jsx(hL,{})})}));pL();export{h4 as $,qs as A,Tn as B,Un as C,xs as D,Rl as E,Vi as F,Nl as G,xo as H,Me as I,B1 as J,UO as K,ft as L,dd as M,Kv as N,Nn as O,Qn as P,tl as Q,os as R,Pi as S,Al as T,l3 as U,Yc as V,Yn as W,tn as X,ui as Y,is as Z,Sn as _,mn as a,K$ as a$,kl as a0,v4 as a1,xj as a2,m4 as a3,vj as a4,OO as a5,yj as a6,An as a7,ZL as a8,eO as a9,Jz as aA,aw as aB,Hr as aC,m3 as aD,d3 as aE,u3 as aF,h3 as aG,Ur as aH,fy as aI,Rr as aJ,Bs as aK,ry as aL,Ix as aM,js as aN,cf as aO,XO as aP,ZO as aQ,$l as aR,pD as aS,Xu as aT,ec as aU,Ua as aV,t1 as aW,Uz as aX,Bz as aY,s1 as aZ,i1 as a_,Sk as aa,qd as ab,Ja as ac,ha as ad,ji as ae,Ni as af,hi as ag,Hz as ah,Wz as ai,Vz as aj,qz as ak,Kz as al,vs as am,zs as an,Cy as ao,pi as ap,zx as aq,Jr as ar,Ii as as,Gz as at,Yz as au,t3 as av,e3 as aw,Zz as ax,Xz as ay,Qz as az,In as b,eo as b$,Hl as b0,ZN as b1,of as b2,z$ as b3,V$ as b4,sa as b5,sf as b6,Mu as b7,Ri as b8,sz as b9,HL as bA,qL as bB,FL as bC,LL as bD,OL as bE,zL as bF,DL as bG,$L as bH,AL as bI,UL as bJ,YT as bK,yO as bL,vO as bM,CO as bN,xO as bO,wO as bP,kO as bQ,jO as bR,NO as bS,Jk as bT,SO as bU,Gd as bV,Wk as bW,Kk as bX,Gk as bY,Vk as bZ,bO as b_,az as ba,iz as bb,rz as bc,oz as bd,lz as be,cz as bf,dz as bg,uz as bh,mz as bi,hz as bj,pz as bk,fz as bl,gz as bm,xz as bn,vz as bo,bz as bp,ns as bq,Cl as br,ra as bs,zz as bt,Oz as bu,Fz as bv,TL as bw,RL as bx,PL as by,IL as bz,Ze as c,Hi as c$,_l as c0,hy as c1,Da as c2,La as c3,Cj as c4,Gy as c5,Jy as c6,Tw as c7,Iw as c8,Iz as c9,GO as cA,vL as cB,wL as cC,_L as cD,ML as cE,Xw as cF,Uw as cG,ki as cH,Bw as cI,qw as cJ,Hw as cK,Vw as cL,Ww as cM,GL as cN,JO as cO,YO as cP,QO as cQ,Li as cR,s3 as cS,i3 as cT,nz as cU,kL as cV,ad as cW,fs as cX,GT as cY,w4 as cZ,j4 as c_,nO as ca,tO as cb,$z as cc,sO as cd,uO as ce,lO as cf,iO as cg,cO as ch,aO as ci,dO as cj,rO as ck,oO as cl,ix as cm,Ow as cn,mO as co,zw as cp,hO as cq,ni as cr,Si as cs,cD as ct,DT as cu,VL as cv,tz as cw,bL as cx,xL as cy,Mp as cz,KO as d,KL as d$,Qc as d0,C4 as d1,NL as d2,yL as d3,SL as d4,jL as d5,CL as d6,EL as d7,ca as d8,c3 as d9,HO as dA,BO as dB,nf as dC,TO as dD,RO as dE,u4 as dF,zO as dG,KA as dH,AO as dI,_O as dJ,Ck as dK,PO as dL,IO as dM,Mz as dN,MO as dO,_z as dP,iy as dQ,md as dR,Dz as dS,Rz as dT,Pz as dU,Tz as dV,Az as dW,ez as dX,n3 as dY,JL as dZ,WL as d_,O1 as da,Il as db,a3 as dc,Ch as dd,r3 as de,o3 as df,BL as dg,yz as dh,kz as di,Sz as dj,jz as dk,wz as dl,Nz as dm,Cz as dn,bd as dp,Iu as dq,$O as dr,LO as ds,cd as dt,Ks as du,bv as dv,Ez as dw,FO as dx,Xr as dy,DO as dz,VO as e,QL as e0,XL as e1,YL as e2,Oa as f,WO as g,Ds as h,fa as i,Pn as j,Lz as k,ys as l,bj as m,EO as n,ii as o,gO as p,pO as q,p4 as r,fi as s,fO as t,Ci as u,qO as v,Di as w,q$ as x,as as y,Gs as z};