@runfusion/fusion 0.16.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +3 -19
  2. package/dist/bin.js +3344 -1159
  3. package/dist/client/assets/{AgentDetailView-KQz9dg0n.js → AgentDetailView-DGqT1oDt.js} +2 -2
  4. package/dist/client/assets/AgentDetailView-yu8Xltqk.css +1 -0
  5. package/dist/client/assets/AgentsView-BmemrfrO.js +517 -0
  6. package/dist/client/assets/AgentsView-Bs03ptrd.css +1 -0
  7. package/dist/client/assets/ChatView-CZQUBFlV.js +1 -0
  8. package/dist/client/assets/DevServerView-C3Q0XqDA.js +1 -0
  9. package/dist/client/assets/{DirectoryPicker-CFj7FOgn.js → DirectoryPicker-BZWVA9ND.js} +1 -1
  10. package/dist/client/assets/DocumentsView-DO48ivSq.js +1 -0
  11. package/dist/client/assets/InsightsView-CAngTfMf.js +11 -0
  12. package/dist/client/assets/{MemoryView-DDbr1DaJ.js → MemoryView-B3rNcAOW.js} +1 -1
  13. package/dist/client/assets/NodesView-BnV1LWa8.js +14 -0
  14. package/dist/client/assets/{NodesView-BprfihLf.css → NodesView-DuAXX_0j.css} +1 -1
  15. package/dist/client/assets/{PiExtensionsManager-QgzWFBAT.js → PiExtensionsManager-C3_Lw4sa.js} +3 -3
  16. package/dist/client/assets/{PluginManager-KHiz9oLY.js → PluginManager-Vv3nzrJ1.js} +1 -1
  17. package/dist/client/assets/ResearchView-BzCcDAS4.css +1 -0
  18. package/dist/client/assets/ResearchView-Dfdsuc21.js +1 -0
  19. package/dist/client/assets/{RoadmapsView-BlbAZTdi.js → RoadmapsView-BiIpE-b8.js} +2 -2
  20. package/dist/client/assets/SettingsModal-BN00HYJ2.js +31 -0
  21. package/dist/client/assets/{SettingsModal-D5EUFR2z.js → SettingsModal-CK4w8Ztb.js} +1 -1
  22. package/dist/client/assets/{SettingsModal-D0QA2W5K.css → SettingsModal-Dq4a5KSX.css} +1 -1
  23. package/dist/client/assets/{SetupWizardModal-tTXAm1Wb.js → SetupWizardModal-Dw6N4UvY.js} +1 -1
  24. package/dist/client/assets/SkillsView-C1196wgA.js +1 -0
  25. package/dist/client/assets/{folder-open-DObdkm5J.js → folder-open-WVtgE4k3.js} +1 -1
  26. package/dist/client/assets/index-BIJgrHEn.css +1 -0
  27. package/dist/client/assets/index-Bv0TGzDH.js +682 -0
  28. package/dist/client/assets/{star-BkGA2L-k.js → star-MSImEC8V.js} +1 -1
  29. package/dist/client/assets/{upload-B0NF4J5P.js → upload-Dmvy3xXd.js} +1 -1
  30. package/dist/client/assets/{users-DgomiHTd.js → users-CncYvHNf.js} +1 -1
  31. package/dist/client/index.html +2 -2
  32. package/dist/client/version.json +1 -1
  33. package/dist/extension.js +2228 -715
  34. package/dist/pi-claude-cli/package.json +1 -1
  35. package/dist/pi-claude-cli/src/__tests__/process-manager.test.ts +11 -0
  36. package/dist/pi-claude-cli/src/__tests__/provider.test.ts +25 -0
  37. package/dist/plugins/fusion-plugin-dependency-graph/package.json +7 -5
  38. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.css +31 -0
  39. package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.tsx +156 -48
  40. package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraphView.test.tsx +261 -0
  41. package/package.json +1 -1
  42. package/skill/fusion/SKILL.md +5 -5
  43. package/skill/fusion/references/engine-tools.md +2 -2
  44. package/skill/fusion/references/extension-tools.md +3 -3
  45. package/skill/fusion/references/fusion-capabilities.md +1 -1
  46. package/skill/fusion/references/skill-patterns.md +1 -1
  47. package/skill/fusion/workflows/dashboard-cli.md +3 -3
  48. package/skill/fusion/workflows/task-management.md +1 -1
  49. package/dist/client/assets/AgentDetailView-BoEpPOjM.css +0 -1
  50. package/dist/client/assets/AgentsView-8Xo-c04o.js +0 -517
  51. package/dist/client/assets/AgentsView-V5GhlBYu.css +0 -1
  52. package/dist/client/assets/ChatView-CjgOh8x7.js +0 -1
  53. package/dist/client/assets/DevServerView-BOPrzi-j.js +0 -1
  54. package/dist/client/assets/DocumentsView-CcJNmH06.js +0 -1
  55. package/dist/client/assets/InsightsView-B0DKRIYV.js +0 -11
  56. package/dist/client/assets/NodesView-BqtHfXsl.js +0 -14
  57. package/dist/client/assets/ResearchView-CVxPC1vz.css +0 -1
  58. package/dist/client/assets/ResearchView-s3SrjNBm.js +0 -1
  59. package/dist/client/assets/SettingsModal-c9MG4sxl.js +0 -31
  60. package/dist/client/assets/SkillsView-CS4ONN3D.js +0 -1
  61. package/dist/client/assets/index-BRaIPmpp.js +0 -682
  62. package/dist/client/assets/index-DeED_ky2.css +0 -1
@@ -1,682 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-KQz9dg0n.js","assets/vendor-react-K0fH_qHe.js","assets/star-BkGA2L-k.js","assets/AgentDetailView-BoEpPOjM.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-tTXAm1Wb.js","assets/DirectoryPicker-CFj7FOgn.js","assets/folder-open-DObdkm5J.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-c9MG4sxl.js","assets/SettingsModal-D5EUFR2z.js","assets/SettingsModal-D0QA2W5K.css","assets/users-DgomiHTd.js","assets/SettingsModal-D_AFkDJa.css","assets/AgentsView-8Xo-c04o.js","assets/upload-B0NF4J5P.js","assets/AgentsView-V5GhlBYu.css","assets/DocumentsView-CcJNmH06.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-B0DKRIYV.js","assets/InsightsView-4KiUKzbz.css","assets/ResearchView-s3SrjNBm.js","assets/ResearchView-CVxPC1vz.css","assets/NodesView-BqtHfXsl.js","assets/NodesView-BprfihLf.css","assets/ChatView-CjgOh8x7.js","assets/RoadmapsView-BlbAZTdi.js","assets/RoadmapsView-DdGlfuu-.css","assets/SkillsView-CS4ONN3D.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-DDbr1DaJ.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-BOPrzi-j.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
2
- import{r as i,j as t,R as Vo,a as Ji,g as Fp,c as Pb}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 Up=(...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 Rb=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 Tb=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 mu=e=>{const n=Tb(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 Ul={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 Ib=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},$b=i.createContext({}),Db=()=>i.useContext($b),Lb=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=""}=Db()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Ul,width:n??u??Ul.width,height:n??u??Ul.height,stroke:e??f,strokeWidth:g,className:Up("lucide",p,r),...!o&&!Ib(c)&&{"aria-hidden":"true"},...c},[...l.map(([b,v])=>i.createElement(b,v)),...Array.isArray(o)?o:[o]])});/**
33
- * @license lucide-react v1.7.0 - ISC
34
- *
35
- * This source code is licensed under the ISC license.
36
- * See the LICENSE file in the root directory of this source tree.
37
- */const Ze=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Lb,{ref:o,iconNode:n,className:Up(`lucide-${Rb(mu(e))}`,`lucide-${e}`,a),...r}));return s.displayName=mu(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 zb=[["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"}]],Fs=Ze("activity",zb);/**
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 Ob=[["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"}]],Fb=Ze("archive-restore",Ob);/**
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 Ub=[["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"}]],Ur=Ze("archive",Ub);/**
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 Bb=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Br=Ze("arrow-down",Bb);/**
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 Hb=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ua=Ze("arrow-left",Hb);/**
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 qb=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],Hr=Ze("arrow-right",qb);/**
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 Vb=[["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"}]],Bp=Ze("arrow-up-down",Vb);/**
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 Wb=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Qi=Ze("arrow-up",Wb);/**
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 Kb=[["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"}]],Gb=Ze("book-open",Kb);/**
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 Jb=[["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"}]],Mn=Ze("bot",Jb);/**
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 Yb=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],Gc=Ze("box",Yb);/**
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 Qb=[["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"}]],Pr=Ze("brain",Qb);/**
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 Xb=[["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"}]],Hp=Ze("calendar",Xb);/**
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 Zb=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],ex=Ze("check-check",Zb);/**
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 tx=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Wn=Ze("check",tx);/**
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 nx=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],rn=Ze("chevron-down",nx);/**
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 sx=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],hl=Ze("chevron-left",sx);/**
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 ix=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],_n=Ze("chevron-right",ix);/**
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 ax=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ri=Ze("chevron-up",ax);/**
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 rx=[["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"}]],Ts=Ze("circle-alert",rx);/**
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 ox=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Tn=Ze("circle-check-big",ox);/**
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 lx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],pl=Ze("circle-dot",lx);/**
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 cx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],dx=Ze("circle-plus",cx);/**
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 ux=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]],Jc=Ze("circle-question-mark",ux);/**
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 mx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],hx=Ze("circle-stop",mx);/**
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 px=[["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"}]],qr=Ze("circle-x",px);/**
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 fx=[["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"}]],gx=Ze("clipboard-list",fx);/**
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 bx=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Mi=Ze("clock",bx);/**
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 xx=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],qp=Ze("code",xx);/**
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 vx=[["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"}]],yx=Ze("columns-3",vx);/**
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 wx=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],Zi=Ze("copy",wx);/**
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 kx=[["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"}]],jx=Ze("cpu",kx);/**
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 Nx=[["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"}]],Sx=Ze("download",Nx);/**
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 Cx=[["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"}]],Ex=Ze("ellipsis-vertical",Cx);/**
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 Mx=[["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"}]],Yc=Ze("ellipsis",Mx);/**
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 _x=[["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"}]],Ax=Ze("external-link",_x);/**
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 Px=[["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"}]],Id=Ze("eye-off",Px);/**
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 Rx=[["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"}]],Ba=Ze("eye",Rx);/**
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 Tx=[["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"}]],si=Ze("file-code",Tx);/**
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 Ix=[["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"}]],Qc=Ze("file-diff",Ix);/**
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 $x=[["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"}]],Dx=Ze("file-minus",$x);/**
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 Lx=[["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"}]],Vp=Ze("file-pen",Lx);/**
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 zx=[["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"}]],Ox=Ze("file-plus",zx);/**
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 Fx=[["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"}]],Ux=Ze("file-question-mark",Fx);/**
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 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 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],Li=Ze("file-text",Bx);/**
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 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:"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"}]],qx=Ze("file-type",Hx);/**
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 Vx=[["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"}]],Wp=Ze("file",Vx);/**
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 Wx=[["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"}]],Kx=Ze("flag",Wx);/**
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 Gx=[["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"}]],Xc=Ze("folder-git-2",Gx);/**
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 Jx=[["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"}]],hu=Ze("folder-root",Jx);/**
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 Yx=[["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"}]],as=Ze("folder",Yx);/**
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 Qx=[["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"}]],Wo=Ze("funnel",Qx);/**
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 Xx=[["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"}]],Hs=Ze("git-branch",Xx);/**
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 Zx=[["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"}]],Vr=Ze("git-commit-horizontal",Zx);/**
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 ev=[["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"}]],Kp=Ze("git-merge",ev);/**
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 tv=[["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"}]],Os=Ze("git-pull-request",tv);/**
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 nv=[["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"}]],fl=Ze("globe",nv);/**
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 sv=[["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"}]],gl=Ze("grid-3x3",sv);/**
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 iv=[["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"}]],bl=Ze("grip-vertical",iv);/**
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 av=[["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"}]],rv=Ze("hard-drive",av);/**
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 ov=[["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"}]],lv=Ze("heart",ov);/**
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 cv=[["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"}]],Rr=Ze("history",cv);/**
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 dv=[["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"}]],xr=Ze("inbox",dv);/**
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 uv=[["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"}]],Gp=Ze("key",uv);/**
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 mv=[["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"}]],hv=Ze("keyboard",mv);/**
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 pv=[["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"}]],ea=Ze("layers",pv);/**
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 fv=[["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"}]],zi=Ze("layout-grid",fv);/**
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 gv=[["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"}]],oi=Ze("lightbulb",gv);/**
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 bv=[["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"}]],Ea=Ze("link",bv);/**
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 xv=[["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"}]],Zc=Ze("list-checks",xv);/**
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 vv=[["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"}]],yv=Ze("list-plus",vv);/**
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 wv=[["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"}]],xl=Ze("list-tree",wv);/**
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 kv=[["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"}]],ed=Ze("list",kv);/**
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 jv=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],bt=Ze("loader-circle",jv);/**
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 Nv=[["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"}]],vl=Ze("lock",Nv);/**
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 Sv=[["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"}]],ta=Ze("mail",Sv);/**
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 Cv=[["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"}]],td=Ze("map",Cv);/**
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 Ev=[["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"}]],yl=Ze("maximize-2",Ev);/**
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 Mv=[["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"}]],_v=Ze("message-square-plus",Mv);/**
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 Av=[["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"}]],Ci=Ze("message-square",Av);/**
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 Pv=[["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"}]],Wr=Ze("minimize-2",Pv);/**
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 Rv=[["path",{d:"M5 12h14",key:"1ays0h"}]],Tv=Ze("minus",Rv);/**
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 Iv=[["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"}]],Ma=Ze("monitor",Iv);/**
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 $v=[["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"}]],Dv=Ze("move",$v);/**
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 Lv=[["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"}]],zv=Ze("network",Lv);/**
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 Ov=[["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"}]],nd=Ze("package",Ov);/**
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 Fv=[["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"}]],Jp=Ze("paperclip",Fv);/**
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 Uv=[["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"}]],ii=Ze("pause",Uv);/**
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 Bv=[["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"}]],vs=Ze("pencil",Bv);/**
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 Hv=[["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"}]],On=Ze("play",Hv);/**
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 qv=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],xn=Ze("plus",qv);/**
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 Vv=[["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"}]],Yp=Ze("radio",Vv);/**
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 Wv=[["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"}]],Qn=Ze("refresh-cw",Wv);/**
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 Kv=[["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"}]],pu=Ze("rocket",Kv);/**
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 Gv=[["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"}]],Jv=Ze("rotate-ccw",Gv);/**
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 Yv=[["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"}]],Qv=Ze("rotate-cw",Yv);/**
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 Xv=[["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"}]],Qp=Ze("save",Xv);/**
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 Zv=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Si=Ze("search",Zv);/**
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 ey=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],Yi=Ze("send",ey);/**
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 ty=[["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"}]],Tr=Ze("server",ty);/**
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 ny=[["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"}]],Sr=Ze("settings",ny);/**
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 sy=[["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"}]],iy=Ze("shield-alert",sy);/**
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 ay=[["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"}]],ry=Ze("shield",ay);/**
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 oy=[["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"}]],ly=Ze("skull",oy);/**
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 cy=[["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"}]],ms=Ze("sparkles",cy);/**
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 dy=[["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"}]],Ko=Ze("square-check-big",dy);/**
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 uy=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],zs=Ze("square",uy);/**
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 my=[["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"}]],ks=Ze("target",my);/**
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 hy=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Ei=Ze("terminal",hy);/**
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 py=[["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"}]],Go=Ze("text-wrap",py);/**
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 fy=[["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"}]],vn=Ze("trash-2",fy);/**
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 gy=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],by=Ze("trending-up",gy);/**
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 xy=[["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"}]],wl=Ze("triangle-alert",xy);/**
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 vy=[["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"}]],fu=Ze("unlink",vy);/**
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 yy=[["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"}]],ha=Ze("user",yy);/**
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 wy=[["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"}]],Xp=Ze("webhook",wy);/**
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 ky=[["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"}]],Jo=Ze("workflow",ky);/**
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 jy=[["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"}]],gu=Ze("wrench",jy);/**
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 Ny=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],Wt=Ze("x",Ny);/**
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 Sy=[["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"}]],Kn=Ze("zap",Sy),sd="fusion:version-reload",id="fusion:version-update";function Cy(){try{if(sessionStorage.getItem(id))return sessionStorage.removeItem(id),!0}catch{}return!1}function $d(e){if(sessionStorage.getItem(sd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(sd,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Ey(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 My(e){return Ey(e)?($d(`chunk load error: ${e?.message??e}`),!0):!1}async function _y(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}let Bl=!1;async function Hl(){if(!(Bl||document.visibilityState!=="visible")){Bl=!0;try{const e=await _y();if(e&&e!=="mopjupxc-dafa760f"){try{sessionStorage.setItem(id,"1")}catch{}$d(`build version changed: mopjupxc-dafa760f -> ${e}`)}}finally{Bl=!1}}}function Ay(){window.setTimeout(()=>sessionStorage.removeItem(sd),5e3),document.addEventListener("visibilitychange",()=>{Hl()}),window.addEventListener("focus",()=>{Hl()}),window.setTimeout(()=>void Hl(),2e3)}class kl 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),!My(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(wl,{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 ys({children:e,onError:n}){return t.jsx(kl,{level:"page",onError:n,children:e})}function Vi({children:e,onError:n}){return t.jsx(kl,{level:"modal",onError:n,children:e})}function Py({children:e,onError:n}){return t.jsx(kl,{level:"root",onError:n,children:e})}const Ry="modulepreload",Ty=function(e){return"/"+e},bu={},kn=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=Ty(u),u in bu)return;bu[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":Ry,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)})},Dd="fn.authToken",xu="token",Iy="fn_token";let Na,vu=!1,Yo=!1;const ad="fn:auth-token-recovery-required";function $y(){try{const e=window.localStorage.getItem(Dd);return e&&e.length>0?e:void 0}catch{return}}function Zp(e){try{window.localStorage.setItem(Dd,e)}catch{}}function Dy(){if(!(vu||typeof window>"u")){vu=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(xu);if(!n)return;Zp(n),e.searchParams.delete(xu);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function _a(){if(Na!==void 0)return Na;const e=Dy();if(e)return Na=e,e;const n=$y();if(n)return Na=n,n}function Ly(e){Na=e,Yo=!1,Zp(e)}function zy(){Na=void 0,Yo=!1;try{window.localStorage.removeItem(Dd)}catch{}}function yu(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Oy(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Fy(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Oy(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=yu(e.protocol)===yu(n.protocol);return s&&a&&r}function Uy(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 fi(e){const n=_a();if(!n||typeof window>"u")return e;const s=Uy(e);return!s||!Fy(s.parsed)?e:(s.parsed.searchParams.set(Iy,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function _i(e){const n=_a();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function By(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Hy(){typeof window>"u"||Yo||(Yo=!0,window.dispatchEvent(new CustomEvent(ad)))}async function qy(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();By(a)&&Hy()}catch{}}function Vy(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,_a();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=_a(),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=>(qy(d),d))}}class Wy extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Ky(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ns(e){return`/api${e}`}async function D(e,n={}){const s=Ns(e),a=_a(),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")||Ky(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 Wy(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function WD(){return D("/health")}function KD(){return D("/updates/check")}function Gy(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 D(`/tasks${l}`)}async function Aa(e,n){const a=Ns(q(`/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 Qo(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:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:k,priority:N,source:R}=e;return D(q("/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:b,thinkingLevel:v,summarize:x,reviewLevel:y,executionMode:k,priority:N,source:R})})}function ni(e,n,s){return D(q(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Jy(e,n,s,a,r,o,l,c,d){return D(q("/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 Yy(e,n,s,a){return D(q(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Qy(e,n,s){const a=new URLSearchParams,r=a.size>0?`?${a.toString()}`:"";return D(q(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Xy(e,n){return D(q(`/tasks/${e}/merge`,n),{method:"POST"})}function Zy(e,n){return D(q(`/tasks/${e}/retry`,n),{method:"POST"})}function ew(e,n){return D(q(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function tw(e,n){return D(q(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ef(e,n){return D(q(`/tasks/${e}/pause`,n),{method:"POST"})}function nw(e,n){return D(q(`/tasks/${e}/unpause`,n),{method:"POST"})}function sw(e,n){return D(q(`/tasks/${e}/archive`,n),{method:"POST"})}function iw(e,n){return D(q(`/tasks/${e}/unarchive`,n),{method:"POST"})}function aw(e){return D(q("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function rw(e,n){return D(q(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function ow(e,n){return D(q(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function lw(e){return D(q("/config",e))}function jl(e){return D(q("/settings",e))}function mo(e,n){return D(q("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function cw(e){return D(q("/update-check",e))}function GD(e){return D(q("/remote/settings",e))}function JD(e,n){return D(q("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function YD(e){return D(q("/remote/status",e))}function QD(e){return D(q("/remote/install-cloudflared",e),{method:"POST"})}function XD(e){return D(q("/remote/tunnel/start",e),{method:"POST"})}function ZD(e){return D(q("/remote/tunnel/stop",e),{method:"POST"})}function eL(e){return D(q("/remote/tunnel/kill-external",e),{method:"POST"})}function tL(e){return D(q("/remote/token/persistent/regenerate",e),{method:"POST"})}function nL(e,n){return D(q("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function tf(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 sL(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=tf(null,s,a);return D(q(`/remote/url${r}`,n))}function iL(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=tf(e,a,r);return D(q(`/remote/qr${o}`,s))}function aL(e){return D(q("/memory",e))}function rL(e,n){return D(q("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function oL(e){return D(q("/memory/files",e))}function lL(e,n){const s=`path=${encodeURIComponent(e)}`;return D(q(`/memory/file?${s}`,n))}function cL(e,n,s){return D(q("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function dL(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 D(q("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function uL(e){return D(q("/memory/dream",e),{method:"POST"})}function mL(e){return D(q("/memory/insights",e))}function hL(e,n){return D(q("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function pL(e){return D(q("/memory/extract",e),{method:"POST"})}function fL(e){return D(q("/memory/audit",e))}function gL(e){return D(q("/memory/stats",e))}function bL(e){return D(q("/memory/backend",e))}function xL(e){return D(q("/memory/install-qmd",e),{method:"POST"})}function vL(e,n){return D(q("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ra(){return D("/settings/global")}function Cn(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function yL(e){return D(q("/settings/scopes",e))}function wL(e){return D(q("/settings/pi-extensions",e))}function kL(e,n){return D(q("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function jL(e,n,s){return D(q("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function NL(){return D("/pi-settings")}async function SL(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function CL(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function EL(e){return D(q("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ir(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ns(q(`/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 dw(e,n,s){return D(q(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function wu(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=q(`/tasks/${e}/logs${r}`,n),l=await fetch(Ns(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 uw(e,n,s,a){return D(q(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function mw(e,n,s){return D(q(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function hw(e,n){return D(q(`/tasks/${e}/documents`,n))}function pw(e,n,s){return D(q(`/tasks/${e}/documents/${n}/revisions`,s))}async function ML(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 D(q(r,n))}function _L(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return D(q(r,e))}function ku(e,n,s,a,r){return D(q(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function fw(e,n,s){return D(q(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function gw(e,n,s){return D(q(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function bw(e,n,s){return D(q(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function xw(e,n){return D(q(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function vw(e,n,s){return D(q(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function As(){return D("/models")}function yw(){return D("/usage")}function ww(){return D("/providers/claude-cli/status")}function kw(){return D("/system/fn-binary/status")}function jw(){return D("/system/fn-binary/install",{method:"POST"})}function Nw(){return D("/providers/droid-cli/status")}async function AL(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/hermes/status${n}`)}async function PL(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await D(`/providers/hermes/profiles${n}`)).profiles??[]}async function RL(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return D(`/providers/openclaw/status${n}`)}async function TL(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),D(`/providers/paperclip/status?${n.toString()}`)}async function IL(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await D(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function $L(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await D(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function DL(e){return D("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function LL(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return D(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function zL(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await D(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function OL(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await D(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function FL(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return D(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Sw(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Cw(e){return D("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}async function Ew(){const n=(await D("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function Mw(e){return D("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function UL(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 D(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function BL(e){return D(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function _w(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Mw({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 $r(){return D("/auth/status")}function Aw(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Pw(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Rw(e){return D("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function Tw(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Iw(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function $w(e,n,s,a){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function Dw(e,n,s,a){return D(q("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Lw(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function zw(e,n,s,a){return D(q("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Ow(e){return D(q("/git/remotes",e))}function Fw(e){return D(q("/git/remotes/detailed",e))}function Uw(e,n,s){return D(q("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function Bw(e,n){return D(q(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hw(e,n,s){return D(q(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function qw(e,n,s){return D(q(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Vw(e,n,s){return D(q(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Ww(e,n){return D(q(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Kw(e,n){return(await D(q("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function ho(e,n,s,a){return D(q("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function ju(e,n){return D(q(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gw(e){return D(q("/terminal/sessions",e))}function ei(e){return D(q("/git/status",e))}function Jw(e,n){const s=e?`?limit=${e}`:"";return D(q(`/git/commits${s}`,n))}function Xo(e,n){return D(q(`/git/commits/${e}/diff`,n))}function Yw(e){return D(q("/git/commits/ahead",e))}function Qw(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(q(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function er(e){return D(q("/git/branches",e))}function Xw(e,n,s){const a=`?limit=${n}`;return D(q(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function Zw(e){return D(q("/git/worktrees",e))}function ek(e,n,s){return D(q("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function tk(e,n){return D(q(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Nu(e,n,s){const a=n?"?force=true":"";return D(q(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function nk(e,n){return D(q("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function sk(e){return D(q("/git/pull",e),{method:"POST"})}function ik(e){return D(q("/git/push",e),{method:"POST"})}function po(e){return D(q("/git/stashes",e))}function ak(e,n){return D(q("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function rk(e,n,s){return D(q(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function ok(e,n){return D(q(`/git/stashes/${e}`,n),{method:"DELETE"})}function lk(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),D(q(`/git/diff/file?${a.toString()}`,s))}function pa(e){return D(q("/git/changes",e))}function Su(e,n){return D(q("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function ck(e,n){return D(q("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Cu(e,n){return D(q("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function dk(e,n){return D(q("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function uk(e){return D(q("/workspaces",e))}function mk(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),D(`/files?${a.toString()}`)}function hk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function pk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function fk(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),D(`/files/search?${a.toString()}`)}function gk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function bk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function xk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),D(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function vk(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function nf(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function yk(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function wk(e,n,s){return D(q("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function kk(e,n,s,a,r){return D(q("/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 jk(e,n,s,a){return D(q("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function Nk(e,n,s){return D(q(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Sk(e,n,s){return D(q(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function sf(e,n,s){return D(q("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function HL(e,n,s,a){return D(q("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function qL(e,n,s){return D(q("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function VL(e,n){return D(q("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function Ck(e,n,s){return D(q("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ek(e,n,s){return D(q("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Mk(e,n,s){return D(q("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const rd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(rd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function _k(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ha(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 b=Number.parseInt(g,10);return Number.isFinite(b)?d!==null&&b<=d?!1:(d=b,!0):!0},h=()=>{if(o)return;const p=_k(e,d),g=new EventSource(fi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))g.addEventListener(b,x=>{const y=x;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(),rd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return rd.add(f),f}function Eu(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 Pa(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 Ak(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 Pk(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>Ak(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Rk(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 Mu(e){return Array.isArray(e)?e.map(Eu):(e.candidates??[]).map(Eu)}async function Tk(e){try{const n=await D(q("/dev-server/candidates",e));return Mu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(q("/dev-server/detect",e));return Mu(s)}throw n}}function Ld(e){return D(q("/dev-server/status",e)).then(Pa)}async function WL(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 D(q(`/dev-server/logs/history${a}`,n));return Pk(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Ld(n);return Rk(o.logs,e)}throw r}}function Ik(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return D(q("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(Pa)}function $k(e){return D(q("/dev-server/stop",e),{method:"POST"}).then(Pa)}function Dk(e){return D(q("/dev-server/restart",e),{method:"POST"}).then(Pa)}async function Lk(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await D(q("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Pa(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await D(q("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Pa(r)}throw a}}function KL(e){return Ns(q("/dev-server/logs/stream",e))}async function GL(e){try{return(await D(q("/devserver",e))).sessions??[]}catch{try{const n=await Ld(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 JL(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Ld(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 YL(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Ik({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 QL(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await $k(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 XL(e,n){try{return await D(q(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Dk(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 ZL(e,n,s){try{const a=await D(q(`/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 Lk({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function ez(e){try{return(await D(q("/devserver/detect",e))).candidates??[]}catch{try{return(await Tk(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function tz(e,n){return Ns(q(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Kr(e,n,s=25e3){const a=setInterval(()=>{MN(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function zk(e,n){return Ns(q(`/planning/${encodeURIComponent(e)}/stream`,n))}function Ok(e,n){return Ns(q(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function nz(e,n,s,a){const r=Ok(e,n),o=Ha(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 Fk(e,n,s,a){const r=zk(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ha(r,{onOpen:()=>{c(),o=Kr(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 Gr(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 Uk(e){return D(Gr("/routines",e))}function Bk(e,n){return D(Gr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function _u(e,n,s){return D(Gr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Hk(e,n){await D(Gr(`/routines/${e}`,n),{method:"DELETE"})}function qk(e,n){return D(Gr(`/routines/${e}/trigger`,n),{method:"POST"})}function Au(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity${s}`)}function Vk(e){const n=q("/activity",e);return D(n,{method:"DELETE"})}function Jr(e){return D(q("/workflow-steps",e))}function Pu(e,n){return D(q("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Wk(e,n,s){return D(q(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kk(e,n){return D(q(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Ru(e,n){return D(q(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Gk(e,n){return D(q(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Jk(){return D("/workflow-step-templates")}function Yk(e,n){return D(q(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Dr(e){return D(q("/scripts",e))}function Qk(e,n,s){return D(q("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function Xk(e,n){return D(q(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function af(e,n,s){return(await D(q("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const fo={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 rf(e){if(!(e instanceof Error))return fo.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?fo.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?fo.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:fo.NETWORK}function Zk(e,n){return D(q("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function ej(e,n,s){return D(q(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function tj(e,n){return Ns(q(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function nj(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ha(tj(e,n),{onOpen:()=>{l(),r=Kr(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 sj(e,n,s,a){return D(q("/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 of(e,n,s){return D(q("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function q(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function ij(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 Nl(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=ij(e,s,a);return D(o,r)}function oa(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return D(`/agents${a}`)}function od(e,n){return D(q(`/agents/${encodeURIComponent(e)}`,n))}function aj(e,n){return D(q("/agents",n),{method:"POST",body:JSON.stringify(e)})}function rj(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function sz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function iz(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function az(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function rz(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function oz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function lz(e,n,s){const a=`path=${encodeURIComponent(n)}`;return D(q(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function cz(e,n,s,a){return D(q(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function oj(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function lj(e,n){return D(q(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function dz(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 D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function uz(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function mz(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function hz(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(q(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function pz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function cj(e){return D(q("/agents/stats",e))}function fz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function gz(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return D(`/agents/org-tree${a?`?${a}`:""}`)}function bz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Tu(e,n,s){return D(q(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function xz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/tasks`,n))}function vz(){return D("/agents/companies")}function yz(e,n){return D(q("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function wz(e,n){return D(q("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function kz(e,n){return D(q(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function jz(e){return D(q("/backups",e))}function Nz(e){return D(q("/backups",e),{method:"POST"})}function Sz(e,n){const s=q("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(a)}function Cz(e,n,s){return D(q("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function Iu(){return D("/projects/across-nodes")}function Cr(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function Zo(){return D("/nodes")}function Ez(){return D("/docker-nodes")}function Mz(e){return D("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function dj(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function uj(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function mj(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function hj(e){const n=await D(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function _z(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=_a();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return D(d)}function pj(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function lf(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function $u(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function fj(e){return D(q("/executor/stats",e))}function gj(e){return D(q("/system-stats",e))}function bj(e){return D(q("/kill-vitest",e),{method:"POST"})}function Du(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return D(`/activity-feed${s}`)}function xj(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function vj(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function Az(){return D("/global-concurrency")}function Pz(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function yj(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function cf(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 D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function wj(e){return D(q("/missions",e))}function kj(e,n){return D(q("/missions",n),{method:"POST",body:JSON.stringify(e)})}function df(e,n){return D(q(`/missions/${encodeURIComponent(e)}`,n))}function jj(e,n,s){return D(q(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Nj(e,n){return D(q(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Sj(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 D(q(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Cj(e){return D(q("/missions/health",e))}function Ej(e,n,s){return D(q(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Mj(e,n,s){return D(q(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _j(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Aj(e,n,s){return D(q(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Pj(e,n,s){return D(q(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Rj(e,n){return D(q(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Tj(e,n){return D(q(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Ij(e,n,s){return D(q(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function $j(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Dj(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Lj(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function zj(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Oj(e,n,s,a){return D(q(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Fj(e,n){return D(q(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function ql(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Uj(e,n,s){return D(q(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Bj(e,n,s){return D(q(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Hj(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function qj(e,n,s){return D(q(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Vj(e,n){return D(q(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Vl(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Lu(e,n){return D(q(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function Wj(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function zu(e,n){return D(q(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Kj(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 D(q(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function Gj(e,n){return D(q(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function Jj(e,n){return D(q(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function Yj(e,n){return D(q(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function Qj(e,n){return D(q(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function Xj(e,n,s){return D(q(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zj(e,n,s){return D(q("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function eN(e,n,s,a){return D(q("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function tN(e,n,s){return D(q(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function uf(e,n,s){return D(q("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function nN(e,n,s){return D(q("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function sN(e,n,s,a){const r=Ns(q(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ha(r,{onOpen:()=>{c(),o=Kr(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 Yr(e,n,s){return q(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Qr(e,n,s){return q(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function iN(e,n){return D(Yr(e,"/start",n),{method:"POST"})}function aN(e,n,s,a){return D(Yr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function rN(e,n,s,a){const r=Ns(Yr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ha(r,{onOpen:()=>{c(),o=Kr(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 oN(e,n,s){return D(Yr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function lN(e,n){return D(Yr(e,"/skip",n),{method:"POST"})}function cN(e,n){return D(Qr(e,"/start",n),{method:"POST"})}function dN(e,n,s,a){return D(Qr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function uN(e,n,s,a){const r=Ns(Qr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Ha(r,{onOpen:()=>{c(),o=Kr(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 mN(e,n,s){return D(Qr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function hN(e,n){return D(Qr(e,"/skip",n),{method:"POST"})}async function pN(e,n){try{return await D(q(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function Rz(e){return D(q("/roadmaps",e))}function Tz(e,n){return D(q("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function Iz(e,n){return D(q(`/roadmaps/${encodeURIComponent(e)}`,n))}function $z(e,n,s){return D(q(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Dz(e,n){return D(q(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Lz(e,n,s){return D(q(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function zz(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Oz(e,n){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Fz(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Uz(e,n,s){return D(q(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Bz(e,n){return D(q(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hz(e,n,s){return D(q(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function qz(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function Vz(e,n,s,a){return D(q(`/roadmaps/features/${encodeURIComponent(e)}/move`,a),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function Wz(e,n){return D(q(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function Kz(e,n,s,a){return D(q(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,a),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function Gz(e,n,s){return D(q(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function fN(e){return D(q("/todos",e))}function gN(e,n){const s={title:e};return D(q("/todos",n),{method:"POST",body:JSON.stringify(s)})}function bN(e,n,s){const a={title:n};return D(q(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function xN(e,n){return D(q(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function vN(e,n,s){const a={text:n};return D(q(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function yN(e,n,s){const a=n;return D(q(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function wN(e,n){return D(q(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kN(e,n,s){return D(q(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Ra(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function zd(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(Ns(`/ai-sessions${a?`?${a}`:""}`),{headers:_i()});return r.ok?(await r.json()).sessions??[]:[]}async function jN(e){return D(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function NN(e){return D(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function pi(e){const n=await fetch(Ns(`/ai-sessions/${encodeURIComponent(e)}`),{headers:_i()});return n.ok?n.json():null}async function SN(e,n){const s=await D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function CN(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function EN(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function mf(e){await fetch(Ns(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:_i()})}function MN(e,n){return D(q(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function _N(e,n,s){return D(q(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function AN(e,n){return D(q(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function PN(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 D(`/messages/inbox${a}`)}function RN(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 D(`/messages/outbox${a}`)}function hf(e){return D(q("/messages/unread-count",e))}function TN(e,n){return D(q("/messages",n),{method:"POST",body:JSON.stringify(e)})}function IN(e,n){return D(q(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function $N(e){return D(q("/messages/read-all",e),{method:"POST"})}function DN(e,n){return D(q(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function LN(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(q(a,s))}function zN(e,n){return D(q(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function Jz(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 D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function Yz(e,n){return D(q(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function Qz(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function Xz(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 D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function Zz(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function e6(e,n){return D(q(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function t6(e,n,s){return D(q(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function n6(e,n){return D(q(`/agents/${encodeURIComponent(e)}/budget`,n))}function s6(e,n){return D(q(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function i6(e){return D(q("/plugins",e))}async function a6(e,n){return D(q("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function r6(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function o6(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function l6(e,n){return D(q(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function c6(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function d6(e,n,s){return D(q(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function u6(e,n){return D(q(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function ON(e){return D(q("/plugins/ui-slots",e))}async function FN(e){return D(q("/plugins/dashboard-views",e))}async function m6(e){return D(q("/plugins/runtimes",e))}async function UN(e){return(await D(q("/skills/discovered",e))).skills}async function h6(e,n,s){return D(q("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function p6(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 D(q(`/skills/catalog${r}`,s))}async function f6(e,n){return(await D(q(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Ou(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return D(`/chat/sessions${a?`?${a}`:""}`)}async function BN(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 D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function HN(e,n){return D(q("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function g6(e,n,s){return D(q(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function b6(e,n){return D(q(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Fu(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 D(q(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function qN(e,n){return D(q(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function VN(e,n,s,a,r,o){const l=Ns(q(`/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"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 k=new FormData;return k.append("content",n),a.forEach(N=>k.append("attachments",N)),k})():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 k=await f.text();let N=`Request failed: ${f.status}`;try{N=JSON.parse(k).error||N}catch{}s.onError?.(N);return}if(!f.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const p=f.body.getReader(),g=new TextDecoder;let b="",v="",x=[];const y=(k,N=!1)=>{b+=k;const R=b.split(`
638
- `);b=R.pop()||"",N&&b.length>0&&(R.push(b),b="");for(const w of R){const A=w.endsWith("\r")?w.slice(0,-1):w;if(A.startsWith("event:"))v=A.slice(6).trim();else if(A.startsWith("data:")){const P=A.slice(5);x.push(P.startsWith(" ")?P.slice(1):P)}else if(A===""){const P=x.join(`
639
- `);u(v,P),v="",x=[]}}if(N&&v&&x.length>0){const w=x.join(`
640
- `);u(v,w),v="",x=[]}};for(;;){const{done:k,value:N}=await p.read();if(k){y(g.decode(),!0);break}y(g.decode(N,{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 x6(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 D(q(`/insights${a}`,n))}function v6(e,n){return D(q(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function y6(e="manual",n,s){return D(q("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function w6(e){return D(q("/insights/runs",e))}function k6(e,n){return D(q(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function j6(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 D(q(`/research/runs${a}`,n))}function N6(e,n){return D(q("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function S6(e,n){return D(q(`/research/runs/${encodeURIComponent(e)}`,n))}function C6(e,n){return D(q(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function E6(e,n){return D(q(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}function M6(e,n,s){return D(q(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function _6(e,n,s){const a=n.findingId??"finding-1";return D(q(`/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 A6(e,n,s){const a=n.findingId??"finding-1";return D(q(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}function WN(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 KN({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}=WN(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 GN(e){return e.charAt(0).toUpperCase()+e.slice(1)}function na({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=GN(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 Uu=new Map,JN=6e4;function pf(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=Uu.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 b=await ON(e);if(h||d.current)return;Uu.set(m,{slots:b,expiresAt:Date.now()+JN}),s(b),c.current=!0}catch(b){if(h||d.current)return;l(b instanceof Error?b.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 Sl({slotId:e,projectId:n,pluginIds:s}){const{getSlotsForId:a,loading:r,error:o}=pf(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(kl,{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 YN(){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 la(){const[e,n]=i.useState(YN);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 Od(e){return e.replace(/[\\/]+$/g,"")}function Fd(e){const n=qa(Od(e));return n?n.split("/").filter(Boolean):[]}function Ud(e){const n=qa(Od(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function ff(e,n){const s=Fd(e);return s.length===0?qa(e):s.slice(-2).join("/")}function QN(e){const n=qa(Od(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function XN(e,n){return!e||e==="."?n:[...Fd(e),n].join("/")}function ZN(e){const n=Fd(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function P6(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 e1="dependency-graph-positions";function gf(e){return`kb:${e??"default"}:${e1}`}function t1(e){if(typeof window>"u")return{};try{const n=window.localStorage.getItem(gf(e));return n?JSON.parse(n)??{}:{}}catch{return{}}}function n1(e,n){typeof window>"u"||window.localStorage.setItem(gf(e),JSON.stringify(n))}const s1=new Set(["triage","todo","in-progress","in-review"]),fa=18,Wi=9,i1=3,a1=4,Bu=.5,go=2,r1=2,Hu=.4,qu=2;function Vu(e,n){const s=e.x-n.x,a=e.y-n.y;return Math.hypot(s,a)}function o1({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(()=>t1(e.projectId),[e.projectId]),f=i.useRef(null),p=i.useRef(null),g=i.useMemo(()=>e.tasks.filter(E=>s1.has(E.column)),[e.tasks]),b=i.useMemo(()=>g.map((E,S)=>{const I=o[E.id]??h[E.id];return{task:E,x:I?.x??S%4*(fa+i1),y:I?.y??Math.floor(S/4)*(Wi+a1)}}),[o,h,g]),v=i.useMemo(()=>new Map(b.map(E=>[E.task.id,E])),[b]),x=i.useMemo(()=>{const E=[];return b.forEach(S=>{(S.task.dependencies??[]).forEach(I=>{const F=v.get(I);F&&E.push({from:I,to:S.task.id,x1:F.x+fa,y1:F.y+Wi/2,x2:S.x,y2:S.y+Wi/2})})}),E},[v,b]),y=i.useMemo(()=>{if(b.length===0)return{minX:0,minY:0,width:fa*2,height:Wi*2};const E=Math.min(...b.map(G=>G.x))-go,S=Math.min(...b.map(G=>G.y))-go,I=Math.max(...b.map(G=>G.x+fa))+go,F=Math.max(...b.map(G=>G.y+Wi))+go;return{minX:E,minY:S,width:Math.max(fa*2,I-E),height:Math.max(Wi*2,F-S)}},[b]),k=i.useMemo(()=>b.map(E=>({...E,renderX:E.x-y.minX,renderY:E.y-y.minY})),[y.minX,y.minY,b]),N=i.useMemo(()=>x.map(E=>({...E,renderX1:E.x1-y.minX,renderY1:E.y1-y.minY,renderX2:E.x2-y.minX,renderY2:E.y2-y.minY})),[y.minX,y.minY,x]),R=i.useMemo(()=>{const E=new Map,S=new Map;return x.forEach(I=>{E.set(I.from,(E.get(I.from)??new Set).add(I.to)),S.set(I.to,(S.get(I.to)??new Set).add(I.from))}),{downstream:E,upstream:S}},[x]),w=u??c,A=i.useMemo(()=>{if(!w)return null;const E=new Set([w]),S=(I,F)=>{const G=[I];for(;G.length>0;){const X=G.shift();X&&(F.get(X)??new Set).forEach(M=>{E.has(M)||(E.add(M),G.push(M))})}};return S(w,R.downstream),S(w,R.upstream),E},[R.downstream,R.upstream,w]),P=()=>{const E=f.current;if(!E)return;const S=Number.parseFloat(globalThis.getComputedStyle(document.documentElement).fontSize)||16,I=y.width*S,F=y.height*S,G=r1*S,X=Math.max(1,E.clientWidth-G*2),M=Math.max(1,E.clientHeight-G*2),z=Math.min(qu,Math.max(Hu,Math.min(X/I,M/F))),L=(E.clientWidth-I*z)/(2*S*z),j=(E.clientHeight-F*z)/(2*S*z);s(z),r({x:L,y:j})},T=(E,S)=>{l(I=>({...I,[E]:S})),n1(e.projectId,{...h,...o,[E]:S})},_=(E,S)=>{if(d(F=>F===E?null:E),S.button!==0)return;S.preventDefault(),S.stopPropagation();const I=v.get(E);I&&(p.current={kind:"node",taskId:E,startPointer:{x:S.clientX,y:S.clientY},startNode:{x:I.x,y:I.y},moved:!1},S.currentTarget.setPointerCapture(S.pointerId))},C=E=>{E.button===0&&(p.current={kind:"pan",startPointer:{x:E.clientX,y:E.clientY},startPan:a,moved:!1},E.currentTarget.setPointerCapture(E.pointerId))},$=E=>{const S=p.current;if(!S)return;const I={x:(E.clientX-S.startPointer.x)/16,y:(E.clientY-S.startPointer.y)/16};if(S.kind==="node"){if(Vu({x:0,y:0},I)>Bu&&!S.moved&&(S.moved=!0),!S.moved)return;l(X=>({...X,[S.taskId]:{x:S.startNode.x+I.x/n,y:S.startNode.y+I.y/n}}));return}Vu({x:0,y:0},I)>Bu&&!S.moved&&(S.moved=!0),S.moved&&r({x:S.startPan.x+I.x,y:S.startPan.y+I.y})},O=E=>{const S=p.current;if(p.current=null,!!S){if(S.kind==="node"){const I=v.get(S.taskId);if(!I)return;if(!S.moved){e.openTaskDetail(I.task);return}T(S.taskId,{x:I.x,y:I.y})}E.currentTarget.releasePointerCapture(E.pointerId)}};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(E=>Math.min(E+.1,qu)),children:"Zoom In"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>s(E=>Math.max(E-.1,Hu)),children:"Zoom Out"}),t.jsx("button",{className:"btn btn-sm",onClick:P,children:"Fit"})]}),t.jsx("div",{className:"dependency-graph-canvas",ref:f,onPointerDown:C,onPointerMove:$,onPointerUp:O,children:t.jsxs("div",{className:"dependency-graph-scene",style:{width:`${y.width}rem`,height:`${y.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 ${y.width} ${y.height}`,children:N.map(E=>t.jsx("line",{x1:E.renderX1,y1:E.renderY1,x2:E.renderX2,y2:E.renderY2,className:`dependency-graph-edge${A?A.has(E.from)&&A.has(E.to)?" is-related":" is-dimmed":""}`},`${E.from}-${E.to}`))}),k.map(E=>t.jsx("div",{className:`dependency-graph-node${c===E.task.id?" is-selected":""}${A?A.has(E.task.id)?" is-related":" is-dimmed":""}`,style:{width:`${fa}rem`,minHeight:`${Wi}rem`,transform:`translate(${E.renderX}rem, ${E.renderY}rem)`},onPointerDown:S=>_(E.task.id,S),onPointerEnter:()=>m(E.task.id),onPointerLeave:()=>m(S=>S===E.task.id?null:S),children:e.renderTaskCard(E.task)},E.task.id))]})})]})}const l1=[{pluginId:"fusion-plugin-dependency-graph",viewId:"graph",component:o1}];function Er(e,n){return`plugin:${e}:${n}`}function c1(e){if(!e.startsWith("plugin:"))return null;const[,n,...s]=e.split(":"),a=s.join(":");return!n||!a?null:{pluginId:n,viewId:a}}function d1(e,n){return l1.find(a=>a.pluginId===e&&a.viewId===n)?.component??null}function u1({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(wl,{}),"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:Fs,bot:Mn,brain:Pr,checksquare:Ko,clock:Mi,filetext:Li,folder:as,gitbranch:Hs,grid3x3:gl,layoutgrid:zi,mail:ta,map:td,messagesquare:Ci,monitor:Ma,search:Si,sparkles:ms,target:ks,workflow:Jo,zap:Kn};function h1(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function el(e){return m1[h1(e)]??gl}const bf={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function p1({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(rn,{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=bf[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:ff(d.path)})]}),u&&t.jsx(Wn,{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 Wu({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 f1({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:b,onRunScript:v,onToggleTerminal:x,onOpenFiles:y,filesOpen:k,onOpenTodos:N,todosOpen:R,todosEnabled:w,globalPaused:A,enginePaused:P,onToggleGlobalPause:T,onToggleEnginePause:_,view:C="board",onChangeView:$,showSkillsTab:O,showAgentsTab:E,searchQuery:S="",onSearchChange:I,projects:F=[],currentProject:G,onSelectProject:X,onViewAllProjects:M,projectId:z,isElectron:L=!1,mobileNavEnabled:j,availableNodes:H=[],currentNode:Q,onSelectNode:de,isRemote:pe=!1,experimentalFeatures:B,pluginDashboardViews:ve=[]}){const U=la(),se=U==="mobile",ie=se||U==="tablet",te=se&&j,[xe,ne]=i.useState(!1),[_e,Ne]=i.useState(!1),[Se,He]=i.useState(!1),[Ye,Oe]=i.useState(!1),[ke,De]=i.useState(!1),[re,oe]=i.useState(!1),[we,Z]=i.useState(!1),[qe,Qe]=i.useState(!1),[ge,Ue]=i.useState(!1),[Xe,wt]=i.useState(!1),[ye,le]=i.useState(!1),[Te,be]=i.useState({}),[Le,Je]=i.useState(!1),[nt,mt]=i.useState(-1),[Ie,ze]=i.useState(null),[st,yt]=i.useState({}),[Re,kt]=i.useState(!1),Et=i.useRef(null),jt=i.useRef(null),Rt=i.useRef(null),Dt=i.useRef(null),Tt=i.useRef(null),It=i.useRef(null),Ut=i.useRef(!1),Ft=i.useRef(null),Jt=i.useRef(null),Vt=i.useRef(null),Yt=i.useRef(null),Kt=i.useRef(null),qt=i.useRef(null),Bt=i.useRef(null),Xt=i.useRef(null),an=i.useRef(!1),Qt=i.useMemo(()=>H.filter(he=>he.type==="remote"),[H]),fe=Qt.length>0,Fe=i.useMemo(()=>Object.entries(Te).sort(([he],[ct])=>he.localeCompare(ct)),[Te]),ae=Fe.length>0,Pe=Fe.length+(ae?1:0),Ae=i.useMemo(()=>Object.entries(st).sort(([he],[ct])=>he.localeCompare(ct)),[st]),W=i.useMemo(()=>ve.some(he=>he.pluginId==="fusion-plugin-roadmap"),[ve]),je=i.useMemo(()=>!!(B?.researchView||w||B?.insights||B?.roadmap&&!W||O||B?.memoryView||B?.devServerView||!te||ve.some(he=>he.view.placement!=="primary")),[B,w,O,te,ve,W]),ce=i.useCallback(()=>{const he=window.visualViewport;return he&&he.width>0&&he.height>0?{width:he.width,height:he.height,offsetTop:he.offsetTop,offsetLeft:he.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),$e=i.useCallback(()=>{const he=Bt.current;if(!he)return;const ct=he.getBoundingClientRect(),Zt=Xt.current,{width:Sn,height:In,offsetTop:Hn,offsetLeft:Xn}=ce(),jn=16,Pn=16,rs=6,os=Zt?.offsetWidth||Math.max(ct.width,260),cn=Math.min(os,Math.max(Sn-jn*2,160)),$n=Zt?.offsetHeight||280,nn=Math.min($n,Math.max(In-Pn*2,160)),_t=ct.top-Hn,K=ct.bottom-Hn,Ve=ct.right-Xn,pt=In-K,ht=_t,Nt=pt<nn&&ht>pt,Mt=Math.min(Math.max(Ve-cn,jn),Sn-jn-cn)+Xn,$t=Nt?Math.max(Pn+Hn,_t-nn-rs+Hn):Math.min(K+rs+Hn,In+Hn-Pn-nn);ze({top:$t,left:Mt,width:cn})},[ce]),it=i.useCallback((he,ct)=>{v?.(he,ct),le(!1),mt(-1)},[v]),vt=i.useCallback(()=>{b?.(),le(!1),mt(-1)},[b]),tn=i.useCallback(he=>{switch(he.key){case"ArrowDown":he.preventDefault(),Pe>0&&mt(ct=>ct<Pe-1?ct+1:0);break;case"ArrowUp":he.preventDefault(),Pe>0&&mt(ct=>ct>0?ct-1:Pe-1);break;case"Enter":if(he.preventDefault(),nt>=0)if(nt<Fe.length){const[ct,Zt]=Fe[nt];it(ct,Zt)}else ae&&nt===Fe.length&&vt();break;case"Home":he.preventDefault(),Pe>0&&mt(0);break;case"End":he.preventDefault(),Pe>0&&mt(Pe-1);break}},[vt,it,nt,Fe,ae,Pe]);i.useEffect(()=>{Ut.current=ke},[ke]),i.useEffect(()=>{an.current=ye},[ye]),i.useEffect(()=>{if(!ke||!ie)return;let he=!1;return kt(!0),Dr(z).then(ct=>{he||yt(ct)}).catch(()=>{he||yt({})}).finally(()=>{he||kt(!1)}),()=>{he=!0}},[ke,ie,z]),i.useEffect(()=>{if(!ye||ie)return;let he=!1;return Je(!0),Dr(z).then(ct=>{he||be(ct)}).catch(()=>{he||be({})}).finally(()=>{he||Je(!1)}),()=>{he=!0}},[ye,ie,z]),i.useEffect(()=>{if(!ye)return;const he=ct=>{qt.current&&!qt.current.contains(ct.target)&&le(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[ye]),i.useEffect(()=>{if(!ye)return;const he=ct=>{ct.key==="Escape"&&(le(!1),Bt.current?.focus())};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[ye]),i.useEffect(()=>{if(ye){mt(-1);const he=window.setTimeout(()=>Xt.current?.focus(),0);return()=>window.clearTimeout(he)}ze(null)},[ye]),i.useEffect(()=>{if(!ye)return;const he=requestAnimationFrame(()=>{$e()});return()=>cancelAnimationFrame(he)},[ye,Le,Fe.length,ae,$e]),i.useEffect(()=>{if(!ye)return;const he=()=>$e();window.addEventListener("resize",he),window.addEventListener("scroll",he,!0);const ct=window.visualViewport;return ct&&(ct.addEventListener("resize",he),ct.addEventListener("scroll",he)),()=>{window.removeEventListener("resize",he),window.removeEventListener("scroll",he,!0),ct&&(ct.removeEventListener("resize",he),ct.removeEventListener("scroll",he))}},[ye,$e]),i.useEffect(()=>{ie&&(le(!1),mt(-1))},[ie]);const Pt=xe||S.length>0,Lt=(_e||S.length>0)&&!Se,zt=(C==="board"||C==="list")&&!se&&I&&!Se&&S.length===0,yn=(C==="board"||C==="list")&&!se&&I;i.useEffect(()=>{S===""&&He(!1)},[S]),i.useEffect(()=>{if(!Ye)return;const he=ct=>{jt.current&&!jt.current.contains(ct.target)&&Et.current&&!Et.current.contains(ct.target)&&Oe(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[Ye]),i.useEffect(()=>{if(!ge)return;const he=ct=>{Dt.current&&!Dt.current.contains(ct.target)&&Rt.current&&!Rt.current.contains(ct.target)&&Ue(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[ge]),i.useEffect(()=>{if(!re)return;const he=ct=>{Ft.current&&!Ft.current.contains(ct.target)&&oe(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[re]),i.useEffect(()=>{const he=ct=>{if(ct.key==="Escape"){if(Qe(!1),Ue(!1),Ut.current){De(!1);return}if(an.current){le(!1),Bt.current?.focus();return}Oe(!1),ne(!1),oe(!1),Z(!1)}};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[]),i.useEffect(()=>{if(!we)return;const he=ct=>{Jt.current&&!Jt.current.contains(ct.target)&&Z(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[we]),i.useEffect(()=>{if(!Xe)return;const he=ct=>{Kt.current&&!Kt.current.contains(ct.target)&&wt(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[Xe]),i.useEffect(()=>{if(!Xe)return;const he=ct=>{ct.key==="Escape"&&wt(!1)};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[Xe]),i.useEffect(()=>{if(!qe)return;const he=ct=>{Vt.current&&!Vt.current.contains(ct.target)&&Yt.current&&!Yt.current.contains(ct.target)&&Qe(!1)};return document.addEventListener("mousedown",he),()=>document.removeEventListener("mousedown",he)},[qe]);const ue=i.useCallback(()=>{ne(he=>!he)},[]),lt=i.useCallback(()=>{Ne(!0),He(!1)},[]),ut=i.useCallback(()=>{Ne(!1),He(!0),I&&I("")},[I]),dt=i.useCallback(()=>{Oe(he=>!he)},[]),at=i.useCallback(he=>{he&&he(),Oe(!1),De(!1)},[]),St=i.useCallback(()=>{ne(!1),I&&I("")},[I]);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"})]}),se&&F.length>=1&&X&&t.jsxs("div",{className:"mobile-project-switch",ref:Jt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${we?" mobile-project-switch-trigger--open":""}`,onClick:()=>Z(he=>!he),title:"Switch project","aria-label":"Switch project","aria-expanded":we,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(rn,{size:14,className:`mobile-project-switch-chevron${we?" mobile-project-switch-chevron--open":""}`})}),we&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:F.map(he=>{const ct=G?.id===he.id,Zt=bf[he.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${ct?" mobile-project-switch-item--current":""}`,onClick:()=>{X(he),Z(!1)},role:"option","aria-selected":ct,"data-testid":`mobile-project-switch-item-${he.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Zt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:he.name}),t.jsx("span",{className:"mobile-project-switch-path",children:ff(he.path)})]}),ct&&t.jsx(Wn,{size:14,className:"mobile-project-switch-check"})]},he.id)})})]}),!ie&&F.length>=1&&M&&t.jsx(p1,{projects:F,currentProject:G??null,onViewAll:M,onSelectProject:X}),fe&&t.jsxs("div",{className:`header-node-selector${se?" header-node-selector--mobile":""}`,ref:se?void 0:Ft,children:[t.jsx(KN,{node:Q??null,showDetails:!se}),!se&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${re?" node-selector-trigger--open":""}`,onClick:()=>oe(he=>!he),title:"Switch node","aria-label":"Switch node","aria-expanded":re,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(_n,{size:12,className:`node-selector-chevron${re?" node-selector-chevron--open":""}`})}),re&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${pe?"":" node-selector-option--active"}`,onClick:()=>{de?.(null),oe(!1)},role:"option","aria-selected":!pe,"data-testid":"node-option-local",children:[t.jsx(na,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Qt.map(he=>t.jsxs("button",{className:`node-selector-option${Q?.id===he.id?" node-selector-option--active":""}`,onClick:()=>{de?.(he),oe(!1)},role:"option","aria-selected":Q?.id===he.id,"data-testid":`node-option-${he.id}`,children:[t.jsx(na,{status:he.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:he.name}),t.jsx("span",{className:"node-selector-option-status",children:he.status})]},he.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[te&&$&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>$("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(zi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>$("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(ed,{size:16})})]}),I&&se&&(te||C==="board"||C==="list")&&!Pt&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:ue,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Si,{size:16})}),zt&&t.jsx("button",{className:"btn-icon",onClick:lt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Si,{size:16})}),se&&te&&o&&t.jsx("button",{className:"btn-icon",onClick:he=>o(he.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Fs,{size:16})}),!te&&$&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>$("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(zi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>$("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(ed,{size:16})}),E&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>$("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(Mn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>$("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ks,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>$("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>$("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Li,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>$("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(ta,{size:16})}),ve.filter(he=>he.view.placement==="primary").sort((he,ct)=>(he.view.order??Number.MAX_SAFE_INTEGER)-(ct.view.order??Number.MAX_SAFE_INTEGER)).map(he=>{const ct=Er(he.pluginId,he.view.viewId),Zt=el(he.view.icon);return t.jsx("button",{className:`view-toggle-btn${C===ct?" active":""}`,onClick:()=>$(ct),title:`${he.view.label} view`,"aria-label":`${he.view.label} view`,"aria-pressed":C===ct,"data-testid":`view-toggle-plugin-${he.pluginId}-${he.view.viewId}`,children:t.jsx(Zt,{size:16})},`${he.pluginId}:${he.view.viewId}`)}),je&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Yt,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||w&&R||C.startsWith("plugin:")?" active":""}`,onClick:()=>Qe(he=>!he),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":qe,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(rn,{size:12})}),qe&&t.jsxs("div",{ref:Vt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[B?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="research"?" active":""}`,onClick:()=>{$("research"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Si,{size:14}),t.jsx("span",{children:"Research"})]}),B?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{$("insights"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(ms,{size:14}),t.jsx("span",{children:"Insights"})]}),B?.roadmap&&!W&&t.jsx("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{$("roadmaps"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:t.jsx("span",{children:"Roadmaps"})}),O&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{$("skills"),Qe(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Kn,{size:14}),t.jsx("span",{children:"Skills"})]}),B?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{$("memory"),Qe(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Pr,{size:14}),t.jsx("span",{children:"Memory"})]}),B?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{$("devserver"),Qe(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Ma,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),w&&N&&t.jsxs("button",{className:`view-toggle-overflow-item${R?" active":""}`,onClick:()=>{N(),Qe(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Ko,{size:14}),t.jsx("span",{children:"Todos"})]}),ve.filter(he=>he.view.placement!=="primary").sort((he,ct)=>(he.view.order??Number.MAX_SAFE_INTEGER)-(ct.view.order??Number.MAX_SAFE_INTEGER)).map(he=>{const ct=Er(he.pluginId,he.view.viewId),Zt=el(he.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${C===ct?" active":""}`,onClick:()=>{$(ct),Qe(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${he.pluginId}-${he.view.viewId}`,children:[t.jsx(Zt,{size:14}),t.jsx("span",{children:he.view.label})]},`${he.pluginId}:${he.view.viewId}`)})]})]})]}),!ie&&o&&t.jsx("button",{className:"btn-icon",onClick:he=>o(he.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Fs,{size:16})}),!ie&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(Ma,{size:16})}),!ie&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Rr,{size:16})}),!ie&&!L&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Wu,{size:16})}),!ie&&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(oi,{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})]}),!ie&&t.jsxs("div",{className:"terminal-split-btn",ref:qt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:x,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Ei,{size:16})}),b&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Bt,className:`btn-icon terminal-split-btn__chevron${ye?" btn-icon--active":""}`,onClick:()=>le(he=>!he),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ye,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(rn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ye?" rotate":""}`})}),ye&&t.jsx("div",{ref:Xt,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:tn,"data-testid":"quick-scripts-dropdown",style:Ie?{position:"fixed",top:`${Ie.top}px`,left:`${Ie.left}px`,width:`${Ie.width}px`,right:"auto"}:void 0,children:Le?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Fe.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(Ei,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:vt,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Fe.map(([he,ct],Zt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${nt===Zt?"highlighted":""}`,onClick:()=>it(he,ct),role:"option","aria-selected":nt===Zt,"data-testid":`quick-script-item-${he}`,children:[t.jsx(On,{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:he}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:ct,children:ct.length>50?`${ct.slice(0,50)}...`:ct})]})]},he))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${ae&&nt===Fe.length?"highlighted":""}`,onClick:vt,"data-testid":"quick-scripts-manage",children:[t.jsx(Sr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!ie&&y&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(as,{size:16})}),!ie&&w&&N&&t.jsx("button",{className:`btn-icon${R?" btn-icon--active":""}`,onClick:N,title:"Open todos","data-testid":"todos-toggle-btn",children:t.jsx(Ko,{size:16})}),!ie&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Hs,{size:16})}),!ie&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Jo,{size:16})}),!ie&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Rt,className:"btn-icon",onClick:()=>Ue(he=>!he),title:"More actions","aria-label":"More actions","aria-expanded":ge,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Yc,{size:16})}),ge&&t.jsxs("div",{ref:Dt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[f&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{f(),Ue(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Tr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{at(m),Ue(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Mi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Kt,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${A?" btn-icon--stopped":""}`,onClick:T,title:A?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:A?t.jsx(On,{size:16}):t.jsx(zs,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Xe?" btn-icon--active":""}`,onClick:()=>wt(he=>!he),title:"Engine options","aria-haspopup":"menu","aria-expanded":Xe,"data-testid":"engine-control-chevron-btn",children:t.jsx(rn,{size:12})}),Xe&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${P?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{_?.(),wt(!1)},role:"menuitem",title:P?"Resume scheduling":"Pause triage",disabled:!!A,"data-testid":"engine-control-pause-triage-btn",children:[P?t.jsx(On,{size:14}):t.jsx(ii,{size:14}),t.jsx("span",{children:P?"Resume scheduling":"Pause triage"})]})})]}),!ie&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Sr,{size:16})}),t.jsx(Sl,{slotId:"header-action",projectId:z}),ie&&!te&&t.jsx("button",{ref:Et,className:"btn-icon compact-overflow-trigger",onClick:dt,title:"More header actions","aria-label":"More header actions","aria-expanded":Ye,"aria-haspopup":"menu",children:t.jsx(Yc,{size:16})}),ie&&!te&&Ye&&t.jsxs("div",{ref:jt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[F.length>=1&&M&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(M),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(gl,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(as,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>at(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(oi,{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:()=>at(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Hs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),f&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(f),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Tr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!L&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(n),role:"menuitem",children:[t.jsx(Wu,{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:()=>at(x),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Ei,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>De(he=>!he),role:"menuitem","aria-expanded":ke,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(_n,{size:14,className:`mobile-overflow-chevron${ke?" mobile-overflow-chevron--open":""}`})})]}),ke&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Re?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(bt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Ae.length>0?t.jsxs(t.Fragment,{children:[Ae.map(([he,ct])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(he,ct),Oe(!1),De(!1)},role:"menuitem","data-testid":`overflow-script-item-${he}`,children:[t.jsx(On,{size:14}),t.jsx("span",{children:he})]},he)),b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>at(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(si,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):b&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>at(b),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(si,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Mi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Rr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(ta,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:he=>at(()=>o(he.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Fs,{size:16}),t.jsx("span",{children:"View Usage"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(g),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Jo,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>at(e),role:"menuitem",children:[t.jsx(Sr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),yn&&Lt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Si,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:S,onChange:he=>I(he.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:ut,"aria-label":"Close search",children:t.jsx(Wt,{size:14})})]})}),I&&se&&Pt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:Tt,className:"header-search mobile-search-expanded",children:[t.jsx(Si,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:It,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:S,onChange:he=>I(he.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:St,"aria-label":"Close search",children:t.jsx(Wt,{size:14})})]})})]})}const g1={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",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:{}},b1={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},x1=Object.freeze(Object.keys(g1)),v1=Object.freeze(Object.keys(b1));function R6(e){return x1.includes(e)}function T6(e){return v1.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 y1(e){return!!(e?.provider&&e?.modelId)}function Oi(...e){for(const n of e)if(y1(n))return{provider:n.provider,modelId:n.modelId};return{}}function Cl(e){return Oi({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function w1(e){return Oi({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Cl(e))}function k1(e){return Oi({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Cl(e))}function j1(e){return Oi({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Cl(e))}function I6(e){return Oi({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Cl(e))}function xf(e,n){return Oi({provider:e.modelProvider,modelId:e.modelId},w1(n))}function vf(e,n){return Oi({provider:e.validatorModelProvider,modelId:e.validatorModelId},j1(n))}function yf(e,n){return Oi({provider:e.planningModelProvider,modelId:e.planningModelId},k1(n))}const $6=["off","minimal","low","medium","high"],Xi=["triage","todo","in-progress","in-review","done","archived"],Xr=["low","normal","high","urgent"],Ms="normal",N1=["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"],ns={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},S1={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"},ld={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 C1(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 E1(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 M1({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 wf=i.createContext(null);function _1({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 Vo.createElement(wf.Provider,{value:d},e,Vo.createElement(M1,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function qs(){const e=i.useContext(wf);return e||{confirm:async n=>!1}}function A1(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 kf({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(Os,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${A1(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(pl,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function bo(e,n){return`${e??"default"}:${n}`}class P1{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=bo(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=bo(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=bo(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(fi(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=bo(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Ku(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Ku(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 Ki=new P1;let R1=0;function Ku(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function jf(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${R1++}`);const s=i.useSyncExternalStore(o=>Ki.subscribe(o),()=>Ki.getSnapshot(),()=>Ki.getSnapshot()),a=i.useCallback(o=>{Ki.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ki.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ki.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ki.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function tl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function T1({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=jf(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=tl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=tl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(kf,{prInfo:h,issueInfo:f})}const I1=i.memo(T1);I1.displayName="TaskCardBadge";const $1={sm:16,md:20,lg:24};function D1({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 Gu({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 di({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 L1({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 Ju({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 z1({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 Wl({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 Yu({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 Qu({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 Xu({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 tr({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 Zu({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 Kl({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 em({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 Gl({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 O1({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 F1({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 tm({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 Jl({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 U1({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 nm({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 Yl({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 sm({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 Ql({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 im({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 B1({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 H1={anthropic:{component:D1,color:"var(--provider-anthropic)"},"claude-cli":{component:im,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:im,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:B1,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},openai:{component:Gu,color:"var(--provider-openai)"},"openai-codex":{component:Gu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:di,color:"var(--provider-gemini)"},gemini:{component:di,color:"var(--provider-gemini)"},"google-antigravity":{component:di,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:di,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:di,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:di,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:di,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:di,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:di,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:di,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:L1,color:"var(--text)"},github:{component:nm,color:"var(--text)"},"github-copilot":{component:nm,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:U1,color:"var(--provider-openrouter)"},minimax:{component:Ju,color:"var(--provider-minimax)"},"minimax-cn":{component:Ju,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:z1,color:"var(--provider-zai)"},kimi:{component:Wl,color:"var(--provider-kimi)"},moonshot:{component:Wl,color:"var(--provider-kimi)"},"kimi-coding":{component:Wl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Yu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Yu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Qu,color:"var(--text)"},grok:{component:Qu,color:"var(--text)",label:"xAI"},opencode:{component:Xu,color:"var(--provider-opencode)"},"opencode-go":{component:Xu,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:tr,color:"var(--provider-qwen)"},"qwen-ai":{component:tr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:tr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:tr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:tr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:Zu,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:Zu,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:Kl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:Kl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:Kl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:em,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:em,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Gl,color:"var(--provider-azure)"},"azure-openai":{component:Gl,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Gl,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:Jl,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:Jl,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:Jl,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:O1,color:"var(--provider-cerebras)"},groq:{component:F1,color:"var(--provider-groq)"},vercel:{component:tm,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:tm,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Yl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Yl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Yl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:sm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:sm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:Ql,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:Ql,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:Ql,color:"var(--provider-paperclip)",label:"Paperclip"}};function Fn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=H1[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=$1[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(jx,{size:c})})}const Js={data:new Map,pendingPromise:null,lastFetchTime:null},q1=5e3;function Uo(e,n){return n?`${n}::${e}`:e}function V1(e,n){const s=Js.data.get(Uo(e,n));if(!(!s||Date.now()-s.timestamp>q1))return s}function W1(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 Kw(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=Js.data.get(Uo(f,e));return p&&p.timestamp>u})&&Js.lastFetchTime&&Js.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),Js.pendingPromise){s(!0);try{await Js.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);Js.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,b]of Object.entries(f))Js.data.set(Uo(g,e),{result:b,timestamp:p});Js.lastFetchTime=p}catch{}finally{Js.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>Js.data.get(Uo(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:Js.lastFetchTime,getBatchData:l}}const cd=new Map,K1=3e4;function Nf(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function G1(e,n,s,a){const r=Nf(e,n,s,a),o=cd.get(r);return o?Date.now()>o.expiresAt?(cd.delete(r),null):o.stats:null}function J1(e,n,s,a,r){const o=Nf(e,n,s,a);cd.set(o,{stats:r,expiresAt:Date.now()+K1})}function Y1(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 b=g?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function y(N=!1){if(!N){const R=G1(e,a,b,v);if(R){x||(m(R),f(!1));return}}f(!0);try{const R=await cf(e,b,a);x||(m(R.stats),J1(e,a,b,v,R.stats))}catch{x||m(null)}finally{x||f(!1)}}y();let k;return d&&g&&(k=setInterval(()=>{y(!0)},d)),()=>{x=!0,k&&clearInterval(k)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const Q1=new Set(["failed","stuck-killed"]);function nl(e,n,s){if(e.column!=="in-progress"||e.status&&Q1.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function X1(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Z1(e){return e==="done"||e==="skipped"}function eS(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Sf(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:eS(d,u,n),status:u?X1(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>Z1(d.status)).length;return{total:l,completed:c,items:o}}function tS(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 Cf(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:tS(n)}})}function nS(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Cf(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}const dd=new Map;async function sS(e,n){const s=dd.get(e);if(s)return s;try{const a=await df(e,n);return dd.set(e,a.title),a.title}catch{return e}}const am=12;function iS(e){return e.length<=am?e:e.slice(0,am-3)+"..."}const ud=new Map;async function aS(e,n){const s=ud.get(e);if(s)return s;try{const a=await od(e,n);return ud.set(e,a.name),a.name}catch{return e}}function rS(e){return typeof e=="string"&&Xr.includes(e)?e:Ms}function oS(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const lS=new Set(["triage","todo"]),rm=new Set(["planning","researching","executing","finalizing","merging"]),om=new Set(["merging","merging-pr"]),cS={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},dS=new Set(["in-progress","in-review","done"]),uS=3e4;function sa(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function mS(e){const n=sa(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function lm(e,n){const s=sa(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function vr(e,n){const s=sa(e.executionStartedAt);if(s==null)return null;const a=sa(e.executionCompletedAt),r=a!=null&&a>=s?a:n;return Math.max(0,r-s)}function hS(e){return e.column==="done"?mS(e):null}function Ef(e,n){const s=sa(e.updatedAt);return s==null?null:Math.max(0,n-s)}function pS(e,n){const s=vr(e,n);if(s!=null)return s;const a=Ef(e,n),r=yr(e,n);return r!=null?r+(a??0):a}function fS(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=sa(o.startedAt);if(l==null)continue;let c;if(o.completedAt){const d=sa(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 yr(e,n){const s=typeof e.timedExecutionMs=="number"?e.timedExecutionMs:nS(e.log),a=fS(e,n);return s==null&&a==null?null:(s??0)+(a??0)}function cm(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 dm(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 um(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 gS(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function bS(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function xS(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function vS(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function yS(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 wS(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 kS(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 jS(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 NS(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&&kS(s.attachments,a.attachments)&&jS(s.comments,a.comments)&&bS(s.dependencies,a.dependencies)&&gS(s.steps,a.steps)&&xS(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&wS(s.workflowStepResults,a.workflowStepResults)&&um(s.prInfo,a.prInfo)&&um(s.issueInfo,a.issueInfo)}function SS({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:b,workflowStepNameLookup:v}){const[x,y]=i.useState(!1),[k,N]=i.useState(!1),[R,w]=i.useState(!1),[A,P]=i.useState(e.description||""),[T,_]=i.useState(!1),[C,$]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(ce=>ce.status==="done"||ce.status==="skipped")),[O,E]=i.useState(null),[S,I]=i.useState(null),[F,G]=i.useState(!1),[X,M]=i.useState(!1),[z,L]=i.useState(()=>Date.now()),j=i.useRef(null),H=i.useRef(!1),Q=i.useRef(null),de=i.useRef(null),[pe,B]=i.useState(!1),{badgeUpdates:ve,subscribeToBadge:U,unsubscribeFromBadge:se}=jf(n),{confirm:ee}=qs(),ie=i.useRef(null),te=i.useRef(!1),xe=i.useCallback(ce=>ce instanceof Element?!!ce.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{P(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!F)return;const ce=$e=>{de.current&&!de.current.contains($e.target)&&G(!1)};return document.addEventListener("click",ce),()=>document.removeEventListener("click",ce)},[F]),i.useEffect(()=>{if(!e.missionId){E(null);return}const ce=dd.get(e.missionId);if(ce){E(ce);return}let $e=!1;return sS(e.missionId,n).then(it=>{$e||E(it)}),()=>{$e=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const ce=ud.get(e.assignedAgentId);if(ce){I(ce);return}I(null);let $e=!1;return aS(e.assignedAgentId,n).then(it=>{$e||I(it)}),()=>{$e=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(R&&j.current){const ce=j.current;ce.focus(),ce.style.height="auto",ce.style.height=ce.scrollHeight+"px"}},[R]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){B(!0);return}const ce=Q.current;if(!ce)return;const $e=new IntersectionObserver(([it])=>{B(it?.isIntersecting??!0)},{rootMargin:"200px"});return $e.observe(ce),()=>$e.disconnect()},[R,e.id]);const ne=i.useCallback(ce=>{ce.dataTransfer.setData("text/plain",e.id),ce.dataTransfer.effectAllowed="move",y(!0)},[e.id]),_e=i.useCallback(()=>{y(!1)},[]),Ne=i.useCallback(ce=>ce.dataTransfer.types.includes("Files"),[]),Se=i.useCallback(ce=>{Ne(ce)&&(ce.preventDefault(),ce.stopPropagation(),ce.dataTransfer.dropEffect="copy",N(!0))},[Ne]),He=i.useCallback(ce=>{Ne(ce)&&(ce.preventDefault(),ce.stopPropagation(),N(!1))},[Ne]),Ye=i.useCallback(async ce=>{if(!Ne(ce))return;ce.preventDefault(),ce.stopPropagation(),N(!1);const $e=Array.from(ce.dataTransfer.files);for(const it of $e)try{await Ir(e.id,it,n),r(`Attached ${it.name} to ${e.id}`,"success")}catch(vt){r(`Failed to attach ${it.name}: ${Me(vt)}`,"error")}},[e.id,Ne,r]),Oe=i.useCallback(()=>{R||a(e)},[e,a,R]),ke=i.useCallback(ce=>{if(H.current){H.current=!1;return}xe(ce.target)||Oe()},[Oe,xe]),De=i.useCallback(ce=>{const $e=ce.touches[0];$e&&(ie.current={x:$e.clientX,y:$e.clientY,time:Date.now()},te.current=!1)},[]),re=i.useCallback(ce=>{if(!ie.current)return;const $e=ce.touches[0];if(!$e)return;const it=Math.abs($e.clientX-ie.current.x),vt=Math.abs($e.clientY-ie.current.y);(it>mm||vt>mm)&&(te.current=!0)},[]),oe=i.useCallback(ce=>{if(xe(ce.target)||!ie.current)return;const it=Date.now()-ie.current.time<CS,vt=!te.current;it&&vt&&(H.current=!0,Oe()),ie.current=null,te.current=!1},[Oe,xe]),we=i.useCallback(async(ce,$e)=>{ce.stopPropagation();try{const it=await Aa($e,n);a(it)}catch{r(`Failed to load dependency ${$e}`,"error")}},[a,r]),Z=e.status==="failed",qe=e.paused===!0,Qe=rS(e.priority),ge=Qe!==Ms,Ue=nl(e,f,b),Xe=e.column==="triage"&&e.status==="awaiting-approval",wt=e.column==="archived",ye=!o&&!s&&!Z&&!qe&&!Ue&&!Xe&&(e.column==="in-progress"||rm.has(e.status)),le=!s&&!qe&&!R&&!wt,Te=lS.has(e.column)&&!ye&&!qe&&!s&&l,be=!!(e.prInfo||e.issueInfo),Le=e.sourceType==="github_import",Je=vS(e.sourceMetadata),nt=!!(e.assignedAgentId&&S===null),mt=i.useMemo(()=>{const ce=[];return e.modelProvider&&ce.push(e.modelProvider),e.validatorModelProvider&&!ce.includes(e.validatorModelProvider)&&ce.push(e.validatorModelProvider),e.planningModelProvider&&!ce.includes(e.planningModelProvider)&&ce.push(e.planningModelProvider),ce},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),Ie=i.useMemo(()=>Sf(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),ze=Ie.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const ce=e.status!=null&&om.has(e.status);if(e.column==="in-progress"){const it=vr(e,Date.now()),vt=lm(e,Date.now()),tn=yr(e,Date.now());if(it==null&&vt==null&&tn==null)return}if(!ce&&e.column==="in-review"){const it=vr(e,Date.now()),vt=yr(e,Date.now());if(it==null&&vt==null)return}L(Date.now());const $e=window.setInterval(()=>{L(Date.now())},uS);return()=>window.clearInterval($e)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const st=i.useMemo(()=>{if(!dS.has(e.column))return null;if(e.status!=null&&om.has(e.status)){const Pt=pS(e,z);if(Pt!=null){const Lt=dm(Pt);if(Lt){const zt=Ef(e,z),yn=zt==null?null:cm(zt),ue=yn?`Execution time ${Lt}. Merge phase ${yn}`:`Execution time ${Lt}. Merging`;return{label:Lt,title:ue,ariaLabel:ue}}}}if(e.column==="in-progress"){const Pt=vr(e,z)??lm(e,z)??yr(e,z);if(Pt==null)return null;const Lt=cm(Pt);return Lt?{label:Lt,title:`In progress ${Lt}`,ariaLabel:`In progress ${Lt}`}:null}const $e=vr(e,z)??yr(e,z);if($e==null)return null;const it=dm($e);if(!it)return null;const vt=hS(e);if(vt==null)return{label:it,title:`Execution time ${it}`,ariaLabel:`Execution time ${it}`};const tn=new Date(vt).toLocaleString();return{label:it,title:`Execution time ${it}. Completed ${tn}`,ariaLabel:`Execution time ${it}. Completed ${tn}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,z]);i.useEffect(()=>{if(!be||!pe){se(e.id);return}return U(e.id),()=>{se(e.id)}},[be,pe,U,e.id,se]);const yt=ve.get(`${n??"default"}:${e.id}`),Re=e.column==="in-progress"||e.column==="in-review",kt=i.useMemo(()=>e.steps.map(ce=>`${ce.name}:${ce.status}`).join("|"),[e.steps]),{stats:Et}=Y1(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:pe,worktree:e.worktree,stepVersion:Re?kt:void 0,pollIntervalMs:Re?3e4:void 0}),jt=i.useMemo(()=>V1(e.id,n),[e.id,n]),Rt=i.useMemo(()=>{const ce=yt?.prInfo,$e=yt?.timestamp,it=jt?.result?.prInfo,vt=jt?.timestamp?new Date(jt.timestamp).toISOString():void 0,tn=e.prInfo,Pt=e.prInfo?.lastCheckedAt??e.updatedAt;let Lt=tl(ce,$e,tn,Pt);const zt=$e&&$e>=Pt?$e:Pt;return it&&vt&&(!zt||vt>zt)&&(Lt=it),Lt},[yt,jt,e.prInfo,e.updatedAt]),Dt=i.useMemo(()=>{const ce=yt?.issueInfo,$e=yt?.timestamp,it=jt?.result?.issueInfo,vt=jt?.timestamp?new Date(jt.timestamp).toISOString():void 0,tn=e.issueInfo,Pt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Lt=tl(ce,$e,tn,Pt);const zt=$e&&$e>=Pt?$e:Pt;return it&&vt&&(!zt||vt>zt)&&(Lt=it),Lt},[yt,jt,e.issueInfo,e.updatedAt]),Tt=i.useCallback(ce=>{ce?.stopPropagation(),!(!Te||T)&&(w(!0),P(e.description||""))},[Te,T,e.description]),It=i.useCallback(()=>{w(!1),P(e.description||"")},[e.description]),Ut=i.useCallback(()=>A!==(e.description||""),[A,e.description]),Ft=i.useCallback(async()=>{if(!(!l||T)){if(!Ut()){It();return}_(!0);try{await l(e.id,{description:A.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(ce){r(`Failed to update ${e.id}: ${Me(ce)}`,"error")}finally{_(!1)}}},[l,e.id,A,T,Ut,It,r]),Jt=i.useCallback(ce=>{ce.key==="Enter"&&!ce.shiftKey?(ce.preventDefault(),Ft()):ce.key==="Escape"&&(ce.preventDefault(),It())},[Ft,It]),Vt=i.useCallback(()=>{setTimeout(()=>{const ce=document.activeElement;ce===j.current||ce?.closest(".card-editing-content")||(Ut()?Ft():It())},0)},[Ut,Ft,It]),Yt=i.useCallback(ce=>{Te&&(ce.stopPropagation(),Tt(ce))},[Te,Tt]),Kt=i.useCallback(ce=>{ce.stopPropagation(),Tt(ce)},[Tt]),qt=i.useCallback(ce=>{P(ce.target.value);const $e=ce.target;$e.style.height="auto",$e.style.height=$e.scrollHeight+"px"},[]),Bt=i.useCallback(ce=>{ce.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch($e=>{r(`Failed to archive ${e.id}: ${Me($e)}`,"error")})},[r,c,e.id]),Xt=i.useCallback(ce=>{ce.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch($e=>{r(`Failed to unarchive ${e.id}: ${Me($e)}`,"error")})},[r,d,e.id]),an=i.useCallback(async ce=>{if(ce.stopPropagation(),!(!u||!await ee({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(it){const vt=yS(it);if(!vt||vt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Me(it)}`,"error");return}const tn=vt.dependentIds.join(", ");if(!await ee({title:"Force Delete Task",message:`${e.id} is a dependency of ${tn}.
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(Lt){r(`Failed to delete ${e.id}: ${Me(Lt)}`,"error")}}},[r,ee,u,e.id]),Qt=i.useCallback(ce=>{ce.stopPropagation(),h?.(e,"changes")},[e,h]),fe=i.useCallback(ce=>{ce.stopPropagation(),$($e=>!$e)},[]),Fe=i.useCallback(ce=>{ce.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),ae=i.useCallback(ce=>{ce.stopPropagation(),G($e=>!$e)},[]),Pe=i.useCallback(async(ce,$e)=>{if(ce.stopPropagation(),G(!1),!!g)try{const it=e.steps.some(Pt=>Pt.status!=="pending"),vt=($e==="todo"||$e==="triage")&&it;let tn;if(vt){if(await ee({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))tn={preserveProgress:!0};else if(!await ee({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,$e,tn),r(`Moved ${e.id} to ${ns[$e]}`,"success")}catch(it){r(`Failed to move ${e.id}: ${Me(it)}`,"error")}},[r,ee,g,e.id,e.steps]),Ae=i.useCallback(async ce=>{if(ce.stopPropagation(),!(!m||X)){M(!0);try{await m(e.id)}catch($e){r(`Failed to retry ${e.id}: ${Me($e)}`,"error")}finally{M(!1)}}},[r,X,m,e.id]),W=`card${x?" dragging":""}${s?" queued":""}${ye?" agent-active":""}${Z?" failed":""}${qe?" paused":""}${Ue?" stuck":""}${Xe?" awaiting-approval":""}${k?" file-drop-target":""}${R?" card-editing":""}${T?" card-saving":""}`,je=(()=>{if(e.column==="in-progress"){const ce=Et?.filesChanged,$e=ce==null||ce===0?e.modifiedFiles?.length:void 0,it=ce!=null&&ce>0?ce:$e;return it==null||it===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Qt,disabled:!h,children:[t.jsx(as,{size:12}),t.jsxs("span",{children:[it," ",it===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const ce=Et?.filesChanged,$e=ce==null||ce===0?e.modifiedFiles?.length:void 0,it=ce!=null&&ce>0?ce:$e;return it==null||it===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Qt,disabled:!h,children:[t.jsx(as,{size:12}),t.jsxs("span",{children:[it," ",it===1?"file":"files"," changed"]})]})}if(e.column==="done"){const ce=Et?.filesChanged,$e=e.mergeDetails?.filesChanged,it=ce??$e;if(it!=null&&it>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Qt,disabled:!h,children:[t.jsx(as,{size:12}),t.jsxs("span",{children:[it," ",it===1?"file":"files"," changed"]})]});const vt=e.modifiedFiles?.length;if(vt!=null&&vt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Qt,disabled:!h,children:[t.jsx(as,{size:12}),t.jsxs("span",{children:[vt," ",vt===1?"file":"files"," changed"]})]})}return null})();return R?t.jsx("div",{ref:Q,className:W,"data-id":e.id,onDoubleClick:Yt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:j,className:"card-edit-desc-textarea",placeholder:"Task description",value:A,onChange:qt,onKeyDown:Jt,onBlur:Vt,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:Q,className:W,"data-id":e.id,draggable:le,onDragStart:le?ne:void 0,onDragEnd:le?_e:void 0,onDragOver:Se,onDragLeave:He,onDrop:Ye,onClick:ke,onTouchStart:De,onTouchMove:re,onTouchEnd:oe,onDoubleClick:Yt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),qe&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!qe&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Xe?" awaiting-approval":""}${rm.has(e.status)?" pulsing":""}${Z?" failed":""}${Ue?" stuck":""}`,children:Ue?"Stuck":Xe?"Awaiting Approval":e.status}),Ue&&(qe||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),be&&t.jsx(kf,{prInfo:Rt,issueInfo:Dt}),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(Kn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Fe,title:`Mission: ${O??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ks,{size:11}),iS(O??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Te&&t.jsx("button",{className:"card-edit-btn",onClick:Kt,title:"Edit task","aria-label":"Edit task",children:t.jsx(vs,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:an,title:"Delete task","aria-label":"Delete task",children:t.jsx(vn,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Bt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Xt,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:de,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ae,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":F,children:["Send back",t.jsx(rn,{size:10})]}),F&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:ld["in-progress"].filter(ce=>ce!=="in-review").map(ce=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:$e=>Pe($e,ce),children:ns[ce]},ce))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:de,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ae,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":F,children:["Move",t.jsx(rn,{size:10})]}),F&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:ld["in-review"].map(ce=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:$e=>Pe($e,ce),children:ce==="done"?"Done (no merge)":ns[ce]},ce))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Z&&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:Ae,disabled:X,children:[t.jsx(Qv,{size:12}),X?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:pm(e.title,hm)||pm(e.description,hm)||e.id}),ze&&(()=>{const ce=Ie.completed/Ie.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:`${ce}%`,backgroundColor:cS[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[Ie.completed,"/",Ie.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:fe,"aria-expanded":C,"aria-label":C?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[Ie.total," step",Ie.total===1?"":"s"]}),t.jsx(rn,{size:14,className:`card-steps-toggle-icon${C?" expanded":""}`})]}),C&&t.jsx("div",{className:"card-steps-list",children:Ie.items.map($e=>{const it=$e.source==="workflow"&&$e.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${$e.status}${it?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${$e.status==="done"?" completed":""}`,children:$e.name}),$e.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${$e.phase}`,title:"Workflow check",children:"workflow"})]},$e.id)})})]})})(),(je||st||Le)&&t.jsxs("div",{className:"card-footer-row",children:[je,Le&&t.jsx("span",{className:"card-source-provenance",title:Je?`Imported from GitHub: ${Je}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Fn,{provider:"github",size:"sm"})}),st&&t.jsxs("span",{className:"card-time-indicator",title:st.title,"aria-label":st.ariaLabel,children:[t.jsx(Mi,{size:12}),t.jsx("span",{children:st.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(ce=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:$e=>void we($e,ce),title:`Click to view ${ce}`,children:[t.jsx(Ea,{size:12,style:{verticalAlign:"middle"}})," ",ce]},ce))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(ea,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Mi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||mt.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[mt.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:mt.map(ce=>t.jsx(Fn,{provider:ce,size:"sm"},ce))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${nt?" card-agent-badge--loading":""}`,title:`Assigned to ${S??e.assignedAgentId}`,children:[t.jsx(Mn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:oS(S??e.assignedAgentId,15)})]})]}),t.jsx(Sl,{slotId:"task-card-badge",projectId:n})]})}const mm=10,CS=300,hm=140;function pm(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const Lr=i.memo(SS,NS);Lr.displayName="TaskCard";function ES({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(gx,{size:14}):t.jsx(Hs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(Lr,{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(Lr,{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 Mf=i.memo(ES);Mf.displayName="WorktreeGroup";function fm(e){return e.toLowerCase().replace(/[-_./]/g,"")}function MS(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 _S(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 AS(e,n){const s=fm(e),a=fm(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&&MS(s,o)||s.length>=4&&_S(s,o,1))return!0;return!1}function PS(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=>AS(o,r))})}function hs({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),[b,v]=i.useState(""),[x,y]=i.useState(0),[k,N]=i.useState(null),[R,w]=i.useState(null),A=i.useRef(null),P=i.useRef(null),T=i.useRef(null),_=i.useRef(null),C=i.useRef(null),$=i.useMemo(()=>PS(e,b),[e,b]),O=i.useMemo(()=>$.reduce((ee,ie)=>((ee[ie.provider]??=[]).push(ie),ee),{}),[$]),E=i.useMemo(()=>{const ee=[];for(const ie of u){const te=ie.indexOf("/");if(te===-1)continue;const xe=ie.slice(0,te),ne=ie.slice(te+1),_e=$.find(Ne=>Ne.provider===xe&&Ne.id===ne);_e&&ee.push({model:_e,fullId:ie})}return ee},[u,$]),S=i.useMemo(()=>{const ee=Object.entries(O),ie=new Set(c);return ee.sort(([te],[xe])=>{const ne=ie.has(te),_e=ie.has(xe);if(ne&&!_e)return-1;if(!ne&&_e)return 1;if(ne&&_e){const Ne=c.indexOf(te),Se=c.indexOf(xe);if(Ne!==Se)return Ne-Se}return te.localeCompare(xe)})},[O,c]),I=typeof h=="string"&&h.length>0,F=i.useMemo(()=>{if(!n||I&&n===h)return null;const ee=n.indexOf("/");return ee===-1?null:n.slice(0,ee)},[I,h,n]),G=i.useMemo(()=>{const ee=[];return I&&ee.push({type:"no-change",value:h,label:f}),ee.push({type:"default",value:"",label:"Use default"}),ee},[I,f,h]),X=i.useMemo(()=>{const ee=[...G];for(const{model:ie,fullId:te}of E)ee.push({type:"favorite",value:te,label:ie.name,provider:ie.provider});return S.forEach(([ie,te])=>{ee.push({type:"provider",value:`__group_${ie}`,label:ie,provider:ie}),te.forEach(xe=>{ee.push({type:"model",value:`${xe.provider}/${xe.id}`,label:xe.name,provider:xe.provider})})}),ee},[E,S,G]),M=i.useMemo(()=>{if(I&&n===h)return f;if(!n)return"Use default";const ee=n.indexOf("/");if(ee===-1)return n;const ie=n.slice(0,ee),te=n.slice(ee+1);return e.find(ne=>ne.provider===ie&&ne.id===te)?.name||n},[I,f,h,n,e]),z=i.useMemo(()=>X.findIndex(ee=>ee.value===n),[X,n]),L=i.useCallback(()=>{const ee=window.visualViewport;return ee&&ee.height>0&&ee.width>0?{width:ee.width,height:ee.height,offsetTop:ee.offsetTop,offsetLeft:ee.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),j=i.useCallback(()=>{const{height:ee}=L(),ie=typeof window.matchMedia=="function",te=ie?window.matchMedia("(max-width: 640px)").matches:!1,xe=ie?window.matchMedia("(max-width: 768px)").matches:!1;return ee<=0?320:te?Math.min(ee*.6,360):xe?Math.min(ee*.7,420):320},[L]),H=i.useCallback(()=>{const ee=P.current;if(!ee)return;const ie=ee.getBoundingClientRect(),{width:te,height:xe,offsetTop:ne,offsetLeft:_e}=L(),Ne=16,Se=16,He=4,Ye=j(),Oe=ie.bottom-ne,ke=ie.top-ne,De=ie.left-_e,re=xe-Oe,oe=ke,we=Math.max(re-Se-He,160),Z=Math.max(oe-Se-He,160),qe=re<Ye&&oe>re,Qe=Math.max(Math.min(qe?Z:we,Ye),160),ge=Math.min(ie.width,te-Ne*2),Ue=Math.min(Math.max(De,Ne),te-Ne-ge)+_e,Xe=qe?Math.max(Se+ne,ke-Qe-He+ne):Math.min(Oe+He+ne,xe+ne-Se-Qe);N({top:Xe,left:Ue,width:ge,maxHeight:Qe})},[L,j]);i.useEffect(()=>{w(document.body)},[]);const Q=i.useRef(!1);i.useEffect(()=>{if(!p){Q.current=!1;return}if(Q.current||X.length===0)return;const ee=X.findIndex((ie,te)=>te>=(z>=0?z:0)&&ie.type!=="provider");y(ee>=0?ee:0),Q.current=!0},[p,X,z]),i.useEffect(()=>{p&&Q.current&&(y(0),C.current&&(C.current.scrollTop=0))},[b,p]),i.useEffect(()=>{if(!p)return;H();const ee=requestAnimationFrame(()=>_.current?.focus());return()=>cancelAnimationFrame(ee)},[p,H]),i.useEffect(()=>{if(!p)return;const ee=()=>H();window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0);const ie=window.visualViewport;return ie&&(ie.addEventListener("resize",ee),ie.addEventListener("scroll",ee)),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0),ie&&(ie.removeEventListener("resize",ee),ie.removeEventListener("scroll",ee))}},[p,H]),i.useEffect(()=>{if(!p)return;const ee=ie=>{const te=ie.target,xe=A.current?.contains(te),ne=T.current?.contains(te);!xe&&!ne&&(g(!1),v(""))};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[p]);const de=i.useCallback(ee=>{switch(ee.key){case"ArrowDown":if(ee.preventDefault(),!p)g(!0);else{let ie=x;for(let te=1;te<=X.length;te++){const xe=(x+te)%X.length;if(X[xe]?.type!=="provider"){ie=xe;break}}y(ie)}break;case"ArrowUp":if(ee.preventDefault(),p){let ie=x;for(let te=1;te<=X.length;te++){const xe=(x-te+X.length)%X.length;if(X[xe]?.type!=="provider"){ie=xe;break}}y(ie)}break;case"Enter":if(ee.preventDefault(),p){const ie=X[x];ie&&ie.type!=="provider"&&ie.type!=="favorite"&&(s(ie.value),g(!1),v(""))}else g(!0);break;case"Escape":ee.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,x,X,s]),pe=i.useCallback(ee=>{s(ee),g(!1),v("")},[s]),B=i.useCallback(()=>{v(""),_.current?.focus()},[]),ve=i.useCallback(()=>{r||g(ee=>!ee)},[r]);i.useEffect(()=>{if(p&&C.current){const ee=C.current.querySelector(`[data-index="${x}"]`);ee&&typeof ee.scrollIntoView=="function"&&ee.scrollIntoView({block:"nearest"})}},[x,p]);const U=b.length>0,se=p&&k?t.jsxs("div",{ref:T,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:de,style:{top:`${k.top}px`,left:`${k.left}px`,width:`${k.width}px`,maxHeight:`${k.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:_,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:ee=>v(ee.target.value),onClick:ee=>ee.stopPropagation()}),U&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:B,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[$.length," model",$.length!==1?"s":""]}),t.jsxs("div",{ref:C,className:"model-combobox-list",children:[G.map((ee,ie)=>t.jsx("div",{"data-index":ie,className:`model-combobox-option ${x===ie?"model-combobox-option--highlighted":""} ${n===ee.value?"model-combobox-option--selected":""}`,onClick:()=>pe(ee.value),onMouseEnter:()=>y(ie),role:"option","aria-selected":n===ee.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ee.label})},`${ee.type}-${ee.value}`)),E.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),E.map(({model:ee,fullId:ie},te)=>{const xe=te+G.length,ne=x===xe,_e=n===ie;return t.jsxs("div",{"data-index":xe,className:`model-combobox-option model-combobox-option--favorite ${ne?"model-combobox-option--highlighted":""} ${_e?"model-combobox-option--selected":""}`,onClick:()=>pe(ie),onMouseEnter:()=>y(xe),role:"option","aria-selected":_e,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Fn,{provider:ee.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ee.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ee.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:Ne=>{Ne.stopPropagation(),m(ie)},title:"Remove from favorites","aria-label":`Remove ${ee.name} from favorites`,children:"★"})]},ie)}),t.jsx("div",{className:"model-combobox-divider"})]}),S.map(([ee,ie])=>{const te=X.findIndex(_e=>_e.value===`__group_${ee}`),xe=c.includes(ee),ne=ie.filter(_e=>{const Ne=`${_e.provider}/${_e.id}`;return!u.includes(Ne)});return ne.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":te,children:[t.jsx(Fn,{provider:ee,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ee}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${xe?"model-combobox-optgroup-favorite--active":""}`,onClick:_e=>{_e.stopPropagation(),d(ee)},title:xe?"Remove from favorites":"Add to favorites","aria-label":xe?`Remove ${ee} from favorites`:`Add ${ee} to favorites`,children:"★"})]}),ne.map(_e=>{const Ne=`${_e.provider}/${_e.id}`,Se=X.findIndex(ke=>ke.value===Ne),He=x===Se,Ye=n===Ne,Oe=u.includes(Ne);return t.jsxs("div",{"data-index":Se,className:`model-combobox-option ${He?"model-combobox-option--highlighted":""} ${Ye?"model-combobox-option--selected":""}`,onClick:()=>pe(Ne),onMouseEnter:()=>y(Se),role:"option","aria-selected":Ye,children:[t.jsx("span",{className:"model-combobox-option-text",children:_e.name}),t.jsx("span",{className:"model-combobox-option-id",children:_e.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Oe?"model-combobox-option-favorite--active":""}`,onClick:ke=>{ke.stopPropagation(),m(Ne)},title:Oe?"Remove from favorites":"Add to favorites","aria-label":Oe?`Remove ${_e.name} from favorites`:`Add ${_e.name} to favorites`,children:Oe?"★":"☆"})]},Ne)})]},ee)}),$.length===0&&U&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:A,className:"model-combobox",onKeyDown:de,children:t.jsxs("button",{ref:P,type:"button",id:o,className:"model-combobox-trigger",onClick:ve,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[F&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Fn,{provider:F,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:M||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),R&&se?Ji.createPortal(se,R):null]})}function Bd(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Gn(e,n){return typeof window>"u"?null:window.localStorage.getItem(Bd(e,n))}function us(e,n,s){typeof window>"u"||window.localStorage.setItem(Bd(e,s),n)}function Ta(e,n){typeof window>"u"||window.localStorage.removeItem(Bd(e,n))}const RS=1e4,TS=1e3;function El(){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 Zo();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 Zo();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||a(!1)}}g();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<TS||(c.current=v,d())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},RS),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async p=>{const g=await dj(p);return n(b=>[...b,g]),g},[]),m=i.useCallback(async(p,g)=>{const b=await uj(p,g);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=i.useCallback(async p=>{await mj(p),n(g=>g.filter(b=>b.id!==p))},[]),f=i.useCallback(async p=>{const g=await hj(p);n(b=>b.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 nr="kb-quick-entry-text",IS=["image/png","image/jpeg","image/gif","image/webp"];function $S(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Xl(e,n){return e&&n?`${e}/${n}`:""}function Zl(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 _f({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"&&Gn(nr,l)||""),[g,b]=i.useState(!1),[v,x]=i.useState(!1),[y,k]=i.useState(!1),N=i.useRef(null),R=i.useRef(null),w=i.useRef(!1),A=i.useRef(l),[P,T]=i.useState([]),_=i.useRef([]),[C,$]=i.useState([]),[O,E]=i.useState(!1),[S,I]=i.useState(""),[F,G]=i.useState(null),[X,M]=i.useState([]),[z,L]=i.useState(void 0),[j,H]=i.useState(!1),[Q,de]=i.useState(!1),[pe,B]=i.useState(!1),[ve,U]=i.useState(!1),[se,ee]=i.useState(!1),[ie,te]=i.useState(null),[xe,ne]=i.useState(void 0),[_e,Ne]=i.useState(void 0),[Se,He]=i.useState(void 0),[Ye,Oe]=i.useState(void 0),[ke,De]=i.useState(void 0),[re,oe]=i.useState(void 0),we=i.useRef(null),Z=i.useRef(null),qe=i.useRef(null),Qe=i.useRef(null),ge=i.useRef(null),Ue=i.useRef(null),Xe=i.useRef(null),wt=i.useRef(null),[ye,le]=i.useState(null),[Te,be]=i.useState(null),[Le,Je]=i.useState(null),[nt,mt]=i.useState(null),Ie=i.useRef(null),ze=i.useRef(null),[st,yt]=i.useState(null),[Re]=i.useState(()=>typeof document<"u"?document.body:null),[kt,Et]=i.useState(!1),[jt,Rt]=i.useState(null),[Dt,Tt]=i.useState(a??[]),[It,Ut]=i.useState([]),[Ft,Jt]=i.useState([]),[Vt,Yt]=i.useState(null),[Kt,qt]=i.useState(void 0),[Bt,Xt]=i.useState(!1),[an,Qt]=i.useState(Ms),[fe,Fe]=i.useState(void 0),{nodes:ae}=El(),[Pe,Ae]=i.useState(!1),[W,je]=i.useState(!1),ce=i.useRef(null),$e=i.useRef(null),[it,vt]=i.useState(null),tn=d??It,Pt=u??Ft,Lt=!e;i.useEffect(()=>{if(a)Tt(a),Et(!1),Rt(null);else{let Y=!1;return Et(!0),Rt(null),As().then(Ee=>{Y||(Tt(Ee.models),d||Ut(Ee.favoriteProviders),u||Jt(Ee.favoriteModels))}).catch(Ee=>{Y||Rt(Me(Ee)||"Failed to load models")}).finally(()=>{Y||Et(!1)}),jl(l).then(Ee=>{Y||Yt(Ee)}).catch(()=>{}),()=>{Y=!0}}},[a,d,u,l]);const zt=Xl(xe,_e),yn=Xl(Se,Ye),ue=Xl(ke,re),lt=!!(xe&&_e),ut=!!(Se&&Ye),dt=!!(ke&&re),at=Number(lt)+Number(ut)+Number(dt),St=Kt?Vt?.modelPresets?.find(Y=>Y.id===Kt)?.name??"Models":at>0?`${at} model${at===1?"":"s"}`:"Models",he=i.useCallback((Y,Ee)=>{if(!Y||!Ee)return"Using default";const rt=Dt.find(Be=>Be.provider===Y&&Be.id===Ee);return rt?`${rt.provider}/${rt.id}`:`${Y}/${Ee}`},[Dt]);i.useEffect(()=>{p(Gn(nr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&us(nr,f,l)},[f,l]),i.useEffect(()=>{A.current!==l&&(A.current=l,M([]),L(void 0),G(null),H(!1),le(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{_.current=P},[P]),i.useEffect(()=>()=>{_.current.forEach(Y=>URL.revokeObjectURL(Y.previewUrl))},[]);const ct=i.useCallback(()=>{const Y=N.current;if(!Y)return;Y.style.height="auto";const Ee=Math.min(Y.scrollHeight,200);Y.style.height=`${Ee}px`},[]);i.useEffect(()=>{v&&ct()},[f,v,ct]),i.useEffect(()=>{if(!g&&f===""&&N.current){const Y=setTimeout(()=>{N.current?.focus()},0);return()=>clearTimeout(Y)}},[g,f]),i.useEffect(()=>{O||I("")},[O]),i.useEffect(()=>{if(!Pe)return;const Y=Ee=>{const rt=Ee.target,Be=ce.current?.contains(rt),ft=$e.current?.contains(rt);!Be&&!ft&&Ae(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[Pe]),i.useEffect(()=>{if(!se)return;const Y=Ee=>{const rt=Ee.target,Be=we.current?.contains(rt),ft=Z.current?.contains(rt),mn=rt instanceof Element&&rt.closest?.(".model-combobox-dropdown--portal")!=null;!Be&&!ft&&!mn&&(ee(!1),te(null))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[se]),i.useEffect(()=>{if(!Q)return;const Y=Ee=>{const rt=Ee.target;ge.current?.contains(rt)||Ue.current?.contains(rt)||(de(!1),be(null))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[Q]),i.useEffect(()=>{if(!j)return;const Y=Ee=>{const rt=Ee.target;qe.current?.contains(rt)||Qe.current?.contains(rt)||(H(!1),le(null))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[j]),i.useEffect(()=>{if(!pe)return;const Y=Ee=>{const rt=Ee.target;Xe.current?.contains(rt)||wt.current?.contains(rt)||(B(!1),Je(null))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[pe]);const Zt=i.useCallback(()=>{P.forEach(Y=>URL.revokeObjectURL(Y.previewUrl)),T([]),R.current&&(R.current.value=""),p(""),$([]),G(null),H(!1),le(null),de(!1),be(null),B(!1),Je(null),ne(void 0),Ne(void 0),He(void 0),Oe(void 0),De(void 0),oe(void 0),qt(void 0),Xt(!1),Qt(Ms),Fe(void 0),E(!1),ee(!1),mt(null),te(null),Ae(!1),je(!1),x(!1),k(!1),w.current=!0,N.current&&(N.current.style.height="auto"),typeof window<"u"&&Ta(nr,l)},[P,l]),Sn=i.useCallback(Y=>{if(!Y||Y.length===0)return;const Ee=[];for(let rt=0;rt<Y.length;rt++){const Be=Y[rt];IS.includes(Be.type)&&Ee.push({file:Be,previewUrl:URL.createObjectURL(Be)})}Ee.length>0&&T(rt=>[...rt,...Ee])},[]),In=i.useCallback(Y=>{g||Sn(Y.clipboardData?.files)},[Sn,g]),Hn=i.useCallback(Y=>{T(Ee=>{const rt=Ee[Y];return rt&&URL.revokeObjectURL(rt.previewUrl),Ee.filter((Be,ft)=>ft!==Y)})},[]),Xn=i.useCallback(async()=>{const Y=f.trim();if(!Y||g||!e)return;const Ee=f;b(!0),p("");try{const rt=await e({description:Y,column:"triage",dependencies:C.length?C:void 0,...F?{assignedAgentId:F}:{},modelPresetId:Kt,modelProvider:lt?xe:void 0,modelId:lt?_e:void 0,validatorModelProvider:ut?Se:void 0,validatorModelId:ut?Ye:void 0,planningModelProvider:dt?ke:void 0,planningModelId:dt?re:void 0,...Bt?{executionMode:"fast"}:{},priority:an,nodeId:fe});if(rt&&P.length>0){const Be=[];for(const ft of P)try{await Ir(rt.id,ft.file,l)}catch{Be.push(ft.file.name)}Be.length>0&&n(`Failed to upload: ${Be.join(", ")}`,"error")}Zt()}catch(rt){p(Ee),n(Me(rt)||"Failed to create task","error")}finally{b(!1)}},[f,g,e,C,F,lt,xe,_e,ut,Se,Ye,dt,ke,re,P,l,n,Zt,Bt,an,fe]),jn=i.useCallback(Y=>{if(Y.key==="Enter"){if(Y.shiftKey&&v)return;Y.preventDefault(),Xn()}else if(Y.key==="Escape"){if(Y.preventDefault(),ie){te(null);return}if(se){ee(!1),mt(null);return}if(O){E(!1);return}if(Pe){Ae(!1);return}if(Q){de(!1),be(null);return}if(pe){B(!1),Je(null);return}if(j){H(!1),le(null);return}f.trim()&&(p(""),N.current&&(N.current.style.height="auto"),typeof window<"u"&&Ta(nr,l)),x(!1),k(!1),N.current?.blur()}},[Xn,f,v,O,j,Q,se,ie,Pe,pe,l,k]),Pn=i.useCallback(()=>{w.current&&(w.current=!1)},[]),rs=i.useCallback(()=>{c&&x(!0)},[c]),os=i.useCallback(Y=>{$(Ee=>Ee.includes(Y)?Ee.filter(rt=>rt!==Y):[...Ee,Y])},[]),cn=i.useCallback(()=>{const Y=window.visualViewport;return Y&&Y.width>0&&Y.height>0?{width:Y.width,height:Y.height,offsetTop:Y.offsetTop,offsetLeft:Y.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),$n=i.useCallback(()=>{const Y=we.current;if(!Y)return;const Ee=Y.getBoundingClientRect(),{width:rt,height:Be,offsetTop:ft,offsetLeft:mn}=cn(),un=16,on=16,fn=4,Ln=rt<=768,Zn=Math.min(Ln?Be*.6:Be*.5,360),qn=Math.max(Ee.width*1.35,320),es=Ln?Math.min(rt-un*2,360):qn,Un=Math.min(es,Math.max(rt-un*2,240)),En=Ee.top-ft,fs=Ee.bottom-ft,Jn=Ee.left-mn,Bn=Be-fs,gs=En,Vn=Math.max(Bn-on-fn,160),bs=Math.max(gs-on-fn,160),Yn=Bn<Zn&&gs>Bn,Es=Math.max(Math.min(Yn?bs:Vn,Zn),160),Ws=Math.min(Math.max(Jn,un),rt-un-Un)+mn,ua=Yn?Math.max(on+ft,En-Es-fn+ft):Math.min(fs+fn+ft,Be+ft-on-Es);mt({top:ua,left:Ws,width:Un,maxHeight:Es})},[cn]),nn=i.useCallback(()=>{const Y=ce.current?.querySelector(".refine-button");if(!Y)return;const Ee=Y.getBoundingClientRect(),{width:rt,height:Be,offsetTop:ft,offsetLeft:mn}=cn(),un=8,on=12,fn=4,Ln=Math.min(200,Math.max(Be-on*2,160)),Zn=Math.min(200,rt-un*2),qn=Ee.top-ft,es=Ee.bottom-ft,Un=Ee.left-mn,En=Be-es,fs=qn,Jn=En<Ln&&fs>En,Bn=Math.min(Math.max(Un,un),rt-un-Zn)+mn,gs=Jn?Math.max(on+ft,qn-Ln-fn+ft):Math.min(es+fn+ft,Be+ft-on-Ln);vt({top:gs,left:Bn})},[cn]),_t=i.useCallback(()=>{const Y=Ie.current;if(!Y)return;const Ee=Y.getBoundingClientRect(),{width:rt,height:Be,offsetTop:ft,offsetLeft:mn}=cn(),un=16,on=16,fn=4,Ln=rt<=768,Zn=Math.min(Ln?Be*.6:Be*.5,320),qn=Ln?Math.min(rt-un*2,360):Math.max(Ee.width,280),es=Math.min(qn,Math.max(rt-un*2,240)),Un=Ee.top-ft,En=Ee.bottom-ft,fs=Ee.left-mn,Jn=Be-En,Bn=Un,gs=Math.max(Jn-on-fn,200),Vn=Math.max(Bn-on-fn,200),bs=Jn<Zn&&Bn>Jn,Yn=Math.max(Math.min(bs?Vn:gs,Zn),200),Es=Math.min(Math.max(fs,un),rt-un-es)+mn,Ws=bs?Math.max(on+ft,Un-Yn-fn+ft):Math.min(En+fn+ft,Be+ft-on-Yn);yt({top:Ws,left:Es,width:es,maxHeight:Yn})},[cn]),K=i.useCallback(()=>{const Y=qe.current?.querySelector("button");if(!Y)return;const Ee=Y.getBoundingClientRect(),{width:rt,height:Be,offsetTop:ft,offsetLeft:mn}=cn(),un=16,on=16,fn=4,Ln=rt<=768,Zn=Math.min(Ln?Be*.6:Be*.5,320),qn=Ln?Math.min(rt-un*2,280):Math.max(Ee.width,240),es=Math.min(qn,Math.max(rt-un*2,200)),Un=Ee.top-ft,En=Ee.bottom-ft,fs=Ee.left-mn,Jn=Be-En,Bn=Un,gs=Math.max(Jn-on-fn,160),Vn=Math.max(Bn-on-fn,160),bs=Jn<Zn&&Bn>Jn,Yn=Math.max(Math.min(bs?Vn:gs,Zn),160),Es=Math.min(Math.max(fs,un),rt-un-es)+mn,Ws=bs?Math.max(on+ft,Un-Yn-fn+ft):Math.min(En+fn+ft,Be+ft-on-Yn);le({top:Ws,left:Es,width:es,maxHeight:Yn})},[cn]),Ve=i.useCallback(()=>{const Y=ge.current?.querySelector("button");if(!Y)return;const Ee=Y.getBoundingClientRect(),{width:rt,height:Be,offsetTop:ft,offsetLeft:mn}=cn(),un=16,on=16,fn=4,Ln=rt<=768,Zn=Math.min(Ln?Be*.6:Be*.5,320),qn=Ln?Math.min(rt-un*2,280):Math.max(Ee.width,240),es=Math.min(qn,Math.max(rt-un*2,200)),Un=Ee.top-ft,En=Ee.bottom-ft,fs=Ee.left-mn,Jn=Be-En,Bn=Un,gs=Math.max(Jn-on-fn,160),Vn=Math.max(Bn-on-fn,160),bs=Jn<Zn&&Bn>Jn,Yn=Math.max(Math.min(bs?Vn:gs,Zn),160),Es=Math.min(Math.max(fs,un),rt-un-es)+mn,Ws=bs?Math.max(on+ft,Un-Yn-fn+ft):Math.min(En+fn+ft,Be+ft-on-Yn);be({top:Ws,left:Es,width:es,maxHeight:Yn})},[cn]),pt=i.useCallback(()=>{const Y=Xe.current?.querySelector("button");if(!Y)return;const Ee=Y.getBoundingClientRect(),{width:rt,height:Be,offsetTop:ft,offsetLeft:mn}=cn(),un=16,on=16,fn=4,Ln=220,Zn=Math.min(Math.max(Ee.width,200),Math.max(rt-un*2,200)),qn=Ee.top-ft,es=Ee.bottom-ft,Un=Ee.left-mn,En=Be-es,fs=qn,Jn=Math.max(En-on-fn,160),Bn=Math.max(fs-on-fn,160),gs=En<Ln&&fs>En,Vn=Math.max(Math.min(gs?Bn:Jn,Ln),160),bs=Math.min(Math.max(Un,un),rt-un-Zn)+mn,Yn=gs?Math.max(on+ft,qn-Vn-fn+ft):Math.min(es+fn+ft,Be+ft-on-Vn);Je({top:Yn,left:bs,width:Zn,maxHeight:Vn})},[cn]);i.useEffect(()=>{if(!se)return;const Y=()=>$n();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",Y),Ee.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ee&&(Ee.removeEventListener("resize",Y),Ee.removeEventListener("scroll",Y))}},[se,$n]),i.useEffect(()=>{if(!Pe)return;const Y=()=>nn();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",Y),Ee.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ee&&(Ee.removeEventListener("resize",Y),Ee.removeEventListener("scroll",Y))}},[Pe,nn]),i.useEffect(()=>{if(!O)return;const Y=()=>_t();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",Y),Ee.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ee&&(Ee.removeEventListener("resize",Y),Ee.removeEventListener("scroll",Y))}},[O,_t]),i.useEffect(()=>{if(!j)return;const Y=()=>K();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",Y),Ee.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ee&&(Ee.removeEventListener("resize",Y),Ee.removeEventListener("scroll",Y))}},[j,K]),i.useEffect(()=>{if(!Q)return;const Y=()=>Ve();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",Y),Ee.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ee&&(Ee.removeEventListener("resize",Y),Ee.removeEventListener("scroll",Y))}},[Q,Ve]),i.useEffect(()=>{if(!pe)return;const Y=()=>pt();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",Y),Ee.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ee&&(Ee.removeEventListener("resize",Y),Ee.removeEventListener("scroll",Y))}},[pe,pt]);const ht=i.useCallback(Y=>{const Ee=Zl(Y);De(Ee.provider),oe(Ee.modelId)},[]),Nt=i.useCallback(Y=>{const Ee=Zl(Y);ne(Ee.provider),Ne(Ee.modelId)},[]),Mt=i.useCallback(Y=>{const Ee=Zl(Y);He(Ee.provider),Oe(Ee.modelId)},[]),$t=i.useCallback(async Y=>{if(m){m(Y);return}const Ee=It,Be=Ee.includes(Y)?Ee.filter(ft=>ft!==Y):[Y,...Ee];Ut(Be);try{await Cn({favoriteProviders:Be,favoriteModels:Ft})}catch{Ut(Ee)}},[It,Ft,m]),wn=i.useCallback(async Y=>{if(h){h(Y);return}const Ee=Ft,Be=Ee.includes(Y)?Ee.filter(ft=>ft!==Y):[Y,...Ee];Jt(Be);try{await Cn({favoriteProviders:It,favoriteModels:Be})}catch{Jt(Ee)}},[Ft,It,h]),ls=i.useCallback(()=>{const Y=f.trim();if(!Y){n("Enter a description first","error");return}r?.(Y),Zt()},[f,r,n,Zt]),Cs=i.useCallback(()=>{const Y=f.trim();if(!Y){n("Enter a description first","error");return}o?.(Y),Zt()},[f,o,n,Zt]),$s=i.useCallback(()=>{Xn()},[Xn]),ps=i.useCallback(async Y=>{const Ee=f.trim();if(!(!Ee||W)){Ae(!1),je(!0);try{const rt=await af(Ee,Y,l);p(rt),n("Description refined with AI","success"),N.current&&(N.current.style.height="auto",N.current.style.height=`${Math.min(N.current.scrollHeight,200)}px`)}catch(rt){const Be=rf(rt);n(Be,"error")}finally{je(!1)}}},[f,W,n,l]),Vs=(Y,Ee)=>Y.length>Ee?Y.slice(0,Ee)+"…":Y,dn=i.useCallback(async()=>{if(a){Tt(a),Rt(null),Et(!1);return}Et(!0),Rt(null);try{const Y=await As();Tt(Y.models),d||Ut(Y.favoriteProviders),u||Jt(Y.favoriteModels)}catch(Y){Rt(Me(Y)||"Failed to load models")}finally{Et(!1)}},[a,d,u]),yi=i.useCallback(async()=>{if(X.length>0&&z===l){H(!0),K();return}U(!0);try{const Y=await oa(void 0,l);M(Y),L(l),H(!0),K()}catch(Y){const Ee=Me(Y);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),H(!1)}finally{U(!1)}},[X.length,z,l,n,K]),We=(F?X.find(Y=>Y.id===F):void 0)?.name??F,ot=fe?ae.find(Y=>Y.id===fe):void 0,sn=y,Dn=i.useCallback(()=>{k(Y=>{const Ee=!Y;return x(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${y?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:N,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:Y=>p(Y.target.value),onKeyDown:jn,onPaste:In,onFocus:rs,onBlur:Pn,disabled:g||Lt,"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:Dn,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(ri,{size:14}):t.jsx(rn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!sn,"aria-hidden":!sn,children:[sn&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ls,onMouseDown:Y=>Y.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(oi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Cs,onMouseDown:Y=>Y.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(xl,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:ce,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${W?"refine-button--loading":""}`,onClick:()=>{Ae(Y=>{const Ee=!Y;return Ee?nn():vt(null),Ee})},disabled:!f.trim()||W,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),W?"Refining...":"Refine"]}),Pe&&Re&&it&&Ji.createPortal(t.jsxs("div",{ref:$e,className:"refine-menu refine-menu--portal",onMouseDown:Y=>Y.preventDefault(),style:{position:"fixed",top:`${it.top}px`,left:`${it.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ps("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:()=>ps("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:()=>ps("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:()=>ps("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),Re)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Ie,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{E(Y=>{const Ee=!Y;return Ee?(ee(!1),mt(null),te(null),H(!1),le(null),de(!1),be(null),B(!1),Je(null),_t()):yt(null),Ee})},children:[t.jsx(Ea,{size:12,style:{verticalAlign:"middle"}}),C.length>0?`${C.length} deps`:"Deps"]})}),O&&Re&&st&&(()=>{const Y=S.toLowerCase(),Ee=(Y?s.filter(rt=>rt.id.toLowerCase().includes(Y)||rt.title&&rt.title.toLowerCase().includes(Y)||rt.description&&rt.description.toLowerCase().includes(Y)):[...s]).sort((rt,Be)=>{const ft=Be.createdAt.localeCompare(rt.createdAt);if(ft!==0)return ft;const mn=parseInt(rt.id.slice(rt.id.lastIndexOf("-")+1),10)||0;return(parseInt(Be.id.slice(Be.id.lastIndexOf("-")+1),10)||0)-mn});return Ji.createPortal(t.jsxs("div",{ref:ze,className:"dep-dropdown dep-dropdown--portal",onMouseDown:rt=>rt.preventDefault(),style:{position:"fixed",top:`${st.top}px`,left:`${st.left}px`,width:`${st.width}px`,maxHeight:st.maxHeight?`${st.maxHeight}px`:void 0,overflowY:st.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:S,onChange:rt=>I(rt.target.value),onClick:rt=>rt.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(rt=>t.jsxs("div",{className:`dep-dropdown-item${C.includes(rt.id)?" selected":""}`,onMouseDown:Be=>Be.preventDefault(),onClick:()=>os(rt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:rt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Vs(rt.title||rt.description||rt.id,60)})]},rt.id))]}),Re)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>R.current?.click(),children:[t.jsx(Jp,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`Attach (${P.length})`:"Attach"]}),t.jsxs("button",{ref:we,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{E(!1),H(!1),le(null),de(!1),be(null),B(!1),Je(null),te(null),ee(!0),$n()},children:[t.jsx(Pr,{size:12,style:{verticalAlign:"middle"}}),St]}),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:()=>{E(!1),H(!1),le(null),ee(!1),mt(null),te(null),B(!1),Je(null),de(Y=>{const Ee=!Y;return Ee?Ve():be(null),Ee})},children:[t.jsx(Tr,{size:12,style:{verticalAlign:"middle"}}),` ${ot?.name??"Node"}`,ot&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(na,{status:ot.status,showLabel:!0})})]})}),Q&&Re&&Te&&Ji.createPortal(t.jsxs("div",{ref:Ue,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:Y=>Y.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${fe==null?" selected":""}`,onMouseDown:Y=>Y.preventDefault(),onClick:()=>{Fe(void 0),de(!1),be(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),ae.map(Y=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${fe===Y.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{Fe(Y.id),de(!1),be(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(na,{status:Y.status})}),t.jsx("span",{className:"node-picker-item-name",children:Y.name}),t.jsx("span",{className:"node-picker-item-status",children:$S(Y.status)})]},Y.id))]}),Re),t.jsx("div",{className:"agent-trigger-wrap",ref:qe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{j?(H(!1),le(null)):(de(!1),be(null),B(!1),Je(null),yi())},"data-testid":"quick-entry-agent-button",children:[t.jsx(Mn,{size:12,style:{verticalAlign:"middle"}}),We?` ${We}`:" Agent"]})}),j&&Re&&ye&&Ji.createPortal(t.jsxs("div",{ref:Qe,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:Y=>Y.preventDefault(),style:{position:"fixed",top:`${ye.top}px`,left:`${ye.left}px`,width:`${ye.width}px`,maxHeight:ye.maxHeight?`${ye.maxHeight}px`:void 0,overflowY:ye.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),ve&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!ve&&X.filter(Y=>Y.state!=="terminated").map(Y=>t.jsxs("div",{className:`dep-dropdown-item${F===Y.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{G(Y.id===F?null:Y.id),H(!1),le(null)},children:[t.jsx(Mn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:Y.role}),t.jsx("span",{className:"dep-dropdown-title",children:Y.name})]},Y.id)),!ve&&X.filter(Y=>Y.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),F&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:Y=>Y.preventDefault(),onClick:()=>{G(null),H(!1),le(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),Re),t.jsx("div",{className:"priority-trigger-wrap",ref:Xe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{E(!1),H(!1),le(null),de(!1),be(null),ee(!1),mt(null),te(null),B(Y=>{const Ee=!Y;return Ee?pt():Je(null),Ee})},children:[t.jsx(Kx,{size:12,style:{verticalAlign:"middle"}}),` ${an[0].toUpperCase()}${an.slice(1)}`]})}),pe&&Re&&Le&&Ji.createPortal(t.jsxs("div",{ref:wt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:Y=>Y.preventDefault(),style:{position:"fixed",top:`${Le.top}px`,left:`${Le.left}px`,width:`${Le.width}px`,maxHeight:Le.maxHeight?`${Le.maxHeight}px`:void 0,overflowY:Le.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),Xr.map(Y=>{const Ee=`${Y[0].toUpperCase()}${Y.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${an===Y?" selected":""}`,"data-testid":`quick-entry-priority-option-${Y}`,onMouseDown:rt=>rt.preventDefault(),onClick:()=>{Qt(Y),B(!1),Je(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:Ee})},Y)})]}),Re),t.jsx("button",{type:"button",className:`btn btn-sm ${Bt?"btn-primary":""}`,onClick:()=>Xt(Y=>!Y),onMouseDown:Y=>Y.preventDefault(),"aria-pressed":Bt,"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:$s,onMouseDown:Y=>Y.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Qp,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),P.length>0&&t.jsx("div",{className:"inline-create-previews",children:P.map((Y,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:Y.previewUrl,alt:Y.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Hn(Ee),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},Y.previewUrl))}),se&&Re&&nt&&Ji.createPortal(t.jsx("div",{ref:Z,className:"model-nested-menu model-nested-menu--portal",onMouseDown:Y=>Y.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${nt.top}px`,left:`${nt.left}px`,width:`${nt.width}px`,maxHeight:nt.maxHeight?`${nt.maxHeight}px`:void 0,overflowY:nt.maxHeight?"auto":void 0},children:ie===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${dt?"model-menu-item--active":""}`,onClick:()=>te("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(oi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:dt?he(ke,re):"Using default"}),t.jsx(_n,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${lt?"model-menu-item--active":""}`,onClick:()=>te("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:lt?he(xe,_e):"Using default"}),t.jsx(_n,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${ut?"model-menu-item--active":""}`,onClick:()=>te("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Pr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:ut?he(Se,Ye):"Using default"}),t.jsx(_n,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>te(null),"data-testid":"model-submenu-back",children:[t.jsx(rn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ie==="plan"&&"Plan Model",ie==="executor"&&"Executor Model",ie==="validator"&&"Reviewer Model"]}),t.jsx(hs,{models:Dt,value:ie==="plan"?ue:ie==="executor"?zt:yn,onChange:ie==="plan"?ht:ie==="executor"?Nt:Mt,placeholder:"Using default",disabled:kt,id:`model-${ie}-select`,label:`${ie} model`,favoriteProviders:tn,onToggleFavorite:$t,favoriteModels:Pt,onToggleModelFavorite:wn}),jt&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:jt}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:dn,children:"Retry"})]})]})}),Re)]}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:Y=>{Sn(Y.target.files),Y.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function DS(e){return Ud(e)||e}function LS(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 zS(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 b=g.worktree,v=o.get(b)||[];v.push(g),o.set(b,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(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=LS(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:DS(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 gm=100,ec=50,bm=25;function OS({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:b,onUnarchiveTask:v,onDeleteTask:x,onArchiveAllDone:y,collapsed:k,onToggleCollapse:N,allTasks:R,availableModels:w,onPlanningMode:A,onSubtaskBreakdown:P,onOpenDetailWithTab:T,favoriteProviders:_,favoriteModels:C,onToggleFavorite:$,onToggleModelFavorite:O,isSearchActive:E,taskStuckTimeoutMs:S,onOpenMission:I,lastFetchTimeMs:F,workflowStepNameLookup:G}){const[X,M]=i.useState(!1),[z,L]=i.useState(ec),[j,H]=i.useState(!1),[Q,de]=i.useState(!1),[pe,B]=i.useState(!1),[ve,U]=i.useState(!1),se=i.useRef(null),ee=E1(n.length),{confirm:ie}=qs();i.useEffect(()=>{if(!j)return;function Ue(wt){se.current?.contains(wt.target)||H(!1)}function Xe(wt){wt.key==="Escape"&&H(!1)}return document.addEventListener("mousedown",Ue),document.addEventListener("keydown",Xe),()=>{document.removeEventListener("mousedown",Ue),document.removeEventListener("keydown",Xe)}},[j]);const te=e==="archived",xe=te&&k,ne=!te&&!E&&e!=="in-progress"&&n.length>gm;i.useEffect(()=>{L(Ue=>e==="in-progress"||te||n.length<=gm?ec:Math.min(Math.max(Ue,ec),n.length))},[e,te,n.length]);const _e=i.useCallback(Ue=>{te||(Ue.preventDefault(),Ue.dataTransfer.dropEffect="move",M(!0))},[te]),Ne=i.useCallback(Ue=>{Ue.currentTarget.contains(Ue.relatedTarget)||M(!1)},[]),Se=i.useCallback(async Ue=>{Ue.preventDefault(),M(!1);const Xe=Ue.dataTransfer.getData("text/plain");if(!Xe)return;const wt=n.find(ye=>ye.id===Xe);if(!(wt&&wt.column===e))try{const le=(R?.find(Le=>Le.id===Xe)??wt)?.steps.some(Le=>Le.status!=="pending")??!1,Te=(e==="todo"||e==="triage")&&le;let be;if(Te){if(await ie({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))be={preserveProgress:!0};else if(!await ie({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(Xe,e,be)}catch(ye){c(Me(ye),"error")}},[c,R,e,ie,r,n]),He=i.useMemo(()=>e!=="in-progress"?[]:zS(n,n,a),[e,n,a]),Ye=i.useMemo(()=>ne?n.slice(0,z):n,[ne,n,z]),Oe=Math.max(0,n.length-Ye.length),ke=i.useCallback(()=>{L(Ue=>Math.min(Ue+bm,n.length))},[n.length]),De=i.useCallback(async()=>{if(H(!1),!(n.length===0||!await ie({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){de(!0);try{const Xe=await Promise.allSettled(n.map(le=>r(le.id,"triage"))),wt=Xe.filter(le=>le.status==="rejected").length,ye=Xe.length-wt;wt===0?c(`Moved ${ye} task${ye===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${ye} of ${Xe.length} tasks; ${wt} failed`,"error")}finally{de(!1)}}},[n,r,c,ie]),re=i.useMemo(()=>n.filter(Ue=>!Ue.paused),[n]),oe=re.length,we=e==="todo"||e==="in-progress"||e==="in-review",Z=Q||pe||ve,qe=i.useCallback(async()=>{if(!(!o||(H(!1),oe===0)||!await ie({title:"Stop All Tasks",message:`Stop all ${oe} ${ns[e].toLowerCase()} task${oe===1?"":"s"}?`,danger:!0}))){B(!0);try{const Xe=await Promise.allSettled(re.map(le=>o(le.id))),wt=Xe.filter(le=>le.status==="rejected").length,ye=Xe.length-wt;wt===0?c(`Stopped ${ye} task${ye===1?"":"s"}`,"success"):c(`Stopped ${ye} of ${Xe.length} tasks; ${wt} failed`,"error")}finally{B(!1)}}},[o,oe,e,re,c,ie]),Qe=i.useCallback(async()=>{if(H(!1),n.length===0||!await ie({title:"Move All to Todo",message:`Move all ${n.length} ${ns[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const Xe=n.some(ye=>ye.steps.some(le=>le.status!=="pending"));let wt=!1;if(Xe){if(await ie({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))wt=!0;else if(!await ie({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}U(!0);try{const ye=await Promise.allSettled(n.map(be=>r(be.id,"todo",wt?{preserveProgress:!0}:void 0))),le=ye.filter(be=>be.status==="rejected").length,Te=ye.length-le;le===0?c(`Moved ${Te} task${Te===1?"":"s"} to Todo`,"success"):c(`Moved ${Te} of ${ye.length} tasks to Todo; ${le} failed`,"error")}finally{U(!1)}},[n,e,r,c,ie]),ge=i.useCallback(async()=>{if(!(!y||n.length===0||!await ie({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const Xe=await y();c(`Archived ${Xe.length} tasks`,"success")}catch(Xe){c(Me(Xe)||"Failed to archive tasks","error")}},[y,n.length,c,ie]);return t.jsxs("div",{className:`column${X?" drag-over":""}${te?" column-archived":""}${xe?" column-collapsed":""}`,"data-column":e,onDragOver:_e,onDragLeave:Ne,onDrop:Se,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ns[e]}),t.jsx("span",{className:`column-count${ee?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),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(Ur,{})}),te&&N&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:N,title:k?"Expand archived tasks":"Collapse archived tasks","aria-label":k?"Expand archived tasks":"Collapse archived tasks",children:k?t.jsx(rn,{size:16}):t.jsx(ri,{size:16})}),we&&t.jsxs("div",{className:"column-menu",ref:se,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(Ue=>!Ue),"aria-haspopup":"menu","aria-expanded":j,"aria-label":`${ns[e]} column actions`,title:"Column actions",disabled:Z,children:t.jsx(Ex,{})}),j&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void De(),disabled:n.length===0||Q,children:["Replan All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Planning"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void qe(),disabled:oe===0||pe||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":oe===0?"All tasks are already paused":`Pause ${oe} active task${oe===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Qe(),disabled:n.length===0||ve,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!xe&&t.jsx("p",{className:"column-desc",children:S1[e]}),!xe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(_f,{onCreate:d,addToast:c,tasks:R??[],availableModels:w,onPlanningMode:A,onSubtaskBreakdown:P,projectId:s,autoExpand:!1,favoriteProviders:_,favoriteModels:C,onToggleFavorite:$,onToggleModelFavorite:O}),e==="in-progress"?He.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):He.map(Ue=>t.jsx(Mf,{label:Ue.label,activeTasks:Ue.activeTasks,queuedTasks:Ue.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:T,taskStuckTimeoutMs:S,onOpenMission:I,lastFetchTimeMs:F,workflowStepNameLookup:G},Ue.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Ye.map(Ue=>t.jsx(Lr,{task:Ue,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:b,onUnarchiveTask:v,onDeleteTask:x,onOpenDetailWithTab:T,taskStuckTimeoutMs:S,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:F,workflowStepNameLookup:G},Ue.id)),ne&&Oe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ke,children:["Load ",Math.min(bm,Oe)," more (",Oe," remaining)"]})]}),t.jsx(Sl,{slotId:"board-column-footer",projectId:s})]})]})}const Af=i.memo(OS);Af.displayName="Column";function FS(e,n){return[...e].sort((s,a)=>{if(n==="in-review"){const r=s.status==="merging"||s.status==="merging-pr",o=a.status==="merging"||a.status==="merging-pr";if(r!==o)return r?-1:1}return s.columnMovedAt&&a.columnMovedAt?a.columnMovedAt.localeCompare(s.columnMovedAt):s.columnMovedAt&&!a.columnMovedAt?-1:!s.columnMovedAt&&a.columnMovedAt?1:s.createdAt.localeCompare(a.createdAt)})}function US(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const xm=new Map;function BS(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 HS({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:b,onDeleteTask:v,onArchiveAllDone:x,onLoadArchivedTasks:y,searchQuery:k="",availableModels:N,onPlanningMode:R,onSubtaskBreakdown:w,onOpenDetailWithTab:A,favoriteProviders:P,favoriteModels:T,onToggleFavorite:_,onToggleModelFavorite:C,taskStuckTimeoutMs:$,onOpenMission:O,lastFetchTimeMs:E}){const[S,I]=i.useState(!0),F=i.useRef(!1),{fetchBatch:G}=W1(n),X=i.useRef(null),[M,z]=i.useState(xm),L=k.trim()!=="",j=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),H=i.useCallback(()=>{I(pe=>{const B=!pe;return!B&&!F.current&&y&&(F.current=!0,y()),B})},[y]),Q=i.useMemo(()=>{const pe=Object.fromEntries(Xi.map(U=>[U,[]]));for(const U of e)pe[U.column].push(U);const B=j.current,ve={};for(const U of Xi){const se=FS(pe[U],U);ve[U]=US(B[U],se)?B[U]:se}return j.current=ve,ve},[e]);i.useEffect(()=>{let pe=!1;return Jr(n).then(B=>{if(pe)return;const ve=new Map(B.map(U=>[U.id,U.name]));z(U=>BS(U,ve)?U:ve)}).catch(()=>{pe||z(B=>B.size===0?B:xm)}),()=>{pe=!0}},[n]);const de=i.useMemo(()=>e.filter(pe=>pe.prInfo||pe.issueInfo).map(pe=>pe.id),[e]);return i.useEffect(()=>{if(de.length!==0)return X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{const pe=[];for(let B=0;B<de.length;B+=50)pe.push(de.slice(B,B+50));pe.forEach(B=>{G(B)})},500),()=>{X.current&&clearTimeout(X.current)}},[de,G]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Xi.map(pe=>t.jsx(Af,{column:pe,tasks:Q[pe],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:b,onDeleteTask:v,allTasks:e,availableModels:N,onOpenDetailWithTab:A,favoriteProviders:P,favoriteModels:T,onToggleFavorite:_,onToggleModelFavorite:C,isSearchActive:L,taskStuckTimeoutMs:$,onOpenMission:O,lastFetchTimeMs:E,workflowStepNameLookup:M,...pe==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:R,onSubtaskBreakdown:w}:{},...pe==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...pe==="done"?{onArchiveAllDone:x}:{},...pe==="archived"?{collapsed:S,onToggleCollapse:H}:{}},pe))})})}function xi(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 Ai(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 qS(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const VS=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,WS=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,KS={};function vm(e,n){return(KS.jsx?WS:VS).test(e)}const GS=/[ \t\n\f\r]/g;function JS(e){return typeof e=="object"?e.type==="text"?ym(e.value):!1:ym(e)}function ym(e){return e.replace(GS,"")===""}class Zr{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Zr.prototype.normal={};Zr.prototype.property={};Zr.prototype.space=void 0;function Pf(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Zr(s,a,n)}function md(e){return e.toLowerCase()}class Is{constructor(n,s){this.attribute=s,this.property=n}}Is.prototype.attribute="";Is.prototype.booleanish=!1;Is.prototype.boolean=!1;Is.prototype.commaOrSpaceSeparated=!1;Is.prototype.commaSeparated=!1;Is.prototype.defined=!1;Is.prototype.mustUseProperty=!1;Is.prototype.number=!1;Is.prototype.overloadedBoolean=!1;Is.prototype.property="";Is.prototype.spaceSeparated=!1;Is.prototype.space=void 0;let YS=0;const en=ca(),ts=ca(),hd=ca(),gt=ca(),Rn=ca(),Ca=ca(),Ls=ca();function ca(){return 2**++YS}const pd=Object.freeze(Object.defineProperty({__proto__:null,boolean:en,booleanish:ts,commaOrSpaceSeparated:Ls,commaSeparated:Ca,number:gt,overloadedBoolean:hd,spaceSeparated:Rn},Symbol.toStringTag,{value:"Module"})),tc=Object.keys(pd);class Hd extends Is{constructor(n,s,a,r){let o=-1;if(super(n,s),wm(this,"space",r),typeof a=="number")for(;++o<tc.length;){const l=tc[o];wm(this,tc[o],(a&pd[l])===pd[l])}}}Hd.prototype.defined=!0;function wm(e,n,s){s&&(e[n]=s)}function Va(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new Hd(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[md(a)]=a,s[md(o.attribute)]=a}return new Zr(n,s,e.space)}const Rf=Va({properties:{ariaActiveDescendant:null,ariaAtomic:ts,ariaAutoComplete:null,ariaBusy:ts,ariaChecked:ts,ariaColCount:gt,ariaColIndex:gt,ariaColSpan:gt,ariaControls:Rn,ariaCurrent:null,ariaDescribedBy:Rn,ariaDetails:null,ariaDisabled:ts,ariaDropEffect:Rn,ariaErrorMessage:null,ariaExpanded:ts,ariaFlowTo:Rn,ariaGrabbed:ts,ariaHasPopup:null,ariaHidden:ts,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Rn,ariaLevel:gt,ariaLive:null,ariaModal:ts,ariaMultiLine:ts,ariaMultiSelectable:ts,ariaOrientation:null,ariaOwns:Rn,ariaPlaceholder:null,ariaPosInSet:gt,ariaPressed:ts,ariaReadOnly:ts,ariaRelevant:null,ariaRequired:ts,ariaRoleDescription:Rn,ariaRowCount:gt,ariaRowIndex:gt,ariaRowSpan:gt,ariaSelected:ts,ariaSetSize:gt,ariaSort:null,ariaValueMax:gt,ariaValueMin:gt,ariaValueNow:gt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Tf(e,n){return n in e?e[n]:n}function If(e,n){return Tf(e,n.toLowerCase())}const QS=Va({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ca,acceptCharset:Rn,accessKey:Rn,action:null,allow:null,allowFullScreen:en,allowPaymentRequest:en,allowUserMedia:en,alt:null,as:null,async:en,autoCapitalize:null,autoComplete:Rn,autoFocus:en,autoPlay:en,blocking:Rn,capture:null,charSet:null,checked:en,cite:null,className:Rn,cols:gt,colSpan:null,content:null,contentEditable:ts,controls:en,controlsList:Rn,coords:gt|Ca,crossOrigin:null,data:null,dateTime:null,decoding:null,default:en,defer:en,dir:null,dirName:null,disabled:en,download:hd,draggable:ts,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:en,formTarget:null,headers:Rn,height:gt,hidden:hd,high:gt,href:null,hrefLang:null,htmlFor:Rn,httpEquiv:Rn,id:null,imageSizes:null,imageSrcSet:null,inert:en,inputMode:null,integrity:null,is:null,isMap:en,itemId:null,itemProp:Rn,itemRef:Rn,itemScope:en,itemType:Rn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:en,low:gt,manifest:null,max:null,maxLength:gt,media:null,method:null,min:null,minLength:gt,multiple:en,muted:en,name:null,nonce:null,noModule:en,noValidate:en,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:en,optimum:gt,pattern:null,ping:Rn,placeholder:null,playsInline:en,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:en,referrerPolicy:null,rel:Rn,required:en,reversed:en,rows:gt,rowSpan:gt,sandbox:Rn,scope:null,scoped:en,seamless:en,selected:en,shadowRootClonable:en,shadowRootDelegatesFocus:en,shadowRootMode:null,shape:null,size:gt,sizes:null,slot:null,span:gt,spellCheck:ts,src:null,srcDoc:null,srcLang:null,srcSet:null,start:gt,step:null,style:null,tabIndex:gt,target:null,title:null,translate:null,type:null,typeMustMatch:en,useMap:null,value:ts,width:gt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Rn,axis:null,background:null,bgColor:null,border:gt,borderColor:null,bottomMargin:gt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:en,declare:en,event:null,face:null,frame:null,frameBorder:null,hSpace:gt,leftMargin:gt,link:null,longDesc:null,lowSrc:null,marginHeight:gt,marginWidth:gt,noResize:en,noHref:en,noShade:en,noWrap:en,object:null,profile:null,prompt:null,rev:null,rightMargin:gt,rules:null,scheme:null,scrolling:ts,standby:null,summary:null,text:null,topMargin:gt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:gt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:en,disableRemotePlayback:en,prefix:null,property:null,results:gt,security:null,unselectable:null},space:"html",transform:If}),XS=Va({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:Ls,accentHeight:gt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:gt,amplitude:gt,arabicForm:null,ascent:gt,attributeName:null,attributeType:null,azimuth:gt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:gt,by:null,calcMode:null,capHeight:gt,className:Rn,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:gt,diffuseConstant:gt,direction:null,display:null,dur:null,divisor:gt,dominantBaseline:null,download:en,dx:null,dy:null,edgeMode:null,editable:null,elevation:gt,enableBackground:null,end:null,event:null,exponent:gt,externalResourcesRequired:null,fill:null,fillOpacity:gt,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:Ca,g2:Ca,glyphName:Ca,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:gt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:gt,horizOriginX:gt,horizOriginY:gt,id:null,ideographic:gt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:gt,k:gt,k1:gt,k2:gt,k3:gt,k4:gt,kernelMatrix:Ls,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:gt,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:gt,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:gt,overlineThickness:gt,paintOrder:null,panose1:null,path:null,pathLength:gt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Rn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:gt,pointsAtY:gt,pointsAtZ:gt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:Ls,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:Ls,rev:Ls,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:Ls,requiredFeatures:Ls,requiredFonts:Ls,requiredFormats:Ls,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:gt,specularExponent:gt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:gt,strikethroughThickness:gt,string:null,stroke:null,strokeDashArray:Ls,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:gt,strokeOpacity:gt,strokeWidth:null,style:null,surfaceScale:gt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:Ls,tabIndex:gt,tableValues:null,target:null,targetX:gt,targetY:gt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:Ls,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:gt,underlineThickness:gt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:gt,values:null,vAlphabetic:gt,vMathematical:gt,vectorEffect:null,vHanging:gt,vIdeographic:gt,version:null,vertAdvY:gt,vertOriginX:gt,vertOriginY:gt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:gt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Tf}),$f=Va({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()}}),Df=Va({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:If}),Lf=Va({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),ZS={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"},e0=/[A-Z]/g,km=/-[a-z]/g,t0=/^data[-\w.:]+$/i;function n0(e,n){const s=md(n);let a=n,r=Is;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&t0.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(km,i0);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!km.test(o)){let l=o.replace(e0,s0);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Hd}return new r(a,n)}function s0(e){return"-"+e.toLowerCase()}function i0(e){return e.charAt(1).toUpperCase()}const a0=Pf([Rf,QS,$f,Df,Lf],"html"),qd=Pf([Rf,XS,$f,Df,Lf],"svg");function r0(e){return e.join(" ").trim()}var ga={},nc,jm;function o0(){if(jm)return nc;jm=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,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var y=1,k=1;function N(E){var S=E.match(n);S&&(y+=S.length);var I=E.lastIndexOf(d);k=~I?E.length-I:k+E.length}function R(){var E={line:y,column:k};return function(S){return S.position=new w(E),T(),S}}function w(E){this.start=E,this.end={line:y,column:k},this.source=x.source}w.prototype.content=v;function A(E){var S=new Error(x.source+":"+y+":"+k+": "+E);if(S.reason=E,S.filename=x.source,S.line=y,S.column=k,S.source=v,!x.silent)throw S}function P(E){var S=E.exec(v);if(S){var I=S[0];return N(I),v=v.slice(I.length),S}}function T(){P(s)}function _(E){var S;for(E=E||[];S=C();)S!==!1&&E.push(S);return E}function C(){var E=R();if(!(u!=v.charAt(0)||m!=v.charAt(1))){for(var S=2;h!=v.charAt(S)&&(m!=v.charAt(S)||u!=v.charAt(S+1));)++S;if(S+=2,h===v.charAt(S-1))return A("End of comment missing");var I=v.slice(2,S-2);return k+=2,N(I),v=v.slice(S),k+=2,E({type:f,comment:I})}}function $(){var E=R(),S=P(a);if(S){if(C(),!P(r))return A("property missing ':'");var I=P(o),F=E({type:p,property:b(S[0].replace(e,h)),value:I?b(I[0].replace(e,h)):h});return P(l),F}}function O(){var E=[];_(E);for(var S;S=$();)S!==!1&&(E.push(S),_(E));return E}return T(),O()}function b(v){return v?v.replace(c,h):h}return nc=g,nc}var Nm;function l0(){if(Nm)return ga;Nm=1;var e=ga&&ga.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(ga,"__esModule",{value:!0}),ga.default=s;const n=e(o0());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 ga}var sr={},Sm;function c0(){if(Sm)return sr;Sm=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.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 sr.camelCase=d,sr}var ir,Cm;function d0(){if(Cm)return ir;Cm=1;var e=ir&&ir.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(l0()),s=c0();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,ir=a,ir}var u0=d0();const m0=Fp(u0),zf=Of("end"),Vd=Of("start");function Of(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 h0(e){const n=Vd(e),s=zf(e);if(n&&s)return{start:n,end:s}}function Mr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Em(e.position):"start"in e||"end"in e?Em(e):"line"in e||"column"in e?fd(e):""}function fd(e){return Mm(e&&e.line)+":"+Mm(e&&e.column)}function Em(e){return fd(e&&e.start)+"-"+fd(e&&e.end)}function Mm(e){return e&&typeof e=="number"?e:1}class Ss 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=Mr(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}}Ss.prototype.file="";Ss.prototype.name="";Ss.prototype.reason="";Ss.prototype.message="";Ss.prototype.stack="";Ss.prototype.column=void 0;Ss.prototype.line=void 0;Ss.prototype.ancestors=void 0;Ss.prototype.cause=void 0;Ss.prototype.fatal=void 0;Ss.prototype.place=void 0;Ss.prototype.ruleId=void 0;Ss.prototype.source=void 0;const Wd={}.hasOwnProperty,p0=new Map,f0=/[A-Z]/g,g0=new Set(["table","tbody","thead","tfoot","tr"]),b0=new Set(["td","th"]),Ff="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function x0(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=C0(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=S0(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"?qd:a0,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Uf(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Uf(e,n,s){if(n.type==="element")return v0(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return y0(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return k0(e,n,s);if(n.type==="mdxjsEsm")return w0(e,n);if(n.type==="root")return j0(e,n,s);if(n.type==="text")return N0(e,n)}function v0(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=qd,e.schema=r),e.ancestors.push(n);const o=Hf(e,n.tagName,!1),l=E0(e,n);let c=Gd(e,n);return g0.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!JS(d):!0})),Bf(e,l,o,n),Kd(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function y0(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)}zr(e,n.position)}function w0(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);zr(e,n.position)}function k0(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=qd,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Hf(e,n.name,!0),l=M0(e,n),c=Gd(e,n);return Bf(e,l,o,n),Kd(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function j0(e,n,s){const a={};return Kd(a,Gd(e,n)),e.create(n,e.Fragment,a,s)}function N0(e,n){return n.value}function Bf(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function Kd(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function S0(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 C0(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=Vd(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 E0(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&Wd.call(n.properties,r)){const o=_0(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&b0.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 M0(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 zr(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 zr(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function Gd(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:p0;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=Uf(e,o,l);c!==void 0&&s.push(c)}return s}function _0(e,n,s){const a=n0(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?qS(s):r0(s)),a.property==="style"){let r=typeof s=="object"?s:A0(e,String(s));return e.stylePropertyNameCase==="css"&&(r=P0(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?ZS[a.property]||a.property:a.attribute,s]}}function A0(e,n){try{return m0(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Ss("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=Ff+"#cannot-parse-style-attribute",r}}function Hf(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=vm(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=vm(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return Wd.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);zr(e)}function zr(e,n){const s=new Ss("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=Ff+"#cannot-handle-mdx-estrees-without-createevaluater",s}function P0(e){const n={};let s;for(s in e)Wd.call(e,s)&&(n[R0(s)]=e[s]);return n}function R0(e){let n=e.replace(f0,T0);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function T0(e){return"-"+e.toLowerCase()}const sc={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"]},I0={};function Jd(e,n){const s=I0,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return qf(e,a,r)}function qf(e,n,s){if($0(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 _m(e.children,n,s)}return Array.isArray(e)?_m(e,n,s):""}function _m(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=qf(e[r],n,s);return a.join("")}function $0(e){return!!(e&&typeof e=="object")}const Am=document.createElement("i");function Yd(e){const n="&"+e+";";Am.innerHTML=n;const s=Am.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Us(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 Xs(e,n){return e.length>0?(Us(e,e.length,0,n),e):n}const Pm={}.hasOwnProperty;function Vf(e){const n={};let s=-1;for(;++s<e.length;)D0(n,e[s]);return n}function D0(e,n){let s;for(s in n){const r=(Pm.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){Pm.call(r,l)||(r[l]=[]);const c=o[l];L0(r[l],Array.isArray(c)?c:c?[c]:[])}}}function L0(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Us(e,0,0,a)}function Wf(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 ai(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const _s=Fi(/[A-Za-z]/),js=Fi(/[\dA-Za-z]/),z0=Fi(/[#-'*+\--9=?A-Z^-~]/);function sl(e){return e!==null&&(e<32||e===127)}const gd=Fi(/\d/),O0=Fi(/[\dA-Fa-f]/),F0=Fi(/[!-/:-@[-`{-~]/);function Ot(e){return e!==null&&e<-2}function An(e){return e!==null&&(e<0||e===32)}function ln(e){return e===-2||e===-1||e===32}const Ml=Fi(/\p{P}|\p{S}/u),ia=Fi(/\s/);function Fi(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Wa(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&js(e.charCodeAt(s+1))&&js(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 gn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return ln(d)?(e.enter(s),c(d)):n(d)}function c(d){return ln(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const U0={tokenize:B0};function B0(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"),gn(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 H0={tokenize:q0},Rm={tokenize:V0};function q0(e){const n=this,s=[];let a=0,r,o,l;return c;function c(k){if(a<s.length){const N=s[a];return n.containerState=N[1],e.attempt(N[0].continuation,d,u)(k)}return u(k)}function d(k){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const N=n.events.length;let R=N,w;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){w=n.events[R][1].end;break}x(a);let A=N;for(;A<n.events.length;)n.events[A][1].end={...w},A++;return Us(n.events,R+1,0,n.events.slice(N)),n.events.length=A,u(k)}return c(k)}function u(k){if(a===s.length){if(!r)return f(k);if(r.currentConstruct&&r.currentConstruct.concrete)return g(k);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(Rm,m,h)(k)}function m(k){return r&&y(),x(a),f(k)}function h(k){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(k)}function f(k){return n.containerState={},e.attempt(Rm,p,g)(k)}function p(k){return a++,s.push([n.currentConstruct,n.containerState]),f(k)}function g(k){if(k===null){r&&y(),x(0),e.consume(k);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(k)}function b(k){if(k===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(k);return}return Ot(k)?(e.consume(k),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(k),b)}function v(k,N){const R=n.sliceStream(k);if(N&&R.push(null),k.previous=o,o&&(o.next=k),o=k,r.defineSkip(k.start),r.write(R),n.parser.lazy[k.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const A=n.events.length;let P=A,T,_;for(;P--;)if(n.events[P][0]==="exit"&&n.events[P][1].type==="chunkFlow"){if(T){_=n.events[P][1].end;break}T=!0}for(x(a),w=A;w<n.events.length;)n.events[w][1].end={..._},w++;Us(n.events,P+1,0,n.events.slice(A)),n.events.length=w}}function x(k){let N=s.length;for(;N-- >k;){const R=s[N];n.containerState=R[1],R[0].exit.call(n,e)}s.length=k}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function V0(e,n,s){return gn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Ia(e){if(e===null||An(e)||ia(e))return 1;if(Ml(e))return 2}function _l(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 bd={name:"attention",resolveAll:W0,tokenize:K0};function W0(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};Tm(h,-d),Tm(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=Xs(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=Xs(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=Xs(u,_l(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=Xs(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=Xs(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Us(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 K0(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Ia(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=Ia(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 Tm(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const G0={name:"autolink",tokenize:J0};function J0(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||js(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||js(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||sl(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):z0(p)?(e.consume(p),u):s(p)}function m(p){return js(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||js(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const eo={partial:!0,tokenize:Y0};function Y0(e,n,s){return a;function a(o){return ln(o)?gn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Ot(o)?n(o):s(o)}}const Kf={continuation:{tokenize:X0},exit:Z0,name:"blockQuote",tokenize:Q0};function Q0(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 ln(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function X0(e,n,s){const a=this;return r;function r(l){return ln(l)?gn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Kf,n,s)(l)}}function Z0(e){e.exit("blockQuote")}const Gf={name:"characterEscape",tokenize:eC};function eC(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 F0(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const Jf={name:"characterReference",tokenize:tC};function tC(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=js,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=O0,m):(e.enter("characterReferenceValue"),o=7,l=gd,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===js&&!Yd(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 Im={partial:!0,tokenize:sC},$m={concrete:!0,name:"codeFenced",tokenize:nC};function nC(e,n,s){const a=this,r={partial:!0,tokenize:R};let o=0,l=0,c;return d;function d(w){return u(w)}function u(w){const A=a.events[a.events.length-1];return o=A&&A[1].type==="linePrefix"?A[2].sliceSerialize(A[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),ln(w)?gn(e,h,"whitespace")(w):h(w))}function h(w){return w===null||Ot(w)?(e.exit("codeFencedFence"),a.interrupt?n(w):e.check(Im,b,N)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||Ot(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):ln(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),gn(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),f)}function p(w){return w===null||Ot(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||Ot(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),g)}function b(w){return e.attempt(r,N,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),x}function x(w){return o>0&&ln(w)?gn(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||Ot(w)?e.check(Im,b,N)(w):(e.enter("codeFlowValue"),k(w))}function k(w){return w===null||Ot(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),k)}function N(w){return e.exit("codeFenced"),n(w)}function R(w,A,P){let T=0;return _;function _(S){return w.enter("lineEnding"),w.consume(S),w.exit("lineEnding"),C}function C(S){return w.enter("codeFencedFence"),ln(S)?gn(w,$,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(S):$(S)}function $(S){return S===c?(w.enter("codeFencedFenceSequence"),O(S)):P(S)}function O(S){return S===c?(T++,w.consume(S),O):T>=l?(w.exit("codeFencedFenceSequence"),ln(S)?gn(w,E,"whitespace")(S):E(S)):P(S)}function E(S){return S===null||Ot(S)?(w.exit("codeFencedFence"),A(S)):P(S)}}}function sC(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 ic={name:"codeIndented",tokenize:aC},iC={partial:!0,tokenize:rC};function aC(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),gn(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(iC,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 rC(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):gn(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 oC={name:"codeText",previous:cC,resolve:lC,tokenize:dC};function lC(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 cC(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function dC(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 uC{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&&ar(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),ar(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),ar(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);ar(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);ar(this.left,s.reverse())}}}function ar(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 Yf(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new uC(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,mC(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 Us(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function mC(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,b=0;const v=[b];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&&(b=f+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const x=c.slice(v[f],v[f+1]),y=o.pop();d.push([y,y+x.length-1]),e.splice(y,2,x)}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 hC={resolve:fC,tokenize:gC},pC={partial:!0,tokenize:bC};function fC(e){return Yf(e),e}function gC(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(pC,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 bC(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),gn(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 Qf(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(a),e.enter(r),e.enter(o),e.consume(x),e.exit(o),f):x===null||x===32||x===41||sl(x)?s(x):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function f(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(a),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),f(x)):x===null||x===60||Ot(x)?s(x):(e.consume(x),x===92?g:p)}function g(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||An(x))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(x)):m<u&&x===40?(e.consume(x),m++,b):x===41?(e.consume(x),m--,b):x===null||x===32||x===40||sl(x)?s(x):(e.consume(x),x===92?v:b)}function v(x){return x===40||x===41||x===92?(e.consume(x),b):b(x)}}function Xf(e,n,s,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=!ln(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Zf(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"),gn(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 _r(e,n){let s;return a;function a(r){return Ot(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):ln(r)?gn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const xC={name:"definition",tokenize:yC},vC={partial:!0,tokenize:wC};function yC(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Xf.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=ai(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 An(p)?_r(e,u)(p):u(p)}function u(p){return Qf(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(vC,h,h)(p)}function h(p){return ln(p)?gn(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 wC(e,n,s){return a;function a(c){return An(c)?_r(e,r)(c):s(c)}function r(c){return Zf(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return ln(c)?gn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Ot(c)?n(c):s(c)}}const kC={name:"hardBreakEscape",tokenize:jC};function jC(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 NC={name:"headingAtx",resolve:SC,tokenize:CC};function SC(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"},Us(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function CC(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||An(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)):ln(m)?gn(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||An(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const EC=["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"],Dm=["pre","script","style","textarea"],MC={concrete:!0,name:"htmlFlow",resolveTo:PC,tokenize:RC},_C={partial:!0,tokenize:IC},AC={partial:!0,tokenize:TC};function PC(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 RC(e,n,s){const a=this;let r,o,l,c,d;return u;function u(j){return m(j)}function m(j){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(j),h}function h(j){return j===33?(e.consume(j),f):j===47?(e.consume(j),o=!0,b):j===63?(e.consume(j),r=3,a.interrupt?n:M):_s(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function f(j){return j===45?(e.consume(j),r=2,p):j===91?(e.consume(j),r=5,c=0,g):_s(j)?(e.consume(j),r=4,a.interrupt?n:M):s(j)}function p(j){return j===45?(e.consume(j),a.interrupt?n:M):s(j)}function g(j){const H="CDATA[";return j===H.charCodeAt(c++)?(e.consume(j),c===H.length?a.interrupt?n:$:g):s(j)}function b(j){return _s(j)?(e.consume(j),l=String.fromCharCode(j),v):s(j)}function v(j){if(j===null||j===47||j===62||An(j)){const H=j===47,Q=l.toLowerCase();return!H&&!o&&Dm.includes(Q)?(r=1,a.interrupt?n(j):$(j)):EC.includes(l.toLowerCase())?(r=6,H?(e.consume(j),x):a.interrupt?n(j):$(j)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(j):o?y(j):k(j))}return j===45||js(j)?(e.consume(j),l+=String.fromCharCode(j),v):s(j)}function x(j){return j===62?(e.consume(j),a.interrupt?n:$):s(j)}function y(j){return ln(j)?(e.consume(j),y):_(j)}function k(j){return j===47?(e.consume(j),_):j===58||j===95||_s(j)?(e.consume(j),N):ln(j)?(e.consume(j),k):_(j)}function N(j){return j===45||j===46||j===58||j===95||js(j)?(e.consume(j),N):R(j)}function R(j){return j===61?(e.consume(j),w):ln(j)?(e.consume(j),R):k(j)}function w(j){return j===null||j===60||j===61||j===62||j===96?s(j):j===34||j===39?(e.consume(j),d=j,A):ln(j)?(e.consume(j),w):P(j)}function A(j){return j===d?(e.consume(j),d=null,T):j===null||Ot(j)?s(j):(e.consume(j),A)}function P(j){return j===null||j===34||j===39||j===47||j===60||j===61||j===62||j===96||An(j)?R(j):(e.consume(j),P)}function T(j){return j===47||j===62||ln(j)?k(j):s(j)}function _(j){return j===62?(e.consume(j),C):s(j)}function C(j){return j===null||Ot(j)?$(j):ln(j)?(e.consume(j),C):s(j)}function $(j){return j===45&&r===2?(e.consume(j),I):j===60&&r===1?(e.consume(j),F):j===62&&r===4?(e.consume(j),z):j===63&&r===3?(e.consume(j),M):j===93&&r===5?(e.consume(j),X):Ot(j)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(_C,L,O)(j)):j===null||Ot(j)?(e.exit("htmlFlowData"),O(j)):(e.consume(j),$)}function O(j){return e.check(AC,E,L)(j)}function E(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),S}function S(j){return j===null||Ot(j)?O(j):(e.enter("htmlFlowData"),$(j))}function I(j){return j===45?(e.consume(j),M):$(j)}function F(j){return j===47?(e.consume(j),l="",G):$(j)}function G(j){if(j===62){const H=l.toLowerCase();return Dm.includes(H)?(e.consume(j),z):$(j)}return _s(j)&&l.length<8?(e.consume(j),l+=String.fromCharCode(j),G):$(j)}function X(j){return j===93?(e.consume(j),M):$(j)}function M(j){return j===62?(e.consume(j),z):j===45&&r===2?(e.consume(j),M):$(j)}function z(j){return j===null||Ot(j)?(e.exit("htmlFlowData"),L(j)):(e.consume(j),z)}function L(j){return e.exit("htmlFlow"),n(j)}}function TC(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 IC(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(eo,n,s)}}const $C={name:"htmlText",tokenize:DC};function DC(e,n,s){const a=this;let r,o,l;return c;function c(M){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(M),d}function d(M){return M===33?(e.consume(M),u):M===47?(e.consume(M),R):M===63?(e.consume(M),k):_s(M)?(e.consume(M),P):s(M)}function u(M){return M===45?(e.consume(M),m):M===91?(e.consume(M),o=0,g):_s(M)?(e.consume(M),y):s(M)}function m(M){return M===45?(e.consume(M),p):s(M)}function h(M){return M===null?s(M):M===45?(e.consume(M),f):Ot(M)?(l=h,F(M)):(e.consume(M),h)}function f(M){return M===45?(e.consume(M),p):h(M)}function p(M){return M===62?I(M):M===45?f(M):h(M)}function g(M){const z="CDATA[";return M===z.charCodeAt(o++)?(e.consume(M),o===z.length?b:g):s(M)}function b(M){return M===null?s(M):M===93?(e.consume(M),v):Ot(M)?(l=b,F(M)):(e.consume(M),b)}function v(M){return M===93?(e.consume(M),x):b(M)}function x(M){return M===62?I(M):M===93?(e.consume(M),x):b(M)}function y(M){return M===null||M===62?I(M):Ot(M)?(l=y,F(M)):(e.consume(M),y)}function k(M){return M===null?s(M):M===63?(e.consume(M),N):Ot(M)?(l=k,F(M)):(e.consume(M),k)}function N(M){return M===62?I(M):k(M)}function R(M){return _s(M)?(e.consume(M),w):s(M)}function w(M){return M===45||js(M)?(e.consume(M),w):A(M)}function A(M){return Ot(M)?(l=A,F(M)):ln(M)?(e.consume(M),A):I(M)}function P(M){return M===45||js(M)?(e.consume(M),P):M===47||M===62||An(M)?T(M):s(M)}function T(M){return M===47?(e.consume(M),I):M===58||M===95||_s(M)?(e.consume(M),_):Ot(M)?(l=T,F(M)):ln(M)?(e.consume(M),T):I(M)}function _(M){return M===45||M===46||M===58||M===95||js(M)?(e.consume(M),_):C(M)}function C(M){return M===61?(e.consume(M),$):Ot(M)?(l=C,F(M)):ln(M)?(e.consume(M),C):T(M)}function $(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(e.consume(M),r=M,O):Ot(M)?(l=$,F(M)):ln(M)?(e.consume(M),$):(e.consume(M),E)}function O(M){return M===r?(e.consume(M),r=void 0,S):M===null?s(M):Ot(M)?(l=O,F(M)):(e.consume(M),O)}function E(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||An(M)?T(M):(e.consume(M),E)}function S(M){return M===47||M===62||An(M)?T(M):s(M)}function I(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),n):s(M)}function F(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),G}function G(M){return ln(M)?gn(e,X,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):X(M)}function X(M){return e.enter("htmlTextData"),l(M)}}const Qd={name:"labelEnd",resolveAll:FC,resolveTo:UC,tokenize:BC},LC={tokenize:HC},zC={tokenize:qC},OC={tokenize:VC};function FC(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&&Us(e,0,e.length,s),e}function UC(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=Xs(c,e.slice(o+1,o+a+3)),c=Xs(c,[["enter",m,n]]),c=Xs(c,_l(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=Xs(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=Xs(c,e.slice(l+1)),c=Xs(c,[["exit",d,n]]),Us(e,o,e.length,c),e}function BC(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(ai(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(LC,m,l?m:h)(f):f===91?e.attempt(zC,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(OC,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function HC(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 An(h)?_r(e,o)(h):o(h)}function o(h){return h===41?m(h):Qf(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return An(h)?_r(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?Zf(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return An(h)?_r(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 qC(e,n,s){const a=this;return r;function r(c){return Xf.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(ai(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function VC(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 WC={name:"labelStartImage",resolveAll:Qd.resolveAll,tokenize:KC};function KC(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 GC={name:"labelStartLink",resolveAll:Qd.resolveAll,tokenize:JC};function JC(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 ac={name:"lineEnding",tokenize:YC};function YC(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),gn(e,n,"linePrefix")}}const Bo={name:"thematicBreak",tokenize:QC};function QC(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"),ln(u)?gn(e,c,"whitespace")(u):c(u))}}const Ps={continuation:{tokenize:t2},exit:s2,name:"list",tokenize:e2},XC={partial:!0,tokenize:i2},ZC={partial:!0,tokenize:n2};function e2(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:gd(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(Bo,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 gd(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(eo,a.interrupt?s:m,e.attempt(XC,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return ln(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 t2(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(eo,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,gn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!ln(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(ZC,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,gn(e,e.attempt(Ps,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function n2(e,n,s){const a=this;return gn(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 s2(e){e.exit(this.containerState.type)}function i2(e,n,s){const a=this;return gn(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!ln(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Lm={name:"setextUnderline",resolveTo:a2,tokenize:r2};function a2(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 r2(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"),ln(u)?gn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Ot(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const o2={tokenize:l2};function l2(e){const n=this,s=e.attempt(eo,a,e.attempt(this.parser.constructs.flowInitial,r,gn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(hC,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 c2={resolveAll:tg()},d2=eg("string"),u2=eg("text");function eg(e){return{resolveAll:tg(e==="text"?m2: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 tg(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 m2(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 h2={42:Ps,43:Ps,45:Ps,48:Ps,49:Ps,50:Ps,51:Ps,52:Ps,53:Ps,54:Ps,55:Ps,56:Ps,57:Ps,62:Kf},p2={91:xC},f2={[-2]:ic,[-1]:ic,32:ic},g2={35:NC,42:Bo,45:[Lm,Bo],60:MC,61:Lm,95:Bo,96:$m,126:$m},b2={38:Jf,92:Gf},x2={[-5]:ac,[-4]:ac,[-3]:ac,33:WC,38:Jf,42:bd,60:[G0,$C],91:GC,92:[kC,Gf],93:Qd,95:bd,96:oC},v2={null:[bd,c2]},y2={null:[42,95]},w2={null:[]},k2=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:y2,contentInitial:p2,disable:w2,document:h2,flow:g2,flowInitial:f2,insideSpan:v2,string:b2,text:x2},Symbol.toStringTag,{value:"Module"}));function j2(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:A(R),check:A(w),consume:y,enter:k,exit:N,interrupt:A(w,{interrupt:!0})},u={code:null,containerState:{},defineSkip:b,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(C){return l=Xs(l,C),v(),l[l.length-1]!==null?[]:(P(n,0),u.events=_l(o,u.events,u),u.events)}function f(C,$){return S2(p(C),$)}function p(C){return N2(l,C)}function g(){const{_bufferIndex:C,_index:$,line:O,column:E,offset:S}=a;return{_bufferIndex:C,_index:$,line:O,column:E,offset:S}}function b(C){r[C.line]=C.column,_()}function v(){let C;for(;a._index<l.length;){const $=l[a._index];if(typeof $=="string")for(C=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===C&&a._bufferIndex<$.length;)x($.charCodeAt(a._bufferIndex));else x($)}}function x(C){m=m(C)}function y(C){Ot(C)?(a.line++,a.column=1,a.offset+=C===-3?2:1,_()):C!==-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=C}function k(C,$){const O=$||{};return O.type=C,O.start=g(),u.events.push(["enter",O,u]),c.push(O),O}function N(C){const $=c.pop();return $.end=g(),u.events.push(["exit",$,u]),$}function R(C,$){P(C,$.from)}function w(C,$){$.restore()}function A(C,$){return O;function O(E,S,I){let F,G,X,M;return Array.isArray(E)?L(E):"tokenize"in E?L([E]):z(E);function z(de){return pe;function pe(B){const ve=B!==null&&de[B],U=B!==null&&de.null,se=[...Array.isArray(ve)?ve:ve?[ve]:[],...Array.isArray(U)?U:U?[U]:[]];return L(se)(B)}}function L(de){return F=de,G=0,de.length===0?I:j(de[G])}function j(de){return pe;function pe(B){return M=T(),X=de,de.partial||(u.currentConstruct=de),de.name&&u.parser.constructs.disable.null.includes(de.name)?Q():de.tokenize.call($?Object.assign(Object.create(u),$):u,d,H,Q)(B)}}function H(de){return C(X,M),S}function Q(de){return M.restore(),++G<F.length?j(F[G]):I}}}function P(C,$){C.resolveAll&&!o.includes(C)&&o.push(C),C.resolve&&Us(u.events,$,u.events.length-$,C.resolve(u.events.slice($),u)),C.resolveTo&&(u.events=C.resolveTo(u.events,u))}function T(){const C=g(),$=u.previous,O=u.currentConstruct,E=u.events.length,S=Array.from(c);return{from:E,restore:I};function I(){a=C,u.previous=$,u.currentConstruct=O,u.events.length=E,c=S,_()}}function _(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function N2(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 S2(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 C2(e){const a={constructs:Vf([k2,...(e||{}).extensions||[]]),content:r(U0),defined:[],document:r(H0),flow:r(o2),lazy:{},string:r(d2),text:r(u2)};return a;function r(o){return l;function l(c){return j2(a,o,c)}}}function E2(e){for(;!Yf(e););return e}const zm=/[\0\t\n\r]/g;function M2(){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(zm.lastIndex=h,u=zm.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 _2=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function A2(e){return e.replace(_2,P2)}function P2(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Wf(s.slice(o?2:1),o?16:10)}return Yd(s)||e}const ng={}.hasOwnProperty;function R2(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),T2(s)(E2(C2(s).document().write(M2()(e,n,!0))))}function T2(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(Se),autolinkProtocol:T,autolinkEmail:T,atxHeading:o(xe),blockQuote:o(U),characterEscape:T,characterReference:T,codeFenced:o(se),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(se,l),codeText:o(ee,l),codeTextData:T,data:T,codeFlowValue:T,definition:o(ie),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(te),hardBreakEscape:o(ne),hardBreakTrailing:o(ne),htmlFlow:o(_e,l),htmlFlowData:T,htmlText:o(_e,l),htmlTextData:T,image:o(Ne),label:l,link:o(Se),listItem:o(Ye),listItemValue:f,listOrdered:o(He,h),listUnordered:o(He),paragraph:o(Oe),reference:j,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(xe),strong:o(ke),thematicBreak:o(re)},exit:{atxHeading:d(),atxHeadingSequence:R,autolink:d(),autolinkEmail:ve,autolinkProtocol:B,blockQuote:d(),characterEscapeValue:_,characterReferenceMarkerHexadecimal:Q,characterReferenceMarkerNumeric:Q,characterReferenceValue:de,characterReference:pe,codeFenced:d(v),codeFencedFence:b,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:_,codeIndented:d(x),codeText:d(S),codeTextData:_,data:_,definition:d(),definitionDestinationString:N,definitionLabelString:y,definitionTitleString:k,emphasis:d(),hardBreakEscape:d($),hardBreakTrailing:d($),htmlFlow:d(O),htmlFlowData:_,htmlText:d(E),htmlTextData:_,image:d(F),label:X,labelText:G,lineEnding:C,link:d(I),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:H,resourceDestinationString:M,resourceTitleString:z,resource:L,setextHeading:d(P),setextHeadingLineSequence:A,setextHeadingText:w,strong:d(),thematicBreak:d()}};sg(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(oe){let we={type:"root",children:[]};const Z={stack:[we],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},qe=[];let Qe=-1;for(;++Qe<oe.length;)if(oe[Qe][1].type==="listOrdered"||oe[Qe][1].type==="listUnordered")if(oe[Qe][0]==="enter")qe.push(Qe);else{const ge=qe.pop();Qe=r(oe,ge,Qe)}for(Qe=-1;++Qe<oe.length;){const ge=n[oe[Qe][0]];ng.call(ge,oe[Qe][1].type)&&ge[oe[Qe][1].type].call(Object.assign({sliceSerialize:oe[Qe][2].sliceSerialize},Z),oe[Qe][1])}if(Z.tokenStack.length>0){const ge=Z.tokenStack[Z.tokenStack.length-1];(ge[1]||Om).call(Z,void 0,ge[0])}for(we.position={start:Ti(oe.length>0?oe[0][1].start:{line:1,column:1,offset:0}),end:Ti(oe.length>0?oe[oe.length-2][1].end:{line:1,column:1,offset:0})},Qe=-1;++Qe<n.transforms.length;)we=n.transforms[Qe](we)||we;return we}function r(oe,we,Z){let qe=we-1,Qe=-1,ge=!1,Ue,Xe,wt,ye;for(;++qe<=Z;){const le=oe[qe];switch(le[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{le[0]==="enter"?Qe++:Qe--,ye=void 0;break}case"lineEndingBlank":{le[0]==="enter"&&(Ue&&!ye&&!Qe&&!wt&&(wt=qe),ye=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:ye=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(Ue){let Te=qe;for(Xe=void 0;Te--;){const be=oe[Te];if(be[1].type==="lineEnding"||be[1].type==="lineEndingBlank"){if(be[0]==="exit")continue;Xe&&(oe[Xe][1].type="lineEndingBlank",ge=!0),be[1].type="lineEnding",Xe=Te}else if(!(be[1].type==="linePrefix"||be[1].type==="blockQuotePrefix"||be[1].type==="blockQuotePrefixWhitespace"||be[1].type==="blockQuoteMarker"||be[1].type==="listItemIndent"))break}wt&&(!Xe||wt<Xe)&&(Ue._spread=!0),Ue.end=Object.assign({},Xe?oe[Xe][1].start:le[1].end),oe.splice(Xe||qe,0,["exit",Ue,le[2]]),qe++,Z++}if(le[1].type==="listItemPrefix"){const Te={type:"listItem",_spread:!1,start:Object.assign({},le[1].start),end:void 0};Ue=Te,oe.splice(qe,0,["enter",Te,le[2]]),qe++,Z++,wt=void 0,ye=!0}}}return oe[we][1]._spread=ge,Z}function o(oe,we){return Z;function Z(qe){c.call(this,oe(qe),qe),we&&we.call(this,qe)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(oe,we,Z){this.stack[this.stack.length-1].children.push(oe),this.stack.push(oe),this.tokenStack.push([we,Z||void 0]),oe.position={start:Ti(we.start),end:void 0}}function d(oe){return we;function we(Z){oe&&oe.call(this,Z),u.call(this,Z)}}function u(oe,we){const Z=this.stack.pop(),qe=this.tokenStack.pop();if(qe)qe[0].type!==oe.type&&(we?we.call(this,oe,qe[0]):(qe[1]||Om).call(this,oe,qe[0]));else throw new Error("Cannot close `"+oe.type+"` ("+Mr({start:oe.start,end:oe.end})+"): it’s not open");Z.position.end=Ti(oe.end)}function m(){return Jd(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(oe){if(this.data.expectingFirstListItemValue){const we=this.stack[this.stack.length-2];we.start=Number.parseInt(this.sliceSerialize(oe),10),this.data.expectingFirstListItemValue=void 0}}function p(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.lang=oe}function g(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.meta=oe}function b(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.value=oe.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function x(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.value=oe.replace(/(\r?\n|\r)$/g,"")}function y(oe){const we=this.resume(),Z=this.stack[this.stack.length-1];Z.label=we,Z.identifier=ai(this.sliceSerialize(oe)).toLowerCase()}function k(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.title=oe}function N(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.url=oe}function R(oe){const we=this.stack[this.stack.length-1];if(!we.depth){const Z=this.sliceSerialize(oe).length;we.depth=Z}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function A(oe){const we=this.stack[this.stack.length-1];we.depth=this.sliceSerialize(oe).codePointAt(0)===61?1:2}function P(){this.data.setextHeadingSlurpLineEnding=void 0}function T(oe){const Z=this.stack[this.stack.length-1].children;let qe=Z[Z.length-1];(!qe||qe.type!=="text")&&(qe=De(),qe.position={start:Ti(oe.start),end:void 0},Z.push(qe)),this.stack.push(qe)}function _(oe){const we=this.stack.pop();we.value+=this.sliceSerialize(oe),we.position.end=Ti(oe.end)}function C(oe){const we=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Z=we.children[we.children.length-1];Z.position.end=Ti(oe.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(we.type)&&(T.call(this,oe),_.call(this,oe))}function $(){this.data.atHardBreak=!0}function O(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.value=oe}function E(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.value=oe}function S(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.value=oe}function I(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const we=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=we,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function F(){const oe=this.stack[this.stack.length-1];if(this.data.inReference){const we=this.data.referenceType||"shortcut";oe.type+="Reference",oe.referenceType=we,delete oe.url,delete oe.title}else delete oe.identifier,delete oe.label;this.data.referenceType=void 0}function G(oe){const we=this.sliceSerialize(oe),Z=this.stack[this.stack.length-2];Z.label=A2(we),Z.identifier=ai(we).toLowerCase()}function X(){const oe=this.stack[this.stack.length-1],we=this.resume(),Z=this.stack[this.stack.length-1];if(this.data.inReference=!0,Z.type==="link"){const qe=oe.children;Z.children=qe}else Z.alt=we}function M(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.url=oe}function z(){const oe=this.resume(),we=this.stack[this.stack.length-1];we.title=oe}function L(){this.data.inReference=void 0}function j(){this.data.referenceType="collapsed"}function H(oe){const we=this.resume(),Z=this.stack[this.stack.length-1];Z.label=we,Z.identifier=ai(this.sliceSerialize(oe)).toLowerCase(),this.data.referenceType="full"}function Q(oe){this.data.characterReferenceType=oe.type}function de(oe){const we=this.sliceSerialize(oe),Z=this.data.characterReferenceType;let qe;Z?(qe=Wf(we,Z==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):qe=Yd(we);const Qe=this.stack[this.stack.length-1];Qe.value+=qe}function pe(oe){const we=this.stack.pop();we.position.end=Ti(oe.end)}function B(oe){_.call(this,oe);const we=this.stack[this.stack.length-1];we.url=this.sliceSerialize(oe)}function ve(oe){_.call(this,oe);const we=this.stack[this.stack.length-1];we.url="mailto:"+this.sliceSerialize(oe)}function U(){return{type:"blockquote",children:[]}}function se(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function ie(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function te(){return{type:"emphasis",children:[]}}function xe(){return{type:"heading",depth:0,children:[]}}function ne(){return{type:"break"}}function _e(){return{type:"html",value:""}}function Ne(){return{type:"image",title:null,url:"",alt:null}}function Se(){return{type:"link",title:null,url:"",children:[]}}function He(oe){return{type:"list",ordered:oe.type==="listOrdered",start:null,spread:oe._spread,children:[]}}function Ye(oe){return{type:"listItem",spread:oe._spread,checked:null,children:[]}}function Oe(){return{type:"paragraph",children:[]}}function ke(){return{type:"strong",children:[]}}function De(){return{type:"text",value:""}}function re(){return{type:"thematicBreak"}}}function Ti(e){return{line:e.line,column:e.column,offset:e.offset}}function sg(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?sg(e,a):I2(e,a)}}function I2(e,n){let s;for(s in n)if(ng.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 Om(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Mr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Mr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Mr({start:n.start,end:n.end})+") is still open")}function $2(e){const n=this;n.parser=s;function s(a){return R2(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function D2(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 L2(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
647
- `}]}function z2(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 O2(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function F2(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function U2(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Wa(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 B2(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 H2(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function ig(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 q2(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return ig(e,n);const r={src:Wa(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 V2(e,n){const s={src:Wa(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 W2(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 K2(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return ig(e,n);const r={href:Wa(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 G2(e,n){const s={href:Wa(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 J2(e,n,s){const a=e.all(n),r=s?Y2(s):ag(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 Y2(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=ag(s[a])}return n}function ag(e){const n=e.spread;return n??e.children.length>1}function Q2(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 X2(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function Z2(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function eE(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function tE(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=Vd(n.children[1]),d=zf(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 nE(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 sE(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const Fm=9,Um=32;function iE(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(Bm(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(Bm(n.slice(r),r>0,!1)),o.join("")}function Bm(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===Fm||o===Um;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===Fm||o===Um;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function aE(e,n){const s={type:"text",value:iE(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function rE(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const oE={blockquote:D2,break:L2,code:z2,delete:O2,emphasis:F2,footnoteReference:U2,heading:B2,html:H2,imageReference:q2,image:V2,inlineCode:W2,linkReference:K2,link:G2,listItem:J2,list:Q2,paragraph:X2,root:Z2,strong:eE,table:tE,tableCell:sE,tableRow:nE,text:aE,thematicBreak:rE,toml:xo,yaml:xo,definition:xo,footnoteDefinition:xo};function xo(){}const rg=-1,Al=0,Ar=1,il=2,Xd=3,Zd=4,eu=5,tu=6,og=7,lg=8,Hm=typeof self=="object"?self:globalThis,lE=(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 Al:case rg:return s(l,r);case Ar:{const c=s([],r);for(const d of l)c.push(a(d));return c}case il:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case Xd:return s(new Date(l),r);case Zd:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case eu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case tu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case og:{const{name:c,message:d}=l;return s(new Hm[c](d),r)}case lg: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 Hm[o](l),r)};return a},qm=e=>lE(new Map,e)(0),ba="",{toString:cE}={},{keys:dE}=Object,rr=e=>{const n=typeof e;if(n!=="object"||!e)return[Al,n];const s=cE.call(e).slice(8,-1);switch(s){case"Array":return[Ar,ba];case"Object":return[il,ba];case"Date":return[Xd,ba];case"RegExp":return[Zd,ba];case"Map":return[eu,ba];case"Set":return[tu,ba];case"DataView":return[Ar,s]}return s.includes("Array")?[Ar,s]:s.includes("Error")?[og,s]:[il,s]},vo=([e,n])=>e===Al&&(n==="function"||n==="symbol"),uE=(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]=rr(l);switch(c){case Al:{let m=l;switch(d){case"bigint":c=lg,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([rg],l)}return r([c,m],l)}case Ar:{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 il:{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 dE(l))(e||!vo(rr(l[f])))&&m.push([o(f),o(l[f])]);return h}case Xd:return r([c,l.toISOString()],l);case Zd:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case eu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(vo(rr(f))||vo(rr(p))))&&m.push([o(f),o(p)]);return h}case tu:{const m=[],h=r([c,m],l);for(const f of l)(e||!vo(rr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},Vm=(e,{json:n,lossy:s}={})=>{const a=[];return uE(!(n||s),!!n,new Map,a)(e),a},al=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?qm(Vm(e,n)):structuredClone(e):(e,n)=>qm(Vm(e,n));function mE(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 hE(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function pE(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||mE,a=e.options.footnoteBackLabel||hE,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=Wa(h.toLowerCase());let p=0;const g=[],b=e.footnoteCounts.get(h);for(;b!==void 0&&++p<=b;){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 x={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,x),c.push(x)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...al(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 Pl=(function(e){if(e==null)return xE;if(typeof e=="function")return Rl(e);if(typeof e=="object")return Array.isArray(e)?fE(e):gE(e);if(typeof e=="string")return bE(e);throw new Error("Expected function, string, or object as test")});function fE(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Pl(e[s]);return Rl(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function gE(e){const n=e;return Rl(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function bE(e){return Rl(n);function n(s){return s&&s.type===e}}function Rl(e){return n;function n(s,a,r){return!!(vE(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function xE(){return!0}function vE(e){return e!==null&&typeof e=="object"&&"type"in e}const cg=[],yE=!0,xd=!1,wE="skip";function dg(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Pl(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=cg,g,b,v;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=kE(s(d,m)),p[0]===xd))return p;if("children"in d&&d.children){const x=d;if(x.children&&p[0]!==wE)for(b=(a?x.children.length:-1)+l,v=m.concat(x);b>-1&&b<x.children.length;){const y=x.children[b];if(g=c(y,b,v)(),g[0]===xd)return g;b=typeof g[1]=="number"?g[1]:b+l}}return p}}}function kE(e){return Array.isArray(e)?e:typeof e=="number"?[yE,e]:e==null?cg:[e]}function nu(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),dg(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 vd={}.hasOwnProperty,jE={};function NE(e,n){const s=n||jE,a=new Map,r=new Map,o=new Map,l={...oE,...s.handlers},c={all:u,applyData:CE,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:SE,wrap:ME};return nu(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(vd.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:b,...v}=m,x=al(v);return x.children=c.all(m),x}return al(m)}return(c.options.unknownHandler||EE)(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=Wm(g.value)),!Array.isArray(g)&&g.type==="element")){const b=g.children[0];b&&b.type==="text"&&(b.value=Wm(b.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function SE(e,n){e.position&&(n.position=h0(e))}function CE(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,al(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function EE(e,n){const s=n.data||{},a="value"in n&&!(vd.call(s,"hProperties")||vd.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 ME(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 Wm(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function Km(e,n){const s=NE(e,n),a=s.one(e,void 0),r=pE(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 _E(e,n){return e&&"run"in e?async function(s,a){const r=Km(s,{file:a,...n});await e.run(r,a)}:function(s,a){return Km(s,{file:a,...e||n})}}function Gm(e){if(e)throw e}var rc,Jm;function AE(){if(Jm)return rc;Jm=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 rc=function d(){var u,m,h,f,p,g,b=arguments[0],v=1,x=arguments.length,y=!1;for(typeof b=="boolean"&&(y=b,b=arguments[1]||{},v=2),(b==null||typeof b!="object"&&typeof b!="function")&&(b={});v<x;++v)if(u=arguments[v],u!=null)for(m in u)h=c(b,m),f=c(u,m),b!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(b,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(b,{name:m,newValue:f}));return b},rc}var PE=AE();const oc=Fp(PE);function yd(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 RE(){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?TE(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 TE(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 hi={basename:IE,dirname:$E,extname:DE,join:LE,sep:"/"};function IE(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');to(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 $E(e){if(to(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 DE(e){to(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 LE(...e){let n=-1,s;for(;++n<e.length;)to(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":zE(s)}function zE(e){to(e);const n=e.codePointAt(0)===47;let s=OE(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function OE(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 to(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const FE={cwd:UE};function UE(){return"/"}function wd(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function BE(e){if(typeof e=="string")e=new URL(e);else if(!wd(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 HE(e)}function HE(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 lc=["history","path","basename","stem","extname","dirname"];class ug{constructor(n){let s;n?wd(n)?s={path:n}:typeof n=="string"||qE(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":FE.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<lc.length;){const o=lc[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)lc.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?hi.basename(this.path):void 0}set basename(n){dc(n,"basename"),cc(n,"basename"),this.path=hi.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?hi.dirname(this.path):void 0}set dirname(n){Ym(this.basename,"dirname"),this.path=hi.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?hi.extname(this.path):void 0}set extname(n){if(cc(n,"extname"),Ym(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=hi.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){wd(n)&&(n=BE(n)),dc(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?hi.basename(this.path,this.extname):void 0}set stem(n){dc(n,"stem"),cc(n,"stem"),this.path=hi.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 Ss(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 cc(e,n){if(e&&e.includes(hi.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+hi.sep+"`")}function dc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Ym(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function qE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const VE=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),WE={}.hasOwnProperty;class su extends VE{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=RE()}copy(){const n=new su;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(oc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(hc("data",this.frozen),this.namespace[n]=s,this):WE.call(this.namespace,n)&&this.namespace[n]||void 0:n?(hc("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=yo(n),a=this.parser||this.Parser;return uc("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),uc("process",this.parser||this.Parser),mc("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=yo(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);JE(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(),uc("processSync",this.parser||this.Parser),mc("processSync",this.compiler||this.Compiler),this.process(n,r),Xm("processSync","process",s),a;function r(o,l){s=!0,Gm(o),a=l}}run(n,s,a){Qm(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=yo(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),Xm("runSync","run",a),r;function o(l,c){Gm(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=yo(s),r=this.compiler||this.Compiler;return mc("stringify",r),Qm(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(hc("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=oc(!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 b=a[f][1];yd(b)&&yd(p)&&(p=oc(!0,b,p)),a[f]=[u,p,...g]}}}}const KE=new su().freeze();function uc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function mc(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function hc(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 Qm(e){if(!yd(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Xm(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function yo(e){return GE(e)?e:new ug(e)}function GE(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function JE(e){return typeof e=="string"||YE(e)}function YE(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const QE="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Zm=[],eh={allowDangerousHtml:!0},XE=/^(https?|ircs?|mailto|xmpp)$/i,ZE=[{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 gi(e){const n=eM(e),s=tM(e);return nM(n.runSync(n.parse(s),s),e)}function eM(e){const n=e.rehypePlugins||Zm,s=e.remarkPlugins||Zm,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...eh}:eh;return KE().use($2).use(s).use(_E,a).use(n)}function tM(e){const n=e.children||"",s=new ug;return typeof n=="string"&&(s.value=n),s}function nM(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||sM;for(const m of ZE)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+QE+m.id,void 0);return nu(e,u),x0(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 sc)if(Object.hasOwn(sc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],b=sc[p];(b===null||b.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 sM(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||XE.test(e.slice(0,n))?e:""}function th(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 iM(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function aM(e,n,s){const r=Pl((s||{}).ignore||[]),o=rM(n);let l=-1;for(;++l<o.length;)dg(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 x=!1,y=[];f.lastIndex=0;let k=f.exec(u.value);for(;k;){const N=k.index,R={index:k.index,input:k.input,stack:[...m,u]};let w=p(...k,R);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?f.lastIndex=N+1:(g!==N&&y.push({type:"text",value:u.value.slice(g,N)}),Array.isArray(w)?y.push(...w):w&&y.push(w),g=N+k[0].length,x=!0),!f.global)break;k=f.exec(u.value)}return x?(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 rM(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([oM(r[0]),lM(r[1])])}return n}function oM(e){return typeof e=="string"?new RegExp(iM(e),"g"):e}function lM(e){return typeof e=="function"?e:function(){return e}}const pc="phrasing",fc=["autolink","link","image","label"];function cM(){return{transforms:[gM],enter:{literalAutolink:uM,literalAutolinkEmail:gc,literalAutolinkHttp:gc,literalAutolinkWww:gc},exit:{literalAutolink:fM,literalAutolinkEmail:pM,literalAutolinkHttp:mM,literalAutolinkWww:hM}}}function dM(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:pc,notInConstruct:fc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:pc,notInConstruct:fc},{character:":",before:"[ps]",after:"\\/",inConstruct:pc,notInConstruct:fc}]}}function uM(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function gc(e){this.config.enter.autolinkProtocol.call(this,e)}function mM(e){this.config.exit.autolinkProtocol.call(this,e)}function hM(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 pM(e){this.config.exit.autolinkEmail.call(this,e)}function fM(e){this.exit(e)}function gM(e){aM(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,bM],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,xM]],{ignore:["link","linkReference"]})}function bM(e,n,s,a,r){let o="";if(!mg(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!vM(s)))return!1;const l=yM(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 xM(e,n,s,a){return!mg(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function vM(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 yM(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=th(e,"(");let o=th(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 mg(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||ia(s)||Ml(s))&&(!n||s!==47)}hg.peek=_M;function wM(){this.buffer()}function kM(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function jM(){this.buffer()}function NM(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function SM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ai(this.sliceSerialize(e)).toLowerCase(),s.label=n}function CM(e){this.exit(e)}function EM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ai(this.sliceSerialize(e)).toLowerCase(),s.label=n}function MM(e){this.exit(e)}function _M(){return"["}function hg(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 AM(){return{enter:{gfmFootnoteCallString:wM,gfmFootnoteCall:kM,gfmFootnoteDefinitionLabelString:jM,gfmFootnoteDefinition:NM},exit:{gfmFootnoteCallString:SM,gfmFootnoteCall:CM,gfmFootnoteDefinitionLabelString:EM,gfmFootnoteDefinition:MM}}}function PM(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:hg},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?pg:RM))),u(),d}}function RM(e,n,s){return n===0?e:pg(e,n,s)}function pg(e,n,s){return(s?"":" ")+e}const TM=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];fg.peek=zM;function IM(){return{canContainEols:["delete"],enter:{strikethrough:DM},exit:{strikethrough:LM}}}function $M(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:TM}],handlers:{delete:fg}}}function DM(e){this.enter({type:"delete",children:[]},e)}function LM(e){this.exit(e)}function fg(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 zM(){return"~"}function OM(e){return e.length}function FM(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||OM,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const b=[],v=[];let x=-1;for(e[m].length>u&&(u=e[m].length);++x<e[m].length;){const y=UM(e[m][x]);if(s.alignDelimiters!==!1){const k=r(y);v[x]=k,(d[x]===void 0||k>d[x])&&(d[x]=k)}b.push(y)}l[m]=b,c[m]=v}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=nh(a[h]);else{const b=nh(a);for(;++h<u;)o[h]=b}h=-1;const f=[],p=[];for(;++h<u;){const b=o[h];let v="",x="";b===99?(v=":",x=":"):b===108?v=":":b===114&&(x=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-v.length-x.length);const k=v+"-".repeat(y)+x;s.alignDelimiters!==!1&&(y=v.length+y+x.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=k}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const b=l[m],v=c[m];h=-1;const x=[];for(;++h<u;){const y=b[h]||"";let k="",N="";if(s.alignDelimiters!==!1){const R=d[h]-(v[h]||0),w=o[h];w===114?k=" ".repeat(R):w===99?R%2?(k=" ".repeat(R/2+.5),N=" ".repeat(R/2-.5)):(k=" ".repeat(R/2),N=k):N=" ".repeat(R)}s.delimiterStart!==!1&&!h&&x.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&x.push(" "),s.alignDelimiters!==!1&&x.push(k),x.push(y),s.alignDelimiters!==!1&&x.push(N),s.padding!==!1&&x.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&x.push("|")}g.push(s.delimiterEnd===!1?x.join("").replace(/ +$/,""):x.join(""))}return g.join(`
658
- `)}function UM(e){return e==null?"":String(e)}function nh(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 BM(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()),HM);return r(),l}function HM(e,n,s){return">"+(s?"":" ")+e}function qM(e,n){return sh(e,n.inConstruct,!0)&&!sh(e,n.notInConstruct,!1)}function sh(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 ih(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
659
- `&&qM(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
660
- `}function VM(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 WM(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 KM(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 GM(e,n,s,a){const r=KM(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(WM(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,JM);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(VM(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 JM(e,n,s){return(s?"":" ")+e}function iu(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 YM(e,n,s,a){const r=iu(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 QM(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 Or(e){return"&#x"+e.toString(16).toUpperCase()+";"}function rl(e,n,s){const a=Ia(e),r=Ia(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}}gg.peek=XM;function gg(e,n,s,a){const r=QM(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=rl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Or(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=rl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Or(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function XM(e,n,s){return s.options.emphasis||"*"}function ZM(e,n){let s=!1;return nu(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,xd}),!!((!e.depth||e.depth<3)&&Jd(e)&&(n.options.setext||s))}function e_(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(ZM(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=Or(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}bg.peek=t_;function bg(e){return e.value||""}function t_(){return"<"}xg.peek=n_;function xg(e,n,s,a){const r=iu(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 n_(){return"!"}vg.peek=s_;function vg(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 s_(){return"!"}yg.peek=i_;function yg(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 i_(){return"`"}function wg(e,n){const s=Jd(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))}kg.peek=a_;function kg(e,n,s,a){const r=iu(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(wg(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 a_(e,n,s){return wg(e,s)?"<":"["}jg.peek=r_;function jg(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 r_(){return"["}function au(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 o_(e){const n=au(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 l_(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 Ng(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 c_(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?l_(s):au(s);const c=e.ordered?l==="."?")":".":o_(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),Ng(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 d_(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 u_(e,n,s,a){const r=d_(s);let o=s.bulletCurrent||au(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 m_(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const h_=Pl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function p_(e,n,s,a){return(e.children.some(function(l){return h_(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function f_(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Sg.peek=g_;function Sg(e,n,s,a){const r=f_(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=rl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Or(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=rl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Or(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function g_(e,n,s){return s.options.strong||"*"}function b_(e,n,s,a){return s.safe(e.value,a)}function x_(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 v_(e,n,s){const a=(Ng(s)+(s.options.ruleSpaces?" ":"")).repeat(x_(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Cg={blockquote:BM,break:ih,code:GM,definition:YM,emphasis:gg,hardBreak:ih,heading:e_,html:bg,image:xg,imageReference:vg,inlineCode:yg,link:kg,linkReference:jg,list:c_,listItem:u_,paragraph:m_,root:p_,strong:Sg,text:b_,thematicBreak:v_};function y_(){return{enter:{table:w_,tableData:ah,tableHeader:ah,tableRow:j_},exit:{codeText:N_,table:k_,tableData:bc,tableHeader:bc,tableRow:bc}}}function w_(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 k_(e){this.exit(e),this.data.inTable=void 0}function j_(e){this.enter({type:"tableRow",children:[]},e)}function bc(e){this.exit(e)}function ah(e){this.enter({type:"tableCell",children:[]},e)}function N_(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,S_));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function S_(e,n){return n==="|"?n:e}function C_(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,b,v){return u(m(p,b,v),p.align)}function c(p,g,b,v){const x=h(p,b,v),y=u([x]);return y.slice(0,y.indexOf(`
671
- `))}function d(p,g,b,v){const x=b.enter("tableCell"),y=b.enter("phrasing"),k=b.containerPhrasing(p,{...v,before:o,after:o});return y(),x(),k}function u(p,g){return FM(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,b){const v=p.children;let x=-1;const y=[],k=g.enter("table");for(;++x<v.length;)y[x]=h(v[x],g,b);return k(),y}function h(p,g,b){const v=p.children;let x=-1;const y=[],k=g.enter("tableRow");for(;++x<v.length;)y[x]=d(v[x],p,g,b);return k(),y}function f(p,g,b){let v=Cg.inlineCode(p,g,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function E_(){return{exit:{taskListCheckValueChecked:rh,taskListCheckValueUnchecked:rh,paragraph:__}}}function M_(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:A_}}}function rh(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function __(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 A_(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=Cg.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 P_(){return[cM(),AM(),IM(),y_(),E_()]}function R_(e){return{extensions:[dM(),PM(e),$M(),C_(e),M_()]}}const T_={tokenize:O_,partial:!0},Eg={tokenize:F_,partial:!0},Mg={tokenize:U_,partial:!0},_g={tokenize:B_,partial:!0},I_={tokenize:H_,partial:!0},Ag={name:"wwwAutolink",tokenize:L_,previous:Rg},Pg={name:"protocolAutolink",tokenize:z_,previous:Tg},Pi={name:"emailAutolink",tokenize:D_,previous:Ig},vi={};function $_(){return{text:vi}}let Gi=48;for(;Gi<123;)vi[Gi]=Pi,Gi++,Gi===58?Gi=65:Gi===91&&(Gi=97);vi[43]=Pi;vi[45]=Pi;vi[46]=Pi;vi[95]=Pi;vi[72]=[Pi,Pg];vi[104]=[Pi,Pg];vi[87]=[Pi,Ag];vi[119]=[Pi,Ag];function D_(e,n,s){const a=this;let r,o;return l;function l(h){return!kd(h)||!Ig.call(a,a.previous)||ru(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return kd(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(I_,m,u)(h):h===45||h===95||js(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 L_(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!Rg.call(a,a.previous)||ru(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(T_,e.attempt(Eg,e.attempt(Mg,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function z_(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Tg.call(a,a.previous)&&!ru(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||sl(h)||An(h)||ia(h)||Ml(h)?s(h):e.attempt(Eg,e.attempt(Mg,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function O_(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 F_(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(_g,d,c)(u):u===null||An(u)||ia(u)||u!==45&&Ml(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 U_(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(_g,n,o)(l):l===null||An(l)||ia(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function B_(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||An(c)||ia(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||An(c)||ia(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 H_(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return js(o)?s(o):n(o)}}function Rg(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||An(e)}function Tg(e){return!_s(e)}function Ig(e){return!(e===47||kd(e))}function kd(e){return e===43||e===45||e===46||e===95||js(e)}function ru(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 q_={tokenize:X_,partial:!0};function V_(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:J_,continuation:{tokenize:Y_},exit:Q_}},text:{91:{name:"gfmFootnoteCall",tokenize:G_},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:W_,resolveTo:K_}}}}function W_(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=ai(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 K_(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 G_(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||An(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(ai(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return An(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 J_(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||An(g))return s(g);if(g===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=ai(a.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return An(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),gn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function Y_(e,n,s){return e.check(eo,n,e.attempt(q_,n,s))}function Q_(e){e.exit("gfmFootnoteDefinition")}function X_(e,n,s){const a=this;return gn(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 Z_(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&&Us(f,f.length,0,_l(p,l.slice(u+1,d),c)),Us(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Us(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 b=Ia(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"),x=Ia(g);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(g)}}}class eA{constructor(){this.map=[]}add(n,s,a){tA(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 tA(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 nA(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 sA(){return{flow:{null:{name:"table",tokenize:iA,resolveAll:aA}}}}function iA(e,n,s){const a=this;let r=0,o=0,l;return c;function c(_){let C=a.events.length-1;for(;C>-1;){const E=a.events[C][1].type;if(E==="lineEnding"||E==="linePrefix")C--;else break}const $=C>-1?a.events[C][1].type:null,O=$==="tableHead"||$==="tableRow"?w:d;return O===w&&a.parser.lazy[a.now().line]?s(_):O(_)}function d(_){return e.enter("tableHead"),e.enter("tableRow"),u(_)}function u(_){return _===124||(l=!0,o+=1),m(_)}function m(_){return _===null?s(_):Ot(_)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(_),e.exit("lineEnding"),p):s(_):ln(_)?gn(e,m,"whitespace")(_):(o+=1,l&&(l=!1,r+=1),_===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(_)))}function h(_){return _===null||_===124||An(_)?(e.exit("data"),m(_)):(e.consume(_),_===92?f:h)}function f(_){return _===92||_===124?(e.consume(_),h):h(_)}function p(_){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(_):(e.enter("tableDelimiterRow"),l=!1,ln(_)?gn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(_):g(_))}function g(_){return _===45||_===58?v(_):_===124?(l=!0,e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),b):R(_)}function b(_){return ln(_)?gn(e,v,"whitespace")(_):v(_)}function v(_){return _===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),x):_===45?(o+=1,x(_)):_===null||Ot(_)?N(_):R(_)}function x(_){return _===45?(e.enter("tableDelimiterFiller"),y(_)):R(_)}function y(_){return _===45?(e.consume(_),y):_===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(_),e.exit("tableDelimiterMarker"),k):(e.exit("tableDelimiterFiller"),k(_))}function k(_){return ln(_)?gn(e,N,"whitespace")(_):N(_)}function N(_){return _===124?g(_):_===null||Ot(_)?!l||r!==o?R(_):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(_)):R(_)}function R(_){return s(_)}function w(_){return e.enter("tableRow"),A(_)}function A(_){return _===124?(e.enter("tableCellDivider"),e.consume(_),e.exit("tableCellDivider"),A):_===null||Ot(_)?(e.exit("tableRow"),n(_)):ln(_)?gn(e,A,"whitespace")(_):(e.enter("data"),P(_))}function P(_){return _===null||_===124||An(_)?(e.exit("data"),A(_)):(e.consume(_),_===92?T:P)}function T(_){return _===92||_===124?(e.consume(_),P):P(_)}}function aA(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 eA;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(oh(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=wo(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=wo(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=wo(f,n,o,r,s,h)):l[1]!==0&&(h=wo(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&oh(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=nA(n.events,s))}return e}function wo(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ja(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=ja(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=ja(n.events,s[2]),m=ja(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,b=s[3]-s[2]-1;e.add(g,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},ja(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function oh(e,n,s,a,r){const o=[],l=ja(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 ja(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const rA={name:"tasklistCheck",tokenize:lA};function oA(){return{text:{91:rA}}}function lA(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 An(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):ln(d)?e.check({tokenize:cA},n,s)(d):s(d)}}function cA(e,n,s){return gn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function dA(e){return Vf([$_(),V_(),Z_(e),sA(),oA()])}const uA={};function bi(e){const n=this,s=e||uA,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(dA(s)),o.push(P_()),l.push(R_(s))}const mA=45e3,hA=3e3,pA=2e3,fA=1500,lh="fusion:sse-client-id";let xa=null;const Di=new Map;function ch(){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 $g(){if(!(typeof window>"u")){if(xa)return xa;try{const e=window.sessionStorage.getItem(lh);if(e)return xa=e,e;const n=ch();return window.sessionStorage.setItem(lh,n),xa=n,n}catch{return xa=ch(),xa}}}function Dg(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Lg(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function gA(e){const n=$g();if(!n)return e;const s=Dg(e);return!s||!Lg(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ou(e,n){const s=$g();if(!s)return;const a=Dg(e);if(!a||!Lg(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),fi(`${r.pathname}${r.search}${r.hash}`)}function bA(e){if(typeof window>"u")return;const n=ou(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 Tl(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function dh(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=ou(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),fA):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function xA(e){Tl(e),ou(e.url,"keepalive")&&(dh(e),e.keepaliveTimer=window.setInterval(()=>{dh(e)},pA))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(Di.values()))if(!s.closed){if(Tl(s),bA(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(Di.values()))a.subscribers.size!==0&&(a.closed=!1,lu(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function wr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{zg(e)},mA)}function zg(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Tl(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=Di.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=Di.get(e.url);s&&s===e&&e.subscribers.size>0&&lu(e)},hA)}}function lu(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(fi(gA(e.url)));e.es=n,xA(e),n.addEventListener("open",()=>{wr(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);zg(e)}),n.addEventListener("message",()=>wr(e)),n.addEventListener("heartbeat",()=>wr(e)),Og(e),wr(e)}function Og(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=>{wr(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 vA(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Tl(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),Di.delete(e.url)}function li(e,n={}){let s=Di.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},Di.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;lu(s),Og(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=Di.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&vA(l))}}const uh=100;function Fg(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),b=i.useRef(0),v=i.useRef(e),x=i.useRef(s),y=i.useRef(n),k=i.useRef(0);(v.current!==e||x.current!==s||y.current!==n)&&(v.current=e,x.current=s,y.current=n,b.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 A=b.current,P=++k.current;g.current=!1;const T=e,_=s;async function C(){if(!T)return;l(!0),f(!1);try{const O=await wu(T,_,{limit:uh});if(g.current||b.current!==A||k.current!==P)return;r(O.entries),d(O.hasMore),m(O.total)}catch{if(g.current||b.current!==A||k.current!==P)return;r([]),d(!1),m(null)}finally{!g.current&&b.current===A&&k.current===P&&l(!1)}const $=_?`?projectId=${encodeURIComponent(_)}`:"";p.current=li(`/api/tasks/${T}/logs/stream${$}`,{events:{"agent:log":O=>{if(!(g.current||b.current!==A))try{const E=JSON.parse(O.data);r(S=>[...S,E]),m(S=>S!==null?S+1:null)}catch{}}}})}return C(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=i.useCallback(async()=>{if(!e||h)return;const A=b.current,P=a.length,T=e;f(!0);try{const _=await wu(T,s,{limit:uh,offset:P});if(g.current||b.current!==A)return;r(C=>[..._.entries,...C]),d(_.hasMore),m(_.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),w=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:w,loadMore:R,hasMore:c,total:u,loadingMore:h}}function yA(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 mh={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})},Ug=50,wA={triage:"Plan"};function hh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Ug}function jd(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function kA(e){const n=new Map;return e.map(s=>{const a=jd(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function jA(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function xc({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(rn,{size:14}):t.jsx(_n,{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 NA(e,n){return e.agent?jA(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function SA(e,n){const s=[];for(let a=0;a<e.length;a+=1){const r=e[a],o=n[a]??`${jd(r)}|fallback`,l=a>0?e[a-1]:void 0,c=NA(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]??`${jd(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 CA({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,b]=i.useState(!0),[v,x]=i.useState(!1),[y,k]=i.useState(!1),[N,R]=i.useState(!0),w=i.useMemo(()=>kA(e),[e]),A=i.useMemo(()=>SA(e,w),[e,w]);i.useLayoutEffect(()=>{const S=u.current;if(!S)return;const I=e.length,F=m.current,G=h.current||S.scrollHeight,X=w[0]??null,M=w[w.length-1]??null,z=f.current!==X,L=p.current!==M;if(I>F)if(F===0)S.scrollTop=S.scrollHeight;else{const j=G-(S.scrollTop+S.clientHeight)<=Ug,H=L&&!z,Q=z&&!L;if(H&&j&&(S.scrollTop=S.scrollHeight),Q){const de=S.scrollHeight-G;de>0&&(S.scrollTop+=de)}}m.current=I,h.current=S.scrollHeight,f.current=X,p.current=M,R(hh(S))},[e,w]);const P=i.useCallback(()=>{const S=u.current;S&&R(hh(S))},[]),T=i.useCallback(()=>{const S=u.current;S&&(S.scrollTop=S.scrollHeight,R(!0))},[]),_=i.useCallback(S=>{S.key==="Escape"&&v&&x(!1)},[v]);i.useEffect(()=>{if(v)return document.addEventListener("keydown",_),()=>{document.removeEventListener("keydown",_)}},[v,_]);const C=s?.provider&&s?.modelId,$=a?.provider&&a?.modelId,O=r?.provider&&r?.modelId,E=i.useMemo(()=>{const S=[];return C&&S.push({role:"Executor",provider:s.provider,modelId:s.modelId}),$&&S.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),O&&S.push({role:"Planning",provider:r.provider,modelId:r.modelId}),S},[C,s,$,a,O,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:[E.map(S=>t.jsx(Fn,{provider:S.provider,size:"sm"},`${S.role}-${S.provider}-${S.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>k(S=>!S),"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(rn,{size:14}):t.jsx(_n,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>b(S=>!S),"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:()=>x(S=>!S),"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(Wr,{size:14}):t.jsx(yl,{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:"}),C?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{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:"}),$?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{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:"}),O?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{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:P,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(bt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),A.map(S=>{const I=S.kind==="single"?S.entry:S.entries[0],F=S.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:yA(I.timestamp)}):null,G=S.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",wA[I.agent]??I.agent,"]"]}),F]}):null;if(S.kind==="single"){const{entry:M}=S;if(M.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[G,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",M.text]}),M.detail?t.jsx(xc,{detail:M.detail,type:"tool"}):null]},S.key);if(M.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[G,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",M.text]}),M.detail?t.jsx(xc,{detail:M.detail,type:"tool_result"}):null]},S.key);if(M.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[G,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",M.text]}),M.detail?t.jsx(xc,{detail:M.detail,type:"tool_error"}):null]},S.key)}const X=S.kind==="single"?I.text:S.entries.map(M=>M.text).join("");return S.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[G,g?t.jsx("div",{className:"markdown-body",children:t.jsx(gi,{remarkPlugins:[bi],components:mh,children:X})}):t.jsx("pre",{className:"agent-log-plain-block",children:X})]},S.key):t.jsxs("div",{className:"agent-log-text",children:[G,g?t.jsx("div",{className:"markdown-body",children:t.jsx(gi,{remarkPlugins:[bi],components:mh,children:X})}):t.jsx("pre",{className:"agent-log-plain-block",children:X})]},S.key)}),!N&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:T,"data-testid":"agent-log-return-to-live",children:[t.jsx(rn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function $a(e){return e??void 0}function ko(e){return{provider:$a(e.modelProvider),modelId:$a(e.modelId)}}function jo(e){return{provider:$a(e.validatorModelProvider),modelId:$a(e.validatorModelId)}}function No(e){return{provider:$a(e.planningModelProvider),modelId:$a(e.planningModelId)}}function EA(e,n){return xf(e,n)}function MA(e,n){return vf(e,n)}function _A(e,n){return yf(e,n)}function vc(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 yc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function wc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function AA(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 PA({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,b]=i.useState(()=>ko(e)),[v,x]=i.useState(()=>ko(e)),[y,k]=i.useState(()=>jo(e)),[N,R]=i.useState(()=>jo(e)),[w,A]=i.useState(()=>No(e)),[P,T]=i.useState(()=>No(e)),[_,C]=i.useState(()=>e.thinkingLevel??null),[$,O]=i.useState(()=>e.thinkingLevel??null),[E,S]=i.useState(null),I=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),As().then(te=>{o(te.models),c(te.favoriteProviders),u(te.favoriteModels)}).catch(te=>{p(te.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const F=i.useCallback(async te=>{const xe=l,_e=xe.includes(te)?xe.filter(Ne=>Ne!==te):[te,...xe];c(_e);try{await Cn({favoriteProviders:_e,favoriteModels:d})}catch{c(xe),n("Failed to update favorites","error")}},[l,d,n]),G=i.useCallback(async te=>{const xe=d,_e=xe.includes(te)?xe.filter(Ne=>Ne!==te):[te,...xe];u(_e);try{await Cn({favoriteProviders:l,favoriteModels:_e})}catch{u(xe),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{I.current=e.id;const te=ko(e),xe=jo(e),ne=No(e);b(te),x(te),k(xe),R(xe),A(ne),T(ne);const _e=e.thinkingLevel??null;C(_e),O(_e),S(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const X=i.useMemo(()=>yc(g),[g]),M=i.useMemo(()=>yc(y),[y]),z=i.useMemo(()=>yc(w),[w]),L=i.useMemo(()=>EA(e,a),[e,a]),j=i.useMemo(()=>MA(e,a),[e,a]),H=i.useMemo(()=>_A(e,a),[e,a]),Q=E!==null,de=i.useCallback(async(te,xe)=>{const ne=e.id,_e=v,Ne=N,Se=P;S(te);try{const He=s?te==="executor"?{modelProvider:xe.provider??null,modelId:xe.modelId??null}:te==="validator"?{validatorModelProvider:xe.provider??null,validatorModelId:xe.modelId??null}:{planningModelProvider:xe.provider??null,planningModelId:xe.modelId??null}:{modelProvider:(te==="executor"?xe:v).provider??null,modelId:(te==="executor"?xe:v).modelId??null,validatorModelProvider:(te==="validator"?xe:N).provider??null,validatorModelId:(te==="validator"?xe:N).modelId??null,planningModelProvider:(te==="planning"?xe:P).provider??null,planningModelId:(te==="planning"?xe:P).modelId??null},Ye=await ni(ne,He);if(I.current!==ne)return;const Oe=ko(Ye),ke=jo(Ye),De=No(Ye);x(Oe),b(Oe),R(ke),k(ke),T(De),A(De),s?.(Ye),n(AA(te,{executor:Oe,validator:ke,planning:De}[te]),"success")}catch(He){if(I.current!==ne)return;te==="executor"?b(_e):te==="validator"?k(Ne):A(Se),n(Me(He)||"Failed to save model settings","error")}finally{I.current===ne&&S(null)}},[e.id,v,N,P,n,s]),pe=i.useCallback(te=>{const xe=vc(te);b(xe),!wc(xe,v)&&de("executor",xe)},[v,de]),B=i.useCallback(te=>{const xe=vc(te);k(xe),!wc(xe,N)&&de("validator",xe)},[N,de]),ve=i.useCallback(te=>{const xe=vc(te);A(xe),!wc(xe,P)&&de("planning",xe)},[P,de]),U=i.useCallback(async te=>{const xe=e.id,ne=$,_e=te===""?null:te;C(_e),S("thinking");try{const Ne=await ni(xe,{thinkingLevel:_e});if(I.current!==xe)return;const Se=Ne.thinkingLevel??null;O(Se),C(Se),s?.(Ne);const He=a?.defaultThinkingLevel??"off";n(Se===null?`Thinking level set to default (${He})`:`Thinking level set to ${Se}`,"success")}catch(Ne){if(I.current!==xe)return;C(ne),n(Me(Ne)||"Failed to save thinking level","error")}finally{I.current===xe&&S(null)}},[e.id,$,a,n,s]),se=!v.provider&&!v.modelId,ee=!N.provider&&!N.modelId,ie=!P.provider&&!P.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),As().then(te=>{o(te.models),c(te.favoriteProviders),u(te.favoriteModels)}).catch(te=>p(te.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:se?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",L.provider&&L.modelId?` (${L.provider}/${L.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Fn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(hs,{id:"executorModel",label:"Executor Model",value:X,onChange:pe,models:r,disabled:Q,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:F,favoriteModels:d,onToggleModelFavorite:G}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:ee?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",j.provider&&j.modelId?` (${j.provider}/${j.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[N.provider&&t.jsx(Fn,{provider:N.provider,size:"sm"}),N.provider,"/",N.modelId]})}),t.jsx(hs,{id:"validatorModel",label:"Reviewer Model",value:M,onChange:B,models:r,disabled:Q,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:F,favoriteModels:d,onToggleModelFavorite:G}),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:ie?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:[P.provider&&t.jsx(Fn,{provider:P.provider,size:"sm"}),P.provider,"/",P.modelId]})}),t.jsx(hs,{id:"planningModel",label:"Planning Model",value:z,onChange:ve,models:r,disabled:Q,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:F,favoriteModels:d,onToggleModelFavorite:G}),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:$===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:$})}),t.jsxs("select",{id:"thinkingLevel",value:_??"",onChange:te=>U(te.target.value),disabled:Q,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:se&&ee&&ie&&$===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const RA={open:t.jsx(pl,{size:16}),closed:t.jsx(qr,{size:16}),merged:t.jsx(Kp,{size:16})};function TA({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(""),[b,v]=i.useState(!1),[x,y]=i.useState(!1),[k,N]=i.useState(null),R=i.useCallback(async()=>{if(h.trim()){v(!0);try{const T=await Vw(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]),w=i.useCallback(async()=>{if(s){y(!0);try{const T=await Ww(e,n);N(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(Os,{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(Os,{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(Os,{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:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:T=>g(T.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Os,{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(xn,{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 A=RA[s.status]??t.jsx(pl,{size:16}),P=k?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Os,{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:A}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:w,disabled:x,title:"Refresh PR status",children:t.jsx(Qn,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),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:P.length>0?`Waiting for: ${P.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(Ci,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Ax,{size:14}),"View on GitHub"]})]})]})]})}const ph=2e3;function IA(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function $A(e){return e==="agent"||e==="system"}function DA({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),b=i.useMemo(()=>[...e.comments||[]].sort((A,P)=>new Date(P.createdAt).getTime()-new Date(A.createdAt).getTime()),[e.comments]),v=o.length>ph;async function x(){const A=o.trim();if(A){f(!0);try{const P=await gw(e.id,A,r);l(""),n?.(P),s("Comment added","success")}catch(P){s(Me(P)||"Failed to add comment","error")}finally{f(!1)}}}async function y(A){const P=u.trim();if(P){f(!0);try{const T=await uw(e.id,A,P,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 k(A){g(A);try{const P=await mw(e.id,A,r);n?.(P),s("Comment deleted","success")}catch(P){s(Me(P)||"Failed to delete comment","error")}finally{g(null)}}function N(A){A.key==="Enter"&&(A.ctrlKey||A.metaKey)&&(A.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(A=>{const P=A.author===a,T=c===A.id,_=$A(A.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[_?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:A.author}),t.jsx("span",{className:"detail-log-timestamp",children:IA(A)})]}),P&&!T?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(A.id),m(A.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void k(A.id),disabled:p===A.id,children:p===A.id?"Deleting…":"Delete"})]}):null]}),T?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:C=>m(C.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(A.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:A.text})]},A.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:A=>l(A.target.value),onKeyDown:N,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," / ",ph]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function LA(e){return e?e.slice(0,7):"Unknown"}function zA({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:LA(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 Bg(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(Vo.Fragment,{children:`${s}
675
- `},a)})}function OA(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function FA({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);xi(f,e,"fusion:changes-diff-modal-size");const p=Ai(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)},[]),b=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=k=>{if(k.key==="Escape"){l();return}k.key==="ArrowUp"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),g()),k.key==="ArrowDown"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),b())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,b]),!e)return null;const v=d!==null?s[d]:null,x=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(si,{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(hl,{})}),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:b,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(_n,{})})]}),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(Go,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(Qn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[x&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Vr,{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,k)=>t.jsxs("button",{className:`changes-diff-file-item ${d===k?"selected":""}`,onClick:()=>u(k),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:OA(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:Bg(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(si,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Hg(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function kc(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(Vr,{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(si,{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:Hg("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function UA({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,b]=i.useState(new Set),[v,x]=i.useState(null),[y,k]=i.useState(!0),[N,R]=i.useState(!1),w=a==="done",A=w&&!!r?.commitSha,P=a==="in-progress"||a==="in-review"||A,T=i.useCallback(async()=>{if(!P){h(!1);return}try{h(!0),p(null);const E=await cf(e,void 0,s),S=E.files.map(I=>({path:I.path,status:I.status,additions:I.additions,deletions:I.deletions,patch:I.patch}));c(S),u(E.stats),S.length>0&&(b(new Set([S[0].path])),x(0))}catch(E){p(Me(E)||"Failed to load diff")}finally{h(!1)}},[e,s,P]);i.useEffect(()=>{T()},[T]);const _=E=>{b(S=>{const I=new Set(S);if(I.has(E))I.delete(E);else{I.add(E);const F=l.findIndex(G=>G.path===E);F!==-1&&x(F)}return I})},C=E=>{if(E<0||E>=l.length)return;const S=l[E].path;b(new Set([S])),x(E)},$=v!==null&&v>0,O=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(Ts,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!w&&!n)return o&&o.length>0?kc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(w&&!A){if(o&&o.length>0)return kc(o,!0,r);const E=r?.filesChanged,S=r?.insertions,I=r?.deletions,F=E!=null||S!=null||I!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:F?`Merge summary: ${E??0} file${(E??0)===1?"":"s"} changed, +${S??0} additions, -${I??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?kc(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(si,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:w?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Vr,{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(si,{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:()=>$&&C(v-1),disabled:!$,title:"Previous file","aria-label":"Previous file",children:t.jsx(hl,{})}),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:()=>O&&C(v+1),disabled:!O,title:"Next file","aria-label":"Next file",children:t.jsx(_n,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>k(E=>!E),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Go,{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:()=>R(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(yl,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(E=>{const S=g.has(E.path);return t.jsxs("div",{className:`changes-file-item ${S?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>_(E.path),children:[t.jsx("span",{className:"changes-file-toggle",children:S?t.jsx(rn,{size:14}):t.jsx(_n,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${E.status}`,title:E.status,children:Hg(E.status)}),t.jsx("span",{className:"changes-file-path",title:E.path,children:t.jsx("bdo",{dir:"ltr",children:E.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${E.additions} -${E.deletions}`,children:["+",E.additions," -",E.deletions]})]}),S&&E.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:Bg(E.patch)})})})]},E.path)})}),t.jsx(FA,{isOpen:N,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>R(!1),onRefresh:T})]})}function fh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function BA(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function D6(e,n){const s=BA(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 HA(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const gh=["image/png","image/jpeg","image/gif","image/webp"];function qA(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 qg({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:b,validatorModel:v,onValidatorModelChange:x,planningModel:y,onPlanningModelChange:k,thinkingLevel:N,onThinkingLevelChange:R,presetMode:w,onPresetModeChange:A,selectedPresetId:P,onSelectedPresetIdChange:T,selectedWorkflowSteps:_,onWorkflowStepsChange:C,onDefaultOnApplied:$,pendingImages:O,onImagesChange:E,tasks:S,projectId:I,disabled:F=!1,addToast:G,isActive:X=!0,onAutoSaveDescription:M,onPlanningMode:z,onSubtaskBreakdown:L,onClose:j,renderBelowPrimary:H,renderBelowModelConfiguration:Q,hideDependencies:de,autoExpandMoreOptionsOnSelection:pe=!0,reviewLevel:B,onReviewLevelChange:ve,executionMode:U,onExecutionModeChange:se}){const ee=(de?!1:o.length>0)||O.length>0||_.length>0||w!=="default"||(f??Ms)!==Ms||g!==""||v!==""||(y||"")!==""||(N||"")!==""||B!==void 0||U==="fast"||(c||"")!=="",[ie,te]=i.useState(!1),[xe,ne]=i.useState(pe?ee:!1),[_e,Ne]=i.useState(""),[Se,He]=i.useState([]),[Ye,Oe]=i.useState([]),[ke,De]=i.useState([]),[re,oe]=i.useState(!1),[we,Z]=i.useState(null),[qe,Qe]=i.useState([]),[ge,Ue]=i.useState("idle"),[Xe,wt]=i.useState(!1),[ye,le]=i.useState(!1),[Te,be]=i.useState(!1),Le=i.useRef(null),Je=i.useRef(null),nt=i.useRef(null),mt=i.useRef(null),Ie=i.useRef(null),ze=i.useRef(null),st=i.useRef(null),yt=i.useRef(!1),Re=i.useRef(ee),kt=i.useRef(n.trim()),Et=i.useRef(n.trim());i.useEffect(()=>{X&&(oe(!0),As().then(W=>{He(W.models),Oe(W.favoriteProviders),De(W.favoriteModels)}).catch(()=>{}).finally(()=>oe(!1)),jl(I).then(W=>Z(W)).catch(()=>Z(null)),Jr(I).then(W=>Qe(W.filter(je=>je.enabled))).catch(()=>Qe([])))},[X,I]);const jt=we?.modelPresets||[],Rt=jt.find(W=>W.id===P),Dt=(de?!1:o.length>0)||O.length>0||_.length>0||w!=="default"||(f??Ms)!==Ms||g!==""||v!==""||(y||"")!==""||(N||"")!==""||B!==void 0||U==="fast"||(c||"")!=="";i.useEffect(()=>{if(e!=="create"||!X||!we?.autoSelectModelPreset)return;const W=(we.defaultPresetBySize,void 0);if(W){const je=fh(W);T(W.id),A("preset"),b(je.executorValue),x(je.validatorValue)}},[X,we,jt,e]);const Tt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!X||Tt.current||qe.length===0)return;const W=qe.filter(ce=>ce.defaultOn);if(W.length===0)return;Tt.current=!0;const je=W.map(ce=>ce.id);C(je),$?.(je)},[e,X,qe]),i.useEffect(()=>{X||(Tt.current=!1)},[X]),i.useEffect(()=>{if(!pe){Re.current=Dt;return}Dt&&!Re.current&&ne(!0),Re.current=Dt},[Dt,pe]),i.useEffect(()=>{xe||(te(!1),Ne(""))},[xe]),i.useEffect(()=>{e!=="edit"||!X||mt.current&&(mt.current.focus(),mt.current.select())},[e,X]),i.useEffect(()=>{if(!ie)return;const W=je=>{Je.current&&!Je.current.contains(je.target)&&te(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[ie]),i.useEffect(()=>{(e!=="edit"||F)&&be(!1)},[e,F]),i.useEffect(()=>{if(e!=="edit"){Ue("idle");return}const W=n.trim();kt.current=W,Et.current=W,Ue("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!M||!X)return;const W=n.trim(),je=kt.current;if(W===je||W===Et.current){ze.current&&(clearTimeout(ze.current),ze.current=null),yt.current||Ue("idle");return}return ze.current&&clearTimeout(ze.current),ze.current=setTimeout(async()=>{if(!yt.current){yt.current=!0,Ue("saving");try{await M(W),Et.current=W,Ue("saved"),st.current&&clearTimeout(st.current),st.current=setTimeout(()=>{Ue("idle"),st.current=null},2e3)}catch{Ue("idle")}finally{yt.current=!1,ze.current=null}}},1500),()=>{ze.current&&(clearTimeout(ze.current),ze.current=null)}},[e,n,M,X]),i.useEffect(()=>()=>{ze.current&&clearTimeout(ze.current),st.current&&clearTimeout(st.current)},[]),i.useEffect(()=>{if(!Xe)return;const W=je=>{Le.current&&!Le.current.contains(je.target)&&wt(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[Xe]);const It=i.useCallback(W=>{const je=W.clipboardData?.items;if(je)for(let ce=0;ce<je.length;ce++){const $e=je[ce];if($e.type.startsWith("image/")){const it=$e.getAsFile();if(it&&gh.includes(it.type)){W.preventDefault(),E([...O,{file:it,previewUrl:URL.createObjectURL(it)}]);return}}}},[O,E]),Ut=i.useCallback(W=>{W.preventDefault();const je=W.dataTransfer.files;for(let ce=0;ce<je.length;ce++){const $e=je[ce];if(gh.includes($e.type)){E([...O,{file:$e,previewUrl:URL.createObjectURL($e)}]);return}}},[O,E]),Ft=i.useCallback(W=>{const je=O[W];je&&URL.revokeObjectURL(je.previewUrl),E(O.filter((ce,$e)=>$e!==W))},[O,E]),Jt=i.useCallback(W=>{l(o.includes(W)?o.filter(je=>je!==W):[...o,W])},[o,l]),Vt=(W,je)=>W.length>je?W.slice(0,je)+"…":W,Yt=i.useCallback(W=>{s(W.target.value);const je=W.target;je.style.height="auto",je.style.height=je.scrollHeight+"px"},[s]),Kt=i.useCallback(()=>{be(W=>!W)},[]),qt=i.useCallback(W=>{!Te||W.key!=="Escape"||(W.preventDefault(),W.stopPropagation(),be(!1))},[Te]),Bt=i.useCallback(async W=>{const je=n.trim();if(!(!je||ye)){le(!0);try{const ce=await af(je,W,I);s(ce),wt(!1),G("Description refined with AI","success"),nt.current&&(nt.current.style.height="auto",nt.current.style.height=nt.current.scrollHeight+"px")}catch(ce){const $e=rf(ce);G($e,"error")}finally{le(!1)}}},[n,ye,G,s,I]),Xt=i.useCallback(async W=>{const je=Ye,$e=je.includes(W)?je.filter(it=>it!==W):[W,...je];Oe($e);try{await Cn({favoriteProviders:$e,favoriteModels:ke})}catch{Oe(je)}},[Ye,ke]),an=i.useCallback(async W=>{const je=ke,$e=je.includes(W)?je.filter(it=>it!==W):[W,...je];De($e);try{await Cn({favoriteProviders:Ye,favoriteModels:$e})}catch{De(je)}},[ke,Ye]),Qt=i.useCallback(W=>{if(W<=0)return;const je=[..._];[je[W-1],je[W]]=[je[W],je[W-1]],C(je)},[_,C]),fe=i.useCallback(W=>{if(W>=_.length-1)return;const je=[..._];[je[W],je[W+1]]=[je[W+1],je[W]],C(je)},[_,C]),Fe=i.useCallback(W=>{C(_.filter(je=>je!==W))},[_,C]),ae=new Map;for(const W of qe)ae.set(W.id,{name:W.name,description:W.description});const Pe=S.filter(W=>!o.includes(W.id)).sort((W,je)=>{const ce=je.createdAt.localeCompare(W.createdAt);if(ce!==0)return ce;const $e=parseInt(W.id.slice(W.id.lastIndexOf("-")+1),10)||0;return(parseInt(je.id.slice(je.id.lastIndexOf("-")+1),10)||0)-$e}),Ae=_e?Pe.filter(W=>W.id.toLowerCase().includes(_e.toLowerCase())||W.title&&W.title.toLowerCase().includes(_e.toLowerCase())||W.description&&W.description.toLowerCase().includes(_e.toLowerCase())):Pe;return t.jsxs("div",{className:"task-form",onDrop:Ut,onDragOver:W=>W.preventDefault(),onPaste:It,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:mt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:W=>r(W.target.value),disabled:F})]}),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:Le,onKeyDown:qt,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:Kt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Wr,{size:14})})]}),t.jsx("textarea",{ref:nt,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Yt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:F||ye}),(()=>{const W=!!n.trim()&&!F;return t.jsxs(t.Fragment,{children:[!Te&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${W?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Kt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(yl,{size:14})}),W&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ye?"refine-button--loading":""}`,onClick:()=>wt(je=>!je),disabled:ye,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),ye?"Refining...":"Refine"]})]})})(),Xe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:W=>W.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Bt("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:()=>Bt("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:()=>Bt("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:()=>Bt("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(z||L)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[z&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const W=n.trim();if(!W){G("Enter a description first","error");return}j?.(),z(W)},disabled:F||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),L&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const W=n.trim();if(!W){G("Enter a description first","error");return}j?.(),L(W)},disabled:F||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),H,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>ne(W=>!W),"aria-expanded":xe,"aria-controls":"task-form-more-options",disabled:F,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),xe?t.jsx(ri,{size:14}):t.jsx(rn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${xe?"":" collapsed"}`,"aria-hidden":!xe,hidden:!xe,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),O.length>0&&t.jsx("div",{className:"inline-create-previews",children:O.map((W,je)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:W.previewUrl,alt:W.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Ft(je),disabled:F,title:"Remove image",children:"×"})]},W.previewUrl))}),t.jsx("input",{ref:Ie,type:"file",accept:"image/*",onChange:W=>{const je=W.target.files?.[0];je&&(E([...O,{file:je,previewUrl:URL.createObjectURL(je)}]),W.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Ie.current?.click(),disabled:F,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:W=>d(W.target.value||void 0),disabled:F||m,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(u??[]).map(W=>t.jsxs("option",{value:W.id,children:[W.name," (",HA(W.status),")"]},W.id))]}),(()=>{const W=(u??[]).find(je=>je.id===c);return W?t.jsx("div",{className:"task-form-node-status",children:t.jsx(na,{status:W.status,showLabel:!0})}):null})(),t.jsx("small",{children:h??"Task override takes priority over project default node routing."})]}),!de&&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:Je,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>te(W=>!W),disabled:F,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ie&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:_e,onChange:W=>Ne(W.target.value),onClick:W=>W.stopPropagation()}),Ae.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ae.map(W=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(W.id)?" selected":""}`,onClick:()=>Jt(W.id),onMouseDown:je=>je.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:W.id}),t.jsx("span",{className:"dep-dropdown-title",children:Vt(W.title||W.description||W.id,30)})]},W.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(W=>t.jsxs("span",{className:"dep-chip",children:[W,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Jt(W),disabled:F,children:"×"})]},W))})]})}),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??Ms,onChange:W=>p(W.target.value),disabled:F,children:Xr.map(W=>t.jsx("option",{value:W,children:W[0].toUpperCase()+W.slice(1)},W))})]}),se&&U!==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:U,onChange:W=>se(W.target.value),disabled:F,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),re?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Se.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:w==="preset"?P:w,onChange:W=>{const je=W.target.value;if(je==="default"){A("default"),T(""),b(""),x("");return}if(je==="custom"){A("custom"),T("");return}const ce=jt.find(it=>it.id===je),$e=fh(ce);A("preset"),T(je),b($e.executorValue),x($e.validatorValue)},disabled:F,children:[t.jsx("option",{value:"default",children:"Use default"}),jt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,jt.map(W=>t.jsx("option",{value:W.id,children:W.name},W.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),w==="preset"&&Rt?t.jsxs("small",{children:["Using preset: ",Rt.name]}):null,w==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>A("custom"),disabled:F,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(hs,{id:"executor-model",label:"Executor Model",value:g,onChange:W=>{A("custom"),T(""),b(W)},models:Se,disabled:F||w==="preset",favoriteProviders:Ye,onToggleFavorite:Xt,favoriteModels:ke,onToggleModelFavorite:an})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(hs,{id:"validator-model",label:"Reviewer Model",value:v,onChange:W=>{A("custom"),T(""),x(W)},models:Se,disabled:F||w==="preset",favoriteProviders:Ye,onToggleFavorite:Xt,favoriteModels:ke,onToggleModelFavorite:an})]}),k&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(hs,{id:"planning-model",label:"Planning Model",value:y||"",onChange:W=>{A("custom"),T(""),k(W)},models:Se,disabled:F||w==="preset",favoriteProviders:Ye,onToggleFavorite:Xt,favoriteModels:ke,onToggleModelFavorite:an})]}),R&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:N||"",onChange:W=>R(W.target.value),disabled:F||w==="preset",children:[t.jsxs("option",{value:"",children:["Default (",we?.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"})]})]}),ve&&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:B??"",onChange:W=>ve(W.target.value===""?void 0:parseInt(W.target.value,10)),disabled:F,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),Q,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:qe.length>0&&qe.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:_.includes(W.id),onChange:je=>{C(je.target.checked?[..._,W.id]:_.filter(ce=>ce!==W.id))},disabled:F}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[W.name,qA(W.phase||"pre-merge",W.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:W.description})]})]},W.id))})]}),_.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),_.map((W,je)=>{const ce=ae.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:je+1}),t.jsx("span",{className:"workflow-step-order-name",children:ce?.name||W}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Qt(je),disabled:F||je===0,"data-testid":`workflow-step-move-up-${W}`,title:"Move up",children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>fe(je),disabled:F||je===_.length-1,"data-testid":`workflow-step-move-down-${W}`,title:"Move down",children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Fe(W),disabled:F,"data-testid":`workflow-step-remove-${W}`,title:"Remove",children:t.jsx(Wt,{})})]})]},W)})]})]})]})]})}const bh={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 VA(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function WA(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 KA(e){return e?new Date(e).toLocaleString():null}function GA(e){const n=e.split(`
676
- `);return n.length<=1?e:`${n.length} lines`}function So(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 JA({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 YA({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,b]=i.useState([]),[v,x]=i.useState(!1),y=n.some(j=>j.status==="pending"),{entries:k}=Fg(e,!!l&&y,o);i.useEffect(()=>{let j=!1;return Jr(o).then(H=>{j||b(H.filter(Q=>Q.enabled))}).catch(()=>{j||b([])}),()=>{j=!0}},[o]);const N=a??[],R=i.useMemo(()=>g.map(j=>({id:j.id,name:j.name,description:j.description,phase:j.phase||"pre-merge"})),[g]),w=i.useMemo(()=>new Map(R.map(j=>[j.id,j])),[R]),A=j=>{u(H=>({...H,[j]:!H[j]}))},P=j=>{h(H=>{const Q=H[j]??"markdown";return{...H,[j]:Q==="markdown"?"plain":"markdown"}})},T=j=>{p(j)},_=()=>{p(null)};i.useEffect(()=>{if(!f)return;const j=H=>{H.key==="Escape"&&_()};return document.addEventListener("keydown",j),()=>{document.removeEventListener("keydown",j)}},[f]);const C=i.useCallback((j,H)=>{if(c){if(H){if(N.includes(j)){c(N);return}c([...N,j]);return}c(N.filter(Q=>Q!==j))}},[c,N]),$=i.useCallback(j=>{if(!c||j<=0)return;const H=[...N];[H[j-1],H[j]]=[H[j],H[j-1]],c(H)},[c,N]),O=i.useCallback(j=>{if(!c||j>=N.length-1)return;const H=[...N];[H[j],H[j+1]]=[H[j+1],H[j]],c(H)},[c,N]),E=i.useCallback(j=>{c&&c(N.filter(H=>H!==j))},[c,N]),S=n.length>0,I=N.length>0;i.useEffect(()=>{r||x(!1)},[r]);const F=i.useMemo(()=>N.map(j=>{const H=w.get(j);return{id:j,name:H?.name||j,description:H?.description||"Step definition not found.",phase:H?.phase||"pre-merge"}}),[N,w]),G=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:R.map(j=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${j.id}`,children:[t.jsx("input",{type:"checkbox",checked:N.includes(j.id),onChange:H=>C(j.id,H.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[j.name,So(j.phase,j.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:j.description})]})]},j.id))})]}),N.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:"}),N.map((j,H)=>{const Q=w.get(j);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${j}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:Q?.name||j}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>$(H),disabled:H===0,"data-testid":`workflow-step-move-up-${j}`,title:"Move up",children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(H),disabled:H===N.length-1,"data-testid":`workflow-step-move-down-${j}`,title:"Move down",children:t.jsx(rn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>E(j),"data-testid":`workflow-step-remove-${j}`,title:"Remove",children:t.jsx(Wt,{})})]})]},j)})]})]}),X=()=>{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(!S)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const j=n.filter(B=>B.status==="passed").length,H=n.filter(B=>B.status==="failed").length,Q=n.filter(B=>B.status==="skipped").length,de=n.filter(B=>B.status==="pending").length,pe=[`${n.length} step${n.length!==1?"s":""}`];return j>0&&pe.push(`${j} passed`),H>0&&pe.push(`${H} failed`),Q>0&&pe.push(`${Q} skipped`),de>0&&pe.push(`${de} 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:pe.join(" · ")}),n.map((B,ve)=>{const U=B.phase||"pre-merge",se=d[B.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${B.status}`,"data-testid":`workflow-result-item-${B.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[B.workflowStepName,So(U,B.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${B.status}`,"data-testid":`workflow-result-badge-${B.workflowStepId}`,children:VA(B.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[B.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",KA(B.startedAt)]}),B.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:WA(B.startedAt,B.completedAt)})]}),B.status==="pending"&&B.startedAt?t.jsx(JA,{entries:k,startedAt:B.startedAt,stepId:B.workflowStepId}):B.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:()=>A(B.workflowStepId),"data-testid":`workflow-result-toggle-${B.workflowStepId}`,children:se?"Hide output":"Show output"}),!se&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${B.workflowStepId}`,children:GA(B.output)}),se&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>P(B.workflowStepId),"data-testid":`workflow-result-mode-toggle-${B.workflowStepId}`,title:(m[B.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[B.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{className:"workflow-result-expand-toggle",onClick:()=>T(B.workflowStepId),"data-testid":`workflow-result-expand-${B.workflowStepId}`,title:"Expand output",children:t.jsx(yl,{size:12})})]})]}),se&&t.jsx("div",{className:`workflow-result-output${(m[B.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${B.workflowStepId}`,children:(m[B.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(gi,{remarkPlugins:[bi],components:bh,children:B.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:B.output})})]}):null]},`${B.workflowStepId}-${ve}`)})]})},M=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>x(j=>!j),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Wn,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(vs,{size:14}),"Edit"]})}):null,z=!s&&!S&&I,L=r&&S;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[z?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[F.length," step",F.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:F.map(j=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${j.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[j.name,So(j.phase,j.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:j.description})]},j.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),G()]}):t.jsxs(t.Fragment,{children:[L&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),X(),G()]}),f&&(()=>{const j=n.find(de=>de.workflowStepId===f);if(!j)return null;const H=m[j.workflowStepId]??"markdown",Q=j.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:de=>{de.target===de.currentTarget&&_()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:j.workflowStepName}),So(Q,j.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{className:"workflow-result-mode-toggle",onClick:()=>P(j.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:_,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(Wt,{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(gi,{remarkPlugins:[bi],components:bh,children:j.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:j.output})})})]})})})()]})}function QA(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const XA=new Set(["planning","researching","executing","finalizing","merging"]);function ZA(e){return e!==void 0&&e!=="online"}function eP({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),Zo().then(_=>{o(_)}).catch(_=>{u(Me(_)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const b=i.useMemo(()=>new Map(r.map(_=>[_.id,_])),[r]),v=i.useMemo(()=>[...r].sort((_,C)=>_.name.localeCompare(C.name)),[r]),x=n,y=e.nodeId??x?.defaultNodeId??null,k=e.nodeId?"Per-task override":x?.defaultNodeId?"Project default":"No routing",N=y?b.get(y):void 0,R=N?`${N.name} (${N.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||XA.has(e.status),A=w||f||l,P=i.useCallback(async _=>{if(_===m)return;const C=e.id,$=m;h(_),p(!0);try{const O=await ni(C,{nodeId:_||null});if(g.current!==C)return;h(O.nodeId??""),a?.(O),s(_?"Node override updated":"Node override cleared","success")}catch(O){if(g.current!==C)return;h($),s(Me(O)||"Failed to update node override","error")}finally{g.current===C&&p(!1)}},[s,a,m,e.id]),T=i.useCallback(()=>{P("")},[P]);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:[N?t.jsx(na,{status:N.status,compact:!0}):null,R,ZA(N?.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:k})]}),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:QA(x?.unavailableNodePolicy)})]})]}),w&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),w?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:A,onChange:_=>{P(_.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(_=>t.jsxs("option",{value:_.id,title:`Status: ${_.status}`,children:[_.name," (",_.type,") — ",_.status]},_.id))]}),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: ",b.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:w||f,onClick:T,children:"Clear override"})]}):null]})]})}const tP=/^[a-zA-Z0-9_-]{1,64}$/,nP=200;function xh(e){return e?new Date(e).toLocaleString():""}function sP(e,n=nP){return e.length<=n?e:e.substring(0,n)+"…"}function iP({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),[b,v]=i.useState(""),[x,y]=i.useState(null),[k,N]=i.useState([]),[R,w]=i.useState(!1),[A,P]=i.useState(!1),[T,_]=i.useState(""),[C,$]=i.useState(""),[O,E]=i.useState(!1),[S,I]=i.useState(null),[F,G]=i.useState(null),[X,M]=i.useState(!1),z=i.useCallback(async()=>{try{const U=await hw(e,a);l(U)}catch(U){n(Me(U)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{z()},[z]);async function L(U){u===U.key?(m(null),f(""),g(null),v(""),y(null),N([]),M(!1)):(m(U.key),f(U.content),g(null),v(""),y(null),N([]),M(!1))}async function j(U){if(x===U)y(null),N([]);else{y(U),w(!0);try{const se=await pw(e,U,a);N(se)}catch(se){n(Me(se)||"Failed to load revisions","error")}finally{w(!1)}}}function H(){u&&(g(u),v(h))}function Q(){g(null),v("")}async function de(){if(!(!p||!b.trim())){E(!0);try{await ku(e,p,b,{},a),g(null),v(""),await z();const U=o.find(se=>se.key===p);U&&f(U.content),n("Document saved","success")}catch(U){n(Me(U)||"Failed to save document","error")}finally{E(!1)}}}async function pe(){const U=T.trim(),se=C.trim();if(!U){n("Document key is required","error");return}if(!tP.test(U)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!se){n("Content is required","error");return}E(!0);try{await ku(e,U,se,{},a),P(!1),_(""),$(""),await z(),n("Document created","success")}catch(ee){n(Me(ee)||"Failed to create document","error")}finally{E(!1)}}async function B(U){I(U);try{await fw(e,U,a),G(null),I(null),u===U&&(m(null),f("")),x===U&&(y(null),N([])),await z(),n("Document deleted","success")}catch(se){n(Me(se)||"Failed to delete document","error")}finally{I(null)}}function ve(U){f(U.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"}),A&&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:U=>_(U.target.value),placeholder:"e.g., plan, notes, research",disabled:O}),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:C,onChange:U=>$(U.target.value),rows:6,placeholder:"Enter document content…",disabled:O})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{P(!1),_(""),$("")},disabled:O,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void pe(),disabled:O||!T.trim()||!C.trim(),children:O?"Creating…":"Create"})]})]}),o.length===0&&!A?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(U=>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(Li,{size:14}),t.jsx("span",{className:"task-document-key",children:U.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",U.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:U.author}),t.jsx("span",{className:"task-document-timestamp",children:xh(U.updatedAt||U.createdAt)})]})]}),u===U.key&&p!==U.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>M(se=>!se),"aria-label":X?"Switch to plain text":"Switch to markdown","aria-pressed":X,title:X?"Switch to plain text":"Switch to markdown",children:X?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:X?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(gi,{remarkPlugins:[bi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),x===U.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),R?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):k.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:k.filter(se=>se.revision<U.revision).sort((se,ee)=>ee.revision-se.revision).map(se=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>ve(se),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",se.revision]}),t.jsx("span",{className:"revision-author",children:se.author}),t.jsx("span",{className:"revision-timestamp",children:xh(se.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:sP(se.content,100)})]},se.id))})]})]}),p===U.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:b,onChange:se=>v(se.target.value),rows:10,disabled:O}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Q,disabled:O,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void de(),disabled:O||!b.trim(),children:O?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void L(U),children:u===U.key?t.jsxs(t.Fragment,{children:[t.jsx(ri,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(rn,{size:14})," Expand"]})}),u===U.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void j(U.key),children:[t.jsx(Rr,{size:14})," History"]}),r&&p!==U.key&&t.jsx("button",{className:"btn btn-sm",onClick:H,children:"Edit"}),r&&(F===U.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 B(U.key),disabled:S===U.key,children:S===U.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>G(null),disabled:S===U.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>G(U.key),children:t.jsx(vn,{size:14})}))]})]})]},U.key))}),r&&!A&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>P(!0),children:[t.jsx(xn,{size:14})," New Document"]})]})}function Co(e){return e.toLocaleString()}function jc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function or(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 aP(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 rP({tokenUsage:e,loading:n,task:s}){const a=Cf(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=aP(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:or(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:or(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:or(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} (${or(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} (${or(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 ${jc(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:Co(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:Co(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:Co(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:Co(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:jc(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:jc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const oP=new Set(["planning","researching","executing","finalizing","merging"]);function lP(e,n){return xf(e,n)}function cP(e,n){return vf(e,n)}function dP(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 uP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=dP(n);return a||yf(e,s)}function mP(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 hP(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 pP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function fP(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 vh(e,n){return e.length>n?e.slice(0,n)+"…":e}function yh(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Nc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Sc(e){return e.trim()}function gP(e){const n=e.trim();return n.length>0?n:void 0}function ji(e){return typeof e=="string"&&Xr.includes(e)?e:Ms}function lr(e){return e==="fast"?"fast":"standard"}function bP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function xP(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 vP=i.lazy(()=>kn(()=>import("./AgentDetailView-KQz9dg0n.js").then(e=>e.A),__vite__mapDeps([0,1,2,3])).then(e=>({default:e.AgentDetailView})));function yP(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:bP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:xP(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 Cc=200,wP=new Set(["triage","todo"]);function Vg({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",embedded:g=!1,onRequestClose:b}){const[v,x]=i.useState(p),[y,k]=i.useState(()=>"prompt"in e?e:null),[N,R]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){k(e),R(!1);return}let J=!1;return R(!0),k(null),Aa(e.id,n).then(Ge=>{J||(k(Ge),R(!1))}).catch(()=>{J||R(!1)}),()=>{J=!0}},[e.id,n]);const w=y?{...y,...e,prompt:y.prompt,log:y.log}:{...e,prompt:""},A=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[P,T]=i.useState(null),[_,C]=i.useState(null),$=yP(w,{sourceAgentName:P?.name});i.useEffect(()=>{x(p)},[p]),i.useEffect(()=>{I(!1)},[e.id]);const[O,E]=i.useState("activity"),[S,I]=i.useState(!1),[F,G]=i.useState(e.attachments||[]),[X,M]=i.useState(!1),[z,L]=i.useState(e.dependencies||[]),[j,H]=i.useState(!1),[Q,de]=i.useState(""),[pe,B]=i.useState(null),[ve,U]=i.useState([]),[se,ee]=i.useState(!1),[ie,te]=i.useState(!1),[xe,ne]=i.useState(!1),[_e,Ne]=i.useState(!1),[Se,He]=i.useState(!1),[Ye,Oe]=i.useState(w.prompt||""),[ke,De]=i.useState(""),[re,oe]=i.useState(!1),[we,Z]=i.useState(""),[qe,Qe]=i.useState(!1),[ge,Ue]=i.useState(!1),[Xe,wt]=i.useState(e.title||""),[ye,le]=i.useState(e.description||""),[Te,be]=i.useState(e.dependencies||[]),[Le,Je]=i.useState(""),[nt,mt]=i.useState(""),[Ie,ze]=i.useState(""),[st,yt]=i.useState(""),[Re,kt]=i.useState("default"),[Et,jt]=i.useState(void 0),[Rt,Dt]=i.useState(Ms),[Tt,It]=i.useState(e.nodeId),[Ut,Ft]=i.useState(lr(e.executionMode)),[Jt,Vt]=i.useState(""),[Yt,Kt]=i.useState(e.enabledWorkflowSteps||[]),[qt,Bt]=i.useState(e.sourceIssue?.provider??""),[Xt,an]=i.useState(e.sourceIssue?.repository??""),[Qt,fe]=i.useState(e.sourceIssue?.externalIssueId??""),[Fe,ae]=i.useState(e.sourceIssue?.url??""),[Pe,Ae]=i.useState([]),[W,je]=i.useState(!1),[ce,$e]=i.useState(ji(e.priority)),[it,vt]=i.useState(!1),tn=i.useRef(!1),[Pt,Lt]=i.useState(!1),[zt,yn]=i.useState(!1),[ue,lt]=i.useState(!1),ut=i.useRef(null),dt=i.useRef(null),at=i.useRef(null),{getSlotsForId:St}=pf(n),ct=St("task-detail-tab").map((J,Ge)=>({entry:J,tabId:`plugin-${J.pluginId}-${Ge}`})),Zt=typeof v=="string"&&v.startsWith("plugin-")?ct.find(J=>J.tabId===v)??null:null;i.useEffect(()=>(tn.current=!0,()=>{tn.current=!1}),[]);const[Sn,In]=i.useState(void 0),[Hn,Xn]=i.useState([]),[jn,Pn]=i.useState(!1),[rs,os]=i.useState(e.enabledWorkflowSteps||[]),cn=e.column==="in-progress"||oP.has(e.status);i.useEffect(()=>{wt(e.title||""),le(e.description||""),Bt(e.sourceIssue?.provider??""),an(e.sourceIssue?.repository??""),fe(e.sourceIssue?.externalIssueId??""),ae(e.sourceIssue?.url??""),Ft(lr(e.executionMode)),lt(!1),Ue(!1)},[e.id,e.title,e.description,e.sourceIssue,e.executionMode]),i.useEffect(()=>{os(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{$e(ji(e.priority))},[e.id,e.priority]),i.useEffect(()=>{let J=!1;return jl(n).then(Ge=>{J||In(Ge)}).catch(()=>{}),()=>{J=!0}},[n]),i.useEffect(()=>{if(v!=="workflow")return;let J=!1;return Pn(!0),Gk(e.id,n).then(Ge=>{J||Xn(Ge)}).catch(Ge=>{J||h(`Failed to load workflow results: ${Me(Ge)}`,"error")}).finally(()=>{J||Pn(!1)}),()=>{J=!0}},[v,e.id,n,h]),i.useEffect(()=>{if(v!=="workflow")return;const J=n?`?projectId=${encodeURIComponent(n)}`:"",Ge=xt=>{try{const Ht=JSON.parse(xt.data);Ht.id===e.id&&Array.isArray(Ht.workflowStepResults)&&Xn(Ht.workflowStepResults)}catch{}};return li(`/api/events${J}`,{events:{"task:updated":Ge}})},[v,e.id,n]),i.useEffect(()=>{j||de("")},[j]),i.useEffect(()=>{if(!e.assignedAgentId){B(null);return}const J=ve.find(xt=>xt.id===e.assignedAgentId);if(J){B(J);return}let Ge=!1;return od(e.assignedAgentId,n).then(xt=>{Ge||B(xt)}).catch(()=>{Ge||B(null)}),()=>{Ge=!0}},[e.assignedAgentId,n,ve]),i.useEffect(()=>{if(!e.sourceAgentId){T(null);return}const J=ve.find(xt=>xt.id===e.sourceAgentId);if(J){T(J);return}let Ge=!1;return Promise.resolve(od(e.sourceAgentId,n)).then(xt=>{Ge||T(xt??null)}).catch(()=>{Ge||T(null)}),()=>{Ge=!0}},[e.sourceAgentId,n,ve]),i.useEffect(()=>{ee(!1)},[e.id]),i.useEffect(()=>{if(!(Pt||zt))return;const Ge=xt=>{const Ht=xt.target,is=ut.current?.contains(Ht),Ds=at.current?.contains(Ht);!is&&Pt&&Lt(!1),!Ds&&zt&&yn(!1)};return document.addEventListener("mousedown",Ge),()=>document.removeEventListener("mousedown",Ge)},[Pt,zt]),i.useEffect(()=>{if(!(Pt||zt))return;const Ge=xt=>{xt.key==="Escape"&&(xt.stopPropagation(),Pt&&Lt(!1),zt&&yn(!1))};return document.addEventListener("keydown",Ge),()=>document.removeEventListener("keydown",Ge)},[Pt,zt]),i.useEffect(()=>{He(!1),Oe(w.prompt||""),De("")},[e.id,w.prompt]);const $n=wP.has(e.column)&&!W,nn=i.useCallback(()=>{if(!$n)return;Ue(!0),wt(e.title||""),le(e.description||""),be(e.dependencies||[]);const J=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Ge=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",xt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Je(J),mt(Ge),ze(xt),yt(e.thinkingLevel??""),It(e.nodeId),kt(J||Ge||xt?"custom":"default"),Vt(""),Kt(e.enabledWorkflowSteps||[]),Ft(lr(e.executionMode)),Bt(e.sourceIssue?.provider??""),an(e.sourceIssue?.repository??""),fe(e.sourceIssue?.externalIssueId??""),ae(e.sourceIssue?.url??""),Ae([]),jt(e.reviewLevel),Dt(ji(e.priority))},[$n,e]),_t=i.useCallback(()=>{Ue(!1),wt(e.title||""),le(e.description||""),be(e.dependencies||[]),It(e.nodeId),Bt(e.sourceIssue?.provider??""),an(e.sourceIssue?.repository??""),fe(e.sourceIssue?.externalIssueId??""),ae(e.sourceIssue?.url??""),Dt(ji(e.priority)),Ft(lr(e.executionMode)),Pe.forEach(J=>URL.revokeObjectURL(J.previewUrl)),Ae([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Pe]),K=i.useCallback(async()=>{je(!0);try{const J={},Ge=Xe.trim(),xt=ye.trim();Ge&&Ge!==(e.title??"")&&(J.title=Ge),xt&&xt!==(e.description??"")&&(J.description=xt),yh(Te,e.dependencies??[])||(J.dependencies=Te),yh(Yt,e.enabledWorkflowSteps??[])||(J.enabledWorkflowSteps=Yt);const Ht=Nc(Le),is=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Le!==is&&(J.modelProvider=Ht?.provider??null,J.modelId=Ht?.modelId??null);const Ds=Nc(nt),zl=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";nt!==zl&&(J.validatorModelProvider=Ds?.provider??null,J.validatorModelId=Ds?.modelId??null);const Za=Nc(Ie),ro=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Ie!==ro&&(J.planningModelProvider=Za?.provider??null,J.planningModelId=Za?.modelId??null);const oo=e.thinkingLevel??"";st!==oo&&(J.thinkingLevel=st!==""?st:null),(e.nodeId??void 0)!==Tt&&(J.nodeId=Tt??null);const lo=e.reviewLevel;Et!==lo&&(J.reviewLevel=Et);const co=ji(e.priority);Rt!==co&&(J.priority=Rt);const uo=lr(e.executionMode);Ut!==uo&&(J.executionMode=Ut==="fast"?"fast":null);const V=Sc(qt),Ce=Sc(Xt),Ke=Sc(Qt),At=gP(Fe);if(V.length===0&&Ce.length===0&&Ke.length===0&&!At)e.sourceIssue&&(J.sourceIssue=null);else{if(!V||!Ce||!Ke){h("Source issue provider, repository, and issue identifier are required","error"),je(!1);return}const hn=Number.parseInt(Ke,10),tt=e.sourceIssue?.issueNumber??hn;if(!Number.isFinite(tt)||tt<=0){h("Source issue identifier must be numeric for new metadata","error"),je(!1);return}const et={provider:V,repository:Ce,externalIssueId:Ke,issueNumber:tt,...At?{url:At}:{}},Ct=e.sourceIssue;(!Ct||Ct.provider!==et.provider||Ct.repository!==et.repository||Ct.externalIssueId!==et.externalIssueId||Ct.issueNumber!==et.issueNumber||(Ct.url??void 0)!==et.url)&&(J.sourceIssue=et)}if(Object.keys(J).length>0){const hn=await ni(e.id,J,n);m?.(hn)}if(Pe.length>0){const hn=[];for(const tt of Pe)try{const et=await Ir(e.id,tt.file,n);G(Ct=>[...Ct,et])}catch{hn.push(tt.file.name)}hn.length>0&&h(`Failed to upload: ${hn.join(", ")}`,"error")}Pe.forEach(hn=>URL.revokeObjectURL(hn.previewUrl)),Ae([]),h(`Updated ${e.id}`,"success"),Ue(!1)}catch(J){h(`Failed to update ${e.id}: ${Me(J)}`,"error")}finally{tn.current&&je(!1)}},[e,Xe,ye,Te,Le,nt,Ie,st,Tt,Et,Rt,Ut,Yt,qt,Xt,Qt,Fe,Pe,h,n,m]),Ve=i.useCallback(async J=>{try{const Ge=await ni(e.id,{description:J},n);m?.(Ge),h("Description saved","success")}catch(Ge){h(`Failed to save: ${Me(Ge)}`,"error")}},[e.id,h,n,m]),pt=i.useCallback(async J=>{const Ge=ji(J),xt=ji(e.priority);if(Ge===xt){$e(xt);return}const Ht=ce;$e(Ge),vt(!0);try{const is=await ni(e.id,{priority:Ge},n);$e(ji(is.priority)),m?.(is),h(`Priority updated to ${ji(is.priority)}`,"success")}catch(is){$e(Ht),h(`Failed to update ${e.id}: ${Me(is)}`,"error")}finally{tn.current&&vt(!1)}},[e.id,e.priority,n,ce,m,h]),ht=i.useCallback(J=>{ge&&(J.key==="Escape"?(J.preventDefault(),_t()):J.key==="Enter"&&(J.ctrlKey||J.metaKey)&&(J.preventDefault(),K()))},[ge,_t,K]);i.useEffect(()=>{if(ge)return document.addEventListener("keydown",ht),()=>document.removeEventListener("keydown",ht)},[ge,ht]);const Nt=i.useRef(null),{nodes:Mt}=El(),{confirm:$t}=qs(),{entries:wn,loading:ls,loadMore:Cs,hasMore:$s,total:ps,loadingMore:Vs}=Fg(e.id,v==="logs"&&O==="agent-log",n),dn=i.useCallback(()=>{b?.()},[b]);i.useEffect(()=>{if(g)return;const J=Ge=>{Ge.key==="Escape"&&!ge&&dn()};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[g,dn,ge]);const yi=i.useCallback(async J=>{try{const Ge=e.steps.some(is=>is.status!=="pending"),xt=(J==="todo"||J==="triage")&&Ge;let Ht;if(xt){if(await $t({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ht={preserveProgress:!0};else if(!await $t({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,J,Ht),dn(),h(`Moved to ${ns[J]}`,"success")}catch(Ge){h(Me(Ge),"error")}},[e.id,e.steps,r,dn,h,$t]),me=i.useCallback(async()=>{if(await $t({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),dn(),h(`Deleted ${e.id}`,"info")}catch(Ge){const xt=fP(Ge);if(!xt||xt.dependentIds.length===0){h(Me(Ge),"error");return}const Ht=xt.dependentIds.join(", ");if(!await $t({title:"Force Delete Task",message:`${e.id} is a dependency of ${Ht}.
677
-
678
- Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),dn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Ds){h(Me(Ds),"error")}}},[e.id,o,dn,h,$t]),We=i.useCallback(async()=>{await $t({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(dn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(Ge=>{const xt=Ge.merged?`Merged ${e.id} (branch: ${Ge.branch})`:`Closed ${e.id} (${Ge.error||"no branch to merge"})`;h(xt,"success")}).catch(Ge=>{h(Me(Ge),"error")}))},[e.id,l,dn,h,$t]),ot=i.useCallback(()=>{c&&(dn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(J=>{h(Me(J),"error")}))},[e.id,c,dn,h]),sn=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(dn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(J=>{h(Me(J),"error")}))},[e.id,d,dn,h]),Dn=i.useCallback(async()=>{if(!(!u||!await $t({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Ge=await u(e.id);dn(),h(`Duplicated ${e.id} → ${Ge.id}`,"success")}catch(Ge){h(Me(Ge),"error")}},[e.id,u,dn,h,$t]),Y=i.useCallback(async()=>{try{e.paused?(await nw(e.id,n),h(`Unpaused ${e.id}`,"success")):(await ef(e.id,n),h(`Paused ${e.id}`,"success")),dn()}catch(J){h(Me(J),"error")}},[e.id,e.paused,dn,h]),Ee=i.useCallback(async()=>{try{await rw(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),dn()}catch(J){h(Me(J),"error")}},[e.id,dn,h]),rt=i.useCallback(async()=>{if(await $t({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await ow(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),dn()}catch(Ge){h(Me(Ge),"error")}},[e.id,dn,h,$t]),Be=i.useCallback(async()=>{if(await $t({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await xw(e.id,n),dn(),h(`Replanning ${e.id}...`,"info")}catch(Ge){h(Me(Ge),"error")}},[e.id,n,dn,h,$t]),ft=i.useCallback(()=>{oe(!0),Z("")},[]),mn=i.useCallback(()=>{Lt(!1),yn(!1)},[]),un=i.useCallback(J=>{mn(),yi(J)},[mn]),on=i.useCallback(J=>{mn(),J()},[mn]),fn=i.useCallback(()=>{mn(),We()},[mn,We]),Ln=i.useCallback(()=>{oe(!1),Z(""),Qe(!1)},[]),Zn=i.useCallback(async()=>{if(!we.trim()){h("Please enter feedback describing what needs refinement","error");return}if(we.length>2e3){h("Feedback must be 2000 characters or less","error");return}Qe(!0);try{const J=await vw(e.id,we.trim(),n);h(`Refinement task created: ${J.id}`,"success"),dn()}catch(J){h(Me(J),"error")}finally{Qe(!1)}},[e.id,we,h,dn]),qn=i.useCallback(async J=>{M(!0);try{const Ge=await Ir(e.id,J,n);G(xt=>[...xt,Ge]),h("Screenshot attached","success")}catch(Ge){h(Me(Ge),"error")}finally{M(!1)}},[e.id,h]),es=i.useCallback(async J=>{const Ge=J.target.files?.[0];Ge&&(await qn(Ge),Nt.current&&(Nt.current.value=""))},[qn]);i.useEffect(()=>{const J=Ge=>{const xt=Ge.clipboardData?.items;if(xt)for(let Ht=0;Ht<xt.length;Ht++){const is=xt[Ht];if(is.type.startsWith("image/")){const Ds=is.getAsFile();if(Ds){Ge.preventDefault(),qn(Ds);return}}}};return document.addEventListener("paste",J),()=>document.removeEventListener("paste",J)},[qn]);const Un=i.useCallback(J=>{J.preventDefault()},[]),En=i.useCallback(J=>{J.preventDefault();const Ge=J.dataTransfer.files;for(let xt=0;xt<Ge.length;xt++){const Ht=Ge[xt];if(Ht.type.startsWith("image/")){qn(Ht);return}}},[qn]),fs=i.useCallback(async J=>{try{await dw(e.id,J,n),G(Ge=>Ge.filter(xt=>xt.filename!==J)),h("Attachment deleted","info")}catch(Ge){h(Me(Ge),"error")}},[e.id,h]),Jn=i.useCallback(async J=>{const Ge=rs;os(J);try{const xt=await ni(e.id,{enabledWorkflowSteps:J},n);h("Workflow steps updated","success"),m?.(xt)}catch(xt){os(Ge),h(`Failed to update workflow steps: ${Me(xt)}`,"error")}},[e.id,n,rs,m,h]),Bn=i.useCallback(async()=>{te(!0);try{const J=await oa(void 0,n);U(J),ee(!0)}catch(J){h(`Failed to load agents: ${Me(J)}`,"error"),ee(!1)}finally{te(!1)}},[n,h]),gs=i.useCallback(async J=>{try{const Ge=await Tu(e.id,J,n),xt=ve.find(Ht=>Ht.id===J)??null;B(xt||(Ht=>Ht?.id===J?Ht:null)),ee(!1),m?.(Ge),h("Assigned agent updated","success")}catch(Ge){h(`Failed to assign agent: ${Me(Ge)}`,"error")}},[e.id,n,ve,m,h]),Vn=i.useCallback(async()=>{try{const J=await Tu(e.id,null,n);B(null),ee(!1),m?.(J),h("Agent unassigned","success")}catch(J){h(`Failed to unassign agent: ${Me(J)}`,"error")}},[e.id,n,m,h]),bs=i.useCallback(async J=>{const Ge=[...z,J];L(Ge);try{await ni(e.id,{dependencies:Ge},n)}catch(xt){L(z),h(Me(xt),"error")}},[e.id,z,h]),Yn=i.useCallback(async(J,Ge)=>{J.stopPropagation();const xt=z.filter(Ht=>Ht!==Ge);L(xt);try{await ni(e.id,{dependencies:xt},n)}catch(Ht){L(z),h(Me(Ht),"error")}},[e.id,z,h]),Es=i.useCallback(async J=>{try{const Ge=await Aa(J,n);a(Ge)}catch{h(`Failed to load dependency ${J}`,"error")}},[a,h]),Ws=i.useCallback(async J=>{ne(!0);try{await ni(w.id,{prompt:J},n),h("Spec updated","success"),y&&(y.prompt=J)}catch(Ge){throw h(Me(Ge),"error"),Ge}finally{ne(!1)}},[w,y,h]),ua=i.useCallback(async J=>{Ne(!0);try{await bw(e.id,J,n),h("AI revision requested. Task moved to planning.","success"),dn()}catch(Ge){const xt=Me(Ge);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{Ne(!1)}},[e.id,h,dn]),wi=i.useCallback(()=>{He(!0),Oe(w.prompt||""),De("")},[w.prompt]),Ks=i.useCallback(()=>{He(!1),Oe(w.prompt||""),De("")},[w.prompt]),Ri=i.useCallback(async()=>{if(Ye===(w.prompt||"")){Ks();return}He(!1);try{await Ws(Ye)}catch(J){throw He(!0),J}},[Ye,w.prompt,Ws,Ks]),no=i.useCallback(async()=>{ke.trim()&&await ua(ke.trim())},[ke,ua]),$l=i.useCallback(J=>{J.key==="Escape"?(J.preventDefault(),Ks()):J.key==="Enter"&&(J.ctrlKey||J.metaKey)&&(J.preventDefault(),Ri())},[Ks,Ri]),so=s.filter(J=>J.id!==e.id&&!z.includes(J.id)).sort((J,Ge)=>{const xt=Ge.createdAt.localeCompare(J.createdAt);if(xt!==0)return xt;const Ht=parseInt(J.id.slice(J.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ge.id.slice(Ge.id.lastIndexOf("-")+1),10)||0)-Ht}),Ga=pe?.name??e.assignedAgentId??null,Ja=i.useMemo(()=>{const J=[];return w.modelProvider&&J.push(w.modelProvider),w.validatorModelProvider&&!J.includes(w.validatorModelProvider)&&J.push(w.validatorModelProvider),w.planningModelProvider&&!J.includes(w.planningModelProvider)&&J.push(w.planningModelProvider),J},[w.modelProvider,w.validatorModelProvider,w.planningModelProvider]),io=ld[e.column]||[],Dl=["todo","in-progress"],Ya=e.column==="in-review"?Dl:io,xs=Ya[0],Ui=Ya.slice(1),ss=Ui.length>0,Qa=i.useCallback(()=>{Lt(!1),dt.current?.focus()},[]),Xa=i.useCallback(J=>{if(!ss){xs&&un(xs);return}const Ge=J.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(J.target instanceof Element&&J.target.closest(".detail-move-btn__arrow")||Ge&&J.clientX>0&&J.clientX>=Ge.getBoundingClientRect().left)){Lt(Ht=>!Ht),yn(!1);return}xs&&un(xs)},[ss,xs,un]),Bi=i.useCallback(J=>{!ss||!(J.key==="ArrowDown"||J.altKey&&J.key==="ArrowDown")||(J.preventDefault(),Lt(!0),yn(!1))},[ss]),ma=i.useCallback(J=>{J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),Qa())},[Qa]);i.useEffect(()=>{if(!Pt)return;ut.current?.querySelector(".detail-move-menu-item")?.focus()},[Pt]);const Ll={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…"},ao=e.status?Ll[e.status]:void 0;return t.jsxs("div",{className:g?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Un,onDrop:En,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:ns[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!ge&&$n&&t.jsx("button",{className:"modal-edit-btn",onClick:nn,title:"Edit task","aria-label":"Edit task",children:t.jsx(vs,{size:14})}),!g&&t.jsx("button",{className:"modal-close",onClick:dn,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${v==="logs"&&O==="agent-log"&&!ge?" detail-body--agent-log":""}`,children:[ge?t.jsx("div",{className:"modal-edit-form",children:t.jsx(qg,{mode:"edit",title:Xe,onTitleChange:wt,description:ye,onDescriptionChange:le,dependencies:Te,onDependenciesChange:be,executorModel:Le,onExecutorModelChange:Je,validatorModel:nt,onValidatorModelChange:mt,planningModel:Ie,onPlanningModelChange:ze,thinkingLevel:st,onThinkingLevelChange:yt,presetMode:Re,onPresetModeChange:kt,selectedPresetId:Jt,onSelectedPresetIdChange:Vt,selectedWorkflowSteps:Yt,onWorkflowStepsChange:Kt,pendingImages:Pe,onImagesChange:Ae,tasks:s.filter(J=>J.id!==e.id),projectId:n,disabled:W,addToast:h,isActive:ge,onAutoSaveDescription:Ve,reviewLevel:Et,onReviewLevelChange:jt,priority:Rt,onPriorityChange:Dt,nodeId:Tt,onNodeIdChange:It,nodeOptions:Mt,nodeOverrideDisabled:cn,nodeOverrideDisabledReason:cn?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Ut,onExecutionModeChange:Ft,renderBelowModelConfiguration:t.jsxs("div",{className:"form-group detail-source-edit-group",children:[t.jsx("label",{children:"Source Issue"}),t.jsxs("div",{className:"detail-source-edit-grid",children:[t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:qt,onChange:J=>Bt(J.target.value),disabled:W,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Xt,onChange:J=>an(J.target.value),disabled:W,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Qt,onChange:J=>fe(J.target.value),disabled:W,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Fe,onChange:J=>ae(J.target.value),disabled:W,"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 J=e.title||e.description||e.id,Ge=!S&&J.length>Cc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Ge?J.slice(0,Cc)+"…":J}),J.length>Cc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>I(!S),children:S?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:["Created ",new Date(e.createdAt).toLocaleDateString()," · Updated"," ",new Date(e.updatedAt).toLocaleDateString()," ·",t.jsxs("label",{className:`card-priority-badge card-priority-badge--${ce} detail-priority-chip ${it?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:ce,onChange:J=>{pt(J.target.value)},disabled:it,"aria-label":"Task priority",children:Xr.map(J=>t.jsx("option",{value:J,children:J},J))})]}),$&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Hs,{"aria-hidden":"true"}),t.jsxs("span",{children:[w.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",$.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>C($.sourceAgentId),children:$.label}):$.label]}):t.jsxs(t.Fragment,{children:["Created via ",$.label]}),$.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Es($.parentTaskId),children:$.parentTaskId})]}),$.contextInfo?` (${$.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})]})]}),!ge&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${v==="definition"?" detail-tab-active":""}`,onClick:()=>x("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${v==="logs"?" detail-tab-active":""}`,onClick:()=>x("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${v==="changes"?" detail-tab-active":""}`,onClick:()=>x("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${v==="comments"?" detail-tab-active":""}`,onClick:()=>x("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${v==="documents"?" detail-tab-active":""}`,onClick:()=>x("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${v==="model"?" detail-tab-active":""}`,onClick:()=>x("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${v==="workflow"?" detail-tab-active":""}`,onClick:()=>x("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${v==="stats"?" detail-tab-active":""}`,onClick:()=>x("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${v==="routing"?" detail-tab-active":""}`,onClick:()=>x("routing"),children:"Routing"}),ct.map(({entry:J,tabId:Ge})=>t.jsx("button",{className:`detail-tab${v===Ge?" detail-tab-active":""}`,onClick:()=>x(Ge),children:J.slot.label},`plugin-tab-${J.pluginId}-${Ge}`))]}),v==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(YA,{taskId:e.id,results:Hn,loading:jn,enabledWorkflowSteps:rs,canEdit:$n,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Jn})}):v==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(PA,{task:e,addToast:h,onTaskUpdated:m,settings:Sn})}):v==="logs"?t.jsxs("div",{className:`detail-section${O==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${O==="activity"?" log-subview-btn-active":""}`,onClick:()=>E("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${O==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>E("agent-log"),children:"Agent Log"})]}),O==="agent-log"?t.jsx(CA,{entries:wn,loading:ls,executorModel:lP(e,Sn),validatorModel:cP(e,Sn),planningModel:uP(e,wn,Sn),hasMore:$s,onLoadMore:Cs,loadingMore:Vs,totalCount:ps}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),w.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",w.log.length," activity entries."]}):null,w.log&&w.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...w.log].reverse().map((J,Ge)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:hP(J.timestamp)}),t.jsx("span",{className:"detail-log-action",children:J.action})]}),J.outcome&&t.jsx("div",{className:"detail-log-outcome",children:J.outcome})]},Ge))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):v==="changes"?t.jsx(UA,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):v==="comments"?t.jsx(DA,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):v==="documents"?t.jsx(iP,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:$n}):Zt?t.jsx("div",{className:"detail-section",children:t.jsx(Sl,{slotId:"task-detail-tab",projectId:n,pluginIds:[Zt.entry.pluginId]})}):v==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(rP,{tokenUsage:w.tokenUsage,loading:N,task:w})}):v==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(eP,{task:e,settings:Sn,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(gi,{remarkPlugins:[bi],children:e.summary})})]}),t.jsx(zA,{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(Hs,{"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":ue,"aria-label":ue?"Collapse source issue details":"Expand source issue details",onClick:()=>lt(J=>!J),children:t.jsx(_n,{size:16,className:ue?"detail-source-chevron--expanded":void 0})})]}),ue&&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:[Ja.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Ja.map(J=>t.jsx(Fn,{provider:J,size:"sm"},J))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Mn,{size:14,style:{verticalAlign:"middle",marginRight:6}}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Ga?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Mn,{size:14}),Ga,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Vn(),title:"Unassign agent",children:t.jsx(Wt,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{se?ee(!1):Bn()},children:"Assign Agent"}),se&&t.jsxs("div",{className:"agent-picker-dropdown",children:[ie&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!ie&&ve.filter(J=>J.state!=="terminated").map(J=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===J.id?" selected":""}`,onClick:()=>void gs(J.id),children:[t.jsx(Mn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:J.name}),t.jsx("span",{className:"agent-picker-role",children:J.role})]},J.id)),!ie&&ve.filter(J=>J.state!=="terminated").length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),w.steps&&w.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:w.steps.map((J,Ge)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${J.status}`,"data-tooltip":`${J.name} (${J.status})`,style:{backgroundColor:mP(J.status)}},Ge))}),t.jsxs("span",{className:"step-progress-label",children:[w.steps.filter(J=>J.status==="done").length,"/",w.steps.length," step",w.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Se&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:wi,children:"Edit"})}),Se?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:Ye,onChange:J=>Oe(J.target.value),onKeyDown:$l,disabled:xe,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:Ks,disabled:xe,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Ri(),disabled:Ye===(w.prompt||"")||xe,children:xe?"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:ke,onChange:J=>De(J.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:_e,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[ke.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void no(),disabled:!ke.trim()||_e,children:_e?"Requesting…":"Request AI Revision"})]})]})]}):N?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):w.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(gi,{remarkPlugins:[bi],children:w.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),F.length>0?t.jsx("div",{className:"detail-attachments-grid",children:F.map(J=>{const Ge=fi(`/api/tasks/${e.id}/attachments/${J.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Ge,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Ge,alt:J.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[J.originalName," (",pP(J.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>fs(J.filename),title:"Delete attachment",children:"×"})]},J.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Nt,type:"file",accept:"image/*",onChange:es}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt.current?.click(),disabled:X,children:X?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),z.length>0?t.jsx("ul",{className:"detail-dep-list",children:z.map(J=>{const Ge=s.find(Ht=>Ht.id===J),xt=Ge?.title||Ge?.description||J;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Es(J),onKeyDown:Ht=>{(Ht.key==="Enter"||Ht.key===" ")&&(Ht.preventDefault(),Es(J))},role:"link",tabIndex:0,title:`Click to view ${J}`,children:[t.jsx("span",{className:"detail-dep-id",children:J}),t.jsx("span",{className:"detail-dep-label",children:vh(xt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Ht=>Yn(Ht,J),title:`Remove dependency ${J}`,children:"×"})]},J)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{j&&de(""),H(J=>!J)},children:"Add Dependency"}),j&&(()=>{const J=Q.toLowerCase(),Ge=J?so.filter(xt=>xt.id.toLowerCase().includes(J)||xt.title&&xt.title.toLowerCase().includes(J)||xt.description&&xt.description.toLowerCase().includes(J)):so;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Q,onChange:xt=>de(xt.target.value),onClick:xt=>xt.stopPropagation()}),Ge.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ge.map(xt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{bs(xt.id),H(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:xt.id}),t.jsx("span",{className:"dep-dropdown-title",children:vh(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(TA,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:Sn?.autoMerge??!1,prAuthAvailable:f??!1,onPrCreated:J=>{e.prInfo=J,h(`PR #${J.number} created`,"success")},onPrUpdated:J=>{e.prInfo=J},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:ge?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:_t,disabled:W,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:K,disabled:W,children:W?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&w.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ee,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:rt,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!A&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:me,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||A||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:at,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{yn(J=>!J),Lt(!1)},"aria-haspopup":"menu","aria-expanded":zt,children:["Actions",t.jsx(rn,{size:12})]}),zt&&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:()=>on(me),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>on(Dn),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>on(ft),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>on(Be),children:"Respecify"}),A&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>on(ot),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:()=>on(sn),children:"Reset"}),e.column!=="done"&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>on(Y),children:e.paused?"Unpause":"Pause"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:ut,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:dt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Xa,onKeyDown:Bi,disabled:!xs,"aria-label":xs?`Move to ${ns[xs]}`:void 0,"aria-haspopup":ss?"menu":void 0,"aria-expanded":ss?Pt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",xs?ns[xs]:""]}),ss&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(rn,{size:12})})]}),Pt&&ss&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ma,children:Ui.map(J=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>un(J),onKeyDown:ma,children:J==="in-progress"?"Back to In Progress":`Move to ${ns[J]}`},J))})]}),ao?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:ao}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:fn,children:"Merge & Close"})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:dt,className:"btn btn-primary btn-sm detail-move-btn",onClick:Xa,onKeyDown:Bi,disabled:!xs,"aria-label":xs?`Move to ${ns[xs]}`:void 0,"aria-haspopup":ss?"menu":void 0,"aria-expanded":ss?Pt:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",xs?ns[xs]:""]}),ss&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(rn,{size:12})})]}),Pt&&ss&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:ma,children:Ui.map(J=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>un(J),onKeyDown:ma,children:["Move to ",ns[J]]},J))})]})})]})}),re&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Ln,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:J=>J.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:Ln,"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:we,onChange:J=>Z(J.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:[we.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Zn,disabled:!we.trim()||qe,children:qe?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Ln,disabled:qe,children:"Cancel"})})]})}),_&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(vP,{agentId:_,projectId:n,onClose:()=>C(null),addToast:h})})]})}function kP({onClose:e,...n}){const s=i.useRef(null);xi(s,!0,"task-detail-modal-size");const a=Ai(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(Vg,{...n,onRequestClose:e})})})}const cr={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},wh=new Set(["planning","researching","executing","finalizing","merging"]),Wg=["title","status","column","dependencies","progress"],jP=["title","status","column"];function NP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function SP(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function kh(e){try{const n=Gn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Wg.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(jP)}function jh(e){try{const n=Gn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Nh(e){try{const n=Gn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>Xi.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function Sh(e){try{const n=Gn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function Ch(e){try{const n=Gn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function Eh(e){try{const s=Gn("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 ol=280,Nd=.65,Eo=16;function Sd(e){return Math.max(ol,e*Nd)}function Mo(e,n){const s=Sd(n);return Math.min(Math.max(e,ol),s)}function CP(e){return e.status==="executing"||e.column==="in-progress"}function Mh(e){const n=Sf(e);return n.total===0||!CP(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function EP({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:b,onToggleModelFavorite:v,onPlanningMode:x,onSubtaskBreakdown:y,onTasksUpdated:k,projectId:N,projectName:R,taskStuckTimeoutMs:w,searchQuery:A="",lastFetchTimeMs:P,prAuthAvailable:T}){const[_,C]=i.useState("id"),[$,O]=i.useState("desc"),[E,S]=i.useState(null),[I,F]=i.useState(null),[G,X]=i.useState(null),z=la()==="mobile",{confirm:L}=qs(),[j,H]=i.useState(()=>kh(N)),[Q,de]=i.useState(()=>jh(N)),[pe,B]=i.useState(()=>Nh(N));i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-columns",JSON.stringify([...j]),N)},[N,j]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-hide-done",Q.toString(),N)},[Q,N]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-collapsed",JSON.stringify([...pe]),N)},[pe,N]);const[ve,U]=i.useState(!1),se=i.useRef(null),[ee,ie]=i.useState(!1),[te,xe]=i.useState(()=>Sh(N)),[ne,_e]=i.useState(()=>Ch(N)),[Ne,Se]=i.useState(null),[He,Ye]=i.useState(()=>Eh(N)),Oe=i.useRef(null),ke=i.useRef(null);i.useEffect(()=>{H(kh(N)),de(jh(N)),B(Nh(N)),xe(Sh(N));const fe=Ch(N);_e(fe),Se(fe?e.find(Fe=>Fe.id===fe)??null:null),Ye(Eh(N))},[N,e]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-selected-tasks",JSON.stringify([...te]),N)},[N,te]),i.useEffect(()=>{if(!(typeof window>"u")){if(ne){us("kb-dashboard-list-selected-task",ne,N);return}Ta("kb-dashboard-list-selected-task",N)}},[N,ne]),i.useEffect(()=>{if(!ne){Se(null);return}const fe=e.find(Fe=>Fe.id===ne);fe&&Se(Fe=>!Fe||Fe.id!==ne?fe:{...Fe,...fe})},[ne,e]),i.useEffect(()=>{if(z||typeof ResizeObserver>"u")return;const fe=Oe.current;if(!fe)return;const Fe=()=>{const Pe=Mo(He,fe.clientWidth);Pe!==He&&Ye(Pe)};Fe();const ae=new ResizeObserver(Fe);return ae.observe(fe),()=>ae.disconnect()},[z,He]),i.useEffect(()=>{if(z||typeof ResizeObserver>"u")return;const fe=ke.current,Fe=Oe.current;if(!fe||!Fe)return;let ae=null,Pe=fe.offsetWidth;const Ae=new ResizeObserver(()=>{const W=Mo(fe.offsetWidth,Fe.clientWidth);W!==Pe&&(Pe=W,ae&&clearTimeout(ae),ae=setTimeout(()=>{try{us("kb-dashboard-list-sidebar-width",String(W),N)}catch{}},200))});return Ae.observe(fe),()=>{Ae.disconnect(),ae&&clearTimeout(ae)}},[z,N]);const De=i.useCallback(()=>{ie(fe=>(fe&&xe(new Set),!fe))},[]),re=i.useCallback(fe=>{xe(Fe=>{const ae=new Set(Fe);return ae.has(fe)?ae.delete(fe):ae.add(fe),ae})},[]),oe=i.useCallback(()=>{xe(new Set)},[]),we=i.useCallback(fe=>{H(Fe=>{const ae=new Set(Fe);return ae.has(fe)?ae.size>1&&ae.delete(fe):ae.add(fe),ae})},[]);i.useEffect(()=>{if(!ve)return;const fe=ae=>{se.current&&!se.current.contains(ae.target)&&U(!1)},Fe=ae=>{ae.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",fe),document.addEventListener("keydown",Fe),()=>{document.removeEventListener("mousedown",fe),document.removeEventListener("keydown",Fe)}},[ve]);const Z={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},qe=i.useCallback(fe=>{_===fe?O(Fe=>Fe==="asc"?"desc":"asc"):(C(fe),O("asc"))},[_]),Qe=i.useCallback(fe=>{X(Fe=>Fe===fe?null:fe)},[]),ge=i.useCallback(fe=>{B(Fe=>{const ae=new Set(Fe);return ae.has(fe)?ae.delete(fe):ae.add(fe),ae})},[]),Ue=i.useCallback(()=>{X(null)},[]),Xe=i.useMemo(()=>{let fe=A?e.filter(Ae=>Ae.id.toLowerCase().includes(A.toLowerCase())||Ae.title&&Ae.title.toLowerCase().includes(A.toLowerCase())||Ae.description.toLowerCase().includes(A.toLowerCase())):[...e];Q&&!G&&(fe=fe.filter(Ae=>Ae.column!=="done"&&Ae.column!=="archived"));const ae=[...G?fe.filter(Ae=>Ae.column===G):fe].sort((Ae,W)=>{let je=0;switch(_){case"id":je=Ae.id.localeCompare(W.id);break;case"title":je=(Ae.title||Ae.description).localeCompare(W.title||W.description);break;case"status":je=(Ae.status||"").localeCompare(W.status||"");break;case"column":je=Ae.column.localeCompare(W.column);break}return $==="asc"?je:-je}),Pe={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return ae.forEach(Ae=>Pe[Ae.column].push(Ae)),Pe},[e,A,_,$,Q,G]),wt=i.useMemo(()=>Object.values(Xe).reduce((fe,Fe)=>fe+Fe.length,0),[Xe]),ye=i.useMemo(()=>e.filter(fe=>fe.column==="done"||fe.column==="archived").length,[e]),le=i.useMemo(()=>Q?ye:0,[Q,ye]),Te=i.useCallback(()=>{const fe=Object.values(Xe).flat().filter(Fe=>Fe.column!=="archived").map(Fe=>Fe.id);xe(Fe=>{if(fe.every(Pe=>Fe.has(Pe))){const Pe=new Set(Fe);return fe.forEach(Ae=>Pe.delete(Ae)),Pe}else return new Set([...Fe,...fe])})},[Xe]),be=i.useMemo(()=>{const fe=Object.values(Xe).flat().filter(Fe=>Fe.column!=="archived");return fe.length===0?!1:fe.every(Fe=>te.has(Fe.id))},[Xe,te]),Le=i.useMemo(()=>{const fe=Object.values(Xe).flat().filter(ae=>ae.column!=="archived");if(fe.length===0)return!1;const Fe=fe.filter(ae=>te.has(ae.id)).length;return Fe>0&&Fe<fe.length},[Xe,te]),[Je,nt]=i.useState("__no_change__"),[mt,Ie]=i.useState("__no_change__"),[ze,st]=i.useState("__no_change__"),[yt,Re]=i.useState([]),[kt,Et]=i.useState(!1),jt=i.useMemo(()=>ze&&ze!=="__no_change__"?yt.find(fe=>fe.id===ze):void 0,[yt,ze]),[Rt,Dt]=i.useState(!1);i.useEffect(()=>{if(te.size===0)return;let fe=!1;return(async()=>{Et(!0);try{const ae=await Zo();fe||Re(ae)}catch(ae){console.error("Failed to fetch nodes for bulk edit",ae),fe||Re([])}finally{fe||Et(!1)}})(),()=>{fe=!0}},[te.size]);const Tt=i.useCallback(async()=>{if(te.size===0)return;const fe=Array.from(te).filter(ae=>{const Pe=e.find(Ae=>Ae.id===ae);return Pe&&Pe.column!=="archived"});if(fe.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Fe={taskIds:fe};if(Je!=="__no_change__")if(Je==="")Fe.modelProvider=null,Fe.modelId=null;else{const ae=Je.indexOf("/");ae!==-1&&(Fe.modelProvider=Je.slice(0,ae),Fe.modelId=Je.slice(ae+1))}if(mt!=="__no_change__")if(mt==="")Fe.validatorModelProvider=null,Fe.validatorModelId=null;else{const ae=mt.indexOf("/");ae!==-1&&(Fe.validatorModelProvider=mt.slice(0,ae),Fe.validatorModelId=mt.slice(ae+1))}if(ze!=="__no_change__"&&(ze===""?Fe.nodeId=null:Fe.nodeId=ze),Object.keys(Fe).length===1){d("No changes to apply","info");return}Dt(!0);try{const ae=await Jy(Fe.taskIds,Fe.modelProvider,Fe.modelId,Fe.validatorModelProvider,Fe.validatorModelId,void 0,void 0,Fe.nodeId,N);k&&k(ae.updated),d(`Updated ${fe.length} task${fe.length===1?"":"s"}`,"success"),oe(),nt("__no_change__"),Ie("__no_change__"),st("__no_change__")}catch(ae){d(Me(ae)||"Failed to update models","error")}finally{Dt(!1)}},[te,e,Je,mt,ze,N,d,oe,k]),It=i.useCallback(fe=>{if(z){c(fe);return}_e(fe.id),Se(fe)},[z,c]),Ut=i.useRef(null),Ft=i.useRef(null);i.useEffect(()=>()=>{Ut.current&&clearTimeout(Ut.current)},[]);const Jt=i.useCallback(fe=>{if(_e(fe.id),Se(fe),"prompt"in fe){Ft.current=null,Ut.current&&(clearTimeout(Ut.current),Ut.current=null);return}Ft.current=fe.id,Ut.current&&clearTimeout(Ut.current),Ut.current=setTimeout(()=>{Ut.current=null,Ft.current===fe.id&&Aa(fe.id,N).then(ae=>{Ft.current===ae.id&&Se(Pe=>!Pe||Pe.id!==ae.id?Pe:{...Pe,...ae})}).catch(()=>{})},200)},[N]),Vt=i.useCallback((fe,Fe)=>{if(Fe.paused){fe.preventDefault();return}fe.dataTransfer.setData("text/plain",Fe.id),fe.dataTransfer.effectAllowed="move",S(Fe.id)},[]),Yt=i.useCallback(()=>{S(null),F(null)},[]),Kt=i.useCallback(fe=>{if(z)return;fe.preventDefault();const Fe=Oe.current;if(!Fe)return;const ae=Fe.getBoundingClientRect(),Pe=W=>{const je=W.clientX-ae.left;Ye(Mo(je,ae.width))},Ae=()=>{window.removeEventListener("mousemove",Pe),window.removeEventListener("mouseup",Ae)};window.addEventListener("mousemove",Pe),window.addEventListener("mouseup",Ae)},[z]),qt=i.useCallback(fe=>{if(z)return;const Fe=Oe.current?.clientWidth??0,ae=He/Nd+Eo,Pe=Math.max(Fe,ae),Ae=Sd(Pe);if(fe.key==="ArrowLeft"||fe.key==="ArrowRight"){fe.preventDefault();const W=fe.key==="ArrowLeft"?-Eo:Eo;Ye(je=>Mo(je+W,Pe));return}if(fe.key==="Home"){fe.preventDefault(),Ye(ol);return}fe.key==="End"&&(fe.preventDefault(),Ye(Ae))},[z,He]),Bt=i.useCallback((fe,Fe)=>{fe.preventDefault(),fe.dataTransfer.dropEffect="move",F(Fe)},[]),Xt=i.useCallback(()=>{F(null)},[]),an=i.useCallback(async(fe,Fe)=>{fe.preventDefault(),F(null);const ae=fe.dataTransfer.getData("text/plain");if(ae){if(Fe==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ae=e.find(ce=>ce.id===ae)?.steps.some(ce=>ce.status!=="pending")??!1,W=(Fe==="todo"||Fe==="triage")&&Ae;let je;if(W){if(await L({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))je={preserveProgress:!0};else if(!await L({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(ae,Fe,je)}catch(Pe){d(Me(Pe),"error")}}},[n,d,e,L]),Qt=fe=>_!==fe?t.jsx(Bp,{size:14,className:"sort-icon"}):$==="asc"?t.jsx(Qi,{size:14,className:"sort-icon active"}):t.jsx(Br,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:se,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>U(fe=>!fe),"aria-expanded":ve,"aria-haspopup":"menu",children:[t.jsx(yx,{size:14}),"Columns"]}),ve&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Wg.map(fe=>{const Fe=j.has(fe),ae=Fe&&j.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ae?" disabled":""}`,role:"menuitem",title:ae?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Fe,onChange:()=>we(fe),disabled:ae}),t.jsx("span",{children:Z[fe]})]},fe)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>de(fe=>!fe),"aria-pressed":Q,title:Q?"Show done tasks":"Hide done tasks",children:[Q?t.jsx(Ba,{size:14}):t.jsx(Id,{size:14}),Q?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[G?`${wt} of ${e.length} tasks in ${ns[G]}`:`${wt} of ${e.length} tasks`,le>0&&!G&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",le," hidden)"]}),G&&t.jsx("button",{className:"btn btn-sm list-clear-column-filter-btn",onClick:Ue,"aria-label":"Clear column filter",children:"Clear"})]}),t.jsx("button",{className:"btn btn-sm",onClick:De,"aria-pressed":ee,children:ee?"Done Editing":"Bulk Edit"}),ee&&te.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[te.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:oe,children:"Clear"})]}),ee&&te.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(hs,{models:f,value:Je,onChange:nt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:b,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(hs,{models:f,value:mt,onChange:Ie,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:b,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:ze,onChange:fe=>st(fe.target.value),"aria-label":"Node Override",disabled:kt,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),yt.map(fe=>t.jsx("option",{value:fe.id,children:`${SP(fe.status)} ${fe.name||fe.id} (${NP(fe.status)})`},fe.id))]}),jt?t.jsx(na,{status:jt.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:Tt,disabled:Rt||Je==="__no_change__"&&mt==="__no_change__"&&ze==="__no_change__",children:Rt?"Applying...":"Apply"})]}),m?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:m,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:Xi.map(fe=>{const Fe=e.filter(W=>W.column===fe).length,ae=fe==="done"||fe==="archived",Pe=Q&&ae?0:Fe,Ae=Q&&ae&&Fe>0;return t.jsxs("div",{className:`list-drop-zone${I===fe?" drag-over":""}${G===fe?" active":""}`,onClick:()=>Qe(fe),onDragOver:W=>Bt(W,fe),onDragLeave:Xt,onDrop:W=>an(W,fe),"data-column":fe,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:cr[fe]}}),t.jsx("span",{className:"drop-zone-label",children:ns[fe]}),t.jsx("span",{className:"drop-zone-count",children:Ae?`${Pe} of ${Fe}`:Fe})]},fe)})}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:z?"":"list-split-layout","data-testid":z?void 0:"list-split-layout",ref:Oe,children:[t.jsxs("div",{className:z?"":"list-split-sidebar","data-testid":z?void 0:"list-split-sidebar",ref:ke,style:z?void 0:{width:`${He}px`},children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(_f,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:x,onSubtaskBreakdown:y,projectId:N,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:b,onToggleModelFavorite:v})}),wt===0?t.jsx("div",{className:"list-empty",children:A?"No tasks match your filter":"No tasks yet"}):z?t.jsx("div",{className:"list-cards",children:Xi.map(fe=>{if(G&&fe!==G||Q&&(fe==="done"||fe==="archived")&&!G)return null;const Fe=Xe[fe],ae=Fe.length===0;if(A&&ae)return null;const Pe=pe.has(fe);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>ge(fe),"aria-expanded":!Pe,role:"button",tabIndex:0,onKeyDown:Ae=>{(Ae.key==="Enter"||Ae.key===" ")&&(Ae.preventDefault(),ge(fe))},children:[t.jsx(_n,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${fe}`}),t.jsx("span",{className:"list-section-title",children:ns[fe]}),t.jsx("span",{className:"list-section-count",children:Fe.length})]}),!Pe&&t.jsx(t.Fragment,{children:ae?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Fe.map(Ae=>{const W=Ae.status==="failed",je=Ae.paused===!0,ce=nl(Ae,w,P),$e=!u&&!W&&!je&&!ce&&(Ae.column==="in-progress"||wh.has(Ae.status)),it=typeof Ae.status=="string"&&Ae.status.trim().length>0,vt=!!(Ae.dependencies&&Ae.dependencies.length>0),tn=Mh(Ae),Pt=tn.hasProgress,Lt=ee;return t.jsxs("div",{className:`list-card${$e?" agent-active":""}${Lt?" list-card--selectable":""}`,onClick:()=>It(Ae),"data-id":Ae.id,children:[Lt&&t.jsx("label",{className:"list-card-checkbox",onClick:zt=>zt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:te.has(Ae.id),onChange:zt=>{zt.stopPropagation(),re(Ae.id)},onClick:zt=>zt.stopPropagation(),disabled:Ae.column==="archived","aria-label":`Select ${Ae.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ae.id}),Ae.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(Kn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),ce?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):it?t.jsx("span",{className:`list-status-badge list-status-badge--${Ae.column}${W?" failed":""}${$e?" pulsing":""}`,children:Ae.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ae.title||Ae.description})}),(vt||Pt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[vt&&t.jsxs("span",{className:"list-dep-badge",title:Ae.dependencies.join(", "),children:[t.jsx(Ea,{size:12})," ",Ae.dependencies.length]}),Pt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${tn.percent}%`,backgroundColor:cr[Ae.column]}})}),t.jsx("span",{className:"list-progress-label",children:tn.label})]})]})]},Ae.id)})})]},fe)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[ee&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:be,ref:fe=>{fe&&(fe.indeterminate=Le)},onChange:Te,"aria-label":"Select all visible tasks"})}),j.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>qe("title"),children:["Title ",Qt("title")]}),j.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>qe("status"),children:["Status ",Qt("status")]}),j.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>qe("column"),children:["Column ",Qt("column")]}),j.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),j.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Xi.map(fe=>{if(G&&fe!==G||Q&&(fe==="done"||fe==="archived")&&!G)return null;const Fe=Xe[fe],ae=Fe.length===0;if(A&&ae)return null;const Pe=pe.has(fe);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${Pe?" list-section-header--collapsed":""}`,onClick:()=>ge(fe),"aria-expanded":!Pe,children:t.jsxs("th",{colSpan:j.size+(ee?1:0),className:"list-section-cell",children:[t.jsx(_n,{size:14,className:`list-section-chevron${Pe?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${fe}`}),t.jsx("span",{className:"list-section-title",children:ns[fe]}),t.jsx("span",{className:"list-section-count",children:Fe.length})]})}),!Pe&&t.jsx(t.Fragment,{children:ae?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:j.size+(ee?1:0),className:"list-empty-cell",children:"No tasks"})}):Fe.map(Ae=>{const W=Ae.status==="failed",je=Ae.paused===!0,ce=nl(Ae,w,P),$e=!u&&!W&&!je&&!ce&&(Ae.column==="in-progress"||wh.has(Ae.status)),it=E===Ae.id;return t.jsxs("tr",{className:`list-row${W?" failed":""}${je?" paused":""}${ce?" stuck":""}${$e?" agent-active":""}${it?" dragging":""}${ne===Ae.id?" list-row--selected":""}`,onClick:()=>It(Ae),draggable:!je,onDragStart:vt=>Vt(vt,Ae),onDragEnd:Yt,"data-id":Ae.id,children:[ee&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:te.has(Ae.id),onChange:vt=>{vt.stopPropagation(),re(Ae.id)},onClick:vt=>vt.stopPropagation(),disabled:Ae.column==="archived","aria-label":`Select ${Ae.id}`})}),j.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:Ae.id}),t.jsxs("div",{className:"list-title-row",children:[Ae.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(Kn,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ae.title||Ae.description})]})]})}),j.has("status")&&t.jsx("td",{className:"list-cell",children:ce?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ae.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ae.column}${W?" failed":""}${$e?" pulsing":""}`,children:Ae.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),j.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${cr[Ae.column]}20`,color:cr[Ae.column]},children:ns[Ae.column]})}),j.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ae.dependencies&&Ae.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ae.dependencies.join(", "),children:[t.jsx(Ea,{size:12})," ",Ae.dependencies.length]}):"-"}),j.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const vt=Mh(Ae);return vt.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:`${vt.percent}%`,backgroundColor:cr[Ae.column]}})}),t.jsx("span",{className:"list-progress-label",children:vt.label})]}):"-"})()})]},Ae.id)})})]},fe)})})]})]}),!z&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Kt,onKeyDown:qt,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":ol,"aria-valuemax":Math.round(Sd(Oe.current?.clientWidth??He/Nd+Eo)),"aria-valuenow":Math.round(He)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:Ne?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Vg,{task:Ne,projectId:N,tasks:e,embedded:!0,onOpenDetail:Jt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:fe=>{Se(Fe=>!Fe||Fe.id!==fe.id?Fe:{...Fe,...fe})},addToast:d,prAuthAvailable:T})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const MP={active:{label:"Active",color:"var(--success)",icon:On},paused:{label:"Paused",color:"var(--warning)",icon:ii},errored:{label:"Error",color:"var(--color-error)",icon:Ts},initializing:{label:"Initializing",color:"var(--info)",icon:bt}};function _P(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 AP(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 PP(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 RP({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=MP[e.status],f=h.icon,p=i.useCallback(()=>{s(e)},[s,e]),g=i.useCallback(N=>{N.stopPropagation(),a(e)},[a,e]),b=i.useCallback(N=>{N.stopPropagation(),r(e)},[r,e]),v=i.useCallback(N=>{if(N.stopPropagation(),!u){m(!0);return}o(e),m(!1)},[u,o,e]),x=e.status==="paused",y=e.status==="errored",k=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:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(as,{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:AP(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:k?"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:_P(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[x?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:d,title:"Resume project","aria-label":"Resume project",children:[t.jsx(On,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:d||k,title:k?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(ii,{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(Hr,{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(vn,{size:14}),t.jsx("span",{children:u?"Confirm":""})]})]})]})]})}const TP=i.memo(RP,PP);function IP(){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(as,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__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(Tn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ts,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__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 $P=1e4,_h=5;function DP(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+=_h){const b=e.slice(g,g+_h),v=await Promise.allSettled(b.map(async x=>{try{return await $u(x)}catch{return null}}));if(b.forEach((x,y)=>{const k=v[y];p[x]=k.status==="fulfilled"?k.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 $u(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()},$P),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function LP({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,b]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const O=localStorage.getItem("kb-dashboard-recent-projects");if(O)try{const E=JSON.parse(O);x(E)}catch{}},[]);const[v,x]=i.useState([]),y=i.useMemo(()=>e.map(O=>O.id),[e]),{healthMap:k,loading:N}=DP(y),R=i.useMemo(()=>e.map(O=>({project:O,health:k[O.id]||null})),[e,k]),w=i.useMemo(()=>{let O=[...R];return d!=="all"&&(O=O.filter(({project:E})=>E.status===d)),m!==null&&(O=O.filter(({project:E})=>E.nodeId===m)),O},[R,d,m]),A=i.useMemo(()=>{const O=[...w];return O.sort((E,S)=>{let I=0;switch(f){case"name":I=E.project.name.localeCompare(S.project.name);break;case"activity":{const F=E.project.lastActivityAt||E.health?.lastActivityAt||E.project.updatedAt,G=S.project.lastActivityAt||S.health?.lastActivityAt||S.project.updatedAt;I=new Date(G).getTime()-new Date(F).getTime();break}case"status":{const F={errored:0,initializing:1,paused:2,active:3};I=F[E.project.status]-F[S.project.status];break}}return g==="asc"?I:-I}),O},[w,f,g]),P=i.useMemo(()=>{const O=e.length,E=e.filter(z=>z.status==="active").length,S=e.filter(z=>z.status==="errored").length,I=new Set;e.forEach(z=>{z.nodeId&&I.add(z.nodeId)});const F=I.size||(O>0?1:0);let G=0,X=0,M=0;return Object.values(k).forEach(z=>{z&&(G+=z.activeTaskCount,X+=z.totalTasksCompleted,M+=z.inFlightAgentCount)}),{totalProjects:O,activeProjects:E,erroredProjects:S,totalNodes:F,totalActiveTasks:G,totalCompletedTasks:X,totalInFlightAgents:M}},[e,k]),T=i.useMemo(()=>({all:e.length,active:e.filter(O=>O.status==="active").length,paused:e.filter(O=>O.status==="paused").length,errored:e.filter(O=>O.status==="errored").length}),[e]),_=i.useMemo(()=>{const O=new Map;return e.forEach(E=>{const S=E.nodeId,I=O.get(S);if(I)I.count++;else{const G=c.find(X=>X.id===S)?.name??E._sourceNodeName??"Local";O.set(S,{name:G,count:1})}}),Array.from(O.entries()).map(([E,{name:S,count:I}])=>({nodeId:E??null,name:S,count:I}))},[e,c]),C=i.useCallback(O=>{const E=[O.id,...v.filter(S=>S!==O.id)].slice(0,3);x(E),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(E)),s(O)},[s,v]);return n||N&&e.length>0&&Object.keys(k).length===0?t.jsx(IP,{}):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(xr,{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(xn,{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(zi,{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(as,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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(Fs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Tn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),P.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ts,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),P.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Tr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:P.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(xn,{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})]})]}),_.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Tr,{size:14}),t.jsxs("select",{value:m??"",onChange:O=>{h(O.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),_.map(({nodeId:O,name:E,count:S})=>t.jsxs("option",{value:O??"",children:[E," (",S,")"]},O??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Wo,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:O=>{const[E,S]=O.target.value.split("-");p(E),b(S)},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(Bp,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:A.map(({project:O,health:E})=>{const S=c.find(F=>F.id===O.nodeId),I=S?void 0:O._sourceNodeName;return t.jsx(TP,{project:O,health:E,node:S,nodeNameFallback:I,onSelect:C,onPause:r,onResume:o,onRemove:l},O.id)})}),A.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Wo,{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 cu="kb-planning-last-description",du="kb-subtask-last-description",uu="kb-mission-last-goal";function zP(e,n){us(cu,e,n)}function OP(e){return Gn(cu,e)||""}function va(e){Ta(cu,e)}function FP(e,n){us(du,e,n)}function UP(e){return Gn(du,e)||""}function Ec(e){Ta(du,e)}function BP(e,n){us(uu,e,n)}function HP(e){return Gn(uu,e)||""}function Ii(e){Ta(uu,e)}function qP(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 VP(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 WP(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 Zs({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=WP(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?qP(o):void 0,h=o.question&&m!==void 0?VP(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 Ah="fusion-tab-id";function KP(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function da(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Ah);if(e)return e;const n=KP();return window.sessionStorage.setItem(Ah,n),n}function Il(e){const n=i.useMemo(()=>da(),[]),[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(SN(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=CN(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=fi(`/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:li("/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(EN(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const GP="fusion:ai-session-sync",Ph="fusion:ai-session-sync",JP=3e4,YP=6e4;function ui(){return Date.now()}function QP(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Rh(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 XP{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=QP(),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:ui()})}broadcastUpdate(n){const s=n.timestamp??ui();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??ui();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=ui();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=ui();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=ui();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(GP),this.channel.onmessage=s=>{const a=Rh(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Ph||!s.newValue))try{const a=JSON.parse(s.newValue),r=Rh(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ui();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},JP)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=ui();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(Ph,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:ui()});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=ui(),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>YP;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 mi=new XP;function Ka(){const e=i.useSyncExternalStore(c=>mi.subscribe(c),()=>mi.getSnapshot(),()=>mi.getSnapshot());i.useEffect(()=>{mi.requestSync()},[]);const n=i.useCallback(c=>{mi.broadcastUpdate(c)},[]),s=i.useCallback(c=>{mi.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{mi.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{mi.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{mi.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{mi.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function ZP(e,n){return e&&n?`${e}/${n}`:""}function eR(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 tR=["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 nR({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,b]=i.useState([]),[v,x]=i.useState(null),[y,k]=i.useState(!1),N=i.useRef(!1),[R,w]=i.useState(""),[A,P]=i.useState(!0),[T,_]=i.useState(!1),[C,$]=i.useState(!1),[O,E]=i.useState(!1),S=i.useRef(null),I=i.useRef(null),F=i.useRef(null),G=i.useRef(null),[X,M]=i.useState(o??null),z=i.useMemo(()=>da(),[]),{isLockedByOther:L,takeControl:j,isLoading:H}=Il(e?X:null),{activeTabMap:Q,broadcastUpdate:de,broadcastCompleted:pe,broadcastLock:B,broadcastUnlock:ve,broadcastHeartbeat:U}=Ka(),{confirm:se}=qs(),[ee,ie]=i.useState(void 0),[te,xe]=i.useState(void 0),[ne,_e]=i.useState([]),[Ne,Se]=i.useState(!0),[He,Ye]=i.useState(null),[Oe,ke]=i.useState([]),[De,re]=i.useState([]),oe=ZP(ee,te);i.useEffect(()=>{(async()=>{try{Se(!0);const ze=await As();_e(ze.models),ke(ze.favoriteProviders),re(ze.favoriteModels)}catch(ze){Ye(Me(ze)||"Failed to load models")}finally{Se(!1)}})()},[]);const we=i.useCallback(Ie=>{ke(ze=>{const st=ze,Re=st.includes(Ie)?st.filter(kt=>kt!==Ie):[Ie,...st];return Cn({favoriteProviders:Re,favoriteModels:De}).catch(()=>{ke(st)}),Re})},[De]),Z=i.useCallback(Ie=>{re(ze=>{const st=ze,Re=st.includes(Ie)?st.filter(kt=>kt!==Ie):[Ie,...st];return Cn({favoriteProviders:Oe,favoriteModels:Re}).catch(()=>{re(st)}),Re})},[Oe]),qe=i.useCallback((Ie,ze)=>{if(!Ie||!ze)return"Using default";const st=ne.find(yt=>yt.provider===Ie&&yt.id===ze);return st?`${st.provider}/${st.id}`:`${Ie}/${ze}`},[ne]),Qe=i.useCallback(Ie=>{I.current?.close();const ze=sN(Ie,a,{onThinking:st=>{w(yt=>yt+st),de({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:st=>{_(!1),$(!1),Ii(a),u({type:"question",sessionId:Ie,question:st}),w(""),k(!0),de({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:st=>{_(!1),$(!1),Ii(a),u({type:"summary",sessionId:Ie,summary:st}),x(st),w(""),k(!0),de({sessionId:Ie,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:st=>{const yt=st||"Session failed while contacting the AI.";_(!1),$(!1),h(null),u({type:"error",sessionId:Ie,errorMessage:yt}),w(""),k(!0),F.current=Ie,de({sessionId:Ie,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),pe({sessionId:Ie,status:"error"})},onComplete:()=>{_(!1),$(!1),F.current=null,pe({sessionId:Ie,status:"complete"})},onConnectionStateChange:st=>{_(st==="reconnecting")}});I.current=ze},[pe,de,l,a,z]),ge=i.useCallback(async Ie=>{const ze=Ie??l;if(ze.trim()){h(null),w(""),p([]),b([]),_(!1),u({type:"loading"});try{const{sessionId:st}=await Zj(ze.trim(),a,ee&&te?{modelProvider:ee,modelId:te}:void 0);F.current=st,M(st),Ii(a),Qe(st),p([])}catch(st){_(!1),h(Me(st)||"Failed to start interview session"),u({type:"initial"}),F.current=null,M(null)}}},[Qe,l,ee,te,a]);i.useEffect(()=>{e&&d.type==="initial"&&S.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&r&&!N.current&&d.type==="initial"){c(r);const Ie=setTimeout(()=>{N.current=!0,ge(r)},0);return()=>clearTimeout(Ie)}else if(e&&!r&&!N.current&&d.type==="initial"){const Ie=HP(a);Ie&&c(Ie)}},[e,r,d.type,ge]),i.useEffect(()=>{e||(N.current=!1,_(!1),$(!1),M(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Ie=!1;return pi(o).then(ze=>{if(Ie||!ze)return;const st=Ra(ze.conversationHistory);if(b(st),M(ze.id),p(st.map(yt=>yt.response).filter(yt=>!!(yt&&typeof yt=="object"&&!Array.isArray(yt)))),ze.status==="awaiting_input"&&ze.currentQuestion)try{Ii(a);const yt=JSON.parse(ze.currentQuestion);F.current=ze.id,k(!0),u({type:"question",sessionId:ze.id,question:yt})}catch{h("Failed to restore session question.")}else if(ze.status==="complete"&&ze.result)try{Ii(a);const yt=JSON.parse(ze.result);F.current=ze.id,k(!0),x(yt),u({type:"summary",sessionId:ze.id,summary:yt})}catch{h("Failed to restore session result.")}else ze.status==="generating"?(F.current=ze.id,k(!0),ze.thinkingOutput&&w(ze.thinkingOutput),u({type:"loading"}),Qe(ze.id)):ze.status==="error"&&(F.current=ze.id,k(!0),h(null),u({type:"error",sessionId:ze.id,errorMessage:ze.error??"The session encountered an error."}))}).catch(()=>{Ie||h("Failed to resume session.")}),()=>{Ie=!0}},[Qe,e,o,d.type,a]),i.useEffect(()=>{if(!e){G.current&&(ve(G.current,z),G.current=null);return}if(X&&G.current!==X){G.current&&ve(G.current,z),B(X,z),G.current=X;return}!X&&G.current&&(ve(G.current,z),G.current=null)},[B,ve,e,X,z]),i.useEffect(()=>{if(!e||!X||G.current!==X)return;U(z);const Ie=setInterval(()=>{U(z)},3e4);return()=>{clearInterval(Ie)}},[U,e,X,z]),i.useEffect(()=>()=>{I.current?.close(),I.current=null,G.current&&(ve(G.current,z),G.current=null)},[ve,z]),i.useEffect(()=>{if(!e)return;const Ie=ze=>{(d.type==="question"||d.type==="summary")&&(ze.preventDefault(),ze.returnValue=""),I.current?.close()};return window.addEventListener("beforeunload",Ie),()=>window.removeEventListener("beforeunload",Ie)},[e,d]);const Ue=i.useCallback(()=>{I.current?.close(),I.current=null,n()},[n]),Xe=i.useCallback(async()=>{if(l&&BP(l,a),!(y&&!await se({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(I.current?.close(),I.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await uf(d.sessionId,a,z)}catch{}c(""),u({type:"initial"}),h(null),p([]),b([]),x(null),w(""),_(!1),$(!1),k(!1),E(!1),ie(void 0),xe(void 0),F.current=null,M(null),n()}},[l,y,d,n,a,z,se]);i.useEffect(()=>{if(!e)return;const Ie=ze=>{ze.key==="Escape"&&Xe()};return document.addEventListener("keydown",Ie),()=>document.removeEventListener("keydown",Ie)},[e,Xe]);const wt=i.useCallback(async Ie=>{if(d.type!=="question")return;const{sessionId:ze}=d;h(null),p(st=>[...st,Ie]),b(st=>[...st,{question:d.question,response:Ie}]),u({type:"loading"}),w("");try{Qe(ze),await eN(ze,Ie,a,z),k(!0)}catch(st){I.current?.close(),I.current=null,h(Me(st)||"Failed to submit response"),u({type:"question",sessionId:ze,question:d.question})}},[d,a,z,Qe]),ye=i.useCallback(async()=>{if(d.type!=="error")return;const Ie=d.sessionId;h(null),$(!0),w(""),u({type:"loading"}),Qe(Ie);try{F.current=Ie,M(Ie),await tN(Ie,a,z)}catch(ze){let st=ze;if((Me(ze)||"").includes("not in an error state"))try{const Re=await pi(Ie);if(!Re)throw new Error("Failed to refresh interview session.");const kt=Ra(Re.conversationHistory);if(b(kt),p(kt.map(Et=>Et.response).filter(Et=>!!(Et&&typeof Et=="object"&&!Array.isArray(Et)))),F.current=Re.id,M(Re.id),k(!0),Re.status==="generating")w(Re.thinkingOutput??""),u({type:"loading"}),I.current?.isConnected()||Qe(Re.id);else if(Re.status==="awaiting_input"){if(!Re.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Ii(a);const Et=JSON.parse(Re.currentQuestion);u({type:"question",sessionId:Re.id,question:Et}),I.current?.isConnected()||Qe(Re.id)}else if(Re.status==="complete"){if(!Re.result)throw new Error("Interview session is complete but has no result.");Ii(a);const Et=JSON.parse(Re.result);x(Et),u({type:"summary",sessionId:Re.id,summary:Et})}else Re.status==="error"&&u({type:"error",sessionId:Re.id,errorMessage:Re.error??"Retry failed. Please try again."});_(!1);return}catch(Re){st=Re}I.current?.close(),I.current=null,u({type:"error",sessionId:Ie,errorMessage:Me(st)||"Retry failed. Please try again."}),_(!1)}finally{$(!1)}},[Qe,a,z,d]),le=i.useCallback(async()=>{if(d.type==="summary"){h(null),E(!0);try{const Ie=await nN(d.sessionId,v||void 0,a);s(Ie),Ii(a),I.current?.close(),I.current=null,c(""),u({type:"initial"}),h(null),p([]),b([]),x(null),w(""),_(!1),$(!1),k(!1),E(!1),F.current=null,M(null),n()}catch(Ie){h(Me(Ie)||"Failed to create mission"),E(!1)}}},[d,v,s,n,a]),Te=()=>d.type==="question"?Math.min(f.length+1,6):6,be=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Le=X?Q.get(X):null,Je=Le&&Le.tabId!==z,nt=!!(Je&&!Le.stale),mt=L&&(!Je||Le.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&Xe(),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(ks,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[be&&t.jsx("button",{className:"modal-send-to-background",onClick:Ue,title:"Send to background","aria-label":"Send to background",children:t.jsx(Wr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Xe,"aria-label":"Close",children:t.jsx(Wt,{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…"}),nt&&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(ms,{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:S,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:Ie=>c(Ie.target.value),onKeyDown:Ie=>{Ie.key==="Enter"&&!Ie.shiftKey&&l.trim()&&(Ie.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:tR.map((Ie,ze)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Ie),children:Ie.length>45?Ie.slice(0,45)+"...":Ie},ze))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",Ne&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(hs,{id:"mission-interview-modal-model",label:"Planning Model",value:oe,onChange:Ie=>{const{provider:ze,modelId:st}=eR(Ie);ie(ze),xe(st)},models:ne,disabled:Ne,favoriteProviders:Oe,onToggleFavorite:we,favoriteModels:De,onToggleModelFavorite:Z}),He&&t.jsxs("div",{className:"form-hint form-hint-error",children:[He," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Se(!0);const Ie=await As();_e(Ie.models),ke(Ie.favoriteProviders),re(Ie.favoriteModels),Ye(null)}catch(Ie){Ye(Me(Ie)||"Failed to load models")}finally{Se(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ee&&te?"model-badge-custom":"model-badge-default"}`,children:qe(ee,te)})})]})]}),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(ks,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:R?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>P(!A),type:"button",children:A?"Hide thinking":"Show thinking"}),A&&R&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:R})})]})]}),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(Zs,{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 ye(),disabled:C,children:[C?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Qn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:C?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Xe,disabled:C,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(sR,{question:d.question,progress:Te(),historyEntries:g,onSubmit:wt}),d.type==="summary"&&v&&t.jsx(iR,{summary:v,historyEntries:g,onSummaryChange:x,onApprove:le,onStartOver:()=>{u({type:"initial"}),k(!1),x(null),p([]),b([]),M(null),I.current?.close(),I.current=null},isCreating:O}),L&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(vl,{size:16}),t.jsx("span",{children:mt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),mt&&t.jsx("button",{type:"button",onClick:()=>{j()},disabled:H,className:"btn btn-primary session-lock-take-control",children:H?"Taking control...":"Take Control"})]})})]})]})}):null}function sR({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(Zs,{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 b=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:b})}}),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(Tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Wt,{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(Hr,{size:16,className:"icon-ml-4"})]})})]})}function iR({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((N,R)=>R))),[d,u]=i.useState(()=>{const N=new Set;return e.milestones.forEach((R,w)=>{R.slices.forEach((A,P)=>N.add(`${w}-${P}`))}),N}),m=N=>{c(R=>{const w=new Set(R);return w.has(N)?w.delete(N):w.add(N),w})},h=N=>{u(R=>{const w=new Set(R);return w.has(N)?w.delete(N):w.add(N),w})},f=(N,R)=>{const w=[...e.milestones];w[N]={...w[N],...R},s({...e,milestones:w})},p=(N,R,w)=>{const A=[...e.milestones],P=[...A[N].slices];P[R]={...P[R],...w},A[N]={...A[N],slices:P},s({...e,milestones:A})},g=(N,R,w,A)=>{const P=[...e.milestones],T=[...P[N].slices],_=[...T[R].features];_[w]={..._[w],...A},T[R]={...T[R],features:_},P[N]={...P[N],slices:T},s({...e,milestones:P})},b=N=>{const R=e.milestones.filter((w,A)=>A!==N);s({...e,milestones:R})},v=(N,R)=>{const w=[...e.milestones];w[N]={...w[N],slices:w[N].slices.filter((A,P)=>P!==R)},s({...e,milestones:w})},x=(N,R,w)=>{const A=[...e.milestones],P=[...A[N].slices];P[R]={...P[R],features:P[R].features.filter((T,_)=>_!==w)},A[N]={...A[N],slices:P},s({...e,milestones:A})},y=(N,R)=>{const w=[...e.milestones],A=[...w[N].slices];A[R]={...A[R],features:[...A[R].features,{title:"New feature",description:""}]},w[N]={...w[N],slices:A},s({...e,milestones:w})},k=e.milestones.reduce((N,R)=>N+R.slices.reduce((w,A)=>w+A.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(Zs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",k," 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:N=>s({...e,missionTitle:N.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:N=>s({...e,missionDescription:N.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((N,R)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(R),children:[l.has(R)?t.jsx(rn,{size:16,className:"icon-text-secondary"}):t.jsx(_n,{size:16,className:"icon-text-secondary"}),t.jsx(ea,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:N.title,onChange:w=>f(R,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),b(R)},title:"Remove milestone",children:t.jsx(vn,{size:14,className:"icon-text-secondary"})})]}),l.has(R)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:N.description||"",onChange:w=>f(R,{description:w.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:N.verification||"",onChange:w=>f(R,{verification:w.target.value})})]}),N.slices.map((w,A)=>{const P=`${R}-${A}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(P),children:[d.has(P)?t.jsx(rn,{size:14,className:"icon-text-secondary"}):t.jsx(_n,{size:14,className:"icon-text-secondary"}),t.jsx(nd,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:T=>p(R,A,{title:T.target.value}),onClick:T=>T.stopPropagation()}),N.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:T=>{T.stopPropagation(),v(R,A)},title:"Remove slice",children:t.jsx(vn,{size:12,className:"icon-text-secondary"})})]}),d.has(P)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:w.verification||"",onChange:T=>p(R,A,{verification:T.target.value})})]}),w.features.map((T,_)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Gc,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:T.title,onChange:C=>g(R,A,_,{title:C.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:()=>x(R,A,_),title:"Remove feature",children:t.jsx(vn,{size:12,className:"icon-text-secondary"})})]},_)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(R,A),children:[t.jsx(xn,{size:12}),"Add Feature"]})]})]},A)})]})]},R))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ua,{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(bt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Tn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function aR({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const[u,m]=i.useState({type:"initial"}),[h,f]=i.useState(null),[p,g]=i.useState([]),[b,v]=i.useState([]),[x,y]=i.useState(null),[k,N]=i.useState(""),[R,w]=i.useState(!0),[A,P]=i.useState(!1),[T,_]=i.useState(!1),C=i.useRef(null),$=i.useRef(null),O=i.useRef(null),E=i.useRef(null),[S,I]=i.useState(null),F=i.useMemo(()=>da(),[]);Il(e?S:null);const{activeTabMap:G,broadcastUpdate:X,broadcastCompleted:M,broadcastLock:z,broadcastUnlock:L,broadcastHeartbeat:j}=Ka(),H=a==="milestone"?iN:cN,Q=a==="milestone"?aN:dN,de=a==="milestone"?rN:uN,pe=a==="milestone"?oN:mN,B=a==="milestone"?lN:hN,ve=a==="milestone"?"Milestone":"Slice",U=a==="milestone"?"milestone_interview":"slice_interview",se=i.useCallback(De=>{$.current?.close();const re=de(De,c,{onThinking:oe=>{N(we=>we+oe),X({sessionId:De,status:"generating",needsInput:!1,owningTabId:F,type:U,title:o,projectId:c??null})},onQuestion:oe=>{P(!1),ee(),m({type:"question",sessionId:De,question:oe}),N(""),X({sessionId:De,status:"awaiting_input",needsInput:!0,owningTabId:F,type:U,title:o,projectId:c??null})},onSummary:oe=>{P(!1),ee(),m({type:"summary",sessionId:De,summary:oe}),y(oe),N(""),X({sessionId:De,status:"complete",needsInput:!1,owningTabId:F,type:U,title:o,projectId:c??null})},onError:oe=>{const we=oe||"Session failed while contacting the AI.";P(!1),f(null),m({type:"error",sessionId:De,errorMessage:we}),N(""),O.current=De,X({sessionId:De,status:"error",needsInput:!1,owningTabId:F,type:U,title:o,projectId:c??null}),M({sessionId:De,status:"error"})},onComplete:()=>{P(!1),O.current=null,M({sessionId:De,status:"complete"})},onConnectionStateChange:oe=>{P(oe==="reconnecting")}});$.current=re},[M,X,de,U,c,F,o]),ee=()=>{y(null),g([]),v([]),N("")},ie=i.useCallback(async()=>{f(null),ee(),P(!1),m({type:"loading"});try{const{sessionId:De}=await H(r,c);O.current=De,I(De),se(De)}catch(De){P(!1),f(Me(De)||`Failed to start ${ve.toLowerCase()} interview`),m({type:"initial"}),O.current=null,I(null)}},[se,c,H,r,ve]),te=i.useCallback(async()=>{f(null),_(!0);try{await B(r,c),s(),m({type:"applied"})}catch(De){f(Me(De)||`Failed to skip ${ve.toLowerCase()} interview`),_(!1)}},[s,c,B,r,ve]);i.useEffect(()=>{e&&u.type==="initial"&&C.current?.focus()},[e,u.type]),i.useEffect(()=>{if(!e||!d||u.type!=="initial")return;let De=!1;return pi(d).then(re=>{if(De||!re)return;const oe=Ra(re.conversationHistory);if(v(oe),I(re.id),g(oe.map(we=>we.response).filter(we=>!!(we&&typeof we=="object"&&!Array.isArray(we)))),re.status==="awaiting_input"&&re.currentQuestion)try{const we=JSON.parse(re.currentQuestion);O.current=re.id,m({type:"question",sessionId:re.id,question:we})}catch{f("Failed to restore session question.")}else if(re.status==="complete"&&re.result)try{const we=JSON.parse(re.result);O.current=re.id,y(we),m({type:"summary",sessionId:re.id,summary:we})}catch{f("Failed to restore session result.")}else re.status==="generating"?(O.current=re.id,re.thinkingOutput&&N(re.thinkingOutput),m({type:"loading"}),se(re.id)):re.status==="error"&&(O.current=re.id,f(null),m({type:"error",sessionId:re.id,errorMessage:re.error??"The session encountered an error."}))}).catch(()=>{De||f("Failed to resume session.")}),()=>{De=!0}},[se,e,d,u.type]),i.useEffect(()=>{e||(P(!1),I(null))},[e]),i.useEffect(()=>{if(!(!e||!S)){if(E.current!==S){E.current&&L(E.current,F),z(S,F),E.current=S;return}!S&&E.current&&(L(E.current,F),E.current=null)}},[z,L,e,S,F]),i.useEffect(()=>{if(!e||!S||E.current!==S)return;j(F);const De=setInterval(()=>{j(F)},3e4);return()=>{clearInterval(De)}},[j,e,S,F]),i.useEffect(()=>()=>{$.current?.close(),$.current=null,E.current&&(L(E.current,F),E.current=null)},[L,F]);const xe=i.useCallback(()=>{$.current?.close(),$.current=null,n()},[n]),ne=i.useCallback(async()=>{$.current?.close(),$.current=null,ee(),m({type:"initial"}),f(null),O.current=null,I(null),n()},[n]),_e=i.useCallback(async De=>{if(u.type!=="question")return;const{sessionId:re}=u;f(null),g(oe=>[...oe,De]),v(oe=>[...oe,{question:u.question,response:De}]),m({type:"loading"}),N("");try{se(re),await Q(re,De,c,F)}catch(oe){$.current?.close(),$.current=null,f(Me(oe)||"Failed to submit response"),m({type:"question",sessionId:re,question:u.question})}},[se,c,Q,F,u]),Ne=i.useCallback(async()=>{if(u.type==="summary"){f(null),_(!0);try{await pe(u.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(De){f(Me(De)||"Failed to apply interview results"),_(!1)}}},[pe,x,s,c,u]),Se=()=>u.type==="question"?Math.min(p.length+1,6):6,He=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Ye=S?G.get(S):null,ke=!!(Ye&&Ye.tabId!==F&&!Ye.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:De=>De.target===De.currentTarget&&ne(),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(ms,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",ve,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[He&&t.jsx("button",{className:"modal-send-to-background",onClick:xe,title:"Send to background","aria-label":"Send to background",children:t.jsx(Wr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:ne,"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),A&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ke&&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(ms,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",ve," 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 ie(),children:[t.jsx(ms,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void te(),disabled:T,children:[T?t.jsx(bt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:ne,children:"Cancel"})]})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:k?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>w(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&k&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:k})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Zs,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:ne,children:"Cancel"})})]})]})}),u.type==="question"&&t.jsx(rR,{question:u.question,progress:Se(),historyEntries:b,onSubmit:_e}),u.type==="summary"&&x&&t.jsx(oR,{summary:x,historyEntries:b,onSummaryChange:y,onApply:Ne,onCancel:ne,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(Tn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ve," 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 rR({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(Zs,{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 b=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:b})}}),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(Tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Wt,{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(Hr,{size:16,className:"icon-ml-4"})]})})]})}function oR({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(Zs,{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(rn,{size:16}):t.jsx(_n,{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(bt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const dr={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)"}},Th={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)"}},Ih={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)"}},_o={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)"}},Ao={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)"}},Po={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)"}},$h={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)"}},lR=3;function cR(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function Dh({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 Lh(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Mc={title:"",description:"",status:"planning",autopilotEnabled:!1},_c={title:"",description:"",status:"planning",dependencies:[]},Ac={title:"",description:"",status:"pending"},Pc={title:"",description:"",acceptanceCriteria:"",status:"defined"},dR=3600*1e3;function ll(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 uR(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=dR,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 mR(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 hR(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 Rc(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 Kg=["feature_triaged","feature_completed"],Gg=["slice_activated","slice_completed","milestone_completed"],Jg=["mission_started","mission_paused","mission_resumed","mission_completed"],Yg=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function zh(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Jg.includes(e);case"tasks":return Kg.includes(e);case"slices":return Gg.includes(e);case"autopilot":return Yg.includes(e);default:return!0}}function pR(e){return e==="error"||e==="warning"?"mission-event__type--error":Jg.includes(e)?"mission-event__type--state":Kg.includes(e)?"mission-event__type--task":Gg.includes(e)?"mission-event__type--slice":Yg.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function fR(e){return e.replace(/_/g," ")}function gR(e,n){return n?e==="watching"?`Watching since ${ll(n)}`:`Last activation ${ll(n)}`:null}function bR({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,b]=i.useState(null),[v,x]=i.useState(!0),[y,k]=i.useState(!1),N=la()==="mobile",[R,w]=i.useState(!1),[A,P]=i.useState(null),[T,_]=i.useState(Mc),[C,$]=i.useState(!1),[O,E]=i.useState(new Set),[S,I]=i.useState(new Set),[F,G]=i.useState(null),[X,M]=i.useState(_c),[z,L]=i.useState(!1),[j,H]=i.useState(null),[Q,de]=i.useState(Ac),[pe,B]=i.useState(!1),[ve,U]=i.useState(null),[se,ee]=i.useState(null),[ie,te]=i.useState(Pc),[xe,ne]=i.useState(!1),[_e,Ne]=i.useState(null),[Se,He]=i.useState(null),[Ye,Oe]=i.useState(""),[ke,De]=i.useState(!1),[re,oe]=i.useState([]),[we,Z]=i.useState(void 0),qe=we??c,[Qe,ge]=i.useState(null),[Ue,Xe]=i.useState(null),[wt,ye]=i.useState(null);i.useEffect(()=>{h&&qe&&De(!0)},[h,qe]),i.useEffect(()=>{if(!h||qe)return;let V=!1;return zd(r).then(Ce=>{if(V)return;const Ke=Ce.filter(At=>At.type==="mission_interview"&&(At.status==="awaiting_input"||At.status==="error"));oe(Ke)}).catch(Ce=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ce)}),()=>{V=!0}},[h,r,qe]),i.useEffect(()=>{if(!h||!u)return;let V=!1;return pi(u).then(Ce=>{if(!(V||!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=>{V||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ce),m?.())}),()=>{V=!0}},[h,u,m]);const[le,Te]=i.useState(null),[be,Le]=i.useState(new Map),[Je,nt]=i.useState(null),[mt,Ie]=i.useState({title:"",assertion:"",status:"pending"}),[ze,st]=i.useState(!1),[yt,Re]=i.useState(null),[kt,Et]=i.useState(new Map),[jt,Rt]=i.useState(new Set),[Dt,Tt]=i.useState(new Set),[It,Ut]=i.useState(null),[Ft,Jt]=i.useState(new Map),[Vt,Yt]=i.useState(null),[Kt,qt]=i.useState(null),[Bt,Xt]=i.useState(!0),[an,Qt]=i.useState(new Set),[fe,Fe]=i.useState(new Map),[ae,Pe]=i.useState(null),[Ae,W]=i.useState(new Map),[je,ce]=i.useState(null),[$e,it]=i.useState(new Map),[vt,tn]=i.useState(new Map),[Pt,Lt]=i.useState("structure"),[zt,yn]=i.useState([]),ue=i.useRef([]),lt=i.useRef([]),ut=i.useRef(null),dt=i.useRef(null),at=i.useRef("structure"),St=i.useRef("all"),[he,ct]=i.useState(!1),[Zt,Sn]=i.useState(0),[In,Hn]=i.useState("all"),[Xn,jn]=i.useState(new Set),Pn=i.useRef(null),rs=i.useRef(null);lt.current=f,ut.current=g,dt.current=Vt,at.current=Pt,St.current=In;const os=i.useCallback((V="auto")=>{const Ce=rs.current;if(Ce&&typeof Ce.scrollIntoView=="function"){Ce.scrollIntoView({block:"end",behavior:V});return}const Ke=Pn.current;Ke&&(Ke.scrollTop=Ke.scrollHeight)},[]),cn=i.useCallback(()=>{const V=Pn.current;return V?V.scrollHeight-V.scrollTop-V.clientHeight<=100:!0},[]),$n=i.useCallback(async V=>{if(V.length===0){tn(new Map);return}const Ce=await Cj(r);tn(Ke=>{const At=new Map(Ke);for(const[bn,Gt]of Object.entries(Ce))mR(Gt)&&At.set(bn,Gt);return At})},[r]),nn=i.useCallback(async()=>{try{x(!0);const V=await wj(r);p(V),$n(V)}catch(V){a(Me(V)||"Failed to load missions","error")}finally{x(!1)}},[a,r,$n]),_t=i.useCallback(async V=>{try{k(!0);const Ce=await df(V,r);if(b(Ce),Ce.milestones.length>0){const Ke=Ce.milestones[0].id;Yt(Ke),Xt(!0),E(new Set([Ke])),ql(Ke,r).then(At=>{Le(bn=>{const Gt=new Map(bn);return Gt.set(Ke,At),Gt})}).catch(()=>{}),Vl(Ke,r).then(At=>{Jt(bn=>{const Gt=new Map(bn);return Gt.set(Ke,At),Gt})}).catch(()=>{}),Ce.milestones[0].slices.length>0&&I(new Set([Ce.milestones[0].slices[0].id]))}else Yt(null),qt(null)}catch(Ce){a(Me(Ce)||"Failed to load mission details","error")}finally{k(!1)}},[a,r]);i.useEffect(()=>{if(!h||!Vt){qt(null);return}let V=!1;return qt(null),Lu(Vt,r).then(Ce=>{if(!V){if(!Rc(Ce)){qt(null);return}qt(Ce),Jt(Ke=>{const At=new Map(Ke);return At.set(Vt,Ce.rollup),At})}}).catch(()=>{V||qt(null)}),()=>{V=!0}},[h,Vt,r]),i.useEffect(()=>{Xt(!0)},[Vt]);const K=i.useCallback(V=>{!V||V!==dt.current||Lu(V,r).then(Ce=>{dt.current!==V||!Rc(Ce)||(qt(Ce),Jt(Ke=>{const At=new Map(Ke);return At.set(V,Ce.rollup),At}))}).catch(()=>{})},[r]),Ve=i.useCallback(async(V,Ce)=>{const Ke=Ce?.append??!1,At=Ke?ue.current.length:0;Ke||(ct(!0),jn(new Set));try{const bn=await Sj(V,{limit:50,offset:At,eventType:void 0},r),Gt=bn.events.filter(hn=>zh(hn.eventType,In));yn(hn=>{if(!Ke)return Gt;const tt=new Set(hn.map(Ct=>Ct.id)),et=[...hn];for(const Ct of Gt)tt.has(Ct.id)||et.push(Ct);return et}),Sn(bn.total),Ke||requestAnimationFrame(()=>{os("auto")})}catch(bn){a(Me(bn)||"Failed to load mission activity","error")}finally{Ke||ct(!1)}},[a,In,r,os]);i.useEffect(()=>{ue.current=zt},[zt]),i.useEffect(()=>{h&&(nn(),b(null),Yt(null),qt(null),yn([]),Sn(0),Lt("structure"),Hn("all"),jn(new Set))},[h,nn]);const pt=i.useRef(null);i.useEffect(()=>{h&&d&&pt.current!==d&&f.length>0&&(pt.current=d,_t(d))},[h,d,f,_t]),i.useEffect(()=>{h||(pt.current=null)},[h]),i.useEffect(()=>{!h||!g||Pt!=="activity"||Ve(g.id)},[Pt,h,Ve,g,In]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const V=new URLSearchParams;r&&V.set("projectId",r);const Ce=`/api/events${V.size>0?`?${V.toString()}`:""}`,Ke=()=>{$n(lt.current)},At=cs=>{Ke();const zn=cs;if(zn.data)try{const pn=JSON.parse(zn.data);pn?.id&&p(qi=>qi.map(Gs=>Gs.id===pn.id?{...Gs,...pn}:Gs))}catch{}ut.current&&_t(ut.current.id)},bn=cs=>{Ke(),ut.current&&_t(ut.current.id)},Gt=()=>{Ke(),ut.current&&_t(ut.current.id)},hn=cs=>{Ke(),ut.current&&_t(ut.current.id)},tt=cs=>{const zn=cs;if(zn.data)try{const pn=JSON.parse(zn.data);pn&&pn.featureId&&(wi(pn.featureId),Ks(pn.featureId),pn.milestoneId&&K(pn.milestoneId))}catch{}},et=cs=>{const zn=cs;if(zn.data)try{const pn=JSON.parse(zn.data);pn&&pn.featureId&&(wi(pn.featureId),Ks(pn.featureId),pn.milestoneId&&K(pn.milestoneId),ut.current&&_t(ut.current.id))}catch{}},Ct=cs=>{const zn=cs;if(zn.data)try{const pn=JSON.parse(zn.data);pn&&pn.milestoneId&&(En(pn.milestoneId),K(pn.milestoneId))}catch{}},Nn=cs=>{const zn=cs;if(zn.data)try{const pn=JSON.parse(zn.data);pn&&pn.milestoneId&&(Un(pn.milestoneId),En(pn.milestoneId),K(pn.milestoneId))}catch{}};return li(Ce,{events:{"mission:updated":At,"slice:updated":bn,"feature:updated":Gt,"milestone:updated":hn,"mission:event":cs=>{Ke();const zn=ut.current;if(!zn||at.current!=="activity")return;const pn=cn(),qi=cs;if(qi.data)try{const Gs=JSON.parse(qi.data);if(!hR(Gs)||Gs.missionId!==zn.id||!zh(Gs.eventType,St.current))return;yn(ki=>{const Ol=ki.filter(Fl=>Fl.id!==Gs.id);return[Gs,...Ol].slice(0,100)}),Sn(ki=>ki+1),pn&&requestAnimationFrame(()=>{const ki=Pn.current;ki&&(ki.scrollTop=0)})}catch{}},"validator-run:started":tt,"validator-run:completed":et,"milestone:validation:updated":Ct,"assertion:created":Nn,"assertion:updated":Nn,"assertion:deleted":Nn,"assertion:linked":Nn,"assertion:unlinked":Nn,"fix-feature:created":cs=>{const zn=cs;if(zn.data)try{const pn=JSON.parse(zn.data);if(pn&&pn.sourceFeatureId){wi(pn.sourceFeatureId);const qi=pn?.feature?.sliceId,Gs=ut.current;if(qi&&Gs){const ki=Gs.milestones.find(Ol=>Ol.slices.some(Fl=>Fl.id===qi));ki&&K(ki.id)}ut.current&&_t(ut.current.id)}}catch{}}}})},[h,cn,_t,$n,r,K]);const ht=i.useCallback(()=>{w(!0),P(null),_(Mc)},[]),Nt=i.useCallback(V=>{P(V.id),w(!1),_({title:V.title,description:V.description||"",status:V.status,autopilotEnabled:V.autopilotEnabled??!1})},[]),Mt=i.useCallback(()=>{P(null),w(!1),_(Mc)},[]),$t=i.useCallback(async()=>{if(!T.title.trim()){a("Mission title is required","error");return}try{if($(!0),R)await kj({title:T.title.trim(),description:T.description.trim()||void 0,autopilotEnabled:T.autopilotEnabled},r),a("Mission created","success");else if(A){const V={title:T.title.trim(),description:T.description.trim()||void 0,status:T.status,autopilotEnabled:T.autopilotEnabled};T.autopilotEnabled&&(V.autoAdvance=!0),await jj(A,V,r),a("Mission updated","success"),g?.id===A&&await _t(A)}await nn(),Mt()}catch(V){a(Me(V)||"Failed to save mission","error")}finally{$(!1)}},[T,R,A,a,nn,_t,g,Mt,r]),wn=i.useCallback(async V=>{try{await Nj(V,r),a("Mission deleted","success"),g?.id===V&&b(null),await nn(),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete mission","error")}},[a,nn,g,r]),ls=i.useCallback(()=>{L(!0),G(null),M(_c)},[]),Cs=i.useCallback(V=>{G(V.id),L(!1),M({title:V.title,description:V.description||"",status:V.status,dependencies:V.dependencies})},[]),$s=i.useCallback(()=>{G(null),L(!1),M(_c)},[]),ps=i.useCallback(async()=>{if(!X.title.trim()){a("Milestone title is required","error");return}try{$(!0),z&&g?(await Ej(g.id,{title:X.title.trim(),description:X.description.trim()||void 0,dependencies:X.dependencies},r),a("Milestone created","success")):F&&(await Mj(F,{title:X.title.trim(),description:X.description.trim()||void 0,status:X.status,dependencies:X.dependencies},r),a("Milestone updated","success")),await _t(g.id),$s()}catch(V){a(Me(V)||"Failed to save milestone","error")}finally{$(!1)}},[X,z,F,g,a,_t,$s,T.title,r]),Vs=i.useCallback(async V=>{try{await _j(V,r),a("Milestone deleted","success"),await _t(g.id),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete milestone","error")}},[a,_t,g,r]),dn=i.useCallback(V=>{Yt(V),Xt(!0),E(Ce=>{const Ke=new Set(Ce);return!Ke.has(V)?(Ke.add(V),ql(V,r).then(bn=>{Le(Gt=>{const hn=new Map(Gt);return hn.set(V,bn),hn})}).catch(()=>{}),Vl(V,r).then(bn=>{Jt(Gt=>{const hn=new Map(Gt);return hn.set(V,bn),hn})}).catch(()=>{})):Ke.delete(V),Ke})},[r]),yi=i.useCallback(V=>{U(V),B(!0),H(null),de(Ac)},[]),me=i.useCallback(V=>{H(V.id),B(!1),de({title:V.title,description:V.description||"",status:V.status})},[]),We=i.useCallback(()=>{H(null),B(!1),U(null),de(Ac)},[]),ot=i.useCallback(async()=>{if(!Q.title.trim()){a("Slice title is required","error");return}try{$(!0),pe&&ve?(await Aj(ve,{title:Q.title.trim(),description:Q.description.trim()||void 0},r),a("Slice created","success")):j&&(await Pj(j,{title:Q.title.trim(),description:Q.description.trim()||void 0,status:Q.status},r),a("Slice updated","success")),await _t(g.id),We()}catch(V){a(Me(V)||"Failed to save slice","error")}finally{$(!1)}},[Q,pe,j,ve,g,a,_t,We,r]),sn=i.useCallback(async V=>{try{await Rj(V,r),a("Slice deleted","success"),await _t(g.id),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete slice","error")}},[a,_t,g,r]),Dn=i.useCallback(async V=>{try{await Tj(V,r),a("Slice activated","success"),await _t(g.id)}catch(Ce){a(Me(Ce)||"Failed to activate slice","error")}},[a,_t,g,r]),Y=i.useCallback(V=>{I(Ce=>{const Ke=new Set(Ce);return Ke.has(V)?Ke.delete(V):Ke.add(V),Ke})},[]),Ee=i.useCallback(V=>{Ne(V),ne(!0),ee(null),te(Pc)},[]),rt=i.useCallback(V=>{ee(V.id),ne(!1),te({title:V.title,description:V.description||"",acceptanceCriteria:V.acceptanceCriteria||"",status:V.status})},[]),Be=i.useCallback(()=>{ee(null),ne(!1),Ne(null),te(Pc)},[]),ft=i.useCallback(async()=>{if(!ie.title.trim()){a("Feature title is required","error");return}try{$(!0),xe&&_e?(await Ij(_e,{title:ie.title.trim(),description:ie.description.trim()||void 0,acceptanceCriteria:ie.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):se&&(await $j(se,{title:ie.title.trim(),description:ie.description.trim()||void 0,acceptanceCriteria:ie.acceptanceCriteria.trim()||void 0,status:ie.status},r),a("Feature updated","success")),await _t(g.id),Be()}catch(V){a(Me(V)||"Failed to save feature","error")}finally{$(!1)}},[ie,xe,se,_e,g,a,_t,Be,r]),mn=i.useCallback(async V=>{try{await Dj(V,r),a("Feature deleted","success"),await _t(g.id),Te(null)}catch(Ce){a(Me(Ce)||"Failed to delete feature","error")}},[a,_t,g,r]),un=i.useCallback(async()=>{if(!Se||!Ye.trim()){a("Task ID is required","error");return}try{await Lj(Se,Ye.trim(),r),a("Feature linked to task","success"),await _t(g.id),He(null),Oe("")}catch(V){a(Me(V)||"Failed to link feature to task","error")}},[Se,Ye,a,_t,g,r]),on=i.useCallback(async V=>{try{await zj(V,r),a("Feature unlinked from task","success"),await _t(g.id)}catch(Ce){a(Me(Ce)||"Failed to unlink feature","error")}},[a,_t,g,r]),fn=i.useCallback(async V=>{try{$(!0),await Oj(V,void 0,void 0,r),a("Feature triaged — task created","success"),await _t(g.id)}catch(Ce){a(Me(Ce)||"Failed to triage feature","error")}finally{$(!1)}},[a,_t,g,r]),Ln=i.useCallback(async V=>{ye(V);try{const Ce=await pN(V,r);Xe({featureId:V,enrichedDescription:Ce.description})}catch{await fn(V)}finally{ye(null)}},[fn,r]),Zn=i.useCallback(async()=>{Ue&&(Xe(null),await fn(Ue.featureId))},[fn,Ue]),qn=i.useCallback(()=>{Xe(null)},[]),es=i.useCallback(async V=>{try{$(!0);const Ce=await Fj(V,r);a(`Triaged ${Ce.count} feature${Ce.count!==1?"s":""}`,"success"),await _t(g.id)}catch(Ce){a(Me(Ce)||"Failed to triage slice features","error")}finally{$(!1)}},[a,_t,g,r]),Un=i.useCallback(async V=>{try{const Ce=await ql(V,r);Le(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch{}},[r]),En=i.useCallback(async V=>{try{const Ce=await Vl(V,r);Jt(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch{}},[r]),fs=i.useCallback(async V=>{if(!mt.title.trim()||!mt.assertion.trim()){a("Title and assertion text are required","error");return}try{$(!0),await Uj(V,{title:mt.title.trim(),assertion:mt.assertion.trim(),status:mt.status},r),a("Assertion created","success"),await Un(V),await En(V),st(!1),Ie({title:"",assertion:"",status:"pending"})}catch(Ce){a(Me(Ce)||"Failed to create assertion","error")}finally{$(!1)}},[mt,a,Un,En,r]),Jn=i.useCallback(V=>{nt(V.id),Ie({title:V.title,assertion:V.assertion,status:V.status})},[]),Bn=i.useCallback(()=>{nt(null),st(!1),Ie({title:"",assertion:"",status:"pending"})},[]),gs=i.useCallback(async(V,Ce)=>{if(!mt.title.trim()||!mt.assertion.trim()){a("Title and assertion text are required","error");return}try{$(!0),await Bj(V,{title:mt.title.trim(),assertion:mt.assertion.trim(),status:mt.status},r),a("Assertion updated","success"),await Un(Ce),await En(Ce),Bn()}catch(Ke){a(Me(Ke)||"Failed to update assertion","error")}finally{$(!1)}},[mt,a,Un,En,Bn,r]),Vn=i.useCallback(async V=>{try{const Ce=await Vj(V,r);Et(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch{}},[r]),bs=i.useCallback(async V=>{const Ce=yt!==V;Re(Ke=>Ke===V?null:V),Ce&&await Vn(V)},[yt,Vn]),Yn=i.useCallback(V=>{Re(V),Vn(V),requestAnimationFrame(()=>{const Ce=document.querySelector(`[data-mission-assertion-id="${V}"]`);Ce instanceof HTMLElement&&typeof Ce.scrollIntoView=="function"&&Ce.scrollIntoView({behavior:"smooth",block:"center"})})},[Vn]),Es=i.useCallback(async(V,Ce)=>{try{Rt(Ke=>new Set(Ke).add(Ce)),await Hj(V,Ce,r),a("Feature linked to assertion","success"),await Vn(Ce),Ut(null)}catch(Ke){a(Me(Ke)||"Failed to link feature","error")}finally{Rt(Ke=>{const At=new Set(Ke);return At.delete(Ce),At})}},[a,Vn,r]),Ws=i.useCallback(async(V,Ce)=>{const Ke=`${V}-${Ce}`;try{Tt(At=>new Set(At).add(Ke)),await qj(V,Ce,r),a("Feature unlinked from assertion","success"),await Vn(Ce)}catch(At){a(Me(At)||"Failed to unlink feature","error")}finally{Tt(At=>{const bn=new Set(At);return bn.delete(Ke),bn})}},[a,Vn,r]),ua=i.useCallback(async V=>{try{Qt(Ke=>new Set(Ke).add(V)),await Wj(V,r),a("Validation triggered","success");const Ce=await zu(V,r);Fe(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch(Ce){a(Me(Ce)||"Failed to trigger validation","error")}finally{Qt(Ce=>{const Ke=new Set(Ce);return Ke.delete(V),Ke})}},[a,r]),wi=i.useCallback(async V=>{try{const Ce=await zu(V,r);Fe(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch{}},[r]),Ks=i.useCallback(async V=>{try{const Ce=await Kj(V,{limit:10},r);W(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch{}},[r]),Ri=i.useCallback(V=>{const Ce=ut.current;if(Ce){for(const Ke of Ce.milestones)for(const At of Ke.slices)if(At.features.find(Gt=>Gt.id===V)){E(Gt=>{const hn=new Set(Gt);return hn.add(Ke.id),hn}),I(Gt=>{const hn=new Set(Gt);return hn.add(At.id),hn}),Pe(V),Yt(Ke.id),wi(V),Ks(V),requestAnimationFrame(()=>{const Gt=document.querySelector(`[data-mission-feature-id="${V}"]`);Gt instanceof HTMLElement&&typeof Gt.scrollIntoView=="function"&&Gt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[wi,Ks]),no=i.useCallback(async V=>{try{const Ce=await Gj(V,r);it(Ke=>{const At=new Map(Ke);return At.set(V,Ce),At})}catch{}},[r]),$l=i.useCallback(async V=>{ae===V?Pe(null):(Pe(V),await wi(V),await Ks(V))},[ae,wi,Ks]),so=i.useCallback(async V=>{je===V?ce(null):(ce(V),await no(V))},[je,no]),Ga=i.useCallback(async V=>{try{await Jj(V,r),a("Mission resumed","success"),await _t(V),nn()}catch(Ce){a(Me(Ce)||"Failed to resume mission","error")}},[a,_t,nn,r]),Ja=i.useCallback(async V=>{try{const Ke=(await Yj(V,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ke} task${Ke!==1?"s":""} paused)`,"success"),await _t(V),nn()}catch(Ce){a(Me(Ce)||"Failed to stop mission","error")}},[a,_t,nn,r]),io=i.useCallback(async V=>{try{await Qj(V,r),a("Mission started — first slice activated","success"),await _t(V),nn()}catch(Ce){a(Me(Ce)||"Failed to start mission","error")}},[a,_t,nn,r]),Dl=i.useCallback(async(V,Ce)=>{try{await Xj(V,{enabled:Ce},r),a(Ce?"Autopilot enabled":"Autopilot disabled","success"),await _t(V),nn()}catch(Ke){a(Me(Ke)||"Failed to update autopilot","error")}},[a,_t,nn,r]),Ya=i.useCallback(V=>{Lt("structure"),Yt(null),qt(null),yn([]),Sn(0),Hn("all"),jn(new Set),_t(V.id)},[_t]),xs=i.useCallback(()=>{b(null),Yt(null),qt(null),Lt("structure"),yn([]),Sn(0),Hn("all"),jn(new Set),nn()},[nn]),Ui=zt.length<Zt,ss=g?.autopilotState??"inactive",Qa=ss==="watching"||ss==="activating",Xa=gR(ss,g?.lastAutopilotActivityAt),Bi=i.useMemo(()=>!Kt||!Vt||!Rc(Kt)?null:Kt.rollup.milestoneId===Vt?Kt:null,[Vt,Kt]),ma=i.useMemo(()=>{const V=new Map;for(const Ce of Bi?.validationTelemetry.validationRounds??[]){const Ke=V.get(Ce.featureId);(!Ke||Ce.startedAt>Ke.startedAt)&&V.set(Ce.featureId,Ce)}return V},[Bi]),Ll=i.useCallback(()=>{!g||he||!Ui||Ve(g.id,{append:!0})},[he,Ui,Ve,g]),ao=i.useCallback(V=>{jn(Ce=>{const Ke=new Set(Ce);return Ke.has(V)?Ke.delete(V):Ke.add(V),Ke})},[]),J=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),$t())},[$t]),Ge=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),ps())},[ps]),xt=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),ot())},[ot]),Ht=i.useCallback(V=>{V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),ft())},[ft]),is=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const V=Ce=>{Ce.key==="Escape"&&s()};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[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:[Qa&&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:(dr[g.status]||dr.planning).bg,color:(dr[g.status]||dr.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:V=>Dl(g.id,V.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(Kn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Ao[ss]||Ao.inactive).bg,color:(Ao[ss]||Ao.inactive).text},"data-testid":"autopilot-state-badge",children:[Qa&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),ss]})]}),Xa&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Xa})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ja(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(zs,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ga(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(On,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>io(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(On,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Nt(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(vs,{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(vn,{size:14})})]})]}),A===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:V=>_({...T,title:V.target.value}),onKeyDown:J,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:V=>_({...T,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:V=>_({...T,status:V.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:V=>_({...T,autopilotEnabled:V.target.checked})}),t.jsx(Kn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:$t,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${Pt==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Lt("structure"),role:"tab","aria-selected":Pt==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${Pt==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Lt("activity"),role:"tab","aria-selected":Pt==="activity","data-testid":"mission-tab-activity",children:["Activity (",Zt,")"]})]}),Pt==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(V=>{const Ce=Bi?.rollup.milestoneId===V.id?Bi:null,Ke=Ce?.rollup??Ft.get(V.id),At=Ce?.validationTelemetry.validationRounds??[],bn=Ce?.fixFeatures??[],Gt=$h[Ke?.state??"not_started"]??$h.not_started,hn=Ke&&(Ke.state==="blocked"||Ke.state==="failed")?Ce?.validationTelemetry.validationRounds.find(tt=>tt.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>dn(V.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:O.has(V.id)?t.jsx(rn,{size:16}):t.jsx(_n,{size:16})}),t.jsx(ea,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:V.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Th[V.status].bg,color:Th[V.status].text},children:V.status}),t.jsxs("span",{className:"mission-milestone__count",children:[V.slices.length," slices"]}),t.jsx(Dh,{state:cR(V.interviewState)}),Ke&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Gt.bg,color:Gt.text},title:"Validation state",children:Lh(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)"}})})]}),V.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ge({type:"milestone",id:V.id,title:V.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Li,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:tt=>tt.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>yi(V.id),title:"Add slice",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Cs(V),title:"Edit milestone",children:t.jsx(vs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"milestone",id:V.id}),title:"Delete milestone",children:t.jsx(vn,{size:14})})]})]}),O.has(V.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(z||F===V.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:X.title,onChange:tt=>M({...X,title:tt.target.value}),onKeyDown:Ge,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:tt=>M({...X,description:tt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ps,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),F?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$s,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}`:""]})]}),hn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",hn]}),At.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:()=>Xt(tt=>!tt),title:Bt?"Hide validation rounds":"Show validation rounds",children:[Bt?t.jsx(rn,{size:12}):t.jsx(_n,{size:12}),"Validation rounds (",At.length,")"]}),Bt&&t.jsx("div",{className:"mission-validation-rounds__list",children:At.map(tt=>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--${tt.validatorStatus}`,children:tt.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:tt.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",tt.implementationAttempt," · reviewer #",tt.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),tt.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:tt.failedAssertionIds.map(et=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Yn(et),title:`Jump to assertion ${et}`,children:et},`${tt.roundId}-${et}`))}):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:"}),tt.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:tt.generatedFixFeatureIds.map(et=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ri(et),title:`Jump to fix feature ${et}`,children:et},`${tt.roundId}-${et}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),tt.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:tt.blockedReason})]},tt.roundId))})]}),bn.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:bn.map(tt=>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:()=>Ri(tt.id),title:`Jump to feature ${tt.id}`,children:tt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_o[tt.status].bg,color:_o[tt.status].text},children:tt.status}),tt.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${tt.loopState}`,children:tt.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:()=>Ri(tt.sourceFeatureId),title:`Jump to source feature ${tt.sourceFeatureId}`,children:tt.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:tt.runId})]}),tt.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:tt.failedAssertionIds.map(et=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Yn(et),title:`Jump to assertion ${et}`,children:et},`${tt.id}-${et}`))})]})]},tt.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[V.slices.map(tt=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Y(tt.id),children:[t.jsx("button",{className:"mission-slice__expand",children:S.has(tt.id)?t.jsx(rn,{size:16}):t.jsx(_n,{size:16})}),t.jsx(nd,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:tt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ih[tt.status].bg,color:Ih[tt.status].text},children:tt.status}),t.jsxs("span",{className:"mission-slice__count",children:[tt.features?.length||0," features"]}),t.jsx(Dh,{state:tt.planState??"not_started"}),tt.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ge({type:"slice",id:tt.id,title:tt.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Li,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:et=>et.stopPropagation(),children:[tt.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Dn(tt.id),title:"Activate slice",children:t.jsx(On,{size:14})}),tt.status==="active"&&tt.features?.some(et=>et.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>es(tt.id),title:"Triage all features",disabled:C,children:C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Kn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ee(tt.id),title:"Add feature",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>me(tt),title:"Edit slice",children:t.jsx(vs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"slice",id:tt.id}),title:"Delete slice",children:t.jsx(vn,{size:14})})]})]}),S.has(tt.id)&&t.jsxs("div",{className:"mission-slice__body",children:[pe&&ve===V.id&&!j&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Q.title,onChange:et=>de({...Q,title:et.target.value}),onKeyDown:xt,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Q.description,onChange:et=>de({...Q,description:et.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ot,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:We,children:"Cancel"})]})]}),j===tt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Q.title,onChange:et=>de({...Q,title:et.target.value}),onKeyDown:xt,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Q.description,onChange:et=>de({...Q,description:et.target.value}),rows:2}),t.jsxs("select",{value:Q.status,onChange:et=>de({...Q,status:et.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:ot,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:We,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[tt.features?.map(et=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":et.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>$l(et.id),title:ae===et.id?"Collapse details":"Expand to show run history",children:ae===et.id?t.jsx(rn,{size:14}):t.jsx(_n,{size:14})}),t.jsx(Gc,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:et.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:_o[et.status].bg,color:_o[et.status].text},children:et.status}),et.loopState&&et.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${et.loopState}`,title:`Loop state: ${et.loopState}`,children:[et.loopState==="implementing"&&"⏳",et.loopState==="validating"&&"🔄",et.loopState==="needs_fix"&&"🔧",et.loopState==="passed"&&"✅",et.loopState==="blocked"&&"🚫"]}),et.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ri(et.generatedFromFeatureId),title:`Generated from feature: ${et.generatedFromFeatureId}`,children:"🔗 Fix"}),(et.loopState==="validating"||et.loopState==="needs_fix")&&(()=>{const Ct=fe.get(et.id),Nn=ma.get(et.id),ci=Ct?.implementationAttemptCount??Nn?.implementationAttempt??et.implementationAttemptCount??0,Hi=Ct?.retryBudgetRemaining??Math.max(0,lR-ci);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ci," · ",Hi," ",Hi===1?"retry":"retries"," left"]})})(),et.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>ua(et.id),title:"Validate feature",disabled:an.has(et.id),children:an.has(et.id)?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(ms,{size:14})}),et.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(et.taskId),title:"Click to view task",children:et.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[et.status==="defined"&&!et.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ln(et.id),title:"Triage — create task",disabled:C||wt===et.id,children:wt===et.id?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Kn,{size:14})}),et.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>on(et.id),title:"Unlink task",children:t.jsx(fu,{size:14})}):et.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>He(et.id),title:"Link to task",children:t.jsx(Ea,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>rt(et),title:"Edit feature",children:t.jsx(vs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"feature",id:et.id}),title:"Delete feature",children:t.jsx(vn,{size:14})})]})]}),et.description&&t.jsx("p",{className:"mission-feature__description",children:et.description}),et.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",et.acceptanceCriteria]}),Ue?.featureId===et.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:Ue.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:Zn,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:qn,disabled:C,children:"Cancel"})]})]}),se===et.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ie.title,onChange:Ct=>te({...ie,title:Ct.target.value}),onKeyDown:Ht,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ie.description,onChange:Ct=>te({...ie,description:Ct.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ie.acceptanceCriteria,onChange:Ct=>te({...ie,acceptanceCriteria:Ct.target.value}),rows:2}),t.jsxs("select",{value:ie.status,onChange:Ct=>te({...ie,status:Ct.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:ft,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Be,children:"Cancel"})]})]}),ae===et.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"})}),(Ae.get(et.id)??[]).map(Ct=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>so(Ct.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Ct.status}`,title:Ct.status,children:Ct.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Ct.startedAt).toLocaleString()}),Ct.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Ct.completedAt).getTime()-new Date(Ct.startedAt).getTime())/1e3),"s"]}),Ct.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Ct.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:je===Ct.id?"Hide details":"Show details",children:je===Ct.id?t.jsx(rn,{size:12}):t.jsx(_n,{size:12})})]}),je===Ct.id&&$e.get(Ct.id)&&t.jsxs("div",{className:"mission-run__details",children:[Ct.summary&&t.jsx("p",{className:"mission-run__summary",children:Ct.summary}),Ct.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Ct.blockedReason]}),$e.get(Ct.id)?.failures&&$e.get(Ct.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),$e.get(Ct.id).failures.map(Nn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Nn.message}),Nn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Nn.expected]}),Nn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Nn.actual]})]},Nn.id))]}),(!$e.get(Ct.id)?.failures||$e.get(Ct.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Ct.id)),(!Ae.get(et.id)||Ae.get(et.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},et.id)),xe&&_e===tt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ie.title,onChange:et=>te({...ie,title:et.target.value}),onKeyDown:Ht,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ie.description,onChange:et=>te({...ie,description:et.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ie.acceptanceCriteria,onChange:et=>te({...ie,acceptanceCriteria:et.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ft,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Be,children:"Cancel"})]})]}),!xe&&(!tt.features||tt.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Gc,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},tt.id)),V.slices.length===0&&!pe&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(nd,{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:Gt.bg,color:Gt.text},children:Lh(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:()=>{st(!0),nt(null),Ie({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(xn,{size:14})})]}),ze&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:mt.title,onChange:tt=>Ie({...mt,title:tt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:mt.assertion,onChange:tt=>Ie({...mt,assertion:tt.target.value}),rows:2}),t.jsxs("select",{value:mt.status,onChange:tt=>Ie({...mt,status:tt.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:()=>fs(V.id),disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Bn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(be.get(V.id))?be.get(V.id):[]).map(tt=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":tt.id,children:[t.jsx("div",{className:"mission-assertion__header",children:Je===tt.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:mt.title,onChange:et=>Ie({...mt,title:et.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:mt.assertion,onChange:et=>Ie({...mt,assertion:et.target.value}),rows:2}),t.jsxs("select",{value:mt.status,onChange:et=>Ie({...mt,status:et.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>gs(tt.id,V.id),disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Bn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Po[tt.status]??Po.pending).bg,color:(Po[tt.status]??Po.pending).text},children:tt.status}),t.jsx("span",{className:"mission-assertion__title",children:tt.title}),(()=>{const Ct=kt.get(tt.id)?.length??0;return Ct>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Ct} linked feature${Ct!==1?"s":""}`,children:["(",Ct," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>bs(tt.id),title:"Toggle details",children:yt===tt.id?t.jsx(rn,{size:14}):t.jsx(_n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(tt),title:"Edit assertion",children:t.jsx(vs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Te({type:"assertion",id:tt.id}),title:"Delete assertion",children:t.jsx(vn,{size:14})})]})}),yt===tt.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:tt.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()=>{yt!==tt.id&&await bs(tt.id),Ut(It===tt.id?null:tt.id)},title:"Link a feature",children:[t.jsx(Ea,{size:12}),"Link Feature"]})]}),It===tt.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const et=new Set((kt.get(tt.id)??[]).map(Nn=>Nn.id)),Ct=[];return g?.milestones.forEach(Nn=>Nn.slices.forEach(ci=>Ct.push(...ci.features.filter(Hi=>!et.has(Hi.id))))),Ct.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Ct.map(Nn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Es(Nn.id,tt.id),disabled:jt.has(tt.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Nn.title}),jt.has(tt.id)&&t.jsx(bt,{size:12,className:"spinner"})]},Nn.id))})()})}),(()=>{const et=kt.get(tt.id)??[];return et.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):et.map(Ct=>{const Nn=`${Ct.id}-${tt.id}`,ci=Dt.has(Nn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Ct.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ws(Ct.id,tt.id),disabled:ci,title:"Unlink feature",children:ci?t.jsx(bt,{size:12,className:"spinner"}):t.jsx(fu,{size:12})})]},Ct.id)})})()]})]})]},tt.id)),(!be.get(V.id)||be.get(V.id)?.length===0)&&!ze&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},V.id)}),g&&!z&&F===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ls,children:[t.jsx(xn,{size:16}),"Add Milestone"]}),z&&F===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:X.title,onChange:V=>M({...X,title:V.target.value}),onKeyDown:Ge,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:X.description,onChange:V=>M({...X,description:V.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ps,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$s,children:"Cancel"})]})]}),g.milestones.length===0&&!z&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ea,{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:In,onChange:V=>Hn(V.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:[zt.length," of ",Zt]})]}),!he&&Ui&&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:Ll,"data-testid":"mission-activity-load-more",children:"Load more"})}),he?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(bt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):zt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Fs,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Pn,className:"mission-events","data-testid":"mission-activity-events",children:[zt.map(V=>{const Ce=!!(V.metadata&&Object.keys(V.metadata).length>0),Ke=Xn.has(V.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${pR(V.eventType)}`,children:fR(V.eventType)}),t.jsx("span",{className:"mission-event__time",children:ll(V.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:V.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(V.timestamp).toLocaleString()}),Ce&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>ao(V.id),"data-testid":`mission-event-metadata-${V.id}`,children:[Ke?"Hide":"Show"," metadata"]}),Ke&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(V.metadata,null,2)})]})]},V.id)}),t.jsx("div",{ref:rs})]})]})]}):null,zl=()=>f.map(V=>{const Ce=V,Ke=g?.id===Ce.id,At=dr[Ce.status]||{bg:"",text:""},bn=Ce.summary,Gt=vt.get(Ce.id),hn=uR(Gt),tt=!!(bn&&(bn.totalMilestones>0||bn.totalFeatures>0)),et=Gt?.totalTasks??0,Ct=Gt?.tasksCompleted??0,Nn=Gt?.tasksFailed??0,ci=Gt?.estimatedCompletionPercent??bn?.progressPercent??0,Hi=tt||et>0||Nn>0||!!Gt?.lastActivityAt,cs=Ce.status==="active"&&(Gt?.currentMilestoneId||Gt?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${Ke?"mission-list__item--selected":""}`,onClick:()=>Ya(V),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ks,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ce.title}),V.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(Kn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${hn}`,"data-testid":`mission-health-badge-${Ce.id}`,"aria-label":`Mission health: ${hn}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:At.bg,color:At.text},children:Ce.status})]}),Ce.description&&t.jsx("p",{className:"mission-list__item-description",children:Ce.description}),cs&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",cs]}),Hi&&t.jsxs("div",{className:"mission-list__item-summary",children:[tt&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[bn.completedMilestones,"/",bn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[bn.completedFeatures,"/",bn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ce.id}`,children:[Ct,"/",et," tasks"]}),Nn>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:zn=>{zn.stopPropagation(),Ya(V)},"data-testid":`mission-failed-${Ce.id}`,title:"View mission failures",children:[Nn," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ce.id}`,children:["Activity ",ll(Gt?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${hn}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${ci}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:zn=>zn.stopPropagation(),children:[Ce.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ja(Ce.id),title:"Stop mission",children:t.jsx(zs,{size:14})}),Ce.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ga(Ce.id),title:"Resume mission",children:t.jsx(On,{size:14})}),Ce.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>io(Ce.id),title:"Start mission",children:t.jsx(On,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Nt(V),title:"Edit mission",children:t.jsx(vs,{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(vn,{size:14})})]})]},Ce.id)}),Za=({hideBottomButtons:V=!1}={})=>t.jsxs("div",{className:"mission-list",children:[R&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Ce=>_({...T,title:Ce.target.value}),onKeyDown:J,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Ce=>_({...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:$t,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mt,children:"Cancel"})]})]}),zl(),A&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Ce=>_({...T,title:Ce.target.value}),onKeyDown:J,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Ce=>_({...T,description:Ce.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:Ce=>_({...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=>_({...T,autopilotEnabled:Ce.target.checked})}),t.jsx(Kn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:$t,disabled:C,children:[C?t.jsx(bt,{size:14,className:"spinner"}):t.jsx(Wn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Mt,children:"Cancel"})]})]}),f.length===0&&!R&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ks,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!R&&t.jsxs("div",{className:"mission-list__footer",children:[re.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Ts,{size:16}),t.jsx("span",{children:re.length===1?`Resume "${re[0].title}"?`:`${re.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:re.map(Ce=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{Z(Ce.id),De(!0),oe([])},children:[Ce.status==="error"?t.jsx(Qn,{size:14}):t.jsx(ms,{size:14}),Ce.status==="error"?"Retry":"Resume"]},Ce.id))})]}),!V&&t.jsxs("div",{className:"mission-list__footer-actions",children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>De(!0),children:[t.jsx(ms,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:ht,children:[t.jsx(xn,{size:16}),"New Mission"]})]})]})]}),ro=()=>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 wn(le.id):le.type==="milestone"?await Vs(le.id):le.type==="slice"?await sn(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"})]})]})}),oo=()=>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:Ye,onChange:V=>Oe(V.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(V=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Oe(V.id),children:[V.id,": ",V.title||"Untitled"]},V.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:un,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{He(null),Oe("")},children:"Cancel"})]})]})}),lo=t.jsxs("div",{ref:is,className:`mission-manager mission-manager--desktop-split${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:[N&&g&&t.jsx("button",{className:"mission-manager__back-btn",onClick:xs,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(hl,{size:18})}),t.jsx(ks,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",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(Wt,{size:18})})]}),N?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Ds():Za(),le&&ro(),Se&&oo()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("div",{className:"mission-manager__sidebar",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:()=>De(!0),title:"Plan with AI","aria-label":"Plan with AI",children:t.jsx(ms,{size:14})}),t.jsx("button",{className:"mission-add-btn mission-add-btn--sm",onClick:ht,title:"New Mission","aria-label":"New Mission",children:t.jsx(xn,{size:14})})]})]}),t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):Za({hideBottomButtons:!0})})]}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(bt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Ds():t.jsxs("div",{className:"mission-manager__detail-pane-empty",children:[t.jsx(ks,{size:24}),t.jsx("span",{children:"Select a mission to view details"})]}),le&&ro(),Se&&oo()]})]})]}),co=t.jsx(nR,{isOpen:ke,onClose:()=>De(!1),onMissionCreated:()=>{nn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:qe}),uo=Qe?t.jsx(aR,{isOpen:!0,onClose:()=>ge(null),onApplied:()=>{ge(null),g&&_t(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:[lo,co,uo]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:V=>V.target===V.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:lo}),co,uo]})}const Ro=2e3;function Oh({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,b]=i.useState(!1),[v,x]=i.useState(null),y=d.trim()!==""&&f.trim().length>0&&f.length<=Ro,k=i.useCallback(async()=>{if(!(!y||g)){b(!0),x(null);try{const R=m==="agent"?"user-to-agent":"system";await TN({toId:d.trim(),toType:m,content:f.trim(),type:R,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},a),r()}catch(R){const w=Me(R)||"Failed to send message";x(w),l?.(w,"error")}finally{b(!1)}}},[y,g,d,m,f,n,a,r,l]),N=i.useCallback(R=>{u(R),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Wt,{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:R=>N(R.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(R=>t.jsx("option",{value:R.id,children:R.name||R.id},R.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Mn,{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:R=>p(R.target.value),maxLength:Ro,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>Ro?"over-limit":"",children:[f.length,"/",Ro]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Ts,{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:k,disabled:!y||g,"data-testid":"message-composer-send",children:g?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Yi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function ya(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 xR(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 vR(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 Fh(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function yR(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 wR({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),[b,v]=i.useState([]),[x,y]=i.useState(!1),[k,N]=i.useState(null),[R,w]=i.useState(null),[A,P]=i.useState(null),[T,_]=i.useState("inbox"),[C,$]=i.useState(null),[O,E]=i.useState([]),S=i.useMemo(()=>new Map(O.map(ne=>[ne.id,ne.name??""])),[O]),I=i.useCallback((ne,_e)=>xR(ne,_e,S),[S]),G=la()==="mobile",X=!G,M=i.useCallback(async()=>{f(!0);try{const ne=await PN({limit:50},e);l(ne),m(ne.unreadCount),s?.(ne.unreadCount)}catch{}finally{f(!1)}},[e,s]),z=i.useCallback(async()=>{f(!0);try{const ne=await RN({limit:50},e);d(ne)}catch{}finally{f(!1)}},[e]),L=i.useCallback(async ne=>{f(!0);try{const _e=await zN(ne,e);$(_e)}catch{}finally{f(!1)}},[e]),j=i.useCallback(async()=>{try{const ne=await oa(void 0,e);E(ne)}catch{}},[e]),H=i.useCallback(async()=>{try{const ne=await hf(e);m(ne.unreadCount),s?.(ne.unreadCount)}catch{}},[e,s]);i.useEffect(()=>{a==="inbox"?M():a==="outbox"?z():a==="agents"&&j()},[a,M,z,j]),i.useEffect(()=>{A&&L(A)},[A,L]),i.useEffect(()=>{H()},[H]),i.useEffect(()=>{j()},[j]),i.useEffect(()=>{if(typeof EventSource>"u")return;const ne=e?`?projectId=${encodeURIComponent(e)}`:"",_e=()=>{H(),a==="inbox"?M():a==="outbox"&&z(),A&&L(A)};return li(`/api/events${ne}`,{events:{"message:sent":_e,"message:received":_e,"message:read":_e,"message:deleted":_e}})},[e,a,A,H,M,z,L]);const Q=i.useCallback(async ne=>{if(g(ne),!ne.read)try{const _e=await IN(ne.id,e);_e&&l(Se=>Se&&{...Se,messages:Se.messages.map(He=>He.id===_e.id?_e:He),unreadCount:Math.max(0,Se.unreadCount-1)});const Ne=Math.max(0,u-1);m(Ne),s?.(Ne)}catch{}try{const _e=await LN(ne.fromId,ne.fromType,e);v(_e)}catch{v([ne])}},[e,u,s]),de=i.useCallback(()=>{g(null),v([])},[]),pe=i.useCallback(async()=>{try{const ne=await $N(e);m(0),s?.(0),l(_e=>_e&&{..._e,messages:_e.messages.map(Ne=>({...Ne,read:!0})),unreadCount:0}),n?.(`Marked ${ne.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),B=i.useCallback(async ne=>{try{await DN(ne,e),g(null),v([]),a==="inbox"?M():a==="outbox"?z():A&&L(A),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,A,M,z,L,n]),ve=i.useCallback(ne=>{N({id:ne.fromId,type:ne.fromType}),w({messageId:ne.id,preview:Fh(ne.content,120)}),y(!0)},[]),U=i.useCallback(()=>{y(!1),N(null),w(null),n?.("Message sent","success"),a==="outbox"?z():a==="agents"&&A&&L(A),H()},[a,z,A,L,n,H]),se=i.useCallback(()=>{N(a==="agents"&&A?{id:A,type:"agent"}:null),w(null),y(!0)},[a,A]),ee=i.useCallback(()=>{y(!1),N(null),w(null)},[]),ie=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[G&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:de,"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:vR(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:ya(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ve(p),"data-testid":"mailbox-reply",children:[t.jsx(Ci,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>B(p.id),"data-testid":"mailbox-delete",children:[t.jsx(vn,{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(Mn,{size:14}):t.jsx(ha,{size:14}),I(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(Mn,{size:14}):t.jsx(ha,{size:14}),I(p.toId,p.toType)]})]})]}),b.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(ne=>{const _e=ne.metadata?.replyTo?.messageId,Ne=_e?b.find(Se=>Se.id===_e):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ne.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:I(ne.fromId,ne.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:ya(ne.createdAt)})]}),_e&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ne.id}`,children:["↪ Replying to ",Ne?Fh(Ne.content,60):`message ${_e}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ne.content})]},ne.id)})]}),b.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),te=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Tc,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(xr,{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:yR(o.messages).map(ne=>t.jsxs("div",{className:`mailbox-conversation-group ${ne.unreadCount>0?"unread":""}`,onClick:()=>Q(ne.latestMessage),"data-testid":`mailbox-conversation-${ne.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ne.fromType==="agent"?t.jsx(Mn,{size:16}):t.jsx(ha,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:I(ne.fromId,ne.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ya(ne.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ne.latestMessage.content.slice(0,80),ne.latestMessage.content.length>80?"…":""]})]}),ne.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${ne.key}`,children:ne.unreadCount>9?"9+":ne.unreadCount})]},ne.key))})]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Tc,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Yi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(ne=>t.jsxs("div",{className:"mailbox-item",onClick:()=>Q(ne),"data-testid":`mailbox-item-${ne.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ne.toType==="agent"?t.jsx(Mn,{size:16}):t.jsx(ha,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",I(ne.toId,ne.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ya(ne.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ne.content.slice(0,80),ne.content.length>80?"…":""]})]})]},ne.id))]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:O.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Mn,{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:A??"",onChange:ne=>{P(ne.target.value||null),_("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),O.map(ne=>t.jsx("option",{value:ne.id,children:ne.name||ne.id},ne.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:se,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ci,{size:14}),t.jsx("span",{children:"Compose"})]})]}),A&&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:()=>_("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(xr,{size:12}),t.jsx("span",{children:"Inbox"}),C&&C.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:C.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${T==="outbox"?"active":""}`,onClick:()=>_("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Yi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!A&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Mn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),A&&h&&!C&&t.jsx(Tc,{}),A&&C&&T==="inbox"&&C.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(xr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),A&&C&&T==="outbox"&&C.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Yi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),A&&C&&T==="inbox"&&C.inbox.map(ne=>t.jsxs("div",{className:`mailbox-item ${ne.read?"":"unread"}`,onClick:()=>Q(ne),"data-testid":`mailbox-item-${ne.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ne.fromType==="agent"?t.jsx(Mn,{size:16}):t.jsx(ha,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:I(ne.fromId,ne.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:ya(ne.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ne.content.slice(0,80),ne.content.length>80?"…":""]})]})]},ne.id)),A&&C&&T==="outbox"&&C.outbox.map(ne=>t.jsxs("div",{className:"mailbox-item",onClick:()=>Q(ne),"data-testid":`mailbox-item-${ne.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:ne.toType==="agent"?t.jsx(Mn,{size:16}):t.jsx(ha,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",I(ne.toId,ne.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:ya(ne.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[ne.content.slice(0,80),ne.content.length>80?"…":""]})]})]},ne.id))]})]})})]}),xe=()=>x?t.jsx(Oh,{recipient:k,replyContext:R,agents:O,projectId:e,onSend:U,onCancel:ee,addToast:n}):p?ie():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(ta,{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(ta,{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:se,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ci,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:pe,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(ex,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?M():a==="outbox"?z():A&&L(A)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Qn,{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(xr,{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(Yi,{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(Mn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:X?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:te()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:xe()})]}):t.jsxs(t.Fragment,{children:[ie(),x&&t.jsx(Oh,{recipient:k,replyContext:R,agents:O,projectId:e,onSend:U,onCancel:ee,addToast:n}),!p&&!x&&te()]})})]})}function Tc(){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 kR=640;function jR({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[b,v]=i.useState([]),[x,y]=i.useState(null),[k,N]=i.useState([]),[R,w]=i.useState(null),[A,P]=i.useState(null),[T,_]=i.useState(!1),[C,$]=i.useState([]),[O,E]=i.useState(!1),[S,I]=i.useState(""),F=i.useRef(!1),G=i.useRef(null);xi(G,e,"fusion:github-modal-size");const X=Ai(n),[M,z]=i.useState(!1),[L,j]=i.useState("list"),H=i.useRef(null),Q=new Set;for(const ge of a){const Ue=ge.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Ue&&Q.add(Ue[1]);const Xe=ge.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Xe&&Q.add(Xe[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),y(null),N([]),w(null),g("issues"),P(null),_(!1),$([]),E(!0),I(""),H.current=null,F.current=!0,Ow().then(ge=>{if(F.current)if($(ge),E(!1),ge.length===1){const Ue=ge[0];l(Ue.owner),d(Ue.repo),I(Ue.name)}else ge.length>1&&(l(""),d(""),I(""))}).catch(()=>{F.current&&E(!1)}),()=>{F.current=!1}},[e]);const de=i.useCallback(ge=>{if(I(ge),ge==="")l(""),d("");else{const Ue=C.find(Xe=>Xe.name===ge);Ue&&(l(Ue.owner),d(Ue.repo))}},[C]),pe=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),v([]),y(null);try{const ge=u.split(",").map(Xe=>Xe.trim()).filter(Boolean),Ue=await $w(o.trim(),c.trim(),30,ge.length>0?ge:void 0);v(Ue),Ue.length===0&&P("No open issues found")}catch(ge){P(Me(ge)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),B=i.useCallback(async()=>{if(!o.trim()||!c.trim()){P("Repository must be selected");return}f(!0),P(null),N([]),w(null);try{const ge=await Lw(o.trim(),c.trim(),30);N(ge),ge.length===0&&P("No open pull requests found")}catch(ge){P(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"?pe():B())},[o,c,u,p,e,h,T,pe,B]),i.useEffect(()=>{if(!e)return;const ge=Ue=>{Ue.key==="Escape"&&n()};return document.addEventListener("keydown",ge),()=>document.removeEventListener("keydown",ge)},[e,n]),i.useEffect(()=>{if(!e)return;const ge=()=>{z(window.innerWidth<=kR)};return ge(),window.addEventListener("resize",ge),()=>window.removeEventListener("resize",ge)},[e]);const ve=i.useCallback(ge=>{y(ge),M&&j("preview")},[M]),U=i.useCallback(ge=>{w(ge),M&&j("preview")},[M]),se=i.useCallback(()=>{j("list")},[]),ee=i.useCallback(async()=>{if(p==="issues"){if(x===null)return;_(!0),P(null);try{const ge=await Dw(o.trim(),c.trim(),x,r);s(ge),y(null),M&&L==="preview"&&j("list")}catch(ge){const Ue=Me(ge);Ue?.includes("already imported")?P(Ue):P(Ue||"Failed to import issue")}finally{_(!1)}}else{if(R===null)return;_(!0),P(null);try{const ge=await zw(o.trim(),c.trim(),R,r);s(ge),w(null),M&&L==="preview"&&j("list")}catch(ge){const Ue=Me(ge);Ue?.includes("already imported")?P(Ue):P(Ue||"Failed to import pull request")}finally{_(!1)}}},[p,x,R,o,c,s,M,L]),ie=b.find(ge=>ge.number===x),te=k.find(ge=>ge.number===R);if(!e)return null;const xe=C.length>0,ne=C.length===1,_e=b.filter(ge=>Q.has(ge.html_url)).length,Ne=k.filter(ge=>Q.has(ge.html_url)).length,Se=A==="No open issues found",He=A==="No open pull requests found",Ye=p==="issues"?Se:He,Oe=!!A&&!Se&&b.length===0&&!h,ke=!!A&&!He&&k.length===0&&!h,De=p==="issues"?Oe:ke,re=h||b.length>0||Se||Oe,oe=h||k.length>0||He||ke,we=p==="issues"?re:oe,Z=!!A&&b.length>0&&!Se,qe=!!A&&k.length>0&&!He,Qe=p==="issues"?Z:qe;return t.jsx("div",{className:"modal-overlay open",...X,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:G,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"),w(null)},disabled:h||T,children:[t.jsx(pl,{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(Os,{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:O?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(bt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):xe?ne?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:C[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[C[0].owner,"/",C[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:S,onChange:ge=>de(ge.target.value),disabled:h||T,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),C.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"&&pe(),disabled:h||T||!xe,"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"?pe:B,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(bt,{size:14,className:"spin"}):t.jsx(Qn,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!O&&!xe&&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:A}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${M?"mobile":""} ${L==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&b.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[b.length," issue",b.length===1?"":"s"]}),t.jsxs("span",{children:[_e," imported"]})]}),p==="pulls"&&k.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[k.length," pull request",k.length===1?"":"s"]}),t.jsxs("span",{children:[Ne," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!we&&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(bt,{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."})]})]}),De&&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:A})]})}),Ye&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&b.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:b.map(ge=>{const Ue=Q.has(ge.html_url);return t.jsxs("div",{className:`issue-item ${x===ge.number?"selected":""} ${Ue?"imported":""}`,onClick:()=>!Ue&&ve(ge.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:x===ge.number,onChange:()=>ve(ge.number),disabled:Ue,"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(Xe=>t.jsx("span",{className:"label-chip",children:Xe.name},Xe.name))})]}),Ue&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ge.number)})}),p==="pulls"&&k.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:k.map(ge=>{const Ue=Q.has(ge.html_url);return t.jsxs("div",{className:`issue-item ${R===ge.number?"selected":""} ${Ue?"imported":""}`,onClick:()=>!Ue&&U(ge.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:R===ge.number,onChange:()=>U(ge.number),disabled:Ue,"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]})]}),Ue&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ge.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${M?"mobile":""} ${L==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[M&&t.jsxs("button",{className:"github-import-back-button",onClick:se,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ua,{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"&&ie?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",ie.number]}),t.jsx("div",{className:"preview-title",children:ie.title}),t.jsx("div",{className:"preview-body",children:ie.body?ie.body.slice(0,200)+(ie.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"&&te?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",te.number]}),t.jsx("div",{className:"preview-title",children:te.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",te.headBranch," → ",te.baseBranch]}),t.jsx("div",{className:"preview-body",children:te.body?te.body.slice(0,200)+(te.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:ee,disabled:(p==="issues"?x===null:R===null)||T,children:T?t.jsx(bt,{size:14,className:"spin"}):"Import"})]})]})})}function Qs({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(_n,{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 NR=["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 SR(e,n){return e&&n?`${e}/${n}`:""}function CR(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 ER({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,b]=i.useState([]),[v,x]=i.useState([]),[y,k]=i.useState(null),N=i.useRef(!1),R=i.useRef(!1),[w,A]=i.useState(""),[P,T]=i.useState(!0),[_,C]=i.useState(!1),[$,O]=i.useState(!1),[E,S]=i.useState(null),[I,F]=i.useState(0),G=i.useRef(null),X=i.useRef(null),M=i.useRef(null),z=i.useRef(null),L=i.useRef(null),j=i.useRef(null),H=i.useRef(null),[Q,de]=i.useState(c??null),pe=i.useMemo(()=>da(),[]),{isLockedByOther:B,takeControl:ve,isLoading:U}=Il(e?Q:null),{activeTabMap:se,broadcastUpdate:ee,broadcastCompleted:ie,broadcastLock:te,broadcastUnlock:xe,broadcastHeartbeat:ne}=Ka(),[_e,Ne]=i.useState(void 0),[Se,He]=i.useState(void 0),[Ye,Oe]=i.useState("medium"),[ke,De]=i.useState(""),[re,oe]=i.useState([]),[we,Z]=i.useState(!1),[qe,Qe]=i.useState(null),[ge,Ue]=i.useState([]),[Xe,wt]=i.useState([]),ye=i.useRef(null),[le,Te]=i.useState([]),[be,Le]=i.useState(!1),[Je,nt]=i.useState(c??null),[mt,Ie]=i.useState(!!c),[ze,st]=i.useState(null),[yt,Re]=i.useState(!1),kt=i.useRef(!1),Et=i.useRef(null),jt=i.useRef(null),Rt=i.useRef(null);xi(X,e,"fusion:planning-modal-size"),i.useEffect(()=>{const ue=Et.current;if(!ue)return;ue.scrollHeight-ue.scrollTop-ue.clientHeight<32&&(ue.scrollTop=ue.scrollHeight)},[w]),i.useEffect(()=>{if(m.type!=="loading"){S(null),F(0);return}const ue=Date.now();S(ue),F(0);const lt=setInterval(()=>{F(Math.max(0,Math.floor((Date.now()-ue)/1e3)))},1e3);return()=>clearInterval(lt)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const ue=z.current;if(!ue)return;let lt=!1;const dt=setInterval(async()=>{try{const at=await pi(ue);if(lt||!at||z.current!==ue)return;if(at.status==="awaiting_input"&&at.currentQuestion){const St=JSON.parse(at.currentQuestion);h({type:"question",session:{sessionId:ue,currentQuestion:St,summary:null}}),A("")}else if(at.status==="complete"&&at.result){const St=JSON.parse(at.result);h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:St},summary:St}),k(St),A("")}}catch{}},8e3);return()=>{lt=!0,clearInterval(dt)}},[m.type]);const Dt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),b([]),x([]),k(null),A(""),C(!1),O(!1),Ne(void 0),He(void 0),Oe("medium"),De(""),z.current=null,de(null)},[]),Tt=SR(_e,Se),It=i.useCallback((ue,lt)=>{if(!ue||!lt)return"Using default";const ut=re.find(dt=>dt.provider===ue&&dt.id===lt);return ut?`${ut.provider}/${ut.id}`:`${ue}/${lt}`},[re]),Ut=i.useCallback(async()=>{Z(!0),Qe(null);try{const ue=await As();oe(ue.models),Ue(ue.favoriteProviders),wt(ue.favoriteModels)}catch(ue){Qe(Me(ue)||"Failed to load models")}finally{Z(!1)}},[]),Ft=i.useCallback(ue=>{Ue(lt=>{const ut=lt,at=ut.includes(ue)?ut.filter(St=>St!==ue):[ue,...ut];return Cn({favoriteProviders:at,favoriteModels:Xe}).catch(()=>{Ue(ut)}),at})},[Xe]),Jt=i.useCallback(ue=>{wt(lt=>{const ut=lt,at=ut.includes(ue)?ut.filter(St=>St!==ue):[ue,...ut];return Cn({favoriteProviders:ge,favoriteModels:at}).catch(()=>{wt(ut)}),at})},[ge]),Vt=i.useCallback(ue=>{M.current?.close();const lt=()=>z.current!==ue,ut=Fk(ue,l,{onThinking:dt=>{lt()||(A(at=>at+dt),ee({sessionId:ue,status:"generating",needsInput:!1,owningTabId:pe,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:dt=>{lt()||(C(!1),O(!1),va(l),h({type:"question",session:{sessionId:ue,currentQuestion:dt,summary:null}}),A(""),ee({sessionId:ue,status:"awaiting_input",needsInput:!0,owningTabId:pe,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onSummary:dt=>{lt()||(C(!1),O(!1),va(l),h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:dt},summary:dt}),k(dt),A(""),ee({sessionId:ue,status:"complete",needsInput:!1,owningTabId:pe,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onError:dt=>{const at=dt||"Session failed while contacting the AI.";C(!0),(async()=>{try{const St=await pi(ue);if(St&&(St.status==="generating"||St.status==="awaiting_input")){Vt(ue);return}}catch{}C(!1),O(!1),p(null),h(St=>St.type==="question"||St.type==="summary"||St.type==="error"?{type:"error",session:St.session,errorMessage:at}:{type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:at}),A(""),z.current=ue,ee({sessionId:ue,status:"error",needsInput:!1,owningTabId:pe,type:"planning",title:d.trim()||void 0,projectId:l??null}),ie({sessionId:ue,status:"error"})})()},onComplete:()=>{C(!1),O(!1),z.current=null,ie({sessionId:ue,status:"complete"})},onConnectionStateChange:dt=>{C(dt==="reconnecting")}});M.current=ut},[ie,ee,d,l,pe]),Yt=i.useCallback(async ue=>{const lt=ue??d;if(lt.trim()){p(null),A(""),x([]),b([]),C(!1),h({type:"loading"});try{const ut=_e&&Se?{planningModelProvider:_e,planningModelId:Se}:void 0,dt=ke.trim()?Number.parseInt(ke,10):void 0,at=L.current,{sessionId:St}=await kk(lt.trim(),l,ut,{planningDepth:Ye,customQuestionCount:Number.isInteger(dt)?dt:void 0},at??void 0);L.current=null,z.current=St,de(St),nt(St),Vt(St),b([])}catch(ut){C(!1),p(Me(ut)||"Failed to start planning session"),h({type:"initial"}),z.current=null,de(null)}}},[Vt,ke,d,Ye,Se,_e,l]);i.useEffect(()=>{e&&m.type==="initial"&&G.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&Ut()},[e,Ut]),i.useEffect(()=>{if(e&&o&&!N.current&&m.type==="initial"){u(o);const ue=setTimeout(()=>{N.current=!0,Yt(o)},0);return()=>clearTimeout(ue)}else if(e&&!o&&!N.current&&!R.current&&m.type==="initial"){R.current=!0;const ue=OP(l);ue&&u(ue)}},[e,o,m.type,Yt,l]);const Kt=i.useCallback(async ue=>{M.current?.close(),M.current=null,p(null),A(""),b([]),x([]),k(null),O(!1),h({type:"loading"});try{const lt=await pi(ue);if(!lt){nt(null),Ie(!1),h({type:"initial"});return}z.current=ue,de(ue);const ut=Ra(lt.conversationHistory);if(x(ut),b(ut.map(dt=>dt.response).filter(dt=>!!(dt&&typeof dt=="object"&&!Array.isArray(dt)))),lt.status==="draft"){let dt="",at,St;try{const he=lt.inputPayload?JSON.parse(lt.inputPayload):null;he&&typeof he.initialPlan=="string"&&(dt=he.initialPlan),he&&typeof he.modelProvider=="string"&&typeof he.modelId=="string"&&(at=he.modelProvider,St=he.modelId)}catch{}u(dt),Ne(at),He(St),L.current=ue,Rt.current=dt?{sessionId:ue,initialPlan:dt.trim(),modelProvider:at,modelId:St}:null,h({type:"initial"})}else if(lt.status==="awaiting_input"&&lt.currentQuestion){va(l);const dt=JSON.parse(lt.currentQuestion);h({type:"question",session:{sessionId:ue,currentQuestion:dt,summary:null}}),lt.thinkingOutput&&A(lt.thinkingOutput),Vt(ue)}else if(lt.status==="complete"&&lt.result){va(l);const dt=JSON.parse(lt.result);h({type:"summary",session:{sessionId:ue,currentQuestion:null,summary:dt},summary:dt}),k(dt)}else lt.status==="generating"?(h({type:"loading"}),lt.thinkingOutput&&A(lt.thinkingOutput),Vt(ue)):lt.status==="error"&&h({type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:lt.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Vt,l]);i.useEffect(()=>{!e||!c||z.current!==c&&H.current!==c&&(nt(c),Ie(!0),Kt(c))},[e,c]),i.useEffect(()=>{e&&Je&&(c&&c===Je||Kt(Je))},[e]);const qt=i.useCallback(async()=>{Le(!0);try{const lt=(await zd(l,{includeCompleted:!0,includeArchived:yt})).filter(ut=>ut.type==="planning").sort((ut,dt)=>Date.parse(dt.updatedAt)-Date.parse(ut.updatedAt));Te(lt)}catch{}finally{Le(!1)}},[l,yt]);i.useEffect(()=>{e&&qt()},[e,qt]),i.useEffect(()=>{if(!e)return;const ue=l?`?projectId=${encodeURIComponent(l)}`:"",lt=dt=>{try{const at=JSON.parse(dt.data);if(at.type!=="planning")return;Te(St=>{const he=St.findIndex(Zt=>Zt.id===at.id);return(he>=0?[...St.slice(0,he),at,...St.slice(he+1)]:[at,...St]).sort((Zt,Sn)=>Date.parse(Sn.updatedAt)-Date.parse(Zt.updatedAt))})}catch{}},ut=dt=>{try{const at=JSON.parse(dt.data);Te(St=>St.filter(he=>he.id!==at))}catch{}};return li(`/api/events${ue}`,{events:{"ai_session:updated":lt,"ai_session:deleted":ut},onReconnect:()=>{qt()}})},[e,l,qt]);const Bt=i.useCallback(ue=>{if(Je===ue){Ie(!0);return}nt(ue),Ie(!0),Kt(ue)},[Kt,Je]),Xt=i.useCallback(()=>{M.current?.close(),M.current=null,L.current=null,j.current&&(clearTimeout(j.current),j.current=null),c&&(H.current=c),Dt(),nt(null),Ie(!0)},[Dt,c]),an=i.useCallback(()=>{Ie(!1)},[]),Qt=i.useCallback(async(ue,lt)=>{const ut=lt.trim();if(!(!ut||Rt.current?.sessionId===ue&&Rt.current.initialPlan===ut&&Rt.current.modelProvider===_e&&Rt.current.modelId===Se))try{await _N(ue,{initialPlan:ut,modelProvider:_e&&Se?_e:void 0,modelId:_e&&Se?Se:void 0},l),Rt.current={sessionId:ue,initialPlan:ut,modelProvider:_e,modelId:Se}}catch{}},[Se,_e,l]);i.useEffect(()=>{if(jt.current&&(clearTimeout(jt.current),jt.current=null),!(!e||m.type!=="initial"||!Je))return jt.current=setTimeout(()=>{Qt(Je,d)},500),()=>{jt.current&&(clearTimeout(jt.current),jt.current=null)}},[d,e,Je,Qt,m.type]),i.useEffect(()=>{Rt.current=null},[Je]),i.useEffect(()=>()=>{jt.current&&(clearTimeout(jt.current),jt.current=null)},[]);const fe=i.useCallback(async ue=>{const lt=dt=>dt==="generating"||dt==="awaiting_input",ut=le.find(dt=>dt.id===ue);if(ut&&lt(ut.status))try{await sf(ue,l,pe)}catch{}try{await mf(ue)}catch{}ie({sessionId:ue,status:"complete",timestamp:Date.now()}),Te(dt=>dt.filter(at=>at.id!==ue)),Je===ue&&(M.current?.close(),M.current=null,Dt(),nt(null),Ie(!1)),st(null)},[ie,le,l,Dt,Je,pe]),Fe=i.useCallback(async ue=>{const ut=le.find(dt=>dt.id===ue)?.archived===!0;try{ut?await NN(ue):await jN(ue)}catch{return}Te(dt=>!ut&&!yt?dt.filter(at=>at.id!==ue):dt.map(at=>at.id===ue?{...at,archived:!ut}:at)),!ut&&Je===ue&&!yt&&(M.current?.close(),M.current=null,Dt(),nt(null),Ie(!1))},[le,Dt,Je,Ie,yt]);i.useEffect(()=>{e||(N.current=!1,R.current=!1,C(!1),O(!1),de(null))},[e]),i.useEffect(()=>{if(!e){ye.current&&(xe(ye.current,pe),ye.current=null);return}if(Q&&ye.current!==Q){ye.current&&xe(ye.current,pe),te(Q,pe),ye.current=Q;return}!Q&&ye.current&&(xe(ye.current,pe),ye.current=null)},[te,xe,e,Q,pe]),i.useEffect(()=>{if(!e||!Q||ye.current!==Q)return;ne(pe);const ue=setInterval(()=>{ne(pe)},3e4);return()=>{clearInterval(ue)}},[ne,e,Q,pe]),i.useEffect(()=>()=>{j.current&&(clearTimeout(j.current),j.current=null),M.current?.close(),M.current=null,ye.current&&(xe(ye.current,pe),ye.current=null)},[xe,pe]),i.useEffect(()=>{if(!e)return;const ue=()=>{M.current?.close(),M.current=null};return window.addEventListener("beforeunload",ue),()=>window.removeEventListener("beforeunload",ue)},[e]);const ae=i.useCallback((ue,lt)=>{jt.current&&(clearTimeout(jt.current),jt.current=null),(async()=>{try{await Qt(ue,lt),await AN(ue,l)}catch{}})()},[l,Qt]),Pe=i.useCallback(()=>{d&&m.type==="initial"&&zP(d,l);const ue=L.current;ue&&d.trim()&&ae(ue,d),L.current=null,j.current&&(clearTimeout(j.current),j.current=null),M.current?.close(),M.current=null,C(!1),O(!1),n()},[ae,d,n,l,m.type]);i.useEffect(()=>{if(!e)return;const ue=lt=>{lt.key==="Escape"&&Pe()};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[e,Pe]);const Ae=i.useCallback(async ue=>{if(m.type!=="question")return;const{session:lt}=m,ut=lt.sessionId,dt=lt.currentQuestion;if(!dt){p("No active question in session");return}p(null),b(at=>[...at,ue]),x(at=>[...at,{question:dt,response:ue}]),h({type:"loading"}),A("");try{await jk(ut,ue,l,pe)}catch(at){p(Me(at)||"Failed to submit response"),h({type:"question",session:lt})}},[l,pe,m]),W=i.useCallback(async()=>{const ue=z.current;if(ue){try{await Sk(ue,l,pe)}catch{}M.current?.close(),M.current=null,C(!1),O(!1),h({type:"error",session:{sessionId:ue,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),A("")}},[l,pe]),je=i.useCallback(async()=>{if(m.type!=="error")return;const ue=m.session;p(null),O(!0),A(""),h({type:"loading"}),Vt(ue.sessionId);try{z.current=ue.sessionId,de(ue.sessionId),await Nk(ue.sessionId,l,pe)}catch(lt){let ut=lt;if((Me(lt)||"").includes("not in an error state"))try{const at=await pi(ue.sessionId);if(!at)throw new Error("Failed to refresh planning session.");if(z.current=at.id,de(at.id),at.status==="generating")A(at.thinkingOutput??""),h({type:"loading"});else if(at.status==="awaiting_input"){if(!at.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const St=JSON.parse(at.currentQuestion);va(l),h({type:"question",session:{sessionId:at.id,currentQuestion:St,summary:null}}),M.current?.isConnected()||Vt(at.id)}else if(at.status==="complete"){if(!at.result)throw new Error("Planning session is complete but has no result.");const St=JSON.parse(at.result);va(l),h({type:"summary",session:{sessionId:at.id,currentQuestion:null,summary:St},summary:St}),k(St)}else at.status==="error"&&h({type:"error",session:{sessionId:at.id,currentQuestion:null,summary:null},errorMessage:at.error||"Retry failed. Please try again."});C(!1);return}catch(at){ut=at}M.current?.close(),M.current=null,h({type:"error",session:ue,errorMessage:Me(ut)||"Retry failed. Please try again."}),C(!1)}finally{O(!1)}},[Vt,l,pe,m]),ce=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ue=m.session.sessionId,lt=await Ck(ue,y??void 0,l);s(lt),nt(null),Te(ut=>ut.filter(dt=>dt.id!==ue)),ie({sessionId:ue,status:"complete",timestamp:Date.now()}),Pe()}catch(ue){p(Me(ue)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[ie,y,m,l,s,Pe]),$e=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const ue=await Ek(m.session.sessionId,y??void 0,l);de(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]),it=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const ue=m.sessionId,lt=await Mk(ue,m.subtasks,l);a(lt.tasks),Te(ut=>ut.filter(dt=>dt.id!==ue)),ie({sessionId:ue,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),b([]),x([]),k(null),A(""),Ne(void 0),He(void 0),Oe("medium"),De(""),z.current=null,de(null),nt(null),n()}catch(ue){p(Me(ue)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[ie,m,a,n,l]),vt=i.useCallback(()=>{if(m.type==="question"&&g.length>0){const ue=g.slice(0,-1);b(ue),h({type:"question",session:m.session})}},[m,g]),tn=()=>m.type==="question"?Math.min(g.length+1,3):3,Pt=Q?se.get(Q):null,Lt=Pt&&Pt.tabId!==pe,zt=!!(Lt&&!Pt.stale),yn=B&&(!Lt||Pt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:ue=>{kt.current=ue.target===ue.currentTarget},onClick:ue=>{ue.target===ue.currentTarget&&kt.current&&Pe(),kt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:X,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[mt&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:an,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(hl,{size:18})}),t.jsx(oi,{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:Pe,"aria-label":"Close",children:t.jsx(Wt,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${mt?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(RR,{sessions:le,loading:be,selectedSessionId:Je,pendingDeleteId:ze,showArchived:yt,onToggleShowArchived:()=>Re(ue=>!ue),onArchive:ue=>void Fe(ue),onSelectSession:Bt,onNewSession:Xt,onRequestDelete:st,onConfirmDelete:ue=>void fe(ue),onCancelDelete:()=>st(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),_&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),zt&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),m.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(ms,{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:G,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 lt=ue.target.value;u(lt),!(L.current||lt.trim().length===0)&&(j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{if(L.current)return;const ut=lt.trim();if(!ut)return;wk(ut,l,_e&&Se?{planningModelProvider:_e,planningModelId:Se}:void 0).then(at=>{L.current=at.sessionId,Te(St=>St.some(ct=>ct.id===at.sessionId)?St:[{id:at.sessionId,type:"planning",status:"draft",title:at.title,preview:ut.length>80?`${ut.slice(0,79).trimEnd()}…`:ut,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...St].sort((ct,Zt)=>Date.parse(Zt.updatedAt)-Date.parse(ct.updatedAt))),nt(at.sessionId)}).catch(()=>{})},300))},onKeyDown:ue=>{ue.key==="Enter"&&!ue.shiftKey&&d.trim()&&(ue.preventDefault(),Yt())},onBlur:()=>{const ue=L.current;ue&&d.trim()&&ae(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:NR.map((ue,lt)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(ue),children:ue.length>40?ue.slice(0,40)+"...":ue},lt))})]}),t.jsxs(Qs,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",defaultOpen:!0,children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Choose the planning model and tune plan depth to control how detailed the AI interview should be."}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",we&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(hs,{id:"planning-modal-model",label:"Planning Model",value:Tt,onChange:ue=>{const{provider:lt,modelId:ut}=CR(ue);Ne(lt),He(ut)},models:re,disabled:we,favoriteProviders:ge,onToggleFavorite:Ft,favoriteModels:Xe,onToggleModelFavorite:Jt}),qe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[qe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{Ut()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${_e&&Se?"model-badge-custom":"model-badge-default"}`,children:It(_e,Se)})})]}),t.jsxs("div",{className:"planning-depth-selector",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 ${Ye===ue.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Oe(ue.value),"aria-pressed":Ye===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:ke,onChange:ue=>De(ue.target.value),placeholder:"Auto"})]})]})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Yt(),disabled:!d.trim(),children:[t.jsx(oi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),E&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",I,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>T(!P),type:"button",children:P?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void W(),children:[t.jsx(hx,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),P&&w&&t.jsx("div",{className:"planning-thinking-output",ref:Et,children:t.jsx("pre",{children:w})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Zs,{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 je(),disabled:$,children:[$?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Qn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:$?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Pe,disabled:$,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(bt,{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(MR,{question:m.session.currentQuestion,progress:tn(),historyEntries:v,onSubmit:Ae,onBack:g.length>0?vt:void 0})}),m.type==="summary"&&y&&t.jsx(_R,{summary:y,historyEntries:v,onSummaryChange:k,tasks:r,onCreateTask:ce,onBreakIntoTasks:$e,onRefine:()=>{h({type:"question",session:m.session})},isLoading:!1}),m.type==="breakdown"&&t.jsx(PR,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:ue=>h({...m,subtasks:ue,dirty:!0}),onCreateTasks:it,onBack:()=>{const lt={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:lt,summary:y})}})]}),B&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(vl,{size:16}),t.jsx("span",{children:yn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),yn&&t.jsx("button",{type:"button",onClick:()=>{ve()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function MR({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(Zs,{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:b=>{const v=b.target.checked?[...g,p.id]:g.filter(x=>x!==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(Tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(Wt,{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(Ua,{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(Hr,{size:16,className:"icon-ml-4"})]})]})]})}function _R({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(b=>b!==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(Qs,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(Zs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>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(Ua,{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(bt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Tn,{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(bt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(xl,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Uh(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 AR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function PR({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(A=>!A.title.trim())?!0:Uh(e),[e]),g=i.useCallback((A,P)=>{a(e.map(T=>T.id===A?{...T,...P}:T))},[e,a]),b=i.useCallback(()=>{a([...e,AR(e.length+1)])},[e,a]),v=i.useCallback(A=>{a(e.filter(P=>P.id!==A).map(P=>({...P,dependsOn:P.dependsOn.filter(T=>T!==A)})))},[e,a]),x=i.useCallback((A,P)=>{if(P<0||P>=e.length)return;const T=[...e],[_]=T.splice(A,1);T.splice(P,0,_),a(T)},[e,a]),y=i.useCallback(A=>P=>{c(A),P.dataTransfer.setData("text/plain",A),P.dataTransfer.effectAllowed="move"},[]),k=i.useCallback(()=>{c(null),u(null),h(null)},[]),N=i.useCallback(A=>P=>{if(P.preventDefault(),A===l)return;const T=P.currentTarget.getBoundingClientRect(),_=T.top+T.height/2,C=P.clientY<_?"before":"after";u(A),h(C)},[l]),R=i.useCallback(A=>P=>{P.preventDefault();const T=P.dataTransfer.getData("text/plain");if(!T||T===A){k();return}const _=e.findIndex(S=>S.id===T),C=e.findIndex(S=>S.id===A);if(_===-1||C===-1){k();return}const $=[...e],[O]=$.splice(_,1);let E=C;m==="after"&&_<C&&E--,m==="after"&&E++,$.splice(E,0,O),a($),k()},[e,m,a,k]),w=i.useCallback(A=>{const P=A.currentTarget.getBoundingClientRect(),T=A.clientX,_=A.clientY;(T<P.left||T>P.right||_<P.top||_>P.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(xl,{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((A,P)=>{const T=l===A.id,_=d===A.id,C=["task-detail-section","subtask-item",T?"subtask-item-dragging":"",_?"subtask-item-drop-target":"",_&&m==="before"?"subtask-item-drop-before":"",_&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:C,"data-testid":`subtask-item-${P}`,draggable:!s,onDragStart:y(A.id),onDragEnd:k,onDragOver:N(A.id),onDrop:R(A.id),onDragLeave:w,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(bl,{size:16}),t.jsx("strong",{children:A.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(P,P-1),disabled:s||P===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Qi,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>x(P,P+1),disabled:s||P===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Br,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(A.id),disabled:s,children:[t.jsx(vn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:$=>{f.current[P]=$},value:A.title,onChange:$=>g(A.id,{title:$.target.value}),onKeyDown:$=>{$.key==="Enter"&&($.preventDefault(),P<e.length-1&&f.current[P+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:A.description,onChange:$=>g(A.id,{description:$.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:A.suggestedSize,onChange:$=>g(A.id,{suggestedSize:$.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,P).filter($=>$.id!==A.id).map($=>{const O=A.dependsOn.includes($.id);return t.jsxs("label",{className:`planning-dep-chip ${O?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:O,onChange:()=>{const E=O?A.dependsOn.filter(S=>S!==$.id):[...A.dependsOn,$.id];g(A.id,{dependsOn:E})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:$.id}),t.jsx("span",{className:"planning-dep-title",children:$.title||"Untitled"})]},$.id)}),P===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),P>0&&e.slice(0,P).filter($=>$.id!==A.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},A.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:b,disabled:s,children:[t.jsx(xn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Uh(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(Ua,{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(bt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function RR({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(_v,{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,b=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${b?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(TR,{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(IR,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:$R(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:x=>{x.stopPropagation(),l(f.id)},"aria-label":b?"Unarchive session":"Archive session",title:b?"Unarchive session":"Archive session",children:b?t.jsx(Fb,{size:14}):t.jsx(Ur,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:x=>{x.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(vn,{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 TR({status:e}){switch(e){case"generating":return t.jsx(bt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(Jc,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Tn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Ts,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Mi,{size:14,className:"planning-sidebar-status-icon"})}}function IR({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 $R(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 DR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Bh(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 LR({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const[c,d]=i.useState({type:"initial"}),[u,m]=i.useState([]),[h,f]=i.useState([]),[p,g]=i.useState(""),[b,v]=i.useState(!0),[x,y]=i.useState(!1),[k,N]=i.useState(!1),[R,w]=i.useState(s),[A,P]=i.useState(null),[T,_]=i.useState(!1),[C,$]=i.useState(null),[O,E]=i.useState(null),[S,I]=i.useState(null),F=i.useRef(null),G=i.useRef([]),X=i.useRef(!1),M=i.useRef(null),z=c.type==="generating"||c.type==="editing"||c.type==="creating"||c.type==="error"?c.sessionId:null,L=i.useMemo(()=>da(),[]),{isLockedByOther:j,takeControl:H,isLoading:Q}=Il(e?z:null),{activeTabMap:de,broadcastUpdate:pe,broadcastCompleted:B,broadcastLock:ve,broadcastUnlock:U,broadcastHeartbeat:se}=Ka(),ee=i.useMemo(()=>u.length===0||u.some(le=>!le.title.trim())?!0:Bh(u),[u]),ie=c.type==="generating"||c.type==="editing"||c.type==="error",te=z?de.get(z):null,{confirm:xe}=qs(),ne=te&&te.tabId!==L,_e=!!(ne&&!te.stale),Ne=j&&(!ne||te.stale),Se=i.useCallback(()=>{R&&FP(R,o),F.current?.close(),F.current=null,d({type:"initial"}),m([]),f([]),g(""),v(!0),y(!1),N(!1),P(null),_(!1),X.current=!1},[R,o]),He=i.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),Ye=i.useCallback(async()=>{if(!((T||c.type==="editing"||c.type==="creating")&&!await xe({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(z)try{await of(z,o,L)}catch{}Se(),n()}},[T,n,Se,z,L,c.type,o,xe]),Oe=i.useCallback(le=>{F.current?.close(),F.current=nj(le,o,{onThinking:Te=>{g(be=>be+Te),pe({sessionId:le,status:"generating",needsInput:!1,owningTabId:L,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onSubtasks:Te=>{y(!1),N(!1),Ec(o),m(Te),d({type:"editing",sessionId:le}),_(!1),pe({sessionId:le,status:"awaiting_input",needsInput:!0,owningTabId:L,type:"subtask",title:R.trim()||void 0,projectId:o??null})},onError:Te=>{const be=Te||"Session failed while contacting the AI.";y(!1),N(!1),P(null),d({type:"error",sessionId:le,errorMessage:be}),pe({sessionId:le,status:"error",needsInput:!1,owningTabId:L,type:"subtask",title:R.trim()||void 0,projectId:o??null}),B({sessionId:le,status:"error"})},onComplete:()=>{B({sessionId:le,status:"complete"})},onConnectionStateChange:Te=>{y(Te==="reconnecting")}})},[B,pe,R,o,L]),ke=i.useCallback(async()=>{if(R.trim()){P(null),f([]),g(""),y(!1);try{const{sessionId:le}=await Zk(R.trim(),o);d({type:"generating",sessionId:le}),Oe(le)}catch(le){P(Me(le)||"Failed to start subtask breakdown"),d({type:"initial"})}}},[Oe,R,o]);i.useEffect(()=>{if(!e){Se();return}if(e&&s&&!X.current)w(s),X.current=!0,ke();else if(e&&!s&&!X.current){const le=UP(o);le&&w(le)}},[e,s,ke,Se]),i.useEffect(()=>{!e||!l||c.type!=="initial"||(async()=>{try{const le=await pi(l);if(!le)return;const Te=Ra(le.conversationHistory);if(f(Te),le.status==="generating"||le.status==="awaiting_input")g(le.thinkingOutput??""),d({type:"generating",sessionId:l}),Oe(l);else if(le.status==="complete"&&le.result){Ec(o);const be=JSON.parse(le.result);m(be),d({type:"editing",sessionId:l})}else le.status==="error"&&(P(null),d({type:"error",sessionId:l,errorMessage:le.error??"Session encountered an error"}))}catch(le){P(Me(le)||"Failed to resume session")}})()},[Oe,e,l,c.type,o]),i.useEffect(()=>{if(!e){M.current&&(U(M.current,L),M.current=null);return}if(z&&M.current!==z){M.current&&U(M.current,L),ve(z,L),M.current=z;return}!z&&M.current&&(U(M.current,L),M.current=null)},[ve,U,e,z,L]),i.useEffect(()=>{if(!e||!z||M.current!==z)return;se(L);const le=setInterval(()=>{se(L)},3e4);return()=>{clearInterval(le)}},[se,e,z,L]),i.useEffect(()=>()=>{F.current?.close(),M.current&&(U(M.current,L),M.current=null)},[U,L]),i.useEffect(()=>{if(!e)return;const le=Te=>{Te.key==="Escape"&&(Te.preventDefault(),Ye())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[e,Ye]);const De=i.useCallback((le,Te)=>{m(be=>be.map(Le=>Le.id===le?{...Le,...Te}:Le)),_(!0)},[]),re=i.useCallback(()=>{m(le=>[...le,DR(le.length+1)]),_(!0)},[]),oe=i.useCallback(le=>{m(Te=>Te.filter(be=>be.id!==le).map(be=>({...be,dependsOn:be.dependsOn.filter(Le=>Le!==le)}))),_(!0)},[]),we=i.useCallback(le=>Te=>{$(le),Te.dataTransfer.setData("text/plain",le),Te.dataTransfer.effectAllowed="move"},[]),Z=i.useCallback(()=>{$(null),E(null),I(null)},[]),qe=i.useCallback(le=>Te=>{if(Te.preventDefault(),le===C)return;const be=Te.currentTarget.getBoundingClientRect(),Le=be.top+be.height/2,Je=Te.clientY<Le?"before":"after";E(le),I(Je)},[C]),Qe=i.useCallback(le=>Te=>{Te.preventDefault();const be=Te.dataTransfer.getData("text/plain");if(!be||be===le){$(null),E(null),I(null);return}m(Le=>{const Je=Le.findIndex(st=>st.id===be),nt=Le.findIndex(st=>st.id===le);if(Je===-1||nt===-1)return Le;const mt=[...Le],[Ie]=mt.splice(Je,1);let ze=nt;return S==="after"&&Je<nt&&ze--,S==="after"&&ze++,mt.splice(ze,0,Ie),mt}),_(!0),$(null),E(null),I(null)},[S]),ge=i.useCallback(le=>{const Te=le.currentTarget.getBoundingClientRect(),be=le.clientX,Le=le.clientY;(be<Te.left||be>Te.right||Le<Te.top||Le>Te.bottom)&&(E(null),I(null))},[]),Ue=i.useCallback((le,Te)=>{Te<0||Te>=u.length||(m(be=>{const Le=[...be],[Je]=Le.splice(le,1);return Le.splice(Te,0,Je),Le}),_(!0))},[u.length]),Xe=i.useCallback(le=>{G.current[le+1]?.focus()},[]),wt=i.useCallback(async()=>{if(!(!z||ee)){P(null),d({type:"creating",sessionId:z});try{const le=await sj(z,u,r,o);a(le.tasks),Se(),n()}catch(le){P(Me(le)||"Failed to create tasks"),d({type:"editing",sessionId:z})}}},[ee,n,a,r,o,Se,z,u]),ye=i.useCallback(async()=>{if(c.type!=="error")return;const le=c.sessionId;P(null),N(!0),g(""),d({type:"generating",sessionId:le}),Oe(le);try{await ej(le,o,L)}catch(Te){let be=Te;if((Me(Te)||"").includes("not in an error state"))try{const Je=await pi(le);if(!Je)throw new Error("Failed to refresh subtask session.");if(f(Ra(Je.conversationHistory)),Je.status==="generating"||Je.status==="awaiting_input")g(Je.thinkingOutput??""),d({type:"generating",sessionId:Je.id}),F.current?.isConnected()||Oe(Je.id);else if(Je.status==="complete"){if(!Je.result)throw new Error("Subtask session is complete but has no result.");Ec(o);const nt=JSON.parse(Je.result);m(nt),d({type:"editing",sessionId:Je.id}),_(!1)}else Je.status==="error"&&d({type:"error",sessionId:Je.id,errorMessage:Je.error??"Retry failed. Please try again."});y(!1);return}catch(Je){be=Je}F.current?.close(),F.current=null,d({type:"error",sessionId:le,errorMessage:Me(be)||"Retry failed. Please try again."}),y(!1)}finally{N(!1)}},[Oe,o,L,c]);return e?t.jsx("div",{className:"modal-overlay open",onClick:le=>le.target===le.currentTarget&&void Ye(),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(xl,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ie&&t.jsx("button",{className:"modal-send-to-background",onClick:He,title:"Send to background","aria-label":"Send to background",children:t.jsx(Wr,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ye(),"aria-label":"Close",children:t.jsx(Wt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[A&&t.jsx("div",{className:"form-error planning-error",children:A}),x&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),_e&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),c.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:R})]})}),c.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Zs,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(bt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>v(!b),type:"button",children:b?"Hide thinking":"Show thinking"}),b&&p&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:p})})]})]}),c.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[h.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Zs,{entries:h,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:c.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ye(),disabled:k,children:[k?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Qn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:k?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ye(),disabled:k,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(Zs,{entries:h}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[u.map((le,Te)=>{const be=C===le.id,Le=O===le.id,Je=["task-detail-section","subtask-item",be?"subtask-item-dragging":"",Le?"subtask-item-drop-target":"",Le&&S==="before"?"subtask-item-drop-before":"",Le&&S==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Je,"data-testid":`subtask-item-${Te}`,draggable:c.type!=="creating",onDragStart:we(le.id),onDragEnd:Z,onDragOver:qe(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(bl,{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:()=>Ue(Te,Te-1),disabled:c.type==="creating"||Te===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Qi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ue(Te,Te+1),disabled:c.type==="creating"||Te===u.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Br,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>oe(le.id),disabled:c.type==="creating",children:[t.jsx(vn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:nt=>{G.current[Te]=nt},value:le.title,onChange:nt=>De(le.id,{title:nt.target.value}),onKeyDown:nt=>{nt.key==="Enter"&&(nt.preventDefault(),Xe(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:nt=>De(le.id,{description:nt.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:nt=>De(le.id,{suggestedSize:nt.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(nt=>nt.id!==le.id).map(nt=>{const mt=le.dependsOn.includes(nt.id);return t.jsxs("label",{className:`planning-dep-chip ${mt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:mt,onChange:()=>{const Ie=mt?le.dependsOn.filter(ze=>ze!==nt.id):[...le.dependsOn,nt.id];De(le.id,{dependsOn:Ie})},disabled:c.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:nt.id}),t.jsx("span",{className:"planning-dep-title",children:nt.title||"Untitled"})]},nt.id)}),Te===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),Te>0&&u.slice(0,Te).filter(nt=>nt.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:re,disabled:c.type==="creating",children:[t.jsx(xn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Bh(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 Ye(),disabled:c.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void wt(),disabled:c.type==="creating"||ee,children:c.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),j&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(vl,{size:16}),t.jsx("span",{children:Ne?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ne&&t.jsx("button",{type:"button",onClick:()=>{H()},disabled:Q,className:"btn btn-primary session-lock-take-control",children:Q?"Taking control...":"Take Control"})]})})]})]})}):null}const zR=5,OR=1e3,FR=45e3;function To(){return{scrollback:null,connected:null,data:[]}}function UR(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),b=i.useRef(new Set),v=i.useRef(new Set),x=i.useRef(new Set),y=i.useRef(To()),k=i.useCallback(E=>{p.current.add(E);const S=y.current;return S.data.length>0&&(S.data.forEach(I=>E(I)),S.data=[]),()=>p.current.delete(E)},[]),N=i.useCallback(E=>(g.current.add(E),()=>g.current.delete(E)),[]),R=i.useCallback(E=>{b.current.add(E);const S=y.current;return S.connected&&(E(S.connected),S.connected=null),()=>b.current.delete(E)},[]),w=i.useCallback(E=>{v.current.add(E);const S=y.current;return S.scrollback&&(E(S.scrollback),S.scrollback=null),()=>v.current.delete(E)},[]),A=i.useCallback(E=>(x.current.add(E),()=>x.current.delete(E)),[]),P=i.useCallback(E=>{const S=d.current;S?.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"input",data:E}))},[]),T=i.useCallback((E,S)=>{const I=d.current;I?.readyState===WebSocket.OPEN&&I.send(JSON.stringify({type:"resize",cols:E,rows:S}))},[]),_=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=To()},[]),C=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=To()},[]),$=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 E=r.current;let I=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(I+=`&projectId=${encodeURIComponent(n)}`);const F=new WebSocket(fi(I));d.current=F,F.onopen=()=>{if(r.current!==E){F.close();return}y.current=To(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===E&&F.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"ping"}))},FR)},F.onmessage=G=>{if(r.current===E)try{const X=JSON.parse(G.data),M=y.current;switch(X.type){case"data":X.data&&(p.current.size===0&&M.data.push(X.data),p.current.forEach(z=>z(X.data)));break;case"scrollback":X.data&&(M.scrollback=X.data,v.current.forEach(z=>z(X.data)));break;case"connected":X.shell&&X.cwd&&(M.connected={shell:X.shell,cwd:X.cwd},b.current.forEach(z=>z({shell:X.shell,cwd:X.cwd})));break;case"exit":X.exitCode!==void 0&&g.current.forEach(z=>z(X.exitCode));break;case"ping":F.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},F.onclose=G=>{if(r.current!==E)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(G.code===4e3||G.code===4004){a("disconnected"),G.code===4004&&x.current.forEach(z=>z());return}if(u.current++,u.current>zR){a("disconnected");return}const X=OR*Math.pow(2,u.current-1);a("reconnecting");const M=r.current;m.current=setTimeout(()=>{r.current===M&&(f.current||$())},Math.min(X,16e3))},F.onerror=()=>{}},[e,n]),O=i.useCallback(()=>{u.current=0,C(),$()},[C,$]);return i.useEffect(()=>(c&&(_(),u.current=0,a("disconnected")),e?$():a("disconnected"),C),[e,n,c,$,C,_]),{connectionStatus:s,sendInput:P,resize:T,onData:k,onExit:N,onConnect:R,onScrollback:w,reconnect:O,onSessionInvalid:A}}const Qg="kb-terminal-tabs",BR=15e3,HR=15e3;function Hh(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function qh(e){if(typeof window>"u")return[];try{const n=Gn(Qg,e);if(n)return JSON.parse(n)}catch{}return[]}function Ic(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Vh(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 qR(e){const[n,s]=i.useState(()=>qh(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(qh(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{us(Qg,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let R=!1;const w=h.current;return(async()=>{if(!R)try{const P=await Vh(Gw(e),BR,"listTerminalSessions");if(R||w!==h.current)return;const T=new Set(P.map(_=>_.id));l(!0),s(_=>{if(R||w!==h.current)return _;const $=_.map(S=>({...S,_verified:T.has(S.sessionId)})).filter(S=>S._verified);if($.length===0)return[];const O=$.map(({_verified:S,...I})=>I);return O.find(S=>S.isActive)?O:O.map((S,I)=>({...S,isActive:I===0}))}),r(!0)}catch(P){if(R||w!==h.current)return;const T=Ic(P);T||console.warn("Failed to validate terminal sessions with server:",P),l(!T),r(!0)}})(),()=>{R=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const R=h.current,w=setTimeout(()=>{Vh(ho(void 0,void 0,void 0,e),HR,"createTerminalSession").then(A=>{if(R!==h.current)return;const P={id:Hh(),sessionId:A.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(T=>T.length>0?T:[...T.map(C=>({...C,isActive:!1})),P]),d(null)}).catch(A=>{if(R!==h.current)return;Ic(A)||console.error(A);const P=A instanceof Error?A.message:typeof A=="string"?A:"Failed to create terminal session";d(P)})},0);return()=>clearTimeout(w)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const R=await ho(void 0,void 0,void 0,e),w={id:Hh(),sessionId:R.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(A=>[...A.map(T=>({...T,isActive:!1})),w]),w},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(R=>{s(w=>{const A=w.find(C=>C.id===R);if(!A)return w;ju(A.sessionId,e).catch(C=>{console.warn(`Failed to kill terminal session ${A.sessionId}:`,C)});const P=w.findIndex(C=>C.id===R),T=A.isActive,_=w.filter(C=>C.id!==R);if(_.length===0)return[];if(T){const C=Math.min(P,_.length-1);return _.map(($,O)=>({...$,isActive:O===C}))}return _})},[]),b=i.useCallback(R=>{s(w=>{let A=!1;const P=w.map(T=>T.id===R?(A=!0,{...T,isActive:!0}):{...T,isActive:!1});return A?P:w})},[]),v=i.useCallback((R,w)=>{s(A=>A.map(P=>P.id===R?{...P,title:w}:P))},[]),x=i.useCallback(async()=>{s(A=>{const P=A.find(T=>T.isActive);return P&&ju(P.sessionId,e).catch(T=>{console.warn(`Failed to kill old session ${P.sessionId}:`,T)}),A});const R=n.find(A=>A.isActive);if(!R)return;const w=await ho(void 0,void 0,void 0,e);s(A=>A.map(P=>P.id===R.id?{...P,sessionId:w.sessionId}:P))},[n]),y=i.useCallback(async()=>{const R=n.find(w=>w.isActive);if(R)try{const w=await ho(void 0,void 0,void 0,e);s(A=>A.map(P=>P.id===R.id?{...P,sessionId:w.sessionId}:P)),d(null)}catch(w){Ic(w)||console.error(w);const A=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";d(A)}},[n]),k=n.find(R=>R.isActive)??null,N=i.useCallback(()=>{d(null),h.current+=1,m(R=>R+1)},[]);return{tabs:n,activeTab:k,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:b,updateTabTitle:v,restartActiveTab:x,retryBootstrap:N,replaceActiveTabSession:y}}const VR=1e4,WR=[500,1500,3e3],Xg="kb-terminal-font-size",kr=14,KR=8,GR=32,JR='"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 YR(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 QR(e){return`\x1B${e}`}const XR=[{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 jr(e){return Math.min(GR,Math.max(KR,e))}function ZR(){if(typeof window>"u")return kr;try{const e=window.localStorage.getItem(Xg);if(!e)return kr;const n=Number.parseInt(e,10);return Number.isFinite(n)?jr(n):kr}catch{return kr}}function eT(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 tT(e){return new Promise(n=>setTimeout(n,e))}async function nT(e,n=WR){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!eT(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 tT(o)}throw s??new Error("Dynamic import failed")}function Wh(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function sT(){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=iT()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let $c=null;function iT(){return $c===null&&($c=window.innerHeight),$c}function aT({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,b]=i.useState(0),[v,x]=i.useState(null),[y,k]=i.useState(()=>ZR()),[N,R]=i.useState(!1),[w,A]=i.useState(null),P=i.useRef(null),T=i.useRef(null),_=i.useRef(!1);xi(T,e,"fusion:terminal-modal-size");const C=i.useRef(null),$=i.useRef(null),O=i.useRef(!1),E=i.useRef(!1),S=i.useRef(null),I=i.useRef(()=>{}),F=i.useRef(null),G=i.useRef(0),X=i.useRef(y),M=i.useRef(null),z=i.useRef(a);G.current=g,X.current=y;const L=i.useCallback(be=>{if(be&&E.current!==be)return;const Le=$.current,Je=C.current,nt=S.current;if(!(!Le||!Je)&&!(be&&E.current!==be))try{Le.fit(),nt&&nt(Je.cols,Je.rows)}catch{}},[]);i.useEffect(()=>{e&&p(be=>be+1)},[e]),i.useEffect(()=>{if(!e||!Wh())return;const be=window.visualViewport;if(!be)return;const Le=()=>{const Je=sT();b(Je),x(be.height),Je>0&&T.current?.scrollIntoView&&T.current.scrollIntoView({block:"end",behavior:"smooth"}),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const nt=typeof E.current=="string"?E.current:void 0;M.current=requestAnimationFrame(()=>{M.current=null,L(nt)})};return Le(),be.addEventListener("resize",Le),be.addEventListener("scroll",Le),()=>{be.removeEventListener("resize",Le),be.removeEventListener("scroll",Le),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),b(0),x(null)}},[L,e]),i.useEffect(()=>{if(!e)return;const be=T.current;if(!be||typeof ResizeObserver>"u")return;let Le=null;const Je=new ResizeObserver(()=>{Le!==null&&cancelAnimationFrame(Le),Le=requestAnimationFrame(()=>{Le=null;const nt=typeof E.current=="string"?E.current:void 0;L(nt)})});return Je.observe(be),()=>{Je.disconnect(),Le!==null&&cancelAnimationFrame(Le)}},[L,e]);const{tabs:j,activeTab:H,isReady:Q,bootstrapError:de,createTab:pe,closeTab:B,setActiveTab:ve,updateTabTitle:U,restartActiveTab:se,retryBootstrap:ee,replaceActiveTabSession:ie}=qR(a),{connectionStatus:te,sendInput:xe,resize:ne,onData:_e,onConnect:Ne,onExit:Se,onScrollback:He,reconnect:Ye,onSessionInvalid:Oe}=UR(H?.sessionId??null,a);S.current=ne,I.current=xe,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Xg,String(y))}catch{}},[y]);const ke=i.useCallback(()=>{const be=C.current;if(be)try{$.current?.fit(),ne(be.cols,be.rows)}catch{}},[ne]);i.useEffect(()=>{if(!e||!Q)return;const be=H?.sessionId;if(!be)return;const Le=z.current!==a;if(Le&&(z.current=a),E.current===be&&C.current&&!Le)return;C.current&&(E.current!==be||Le)&&(C.current.dispose(),C.current=null,$.current=null,E.current=!1,F.current&&(window.removeEventListener("resize",F.current),F.current=null),u(!1),h(null));let Je=!0,nt;return(async()=>{const Ie=nT(()=>Promise.all([kn(()=>import("./vendor-xterm-DzcZoU0P.js").then(Re=>Re.x),__vite__mapDeps([4,1,5])),kn(()=>import("./addon-fit-C7jRorKK.js").then(Re=>Re.a),__vite__mapDeps([6,1])),kn(()=>import("./addon-web-links-CkJwd4cQ.js").then(Re=>Re.a),__vite__mapDeps([7,1]))])),ze=new Promise((Re,kt)=>{nt=setTimeout(()=>{kt(new Error("xterm initialization timed out"))},VR)});let st,yt;try{const[{Terminal:Re},{FitAddon:kt},{WebLinksAddon:Et}]=await Promise.race([Ie,ze]);if(!Je||!P.current||C.current)return;st=new Re({cursorBlink:!0,cursorStyle:"block",fontSize:X.current,fontFamily:JR,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}),yt=new kt,st.loadAddon(yt);const jt=new Et;if(st.loadAddon(jt),!Wh())try{const{WebglAddon:Tt}=await kn(async()=>{const{WebglAddon:Ut}=await import("./addon-webgl-BjvOw43o.js").then(Ft=>Ft.a);return{WebglAddon:Ut}},__vite__mapDeps([8,1])),It=new Tt;It.onContextLoss(()=>{It.dispose()}),st.loadAddon(It)}catch{}st.open(P.current),nt&&clearTimeout(nt);const Rt=P.current?.querySelector(".xterm-helper-textarea");if(Rt&&Rt.focus(),P.current)try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{yt.fit();const Tt=P.current?.querySelector(".xterm-helper-textarea");Tt&&Tt.focus()},50),C.current=st,$.current=yt,E.current=be,G.current>0&&(M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),M.current=requestAnimationFrame(()=>{M.current=null,L(be)})),st.onData(Tt=>{E.current===be&&I.current(Tt)});const Dt=()=>{if(E.current===be&&$.current&&C.current)try{$.current.fit();const{cols:Tt,rows:It}=C.current;S.current?.(Tt,It)}catch{}};window.addEventListener("resize",Dt),F.current&&window.removeEventListener("resize",F.current),F.current=Dt,u(!0),h(null)}catch(Re){if(nt&&clearTimeout(nt),!Je)return;const kt=Re instanceof Error?Re.message:"xterm initialization failed";h(kt)}})(),()=>{Je=!1,nt&&clearTimeout(nt)}},[L,e,Q,H?.sessionId,a]),i.useEffect(()=>{e||(C.current&&(C.current.dispose(),C.current=null),$.current=null,E.current=!1,F.current&&(window.removeEventListener("resize",F.current),F.current=null),u(!1),h(null),O.current=!1,o(null),c(null),R(!1),A(null))},[e]),i.useEffect(()=>{if(!d||!C.current||!H)return;const be=H.sessionId,Le=ze=>{E.current===be&&C.current?.write(ze)},Je=_e(ze=>{Le(ze)}),nt=He(ze=>{Le(ze)}),mt=Ne(ze=>{U(H.id,Ud(ze.shell)||ze.shell)}),Ie=Se(ze=>{E.current===be&&(c(ze),C.current?.write(`\r
679
- \x1B[33m[Process exited with code ${ze}]\x1B[0m\r
680
- `))});return()=>{Je(),nt(),mt(),Ie()}},[d,H?.sessionId,H?.id,H,te,_e,He,Ne,Se,U]),i.useEffect(()=>{te==="connected"&&s&&O.current!==s&&H&&(O.current=s,setTimeout(()=>{xe(s+`
681
- `)},500))},[te,s,xe,H,f]),i.useEffect(()=>{if(!d||!C.current)return;C.current.options.fontSize=y,M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const be=requestAnimationFrame(()=>{M.current=null,ke()});return M.current=be,()=>{M.current===be&&(cancelAnimationFrame(be),M.current=null)}},[y,d,ke]),i.useEffect(()=>{if(!e)return;const be=Le=>{if(!(!Le.ctrlKey&&!Le.metaKey)){if(Le.code==="Equal"||Le.code==="NumpadAdd"){Le.preventDefault(),k(Je=>jr(Je+1));return}if(Le.code==="Minus"||Le.code==="NumpadSubtract"){Le.preventDefault(),k(Je=>jr(Je-1));return}if(Le.code==="Digit0"||Le.code==="Numpad0"){Le.preventDefault(),k(kr);return}}};return window.addEventListener("keydown",be),()=>window.removeEventListener("keydown",be)},[e,ke]),i.useEffect(()=>{if(!e)return;const be=Le=>{Le.key==="Escape"&&n()};return document.addEventListener("keydown",be),()=>document.removeEventListener("keydown",be)},[e,n]),i.useEffect(()=>{te==="connected"&&C.current&&setTimeout(()=>{if(!C.current||!P.current)return;const be=P.current.querySelector(".xterm-helper-textarea");be&&be.focus();try{P.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[te]);const De=i.useCallback(()=>{if(!P.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;C.current?.focus();const Le=P.current.querySelector(".xterm-helper-textarea");if(!Le)return;Le.autocapitalize="off",Le.autocomplete="off",Le.autocorrect="off",Le.spellcheck=!1,Le.setAttribute("inputmode","text");try{Le.focus({preventScroll:!0})}catch{Le.focus()}const Je=Le.value.length;Le.setSelectionRange(Je,Je)},[]);i.useEffect(()=>Oe(()=>{C.current?.clear(),c(null),O.current=!1,C.current&&(C.current.dispose(),C.current=null),$.current=null,E.current=!1,F.current&&(window.removeEventListener("resize",F.current),F.current=null),u(!1),h(null),ie().catch(Le=>{console.error("Failed to replace invalid terminal session:",Le)})}),[Oe,ie]);const re=i.useCallback(be=>{be.target===be.currentTarget&&(_.current=!0)},[]),oe=i.useCallback(be=>{_.current&&be.target===be.currentTarget&&n(),_.current=!1},[n]),we=i.useCallback(()=>{C.current?.clear()},[]),Z=i.useCallback(async()=>{C.current?.clear(),c(null),O.current=!1;try{await se()}catch(be){o(Me(be)||"Failed to restart terminal session")}},[se]),qe=i.useCallback(()=>{C.current&&(C.current.dispose(),C.current=null),$.current=null,E.current=!1,F.current&&(window.removeEventListener("resize",F.current),F.current=null),h(null),u(!1)},[]),Qe=i.useCallback(()=>{window.location.reload()},[]),ge=i.useCallback(()=>{k(be=>jr(be+1))},[]),Ue=i.useCallback(()=>{k(be=>jr(be-1))},[]),Xe=i.useCallback(be=>{A(Le=>Le===be?null:be)},[]),wt=i.useCallback(be=>{if(w==="ctrl"){xe(YR(be)),A(null);return}if(w==="alt"){xe(QR(be)),A(null);return}xe(be)},[xe,w]),ye=i.useCallback(be=>{xe(be),A(null)},[xe]);if(!e)return null;const le=()=>{switch(te){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Te=!Q||!H&&!de;return t.jsx("div",{className:"modal-overlay open",onMouseDown:re,onMouseUp:oe,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:[j.map(be=>t.jsxs("div",{className:`terminal-tab ${be.isActive?"terminal-tab--active":""}`,onClick:()=>ve(be.id),title:be.title,role:"tab","aria-selected":be.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:be.title}),j.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Le=>{Le.stopPropagation(),B(be.id)},title:"Close tab",children:"×"})]},be.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:pe,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Ei,{size:16}),le()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[te==="disconnected"&&H&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Ye,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Qn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Z,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Qn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:we,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(vn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>R(be=>!be),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":N,children:[t.jsx(hv,{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(Wt,{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&&!de&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),de&&!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: ",de]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ee,"data-testid":"terminal-retry-btn",children:[t.jsx(Qn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Qe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Qn,{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:qe,"data-testid":"terminal-reinit-btn",children:[t.jsx(Qn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Qe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Qn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:P,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:De,onTouchStart:De},H?.sessionId)]}),N&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Xe("ctrl"),"aria-pressed":w==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Xe("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ye("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ye(" "),children:"Tab"})]}),XR.map(be=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>wt(be.key),title:be.description,children:be.label},be.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${te}`,children:[te==="connected"&&"Connected",te==="connecting"&&"Connecting...",te==="reconnecting"&&"Reconnecting...",te==="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:Ue,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(Tv,{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(xn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const ur={name:"",command:""};function Kh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function rT(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function oT({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(ur),[b,v]=i.useState(!1),[x,y]=i.useState(null),[k,N]=i.useState(null),R=Ai(n),w=i.useCallback(async()=>{try{d(!0);const I=await Dr(a);l(I)}catch(I){s(Me(I)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&w()},[e,w]);const A=i.useCallback(()=>{m(!0),f(null),g(ur),N(null)},[]),P=i.useCallback((I,F)=>{f(I),m(!1),g({name:I,command:F}),N(null)},[]),T=i.useCallback(()=>{f(null),m(!1),g(ur),N(null)},[]),_=i.useCallback(I=>{g(F=>({...F,name:I})),I&&!Kh(I)?N("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):N(null)},[]),C=i.useCallback(async()=>{const I=p.name.trim(),F=p.command.trim();if(!I){s("Script name is required","error");return}if(!Kh(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!F){s("Script command is required","error");return}v(!0);try{await Qk(I,F,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(ur),N(null),await w()}catch(G){const X=Me(G);X?.includes("already exists")?s("A script with this name already exists","error"):s(X||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,a]),$=i.useCallback(async I=>{try{await Xk(I,a),s("Script deleted","success"),y(null),h===I&&(f(null),g(ur)),await w()}catch(F){s(Me(F)||"Failed to delete script","error")}},[h,s,w,a]),O=i.useCallback((I,F)=>{r&&r(I,F)},[r]);if(!e)return null;const E=u||h!==null,S=Object.entries(o).map(([I,F])=>({name:I,command:F}));return t.jsx("div",{className:"modal-overlay open",...R,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Ei,{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(bt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):E?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:I=>_(I.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:k?"var(--color-error)":void 0}}),k&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:k}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:I=>g(F=>({...F,command:I.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:T,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:C,disabled:b||!!k,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(bt,{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:S.length===0?"No scripts defined":`${S.length} script${S.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:A,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(xn,{size:14}),"Add Script"]})]}),S.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(Ei,{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:S.map(I=>t.jsx("div",{className:"script-card","data-testid":`script-${I.name}`,style:{padding:"12px 16px",border:"1px solid var(--border)",borderRadius:"8px",background:"var(--card)"},children:t.jsxs("div",{className:"script-card-header",style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:t.jsx("span",{style:{fontWeight:600,fontSize:"14px",fontFamily:"monospace"},children:I.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.command,children:rT(I.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>O(I.name,I.command),title:"Run script","aria-label":`Run ${I.name}`,"data-testid":`run-script-${I.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(On,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>P(I.name,I.command),title:"Edit","aria-label":`Edit ${I.name}`,"data-testid":`edit-script-${I.name}`,children:t.jsx(xn,{size:14,style:{transform:"rotate(45deg)"}})}),x===I.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>$(I.name),title:"Confirm delete","aria-label":`Confirm delete ${I.name}`,"data-testid":`confirm-delete-script-${I.name}`,style:{color:"var(--color-error)"},children:t.jsx(vn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${I.name}`,children:t.jsx(Wt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(I.name),title:"Delete","aria-label":`Delete ${I.name}`,"data-testid":`delete-script-${I.name}`,children:t.jsx(vn,{size:14})})]})]})},I.name))})]})})]})})}function lT(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(b=>b+1)},[]),g=i.useCallback(b=>{l(b),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){d(!0),m(null);try{const x=await mk(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(Me(x)||"Failed to load files"),r([]))}finally{b||d(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function cT(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,b]=i.useState(null),v=i.useCallback(k=>{o(k),b(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),b(null);return}let k=!1;async function N(){h(!0),b(null);try{const R=await hk(e,n,a);k||(o(R.content),c(R.content),u(R.mtime))}catch(R){k||(b(Me(R)||"Failed to load file"),o(""),c(""),u(null))}finally{k||h(!1)}}return N(),()=>{k=!0}},[e,n,s,a]);const x=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const k=await pk(e,n,r,a);c(r),u(k.mtime)}catch(k){throw b(Me(k)||"Failed to save file"),k}finally{p(!1)}}},[e,n,r,x,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:x,mtime:d}}const dT=1e4;function uT(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function mT(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function hT(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 uk(e);if(u)return;s(uT(f.project)),r(f.tasks.map(mT)),d(null)}catch(f){u||d(Me(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},dT);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function pT(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function fT(e){return e?new Date(e).toLocaleDateString():""}function Gh(e,n){return XN(e,n)}const mr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Dc={type:null,entry:null,entryFullPath:""},gT=200,bT=500,Jh=10;function xT({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,b=f?.offsetLeft??0,v=f?.offsetTop??0,x=8;let y=e-b,k=n-v;y+h.width>p-x&&(y=p-x-h.width),k+h.height>g-x&&(k=g-x-h.height),y<x&&(y=x),k<x&&(k=x),c({x:y+b,y:k+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:Zi,disabled:!1},{id:"move",label:"Move",icon:Dv,disabled:!1},{id:"rename",label:"Rename",icon:vs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:Ur,disabled:!1}]:[{id:"download",label:"Download",icon:Sx,disabled:!1}],{id:"divider",label:"",icon:Zi,disabled:!0},{id:"delete",label:"Delete",icon:vn,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 vT({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 yT({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(mr),[f,p]=i.useState(Dc),[g,b]=i.useState(!1),[v,x]=i.useState(null),[y,k]=i.useState(!1),[N,R]=i.useState(null),w=i.useRef(null),A=i.useRef(null),P=i.useRef(null),T=i.useRef(!1),_=i.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),A.current!==null&&(window.clearTimeout(A.current),A.current=null)},[]),C=i.useCallback(()=>{_(),P.current=null,k(!1),R(null)},[_]);i.useEffect(()=>()=>{_()},[_]);const $=i.useCallback((z,L,j,H)=>{h({visible:!0,x:z,y:L,entry:j,entryFullPath:H})},[]),O=i.useCallback((z,L,j)=>{if(z.touches.length!==1)return;const H=z.touches[0];H&&(C(),P.current={x:H.clientX,y:H.clientY},A.current=window.setTimeout(()=>{k(!0),R(j)},gT),w.current=window.setTimeout(()=>{const Q=P.current;Q&&(T.current=!0,k(!1),R(null),_(),$(Q.x,Q.y,L,j))},bT))},[C,_,$]),E=i.useCallback(z=>{const L=P.current,j=z.touches[0];!L||!j||(Math.abs(j.clientX-L.x)>Jh||Math.abs(j.clientY-L.y)>Jh)&&C()},[C]),S=i.useCallback(()=>{C()},[C]);i.useEffect(()=>{if(!m.visible)return;const z=document.querySelector(".file-browser-list"),L=()=>{T.current=!1,C(),h(mr)};return z?.addEventListener("scroll",L),()=>z?.removeEventListener("scroll",L)},[C,m.visible]),i.useEffect(()=>{if(!m.visible)return;const z=L=>{L.key==="Escape"&&(T.current=!1,h(mr))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m.visible]);const I=i.useCallback((z,L)=>{z.preventDefault(),z.stopPropagation(),C(),T.current=!1,$(z.clientX,z.clientY,L,Gh(n,L.name))},[C,n,$]),F=i.useCallback(z=>{if(!m.entry)return;T.current=!1;const L=m.entry,j=m.entryFullPath;if(h(mr),z==="download"){if(!c)return;const H=nf(c,j,u);window.open(fi(H),"_blank");return}if(z==="download-zip"){if(!c)return;const H=yk(c,j,u);window.open(fi(H),"_blank");return}p({type:z,entry:L,entryFullPath:j}),x(null)},[m,c,u]),G=i.useCallback(async z=>{if(!(!f.type||!f.entry||!c)){b(!0),x(null);try{switch(f.type){case"copy":await gk(c,f.entryFullPath,z,u);break;case"move":await bk(c,f.entryFullPath,z,u);break;case"rename":await vk(c,f.entryFullPath,z,u);break;case"delete":await xk(c,f.entryFullPath,u);break}p(Dc),d?.()}catch(L){x(Me(L)||"Operation failed")}finally{b(!1)}}},[f,c,d,u]),X=i.useCallback(()=>{p(Dc),x(null)},[]),M=i.useCallback((z,L)=>{if(T.current){T.current=!1;return}m.visible||(z.type==="directory"?a(L):s(L))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(bt,{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(ZN(n))},children:[t.jsx(_n,{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(z=>{const L=Gh(n,z.name),j=y&&N===L;return t.jsxs("div",{className:`file-node file-node--${z.type} ${j?"file-node--long-pressing":""}`,onClick:()=>M(z,L),onContextMenu:H=>I(H,z),onTouchStart:H=>O(H,z,L),onTouchMove:E,onTouchEnd:S,onTouchCancel:S,children:[t.jsx("div",{className:"file-node-icon",children:z.type==="directory"?t.jsx(as,{size:16}):t.jsx(Wp,{size:16})}),t.jsx("div",{className:"file-node-name",children:z.name}),z.type==="file"&&z.size!==void 0&&t.jsx("div",{className:"file-node-size",children:pT(z.size)}),z.mtime&&t.jsx("div",{className:"file-node-time",children:fT(z.mtime)})]},z.name)})}),m.visible&&m.entry&&t.jsx(xT,{x:m.x,y:m.y,entry:m.entry,onAction:F,onClose:()=>{T.current=!1,h(mr)}}),f.type&&f.entry&&t.jsx(vT,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:G,onCancel:X,loading:g,error:v})]})}function wT(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function kT({content:e,onChange:n,readOnly:s,filePath:a}){const[r,o]=i.useState(!1),[l,c]=i.useState(!0),d=wT(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(Vp,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:h,disabled:u,"aria-label":"Preview mode",children:[t.jsx(Ba,{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(Go,{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(Go,{size:14})})]}),u?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(gi,{remarkPlugins:[bi],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 jT(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function NT({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(hu,{size:14}):t.jsx(Xc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(rn,{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(hu,{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(Xc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:jT(c.title)})]},c.id))]})]})]})}const ST=768,CT=280,Io=180,$o=500,Yh="fusion:file-browser-sidebar-width",Zg=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),ET=new Set([...Zg,".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 Qh(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ET.has(n)}function MT(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Zg.has(n)}function _T({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=hT(a),l=i.useRef(null);xi(l,!0,"fusion:files-modal-size");const c=Ai(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,b]=i.useState("list"),[v,x]=i.useState(CT),{entries:y,currentPath:k,setPath:N,loading:R,error:w,refresh:A}=lT(d,!0,a),{content:P,setContent:T,originalContent:_,loading:C,saving:$,error:O,save:E,hasChanges:S,mtime:I}=cT(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const B=()=>{p(window.innerWidth<=ST)};return B(),window.addEventListener("resize",B),()=>window.removeEventListener("resize",B)},[]),i.useEffect(()=>{m||b("list")},[m]),i.useEffect(()=>{try{const B=localStorage.getItem(Yh);if(!B)return;const ve=Number.parseInt(B,10);if(!Number.isNaN(ve)){const U=Math.max(Io,Math.min($o,ve));x(U)}}catch{}},[]),i.useEffect(()=>{const B=ve=>{ve.key==="Escape"&&n(),(ve.metaKey||ve.ctrlKey)&&ve.key==="s"&&(ve.preventDefault(),S&&!$&&E())};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[n,S,$,E]);const F=i.useCallback(B=>{h(B),f&&b("editor")},[f]),G=i.useCallback(()=>{b("list")},[]),X=i.useCallback(()=>{T(_)},[_,T]),M=i.useCallback(B=>{u(B),h(null),b("list"),s?.(B)},[s]),z=i.useCallback(B=>{try{localStorage.setItem(Yh,String(B))}catch{}},[]),L=i.useCallback(B=>{if(f)return;B.preventDefault(),B.stopPropagation();const ve=B.currentTarget;typeof ve.setPointerCapture=="function"&&ve.setPointerCapture(B.pointerId);const U=B.clientX,se=v;let ee=se;document.body.style.userSelect="none";const ie=xe=>{const ne=xe.clientX-U,_e=Math.max(Io,Math.min($o,se+ne));ee=_e,x(_e)},te=xe=>{typeof ve.releasePointerCapture=="function"&&ve.releasePointerCapture(xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ie),document.removeEventListener("pointerup",te),z(ee)};document.addEventListener("pointermove",ie),document.addEventListener("pointerup",te)},[f,z,v]),j=i.useCallback(B=>{if(f)return;const ve=20;if(B.key!=="ArrowLeft"&&B.key!=="ArrowRight")return;B.preventDefault();const U=B.key==="ArrowLeft"?-ve:ve,se=Math.max(Io,Math.min($o,v+U));x(se),z(se)},[f,z,v]),Q=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(B=>B.id===d)?.id??d,[d,o])}`,de=i.useMemo(()=>!m||!MT(m)?null:nf(d,m,a),[m,d,a]),pe=B=>{const ve=new Blob([B]).size;return ve<1024?`${ve} B`:`${(ve/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(as,{size:18}),t.jsx("span",{children:Q}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(NT,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:M}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Wt,{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(yT,{entries:y,currentPath:k,onSelectFile:F,onNavigate:N,loading:R,error:w,onRetry:A,workspace:d,onRefresh:A,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Io,"aria-valuemax":$o,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:L,onKeyDown:j}),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:G,"aria-label":"Back to file list",children:[t.jsx(Ua,{size:16}),t.jsx("span",{children:"Back"})]}),m,Qh(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(qx,{size:12}),"Binary file — read only"]}),I&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(I).toLocaleString()]}),C&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!de&&S&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:X,disabled:$,children:[t.jsx(Jv,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void E(),disabled:$,children:[t.jsx(Qp,{size:14}),$?"Saving...":"Save"]})]})})]}),O&&!de&&t.jsx("div",{className:"file-browser-error-banner",children:O}),de?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:de,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(kT,{content:P,onChange:T,filePath:m,readOnly:Qh(m)})}),!de&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:pe(P)}),S&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(as,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function AT(e){const{items:n,...s}=e;return s}function Xh(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function PT(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([]),b=i.useRef(h);b.current=h,i.useEffect(()=>{let P=!1;async function T(){d(!0),m(null);try{const _=await fN(n);if(P)return;g(_),r(_.map(AT));const C=b.current&&_.some($=>$.id===b.current)?b.current:_[0]?.id??null;f(C),l(C?_.find($=>$.id===C)?.items??[]:[])}catch(_){if(P)return;g([]),r([]),l([]),f(null),m(_ instanceof Error?_.message:"Failed to load todo lists")}finally{P||d(!1)}}return T(),()=>{P=!0}},[n]),i.useEffect(()=>{if(!h){l([]);return}const P=p.find(T=>T.id===h);l(P?.items??[])},[p,h]);const v=i.useCallback(async P=>{const T=a,_=p,C=new Date().toISOString(),$={id:Xh("temp-list"),projectId:n??"",title:P,createdAt:C,updatedAt:C};m(null),r(O=>[...O,$]),g(O=>[...O,{...$,items:[]}]);try{const O=await gN(P,n);r(E=>E.map(S=>S.id===$.id?O:S)),g(E=>E.map(S=>S.id===$.id?{...O,items:[]}:S)),b.current||f(O.id)}catch(O){r(T),g(_),m(O instanceof Error?O.message:"Failed to create list"),s?.("Failed to create todo list","error")}},[s,p,a,n]),x=i.useCallback(async(P,T)=>{const _=a,C=p;m(null),r($=>$.map(O=>O.id===P?{...O,title:T}:O)),g($=>$.map(O=>O.id===P?{...O,title:T}:O));try{const $=await bN(P,T,n);r(O=>O.map(E=>E.id===P?$:E)),g(O=>O.map(E=>E.id===P?{...$,items:E.items}:E))}catch($){r(_),g(C),m($ instanceof Error?$.message:"Failed to rename list"),s?.("Failed to rename todo list","error")}},[s,p,a,n]),y=i.useCallback(async P=>{const T=a,_=p,C=b.current,$=C===P?a.find(O=>O.id!==P)?.id??null:C;m(null),r(O=>O.filter(E=>E.id!==P)),g(O=>O.filter(E=>E.id!==P)),C===P&&f($);try{await xN(P,n)}catch(O){r(T),g(_),f(C),m(O instanceof Error?O.message:"Failed to delete list"),s?.("Failed to delete todo list","error")}},[s,p,a,n]),k=i.useCallback(async P=>{const T=b.current;if(!T)return;const _=o,C=p,$=new Date().toISOString(),O=o.reduce((S,I)=>Math.max(S,I.sortOrder),-1),E={id:Xh("temp-item"),listId:T,text:P,completed:!1,completedAt:null,createdAt:$,updatedAt:$,sortOrder:O+1};m(null),l(S=>[...S,E]),g(S=>S.map(I=>I.id===T?{...I,items:[...I.items,E]}:I));try{const S=await vN(T,P,n);l(I=>I.map(F=>F.id===E.id?S:F)),g(I=>I.map(F=>F.id===T?{...F,items:F.items.map(G=>G.id===E.id?S:G)}:F))}catch(S){l(_),g(C),m(S instanceof Error?S.message:"Failed to create item"),s?.("Failed to create todo item","error")}},[s,o,p,n]),N=i.useCallback(async(P,T)=>{const _=o.find(S=>S.id===P);if(!_)return;const C=o,$=p,O=T.completed??_.completed,E={..._,...T,completed:O,completedAt:O?_.completedAt??new Date().toISOString():null,updatedAt:new Date().toISOString()};m(null),l(S=>S.map(I=>I.id===P?E:I)),g(S=>S.map(I=>I.id===E.listId?{...I,items:I.items.map(F=>F.id===P?E:F)}:I));try{const S=await yN(P,T,n);l(I=>I.map(F=>F.id===P?S:F)),g(I=>I.map(F=>F.id===S.listId?{...F,items:F.items.map(G=>G.id===P?S:G)}:F))}catch(S){l(C),g($),m(S instanceof Error?S.message:"Failed to update item"),s?.("Failed to update todo item","error")}},[s,o,p,n]),R=i.useCallback(async P=>{const T=o.find(_=>_.id===P);T&&await N(P,{completed:!T.completed})},[o,N]),w=i.useCallback(async P=>{const T=o,_=p;m(null),l(C=>C.filter($=>$.id!==P)),g(C=>C.map($=>({...$,items:$.items.filter(O=>O.id!==P)})));try{await wN(P,n)}catch(C){l(T),g(_),m(C instanceof Error?C.message:"Failed to delete item"),s?.("Failed to delete todo item","error")}},[s,o,p,n]),A=i.useCallback(async P=>{const T=b.current;if(!T)return;const _=o,C=p,$=new Map(o.map(E=>[E.id,E])),O=P.map((E,S)=>{const I=$.get(E);return I?{...I,sortOrder:S}:null}).filter(E=>E!==null);m(null),l(O),g(E=>E.map(S=>S.id===T?{...S,items:O}:S));try{await kN(T,P,n)}catch(E){l(_),g(C),m(E instanceof Error?E.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:x,deleteList:y,createItem:k,updateItem:N,toggleItem:R,deleteItem:w,reorderItems:A}}function RT(e){return[...e].sort((n,s)=>n.sortOrder-s.sortOrder)}function eb({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:b,deleteItem:v,reorderItems:x}=PT({projectId:e,addToast:(re,oe)=>{if(oe==="success"||oe==="error"||oe==="info"||oe===void 0){n(re,oe);return}n(re,"info")}}),[y,k]=i.useState(null),[N,R]=i.useState(""),[w,A]=i.useState(null),[P,T]=i.useState(""),[_,C]=i.useState(""),[$,O]=i.useState(!1),[E,S]=i.useState(""),[I,F]=i.useState([]),[G,X]=i.useState(!1),[M,z]=i.useState(!1),[L,j]=i.useState(null),H=i.useRef(null),{confirm:Q}=qs(),de=i.useMemo(()=>r.find(re=>re.id===d)??null,[r,d]),pe=i.useMemo(()=>RT(o.filter(re=>re.listId===d)),[o,d]);function B(){k(null),R(""),C(""),O(!1)}function ve(){A(null),T(""),S("")}function U(re){B(),ve(),u(re)}const se=i.useCallback(async()=>{X(!0);try{const re=await oa(void 0,e);F(re),z(!0)}catch(re){n(`Failed to load agents: ${Me(re)}`,"error"),z(!1),j(null)}finally{X(!1)}},[e,n]);i.useEffect(()=>{k(null),R(""),C(""),O(!1),A(null),T(""),S(""),z(!1),j(null)},[d]),i.useEffect(()=>{if(!M)return;const re=oe=>{H.current&&!H.current.contains(oe.target)&&(z(!1),j(null))};return document.addEventListener("mousedown",re),()=>{document.removeEventListener("mousedown",re)}},[M]);function ee(re){ve(),k(re.id),R(re.title),O(!1)}async function ie(){if(!y)return;const re=N.trim();if(!re){k(null),R("");return}await h(y,re),k(null),R("")}function te(){k(null),R("")}function xe(re){B(),A(re.id),T(re.text)}async function ne(){if(!w)return;const re=P.trim();if(!re){A(null),T("");return}await g(w,{text:re}),A(null),T("")}function _e(){A(null),T("")}async function Ne(){const re=_.trim();re&&(await m(re),C(""),O(!1))}async function Se(){if(!d)return;const re=E.trim();re&&(await p(re),S(""))}async function He(re){await Q({title:"Delete List",message:"Delete this list and all its items?",danger:!0})&&await f(re)}async function Ye(re){await v(re)}async function Oe(re,oe){const we=pe.map(Qe=>Qe.id),Z=we.findIndex(Qe=>Qe===re);if(Z<0)return;const qe=oe==="up"?Z-1:Z+1;qe<0||qe>=we.length||([we[Z],we[qe]]=[we[qe],we[Z]],await x(we))}const ke=i.useCallback(async re=>{try{const oe={description:re.text,column:"triage",source:{sourceType:"dashboard_ui"}},we=await Qo(oe,e);a?.(we),n(`Created ${we.id} from todo`,"success")}catch(oe){n(`Failed to create task: ${Me(oe)}`,"error")}},[e,n,a]),De=i.useCallback(async(re,oe)=>{try{const we={description:re.text,column:"triage",assignedAgentId:oe,source:{sourceType:"dashboard_ui"}},Z=await Qo(we,e);a?.(Z);const Qe=I.find(ge=>ge.id===oe)?.name??oe;n(`Created ${Z.id} and assigned to ${Qe}`,"success"),z(!1),j(null)}catch(we){n(`Failed to create and assign task: ${Me(we)}`,"error")}},[e,n,I,a]);return l?t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-loading",children:[t.jsx(bt,{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:()=>{ve(),O(!0),k(null)},"aria-label":"Add list","data-testid":"add-list-button",children:t.jsx(xn,{})})]}),$&&t.jsxs("div",{className:"todo-list-item",children:[t.jsx("input",{className:"input todo-inline-edit-input",placeholder:"New list title",value:_,onChange:re=>C(re.target.value),onKeyDown:re=>{re.key==="Enter"&&Ne(),re.key==="Escape"&&(C(""),O(!1))},autoFocus:!0,"data-testid":"new-list-input"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{Ne()},"aria-label":"Save list",children:t.jsx(Wn,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{C(""),O(!1)},"aria-label":"Cancel list",children:t.jsx(Wt,{})})]}),r.length===0&&!$?t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(Zc,{"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:()=>{ve(),O(!0)},children:"Create List"})]}):t.jsx("div",{className:"todo-list-items",role:"list","aria-label":"Todo lists",children:r.map(re=>{const oe=re.id===d,we=re.id===y;return t.jsx("div",{className:`todo-list-item${oe?" todo-list-item--active":""}`,role:"listitem",children:we?t.jsxs(t.Fragment,{children:[t.jsx("input",{className:"input todo-inline-edit-input",value:N,onChange:Z=>R(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&ie(),Z.key==="Escape"&&te()},autoFocus:!0,"data-testid":`rename-list-input-${re.id}`}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ie()},"aria-label":"Save list rename",children:t.jsx(Wn,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:te,"aria-label":"Cancel list rename",children:t.jsx(Wt,{})})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"todo-list-select-btn",onClick:()=>U(re.id),"aria-label":`Select list ${re.title}`,"aria-current":oe?"true":void 0,"data-testid":`todo-list-${re.id}`,children:t.jsx("span",{className:"todo-list-item-name",children:re.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:()=>{ee(re)},"aria-label":`Rename ${re.title}`,"data-testid":`rename-list-button-${re.id}`,children:t.jsx(vs,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{He(re.id)},"aria-label":`Delete ${re.title}`,"data-testid":`delete-list-button-${re.id}`,children:t.jsx(vn,{})})]})]})},re.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"})]}),de?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"todo-items-header",children:t.jsx("h3",{children:de.title})}),t.jsxs("div",{className:"todo-add-item-row",children:[t.jsx("input",{className:"input",placeholder:"Add a todo item",value:E,onChange:re=>S(re.target.value),onKeyDown:re=>{re.key==="Enter"&&Se(),re.key==="Escape"&&S("")},"data-testid":"new-item-input"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>{Se()},children:"Add"})]}),pe.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:pe.map((re,oe)=>{const we=re.id===w;return t.jsxs("div",{className:"todo-item","data-testid":`todo-item-${re.id}`,children:[t.jsxs("div",{className:"todo-item-main-row",children:[t.jsx("input",{type:"checkbox",checked:re.completed,onChange:()=>{b(re.id)},className:"todo-item-checkbox","aria-label":`Toggle ${re.text}`,"data-testid":`toggle-item-${re.id}`}),we?t.jsx("input",{className:"input todo-inline-edit-input",value:P,onChange:Z=>T(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&ne(),Z.key==="Escape"&&_e()},autoFocus:!0,"data-testid":`edit-item-input-${re.id}`}):t.jsx("button",{type:"button",className:`todo-item-text${re.completed?" todo-item-text--completed":""}`,onClick:()=>xe(re),children:re.text})]}),t.jsx("div",{className:"todo-item-actions","data-testid":`todo-item-actions-${re.id}`,children:we?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ne()},"aria-label":"Save item edit",children:t.jsx(Wn,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:_e,"aria-label":"Cancel item edit",children:t.jsx(Wt,{})})]}):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:()=>{Oe(re.id,"up")},disabled:oe===0,"aria-label":`Move ${re.text} up`,"data-testid":`move-up-${re.id}`,children:t.jsx(ri,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{Oe(re.id,"down")},disabled:oe===pe.length-1,"aria-label":`Move ${re.text} down`,"data-testid":`move-down-${re.id}`,children:t.jsx(rn,{})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{s?.(re.text)},"aria-label":`Start planning from ${re.text}`,"data-testid":`planning-from-${re.id}`,children:t.jsx(oi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ke(re)},"aria-label":`Create task from ${re.text}`,"data-testid":`create-task-from-${re.id}`,children:t.jsx(dx,{})}),t.jsxs("div",{className:"todo-agent-picker-trigger",ref:L===re.id?H:void 0,children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{j(re.id),se()},"aria-label":`Assign ${re.text} to agent`,"data-testid":`assign-agent-for-${re.id}`,children:t.jsx(Mn,{})}),M&&L===re.id&&t.jsx("div",{className:"todo-agent-picker-dropdown",onMouseDown:Z=>{Z.preventDefault()},children:G?t.jsx("div",{className:"todo-agent-picker-loading",children:"Loading agents..."}):I.filter(Z=>Z.state!=="terminated").length>0?I.filter(Z=>Z.state!=="terminated").map(Z=>t.jsxs("button",{type:"button",className:"todo-agent-picker-item",onClick:()=>{De(re,Z.id)},children:[t.jsx(Mn,{}),t.jsx("span",{children:Z.name}),t.jsx("span",{className:"todo-agent-picker-role",children:Z.role})]},Z.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:()=>xe(re),"aria-label":`Edit ${re.text}`,"data-testid":`edit-item-${re.id}`,children:t.jsx(vs,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Ye(re.id)},"aria-label":`Delete ${re.text}`,"data-testid":`delete-item-${re.id}`,children:t.jsx(vn,{})})]})})]},re.id)})})]}):t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(Zc,{"aria-hidden":"true"}),t.jsx("p",{children:"Select a list from the sidebar"})]})]})]})})}const tb=Object.freeze(Object.defineProperty({__proto__:null,TodoView:eb},Symbol.toStringTag,{value:"Module"}));function TT({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Ai(e);return i.useEffect(()=>{const o=l=>{l.key==="Escape"&&e()};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(Zc,{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(Wt,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(eb,{projectId:n,addToast:s,onPlanningMode:a,onClose:e})})]})})}function IT(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 yw();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 $T(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 DT(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const nb="kb-usage-hidden-windows",sb="kb-usage-modal-size",ib="kb-usage-provider-order";function Zh(e){const n=Gn(sb,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 ep(e){const n=Gn(nb,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 LT(e,n){us(nb,JSON.stringify(e),n)}function tp(e){const n=Gn(ib,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function np(e,n){us(ib,JSON.stringify(e),n)}function ab(e,n,s){return s[e]?.includes(n)??!1}function zT({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=DT(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 x=Math.floor(v/36e5),y=Math.floor(x/24),k=x%24;y>0&&k>0?u=`resets in ${y}d ${k}h`:y>0?u=`resets in ${y}d`:x>0?u=`resets in ${x}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",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Ba,{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:$T(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(wl,{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(by,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(Tn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function OT(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 FT({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:b,onMoveUp:v,onMoveDown:x}){const y=s[e.name]?.length??0,k=()=>{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.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(bl,{size:16})}),t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Fn,{provider:OT(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(ri,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:x,disabled:!b,"aria-label":`Move ${e.name} down`,children:t.jsx(rn,{size:14})})]}),k()]})]}),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((N,R)=>{const w=ab(e.name,N.label,s);return t.jsx(zT,{window:N,viewMode:n,isHidden:w,onToggleHidden:()=>a(e.name,N.label)},`${e.name}-${N.label}-${R}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function UT(){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 BT({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=IT({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),[b,v]=i.useState("used"),[x,y]=i.useState(()=>ep(s)),[k,N]=i.useState(()=>tp(s)),[R,w]=i.useState(null),[A,P]=i.useState(null),[T,_]=i.useState(null),C=i.useRef(null),$=i.useRef(null),O=i.useRef(e),E=i.useRef(!1),[S,I]=i.useState(()=>Zh(s));i.useEffect(()=>{I(Zh(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const Ne=$.current;if(!Ne||typeof ResizeObserver>"u")return;let Se=null;const He=new ResizeObserver(Ye=>{const Oe=Ye[0];if(!Oe)return;const{width:ke,height:De}=Oe.contentRect;ke<=0||De<=0||(Se&&clearTimeout(Se),Se=setTimeout(()=>{us(sb,JSON.stringify({width:Math.round(ke),height:Math.round(De)}),s)},250))});return He.observe(Ne),()=>{Se&&clearTimeout(Se),He.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(E.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(E.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const Ne=window.matchMedia?.("(pointer: coarse)"),Se=()=>{f(window.innerWidth>=769),g(Ne?.matches??!1)};return Se(),window.addEventListener("resize",Se),Ne?.addEventListener?.("change",Se),()=>{window.removeEventListener("resize",Se),Ne?.removeEventListener?.("change",Se)}},[]),i.useEffect(()=>{!O.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),O.current=e},[e,c,d]),i.useEffect(()=>{const Ne=Gn("kb-usage-view-mode",s);if(Ne==="used"||Ne==="remaining"){v(Ne);return}v("used")},[s]);const F=i.useCallback(Ne=>{v(Ne),us("kb-usage-view-mode",Ne,s)},[s]);i.useEffect(()=>{y(ep(s)),N(tp(s))},[s]),i.useEffect(()=>{LT(x,s)},[x,s]);const G=i.useCallback((Ne,Se)=>{y(He=>{if(ab(Ne,Se,He)){const Ye=(He[Ne]??[]).filter(Oe=>Oe!==Se);if(Ye.length===0){const{[Ne]:Oe,...ke}=He;return ke}return{...He,[Ne]:Ye}}return{...He,[Ne]:[...He[Ne]??[],Se]}})},[]),X=i.useCallback(Ne=>{y(Se=>{if(!Se[Ne])return Se;const{[Ne]:He,...Ye}=Se;return Ye})},[]),M=i.useCallback(Ne=>{if(k.length===0)return Ne;const Se=new Map(Ne.map(Ye=>[Ye.name,Ye])),He=[];for(const Ye of k){const Oe=Se.get(Ye);Oe&&(He.push(Oe),Se.delete(Ye))}return[...He,...Se.values()]},[k]),z=i.useCallback((Ne,Se)=>{Ne.dataTransfer.effectAllowed="move",Ne.dataTransfer.setData("text/plain",Se),w(Se)},[]),L=i.useCallback((Ne,Se)=>{if(!R||R===Se)return;Ne.preventDefault(),Ne.dataTransfer.dropEffect="move";const{top:He,height:Ye}=Ne.currentTarget.getBoundingClientRect(),Oe=He+Ye/2,ke=Ne.clientY<Oe?"before":"after";P(Se),_(ke)},[R]),j=i.useCallback((Ne,Se)=>{Ne.preventDefault();const He=R??Ne.dataTransfer.getData("text/plain");if(!He||He===Se){P(null),_(null);return}const Oe=M(r).map(re=>re.name).filter(re=>re!==He),ke=Oe.indexOf(Se);if(ke<0){P(null),_(null);return}const De=T==="after"?ke+1:ke;Oe.splice(De,0,He),np(Oe,s),N(Oe),P(null),_(null)},[R,T,s,r,M]),H=i.useCallback(()=>{w(null),P(null),_(null)},[]),Q=i.useCallback((Ne,Se)=>{const He=M(r).map(re=>re.name),Ye=He.indexOf(Ne),Oe=Ye+Se;if(Ye<0||Oe<0||Oe>=He.length)return;const ke=[...He],[De]=ke.splice(Ye,1);ke.splice(Oe,0,De),np(ke,s),N(ke)},[s,r,M]),de=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const Ne=Se=>{Se.key==="Escape"&&n()};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[e,n]);const pe=i.useCallback(Ne=>{Ne.target===Ne.currentTarget&&n()},[n]);if(!e)return null;const B=!!(a&&h),ve=8,U=12,ee=S?.width??420,ie=B?Math.min((a?.bottom??0)+ve,window.innerHeight-U):void 0,te=B?Math.max(8,(a?.right??0)-ee):void 0,xe=h&&S?{width:S.width,height:S.height}:{},ne=M(r),_e=t.jsxs("div",{ref:$,className:`usage-modal${B?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:B?{position:"fixed",top:ie,left:te,...xe}:xe,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Fs,{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 ${b==="used"?"active":""}`,onClick:()=>F("used"),"aria-pressed":b==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${b==="remaining"?"active":""}`,onClick:()=>F("remaining"),"aria-pressed":b==="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(Wt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:C,children:(o||!E.current&&!l)&&r.length===0?t.jsx(UT,{}):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:de,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:ne.map((Ne,Se)=>t.jsx(FT,{provider:Ne,viewMode:b,hiddenWindows:x,onToggleWindow:G,onShowAllHidden:X,isDragging:R===Ne.name,isDragOver:A===Ne.name,dragOverPosition:A===Ne.name?T:null,onDragStart:He=>z(He,Ne.name),onDragOver:He=>L(He,Ne.name),onDragLeave:()=>{A===Ne.name&&(P(null),_(null))},onDrop:He=>j(He,Ne.name),onDragEnd:H,isTouchReorderMode:p,canMoveUp:Se>0,canMoveDown:Se<ne.length-1,onMoveUp:()=>Q(Ne.name,-1),onMoveDown:()=>Q(Ne.name,1)},Ne.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:de,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(Qn,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return B?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),_e]}):t.jsx("div",{className:"modal-overlay open",onClick:pe,"data-testid":"usage-modal-overlay",children:_e})}function rb(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 cl(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 HT={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},ob={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},qT={cron:Hp,webhook:Xp,api:qp,manual:Kn},VT={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},WT={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function KT({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(Tn,{size:12}):t.jsx(qr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:rb(n)})]})}function GT({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"} ${cl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Tn,{size:12}):t.jsx(qr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:cl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:ob[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:rb(r)}),s?t.jsx(ri,{size:12}):t.jsx(rn,{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 JT({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=qs(),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=HT[e.trigger.type],f=qT[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}),ob[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(fl,{size:10}):t.jsx(as,{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(bt,{className:"spinner"}):t.jsx(On,{})}),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(ii,{}):t.jsx(On,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(vs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(vn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ea,{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(Mi,{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:VT[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:WT[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:cl(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:cl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(KT,{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(ri,{size:12}):t.jsx(rn,{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,b)=>t.jsx(GT,{result:g,index:b},`${g.startedAt}-${b}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function YT({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Ei,{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(yv,{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(ms,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Lc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function QT(e){return e==="command"?{id:Lc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Lc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Lc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function XT({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??""),[b,v]=i.useState(e.taskTitle??""),[x,y]=i.useState(e.taskDescription??""),[k,N]=i.useState(e.taskColumn??"triage"),[R,w]=i.useState(e.timeoutMs),[A,P]=i.useState(e.continueOnFailure??!1),[T,_]=i.useState({}),[C,$]=i.useState([]),[O,E]=i.useState(!1),[S,I]=i.useState(null);i.useEffect(()=>{let z=!1;return E(!0),I(null),As().then(L=>{z||$(L.models)}).catch(L=>{z||I(L instanceof Error?L.message:"Failed to load models")}).finally(()=>{z||E(!1)}),()=>{z=!0}},[]);const F=i.useCallback(()=>{const z={};return a.trim()||(z.name="Step name is required"),o==="command"&&!c.trim()&&(z.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(z.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(z.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(z.modelProvider="Both model provider and model ID must be set together"),R!==void 0&&R<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),_(z),Object.keys(z).length===0},[a,o,c,u,x,h,p,R]),G=h&&p?`${h}/${p}`:"",X=i.useCallback(z=>{if(!z)f(""),g("");else{const L=z.indexOf("/");L!==-1&&(f(z.slice(0,L)),g(z.slice(L+1)))}},[]),M=i.useCallback(()=>{if(!F())return;const z={...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"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?k:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:R||void 0,continueOnFailure:A};o!=="ai-prompt"&&delete z.prompt,o!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[F,n,e,a,o,c,u,b,x,k,h,p,R,A]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:z=>r(z.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:z=>l(z.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:z=>d(z.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:z=>m(z.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(hs,{id:`step-model-${e.id}`,label:"Model",models:C,value:G,onChange:X,placeholder:"Use default",disabled:O}),S&&t.jsx("small",{className:"field-error",children:S}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:z=>v(z.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:z=>y(z.target.value),rows:4,"aria-invalid":!!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:k,onChange:z=>N(z.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(hs,{id:`step-task-model-${e.id}`,label:"Model",models:C,value:G,onChange:X,placeholder:"Use default",disabled:O}),S&&t.jsx("small",{className:"field-error",children:S}),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:R??"",onChange:z=>w(z.target.value?Number(z.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:A,onChange:z=>P(z.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:M,children:"Save Step"})]})]})}function ZT({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=QT(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(XT,{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(bl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(YT,{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(ri,{})}),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(rn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(vs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(vn,{})})]})]})},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(xn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(xn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(xn,{size:14}),"Add Create Task Step"]})]})]})}const lb={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},eI={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function tI(e){const n=e.trim();for(const[s,a]of Object.entries(lb))if(a===n)return s;return"custom"}function nI(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function sI(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 iI(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 aI=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],rI=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function sp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function ip({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?iI(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,b]=i.useState(c.cronExpression),[v,x]=i.useState(()=>c.triggerType!=="cron"?"custom":tI(c.cronExpression)),[y,k]=i.useState(c.webhookPath),[N,R]=i.useState(c.webhookSecret),[w,A]=i.useState(c.endpoint),[P,T]=i.useState(e?.executionPolicy??"queue"),[_,C]=i.useState(e?.catchUpPolicy??"run_one"),[$,O]=i.useState(e?.enabled??!0),E=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,S=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[I,F]=i.useState(e?.steps&&e.steps.length>0&&!E&&!S?"advanced":"simple"),[G,X]=i.useState(()=>E?"ai-prompt":S?"create-task":"command"),[M,z]=i.useState(e?.command??""),[L,j]=i.useState(e?.steps??[]),[H,Q]=i.useState(!1),[de,pe]=i.useState(e?.timeoutMs??3e5),[B,ve]=i.useState(E?e.steps?.[0]?.prompt??"":""),[U,se]=i.useState(S?e.steps?.[0]?.taskTitle??"":""),[ee,ie]=i.useState(S?e.steps?.[0]?.taskDescription??"":""),[te,xe]=i.useState(S?e.steps?.[0]?.taskColumn??"triage":"triage"),[ne,_e]=i.useState(E||S?e.steps?.[0]?.modelProvider??"":""),[Ne,Se]=i.useState(E||S?e.steps?.[0]?.modelId??"":""),[He,Ye]=i.useState([]),[Oe,ke]=i.useState(!1),[De,re]=i.useState(null),[oe,we]=i.useState(a??"global"),[Z,qe]=i.useState({}),[Qe,ge]=i.useState(!1),Ue=i.useRef(!0);i.useEffect(()=>()=>{Ue.current=!1},[]),i.useEffect(()=>{a&&we(a)},[a]),i.useEffect(()=>{let Re=!1;return ke(!0),re(null),As().then(kt=>{Re||Ye(kt.models)}).catch(kt=>{Re||re(kt instanceof Error?kt.message:"Failed to load models")}).finally(()=>{Re||ke(!1)}),()=>{Re=!0}},[]);const Xe=ne&&Ne?`${ne}/${Ne}`:"",wt=i.useCallback(Re=>{if(!Re){_e(""),Se("");return}const kt=Re.indexOf("/");kt!==-1&&(_e(Re.slice(0,kt)),Se(Re.slice(kt+1)))},[]),ye=i.useCallback(()=>{const Re={};if(d.trim()||(Re.name="Name is required"),oe==="project"&&!r&&(Re.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?nI(g)||(Re.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):Re.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(Re.webhookPath="Webhook path is required"),f==="api"&&!w.trim()&&(Re.endpoint="API endpoint is required"),I==="simple")G==="command"&&!M.trim()&&(Re.command="Command is required"),G==="ai-prompt"&&!B.trim()&&(Re.prompt="Prompt is required"),G==="create-task"&&!ee.trim()&&(Re.taskDescription="Task description is required"),(ne.trim()&&!Ne.trim()||!ne.trim()&&Ne.trim())&&(Re.model="Both model provider and model ID must be set, or both must be empty");else{L.length===0&&(Re.steps="At least one step is required"),H&&(Re.stepsEditing="Please save or cancel all step edits before saving the routine");const kt=[];L.forEach((Et,jt)=>{Et.name?.trim()||kt.push(`Step ${jt+1}: Name is required`),Et.type==="command"&&!Et.command?.trim()&&kt.push(`Step ${jt+1}: Command is required`),Et.type==="ai-prompt"&&!Et.prompt?.trim()&&kt.push(`Step ${jt+1}: Prompt is required`),Et.type==="create-task"&&!Et.taskDescription?.trim()&&kt.push(`Step ${jt+1}: Task description is required`)}),kt.length>0&&(Re.steps=kt.join("; "))}return de<1e3&&(Re.timeoutMs="Timeout must be at least 1 second (1000ms)"),qe(Re),Object.keys(Re).length===0},[d,f,g,v,y,w,oe,r,I,G,M,B,ee,ne,Ne,L,H,de]),le=i.useCallback(async Re=>{if(Re.preventDefault(),!!ye()){ge(!0);try{let kt=e?.scope??oe??(r?"project":"global");kt==="project"&&!r&&(kt="global");const Et=sI(f,g,y,N,w);let jt,Rt;I==="simple"?G==="command"?jt=M.trim()||void 0:G==="ai-prompt"?Rt=[{id:sp(),type:"ai-prompt",name:d.trim(),prompt:B.trim(),modelProvider:ne.trim()||void 0,modelId:Ne.trim()||void 0}]:Rt=[{id:sp(),type:"create-task",name:d.trim(),taskTitle:U.trim()||void 0,taskDescription:ee.trim(),taskColumn:te,modelProvider:ne.trim()||void 0,modelId:Ne.trim()||void 0}]:Rt=L;const Dt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Et,command:jt,steps:Rt,timeoutMs:de,executionPolicy:P,catchUpPolicy:_,enabled:$,scope:kt};await n(Dt)}finally{Ue.current&&ge(!1)}}},[ye,n,d,m,f,g,y,N,w,I,G,M,B,ne,Ne,U,ee,te,L,de,P,_,$,oe,r,e?.scope,e?.agentId]),Te="routine-name-error",be="routine-cron-error",Le="routine-webhook-error",Je="routine-endpoint-error",nt="routine-command-error",mt="routine-prompt-error",Ie="routine-task-description-error",ze="routine-model-error",st="routine-timeout-error",yt=i.useCallback(Re=>{x(Re),Re!=="custom"&&b(lb[Re])},[]);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:Re=>u(Re.target.value),"aria-invalid":!!Z.name,"aria-describedby":Z.name?Te:void 0}),Z.name&&t.jsx("small",{id:Te,className:"field-error",children:Z.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:Re=>h(Re.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${oe==="global"?" active":""}`,onClick:()=>{we("global"),o?.("global")},role:"radio","aria-checked":oe==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(fl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${oe==="project"?" active":""}`,onClick:()=>{we("project"),o?.("project")},role:"radio","aria-checked":oe==="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(as,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":oe==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Z.scope&&t.jsx("small",{className:"field-error",children:Z.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(Hp,{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(Xp,{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(qp,{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(Kn,{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:Re=>yt(Re.target.value),children:Object.entries(eI).map(([Re,kt])=>t.jsx("option",{value:Re,children:kt},Re))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:Re=>b(Re.target.value),disabled:v!=="custom","aria-invalid":!!Z.cronExpression,"aria-describedby":Z.cronExpression?be:void 0}),Z.cronExpression?t.jsx("small",{id:be,className:"field-error",children:Z.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:Re=>k(Re.target.value),"aria-invalid":!!Z.webhookPath,"aria-describedby":Z.webhookPath?Le:void 0}),Z.webhookPath?t.jsx("small",{id:Le,className:"field-error",children:Z.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:N,onChange:Re=>R(Re.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:w,onChange:Re=>A(Re.target.value),"aria-invalid":!!Z.endpoint,"aria-describedby":Z.endpoint?Je:void 0}),Z.endpoint?t.jsx("small",{id:Je,className:"field-error",children:Z.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${I==="simple"?" active":""}`,onClick:()=>F("simple"),role:"radio","aria-checked":I==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${I==="advanced"?" active":""}`,onClick:()=>F("advanced"),role:"radio","aria-checked":I==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:I==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),I==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${G==="command"?" active":""}`,onClick:()=>X("command"),role:"radio","aria-checked":G==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${G==="ai-prompt"?" active":""}`,onClick:()=>X("ai-prompt"),role:"radio","aria-checked":G==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${G==="create-task"?" active":""}`,onClick:()=>X("create-task"),role:"radio","aria-checked":G==="create-task",children:"Create Task"})]})]}),G==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:M,onChange:Re=>z(Re.target.value),"aria-invalid":!!Z.command,"aria-describedby":Z.command?nt:void 0}),Z.command?t.jsx("small",{id:nt,className:"field-error",children:Z.command}):t.jsx("small",{children:"Shell command to execute."})]}):G==="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:B,onChange:Re=>ve(Re.target.value),rows:3,"aria-invalid":!!Z.prompt,"aria-describedby":Z.prompt?mt:void 0}),Z.prompt?t.jsx("small",{id:mt,className:"field-error",children:Z.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(hs,{id:"routine-model",label:"Model",models:He,value:Xe,onChange:wt,placeholder:"Use default",disabled:Oe}),De&&t.jsx("small",{className:"field-error",children:De}),Z.model&&t.jsx("small",{id:ze,className:"field-error",children:Z.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:U,onChange:Re=>se(Re.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:ee,onChange:Re=>ie(Re.target.value),rows:4,"aria-invalid":!!Z.taskDescription,"aria-describedby":Z.taskDescription?Ie:void 0}),Z.taskDescription?t.jsx("small",{id:Ie,className:"field-error",children:Z.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:te,onChange:Re=>xe(Re.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(hs,{id:"routine-task-model",label:"Executor Model",models:He,value:Xe,onChange:wt,placeholder:"Use default",disabled:Oe}),De&&t.jsx("small",{className:"field-error",children:De}),Z.model&&t.jsx("small",{id:ze,className:"field-error",children:Z.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(ZT,{steps:L,onChange:j,onEditingChange:Q}),Z.steps&&t.jsx("small",{className:"field-error",children:Z.steps}),Z.stepsEditing&&t.jsx("small",{className:"field-error",children:Z.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:de,onChange:Re=>pe(Number(Re.target.value)),"aria-invalid":!!Z.timeoutMs,"aria-describedby":Z.timeoutMs?st:void 0}),Z.timeoutMs?t.jsx("small",{id:st,className:"field-error",children:Z.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:P,onChange:Re=>T(Re.target.value),children:aI.map(Re=>t.jsx("option",{value:Re.value,children:Re.label},Re.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:_,onChange:Re=>C(Re.target.value),children:rI.map(Re=>t.jsx("option",{value:Re.value,children:Re.label},Re.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:$,onChange:Re=>O(Re.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 oI=3e4;function lI({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({}),b=i.useRef(null);xi(b,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),x=i.useCallback(async()=>{try{const E=await Uk(v);l(E),g(S=>{const I={...S};for(const F of E){const G=I[F.id];if(!G||!F.lastRunResult)continue;const X=F.lastRunResult;X.success===G.success&&(X.output||"")===G.output&&(X.error||"")===(G.error||"")&&delete I[F.id]}return I})}catch(E){n(Me(E)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{x()},[x]),i.useEffect(()=>{const E=setInterval(()=>{x()},oI);return()=>clearInterval(E)},[x]),i.useEffect(()=>{const E=S=>{S.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[e,c]);const y=Ai(e),k=i.useCallback(async E=>{try{await Bk(E,v),n("Routine created","success"),d("list"),await x()}catch(S){n(Me(S)||"Failed to create routine","error")}},[n,x,v]),N=i.useCallback(E=>{m(E),d("edit")},[]),R=i.useCallback(async E=>{if(u)try{await _u(u.id,E,v),n("Routine updated","success"),d("list"),m(void 0),await x()}catch(S){n(Me(S)||"Failed to update routine","error")}},[u,n,x,v]),w=i.useCallback(async E=>{try{await Hk(E.id,v),n(`Deleted "${E.name}"`,"success"),await x()}catch(S){n(Me(S)||"Failed to delete routine","error")}},[n,x,v]),A=i.useCallback(async E=>{f(E.id);try{const{result:S}=await qk(E.id,v);g(I=>({...I,[E.id]:{output:S.output||"",error:S.error,success:S.success}})),S.success?n(`"${E.name}" completed successfully`,"success"):n(`"${E.name}" failed: ${S.error||"Unknown error"}`,"error"),await x()}catch(S){n(Me(S)||"Failed to run routine","error")}finally{f(null)}},[n,x,v]),P=i.useCallback(async E=>{try{await _u(E.id,{enabled:!E.enabled},v),n(`"${E.name}" ${E.enabled?"disabled":"enabled"}`,"success"),await x()}catch(S){n(Me(S)||"Failed to toggle routine","error")}},[n,x,v]),T=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const _=i.useCallback(E=>{r(E),d("list"),m(void 0),g({})},[]),C=()=>c==="create"?t.jsx(ip,{onSubmit:k,onCancel:T,scope:a,projectId:s}):c==="edit"&&u?t.jsx(ip,{routine:u,onSubmit:R,onCancel:T,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Kn,{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(xn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(E=>t.jsx(JT,{routine:E,onEdit:N,onDelete:w,onRun:A,onToggle:P,running:h===E.id,lastRunOutput:p[E.id]??null},E.id))}),$=()=>C(),O=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:b,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Kn,{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(Wt,{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:()=>_("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(fl,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>_("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(as,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Kn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:O&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(xn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:$()})]})})}const cI=3e4,Cd=new Map,zc=new Map;function ap(e){return e??"default"}function rp(e){const n=Cd.get(e);return n?Date.now()>=n.expiresAt?(Cd.delete(e),null):n:null}function dI(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 uI(e){const n=zc.get(e);if(n)return n;const s=$r().then(({providers:a,ghCli:r})=>{const l={...dI(a,r),ghCli:r,expiresAt:Date.now()+cI};return Cd.set(e,l),l}).finally(()=>{zc.delete(e)});return zc.set(e,s),s}function cb(e){const n=ap(e),s=rp(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=ap(e),p=rp(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 uI(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 db({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(Wt,{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 mI({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=qs(),[u,m]=i.useState(""),[h,f]=i.useState([]),[p,g]=i.useState([]),[b,v]=i.useState(!1),[x,y]=i.useState(""),[k,N]=i.useState(""),[R,w]=i.useState(""),[A,P]=i.useState(""),[T,_]=i.useState(""),[C,$]=i.useState("default"),[O,E]=i.useState(!1),[S,I]=i.useState([]),[F,G]=i.useState(!1),[X,M]=i.useState(void 0),[z,L]=i.useState(Ms),[j,H]=i.useState(void 0),[Q,de]=i.useState(null),[pe,B]=i.useState([]),[ve,U]=i.useState(!1),[se,ee]=i.useState(!1),ie=i.useRef(null),[te,xe]=i.useState(!1),[ne,_e]=i.useState(""),Ne=i.useRef(null),{hasAiProvider:Se,hasGithub:He,loading:Ye}=cb(s),{nodes:Oe}=El(),ke=i.useCallback(ye=>{G(!0),I(ye)},[]),De=i.useCallback(()=>{G(!1)},[]),re=i.useCallback(async()=>{if(pe.length>0){U(!0);return}ee(!0);try{const ye=await oa(void 0,s);B(ye),U(!0)}catch(ye){const le=Me(ye);o(le?`Failed to load agents: ${le}`:"Failed to load agents","error"),U(!1)}finally{ee(!1)}},[pe.length,s,o]);i.useEffect(()=>{if(!ve)return;const ye=le=>{ie.current&&!ie.current.contains(le.target)&&U(!1)};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[ve]),i.useEffect(()=>{if(!te)return;const ye=le=>{Ne.current&&!Ne.current.contains(le.target)&&(xe(!1),_e(""))};return document.addEventListener("mousedown",ye),()=>document.removeEventListener("mousedown",ye)},[te]);const oe=a.filter(ye=>!h.includes(ye.id)).sort((ye,le)=>{const Te=le.createdAt.localeCompare(ye.createdAt);if(Te!==0)return Te;const be=parseInt(ye.id.slice(ye.id.lastIndexOf("-")+1),10)||0;return(parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0)-be}),we=ne?oe.filter(ye=>ye.id.toLowerCase().includes(ne.toLowerCase())||ye.title&&ye.title.toLowerCase().includes(ne.toLowerCase())||ye.description&&ye.description.toLowerCase().includes(ne.toLowerCase())):oe,Z=(ye,le)=>ye.length>le?ye.slice(0,le)+"…":ye;i.useEffect(()=>{const ye=u.trim()!==""||h.length>0||p.length>0||x!==""||k!==""||R!==""||A!==""||S.length>0||Q!==null||X!==void 0||z!==Ms||j!==void 0;E(ye)},[u,h,p,x,k,R,A,S,Q,X,z,j]);const qe=i.useCallback(async()=>{O&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(ye=>URL.revokeObjectURL(ye.previewUrl)),g([]),m(""),f([]),y(""),N(""),w(""),P(""),_(""),$("default"),I([]),G(!1),de(null),U(!1),M(void 0),L(Ms),H(void 0),E(!1),n())},[O,n,p,d]),Qe=i.useCallback(async()=>{const ye=u.trim();if(!(!ye||b)){v(!0);try{const le=x.indexOf("/"),Te=k.indexOf("/"),be=R.indexOf("/"),Le=await r({title:void 0,description:ye,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:F?S.length>0?S:[]:void 0,...Q?{assignedAgentId:Q}:{},modelPresetId:C==="preset"&&T||void 0,modelProvider:x&&le!==-1?x.slice(0,le):void 0,modelId:x&&le!==-1?x.slice(le+1):void 0,validatorModelProvider:k&&Te!==-1?k.slice(0,Te):void 0,validatorModelId:k&&Te!==-1?k.slice(Te+1):void 0,planningModelProvider:R&&be!==-1?R.slice(0,be):void 0,planningModelId:R&&be!==-1?R.slice(be+1):void 0,thinkingLevel:A!==""?A:void 0,reviewLevel:X,priority:z,nodeId:j});if(p.length>0){const Je=[];for(const nt of p)try{await Ir(Le.id,nt.file,s)}catch{Je.push(nt.file.name)}Je.length>0&&o(`Failed to upload: ${Je.join(", ")}`,"error")}p.forEach(Je=>URL.revokeObjectURL(Je.previewUrl)),g([]),m(""),f([]),y(""),N(""),w(""),P(""),_(""),$("default"),I([]),G(!1),de(null),U(!1),M(void 0),L(Ms),H(void 0),o(`Created ${Le.id}`,"success"),n()}catch(le){o(Me(le)||"Failed to create task","error")}finally{v(!1)}}},[u,h,p,x,k,R,A,b,r,o,n,s,C,T,S,F,Q,X,z,j]),ge=i.useCallback(ye=>{ye.key==="Escape"&&(ye.preventDefault(),qe())},[qe]),Xe=(Q?pe.find(ye=>ye.id===Q):void 0)?.name??Q,wt=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Ne,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>xe(ye=>!ye),disabled:b,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),te&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ne,onChange:ye=>_e(ye.target.value),onClick:ye=>ye.stopPropagation()}),we.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):we.map(ye=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(ye.id)?" selected":""}`,onClick:()=>{f(h.includes(ye.id)?h.filter(le=>le!==ye.id):[...h,ye.id]),xe(!1),_e("")},onMouseDown:le=>le.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ye.id}),t.jsx("span",{className:"dep-dropdown-title",children:Z(ye.title||ye.description||ye.id,30)})]},ye.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(ye=>t.jsxs("span",{className:"dep-chip",children:[ye,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>f(h.filter(le=>le!==ye)),disabled:b,children:"×"})]},ye))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ie,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ve?U(!1):re()},disabled:b,"data-testid":"new-task-agent-button",children:[t.jsx(Mn,{size:12,style:{verticalAlign:"middle"}}),Xe?` ${Xe}`:" Assign agent"]}),ve&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ye=>ye.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),se&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!se&&pe.filter(ye=>ye.state!=="terminated").map(ye=>t.jsxs("div",{className:`dep-dropdown-item${Q===ye.id?" selected":""}`,onMouseDown:le=>le.preventDefault(),onClick:()=>{de(ye.id===Q?null:ye.id),U(!1)},"data-testid":`agent-option-${ye.id}`,children:[t.jsx(Mn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ye.role}),t.jsx("span",{className:"dep-dropdown-title",children:ye.name})]},ye.id)),!se&&pe.filter(ye=>ye.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ye=>ye.preventDefault(),onClick:()=>{de(null),U(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:qe,onKeyDown:ge,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ye=>ye.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:qe,disabled:b,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Ye&&t.jsx(db,{hasAiProvider:Se,hasGithub:He}),t.jsx(qg,{mode:"create",description:u,onDescriptionChange:m,dependencies:h,onDependenciesChange:f,executorModel:x,onExecutorModelChange:y,validatorModel:k,onValidatorModelChange:N,presetMode:C,onPresetModeChange:$,selectedPresetId:T,onSelectedPresetIdChange:_,selectedWorkflowSteps:S,onWorkflowStepsChange:ke,onDefaultOnApplied:De,pendingImages:p,onImagesChange:g,tasks:a,projectId:s,disabled:b,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:qe,planningModel:R,onPlanningModelChange:w,thinkingLevel:A,onThinkingLevelChange:P,reviewLevel:X,onReviewLevelChange:M,priority:z,onPriorityChange:L,nodeId:j,onNodeIdChange:H,nodeOptions:Oe,renderBelowPrimary:wt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:qe,disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Qe,disabled:!u.trim()||b,children:b?"Creating...":"Create Task"})]})]})}):null}function ti(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 op(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function hI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function pI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function fI(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function Oc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function gI(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function bI({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),[b,v]=i.useState(!1),[x,y]=i.useState(null),[k,N]=i.useState(null),[R,w]=i.useState(null),A=i.useCallback(async H=>{l(!0);try{const Q=await gj(s);r(Q),d(null),w(Date.now()),H?.preserveKillResult||y(null)}catch(Q){d(Q instanceof Error?Q.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;A();const H=window.setInterval(()=>{A()},5e3);return()=>{window.clearInterval(H)}},[e,A]),i.useEffect(()=>{if(!e)return;(async()=>{try{const Q=await ra();m(Q.vitestAutoKillEnabled??!0),f(Q.vitestKillThresholdPct??90),N(null)}catch(Q){N(Q instanceof Error?Q.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const H=Q=>{Q.key==="Escape"&&n()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[e,n]);const P=i.useMemo(()=>{if(!a)return[];const H=a.systemStats,Q=Oc(hI(H.heapUsed,H.heapLimit)),de=Oc(pI(H.rss,H.systemTotalMem));return[{label:"RSS",value:ti(H.rss),detail:op(H.rss,H.systemTotalMem),className:de},{label:"Heap Used",value:ti(H.heapUsed),detail:`of ${ti(H.heapTotal)}`,className:Q},{label:"Heap Limit",value:ti(H.heapLimit),detail:"V8 limit"},{label:"External",value:ti(H.external)},{label:"Array Buffers",value:ti(H.arrayBuffers)}]},[a]),T=i.useCallback(async H=>{m(H);try{await Cn({vitestAutoKillEnabled:H}),N(null)}catch(Q){N(Q instanceof Error?Q.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async H=>{const Q=Math.min(99,Math.max(50,Number.isFinite(H)?Math.round(H):90));f(Q);try{await Cn({vitestKillThresholdPct:Q}),N(null)}catch(de){N(de instanceof Error?de.message:"Failed to save vitest settings")}},[]),C=i.useCallback(async()=>{if(!p){if(!b){v(!0);return}g(!0);try{const H=await bj(s);y(H),v(!1),await A({preserveKillResult:!0})}catch(H){d(H instanceof Error?H.message:"Failed to kill vitest processes")}finally{g(!1)}}},[b,p,A,s]);if(!e)return null;const $=a?.systemStats,O=o&&!!a,E=R?`Updated ${new Date(R).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",S=a?.taskStats,I=$?$.systemTotalMem-$.systemFreeMem:0,F=$?fI(I,$.systemTotalMem):"normal",G=$?Oc(F):"",X=$&&Number.isFinite($.systemTotalMem)&&$.systemTotalMem>0?Math.max(0,Math.min(100,I/$.systemTotalMem*100)):0,M=$?`System memory used: ${X.toFixed(1)}% (${ti(I)} of ${ti($.systemTotalMem)})`:"System memory usage unavailable",z=a?.vitestProcessCount,L=x?x.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",j=gI(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(Ma,{}),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:E})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void A(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Qn,{size:16,className:O?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Wt,{})})]})]}),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:P.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:$?.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:$?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:$?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:$?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:$?.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 ${G}`.trim(),children:$?ti(I):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:$?`${op(I,$.systemTotalMem)} of ${ti($.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--${F}`,role:"progressbar","aria-valuenow":Math.round(X),"aria-valuemin":0,"aria-valuemax":100,"aria-label":M,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${F}`,style:{width:`${X}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:$?ti($.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:S?.total??0})]}),Object.entries(S?.byColumn??{}).map(([H,Q])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:H}),t.jsx("dd",{children:Q})]},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:S?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:S?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:S?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:S?.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(iy,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:z??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void C(),disabled:p||z===0,children:[t.jsx(ly,{}),t.jsx("span",{children:b?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked: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 Q=Number.parseInt(H.target.value,10);_(Number.isNaN(Q)?90:Q)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:H=>{const Q=Number.parseInt(H.target.value,10);_(Number.isNaN(Q)?90:Q)},onBlur:()=>{_(h)}})]})]}),x&&t.jsxs("p",{className:L,children:["Killed ",x.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",j]}),k&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:k})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const xI=5e3;function vI(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),b=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let k;o?k=await Du({limit:a,projectId:n,type:s}):k=(await Au({limit:a,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(k),p(k.length===a),k.length>0&&(b.current=k[k.length-1].timestamp)}catch(k){h(k instanceof Error?k.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),x=i.useCallback(async()=>{if(b.current)try{u(!0);let k;o?k=await Du({limit:a,projectId:n,type:s,since:b.current}):k=(await Au({limit:a,type:s,since:b.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(N=>[...N,...k]),p(k.length===a),k.length>0&&(b.current=k[k.length-1].timestamp)}catch(k){h(k instanceof Error?k.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},xI),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:x}}const Fc={"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"},yI={"task:created":t.jsx(xn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Hr,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Qn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Wt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Tn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(qr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Sr,{size:14,className:"activity-icon settings"})};function wI(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 kI({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,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:y,error:k,refresh:N,hasMore:R}=vI({projectId:b,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),w=x.map(C=>({id:C.id,timestamp:C.timestamp,type:C.type,taskId:C.taskId,taskTitle:C.taskTitle,details:C.details,metadata:C.metadata,projectId:C.projectId,projectName:C.projectName})),A=async()=>{try{await Vk(),N(),p(!1)}catch{p(!1)}},P=C=>{a&&a(C)},T=C=>{h(C),l?.(C==="all"?void 0:C)};i.useEffect(()=>{if(!e)return;const C=$=>{$.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[e,n,f]);const _=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:C=>{C.target===C.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(Rr,{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(as,{size:14}),t.jsxs("select",{value:m,onChange:C=>T(C.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(C=>t.jsx("option",{value:C.id,children:C.name},C.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Wo,{size:14}),t.jsxs("select",{value:d,onChange:C=>u(C.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Fc).map(([C,$])=>t.jsx("option",{value:C,children:$},C))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>N(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Qn,{size:14})}),w.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(vn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(C=>C.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Fc[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:[k&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Ts,{size:16}),t.jsx("span",{children:k})]}),w.length===0&&!y&&!k&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Rr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?"No activity matches the current filters":"No activity recorded yet"}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(C=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:yI[C.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:Fc[C.type]}),t.jsx("span",{className:"activity-log-entry-time",children:wI(C.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[C.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>P(C.taskId),"data-testid":"activity-task-link",children:C.taskId}),C.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:C.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:C.details})]}),C.metadata&&Object.keys(C.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof C.metadata.from=="string"&&typeof C.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[C.metadata.from," → ",C.metadata.to]}),typeof C.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${C.metadata.merged?"success":"error"}`,children:C.metadata.merged?"Merged":"Not merged"})]})]})]},C.id))}),R&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:N,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(bt,{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:A,children:"Clear Log"})]})]})})]})}):null}const hr=[{id:"status",label:"Status",icon:Yp},{id:"changes",label:"Changes",icon:Qc},{id:"commits",label:"Commits",icon:Vr},{id:"branches",label:"Branches",icon:Hs},{id:"worktrees",label:"Worktrees",icon:rv},{id:"stashes",label:"Stashes",icon:Ur},{id:"remotes",label:"Remotes",icon:Kp}];function lp({status:e}){switch(e){case"added":case"untracked":return t.jsx(Ox,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Vp,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Dx,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Li,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(Ux,{size:14,className:"gm-file-icon"})}}function cp({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 jI(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 Da(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 NI({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=qs(),[l,c]=i.useState("status"),[d,u]=i.useState(!1),[m,h]=i.useState(null),f=i.useRef(null);xi(f,e,"fusion:git-modal-size");const p=Ai(n),g=jI(a),[b,v]=i.useState(null),[x,y]=i.useState([]),[k,N]=i.useState(new Set),[R,w]=i.useState(""),[A,P]=i.useState(!1),[T,_]=i.useState(null),[C,$]=i.useState(!1),[O,E]=i.useState(null),[S,I]=i.useState(null),F=i.useRef(0),[G,X]=i.useState([]),[M,z]=i.useState(null),[L,j]=i.useState(null),[H,Q]=i.useState(!1),[de,pe]=i.useState(20),[B,ve]=i.useState(""),[U,se]=i.useState([]),[ee,ie]=i.useState(""),[te,xe]=i.useState(""),[ne,_e]=i.useState(""),[Ne,Se]=i.useState(null),[He,Ye]=i.useState([]),[Oe,ke]=i.useState(!1),[De,re]=i.useState(null),[oe,we]=i.useState(null),[Z,qe]=i.useState(!1),[Qe,ge]=i.useState([]),[Ue,Xe]=i.useState([]),[wt,ye]=i.useState(""),[le,Te]=i.useState(null),[be,Le]=i.useState(null),[Je,nt]=i.useState(null),mt=i.useCallback(async()=>{if(e){u(!0),h(null);try{switch(l){case"status":{const ae=await ei(r);v(ae);break}case"changes":{const[ae,Pe]=await Promise.all([ei(r),pa(r)]);v(ae),y(Pe),N(new Set),I(null),_(null),E(null);break}case"commits":{const ae=await Jw(de,r);X(ae);break}case"branches":{const[ae,Pe]=await Promise.all([er(r),ei(r)]);se(ae),v(Pe);break}case"worktrees":{const ae=await Zw(r);ge(ae);break}case"stashes":{const ae=await po(r);Xe(ae);break}case"remotes":{const ae=await ei(r);v(ae);break}}}catch(ae){h(Me(ae)||"Failed to fetch git data"),a(Me(ae)||"Failed to fetch git data","error")}finally{u(!1)}}},[l,e,de,a,r]);i.useEffect(()=>{e&&mt()},[mt,e]),i.useEffect(()=>{if(!e)return;const ae=Pe=>{if(Pe.key==="Escape"){n();return}if((Pe.key==="ArrowUp"||Pe.key==="ArrowDown")&&Pe.altKey){Pe.preventDefault();const Ae=hr.findIndex(W=>W.id===l);Pe.key==="ArrowUp"&&Ae>0?c(hr[Ae-1].id):Pe.key==="ArrowDown"&&Ae<hr.length-1&&c(hr[Ae+1].id)}};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[e,n,l]);const Ie=i.useCallback(async ae=>{try{await Su(ae,r),a(`Staged ${ae.length} file(s)`,"success");const Pe=await pa(r);y(Pe),N(new Set),I(null),_(null),E(null)}catch(Pe){a(Me(Pe)||"Failed to stage files","error")}},[a,r]),ze=i.useCallback(async ae=>{try{await ck(ae,r),a(`Unstaged ${ae.length} file(s)`,"success");const Pe=await pa(r);y(Pe),N(new Set),I(null),_(null),E(null)}catch(Pe){a(Me(Pe)||"Failed to unstage files","error")}},[a,r]),st=i.useCallback(async ae=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${ae.length} file(s)? This cannot be undone.`,danger:!0}))try{await dk(ae,r),a(`Discarded changes to ${ae.length} file(s)`,"success");const[Ae,W]=await Promise.all([pa(r),ei(r)]);y(Ae),v(W),N(new Set),I(null),_(null),E(null)}catch(Ae){a(Me(Ae)||"Failed to discard changes","error")}},[a,r,confirm]),yt=i.useCallback(async ae=>{if(ae.preventDefault(),!!R.trim()){P(!0);try{const Pe=await Cu(R.trim(),r);a(`Committed: ${Pe.hash}`,"success"),w("");const[Ae,W]=await Promise.all([pa(r),ei(r)]);y(Ae),v(W),I(null),_(null),E(null)}catch(Pe){a(Me(Pe)||"Failed to commit","error")}finally{P(!1)}}},[R,a,r]),Re=i.useCallback(async()=>{if(R.trim()){P(!0);try{const ae=x.filter(je=>!je.staged).map(je=>je.file);ae.length>0&&await Su(ae,r);const Pe=await Cu(R.trim(),r);a(`Committed: ${Pe.hash}`,"success"),w("");const[Ae,W]=await Promise.all([pa(r),ei(r)]);y(Ae),v(W),I(null),_(null),E(null)}catch(ae){a(Me(ae)||"Failed to commit","error")}finally{P(!1)}}},[R,x,a,r]),kt=i.useCallback(async(ae,Pe)=>{I({file:ae,staged:Pe}),$(!0),E(null);const Ae=F.current+1;F.current=Ae;try{const W=await lk(ae,Pe,r);if(F.current!==Ae)return;_(W)}catch(W){if(F.current!==Ae)return;const je=Me(W)||"Failed to load file diff";_(null),E(je),a(je,"error")}finally{F.current===Ae&&$(!1)}},[a,r]),Et=i.useCallback(ae=>{N(Pe=>{const Ae=new Set(Pe);return Ae.has(ae)?Ae.delete(ae):Ae.add(ae),Ae})},[]),jt=i.useCallback(async ae=>{if(M===ae){z(null),j(null);return}z(ae),Q(!0);try{const Pe=await Xo(ae,r);j(Pe)}catch(Pe){a(Me(Pe)||"Failed to load diff","error"),j(null)}finally{Q(!1)}},[M,a,r]),Rt=i.useCallback(()=>{pe(ae=>Math.min(ae+20,100))},[]),Dt=i.useMemo(()=>{if(!B.trim())return G;const ae=B.toLowerCase();return G.filter(Pe=>Pe.message.toLowerCase().includes(ae)||Pe.author.toLowerCase().includes(ae)||Pe.shortHash.toLowerCase().includes(ae))},[G,B]),Tt=i.useCallback(async ae=>{if(ae.preventDefault(),!!ee.trim()){u(!0);try{await ek(ee.trim(),te.trim()||void 0,r),a(`Created branch ${ee}`,"success"),ie(""),xe("");const Pe=await er(r);se(Pe)}catch(Pe){a(Me(Pe)||"Failed to create branch","error")}finally{u(!1)}}},[ee,te,a,r]),It=i.useCallback(async ae=>{u(!0);try{await tk(ae,r),a(`Switched to ${ae}`,"success");const[Pe,Ae]=await Promise.all([ei(r),er(r)]);v(Pe),se(Ae)}catch(Pe){a(Me(Pe)||"Failed to checkout branch","error")}finally{u(!1)}},[a,r]),Ut=i.useCallback(async ae=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${ae}"?`,danger:!0})){u(!0);try{await Nu(ae,void 0,r),a(`Deleted branch ${ae}`,"success");const Ae=await er(r);se(Ae)}catch(Ae){if(Me(Ae).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Nu(ae,!0,r),a(`Force deleted branch ${ae}`,"success");const je=await er(r);se(je)}catch(je){a(Me(je)||"Failed to delete branch","error")}}else a(Me(Ae)||"Failed to delete branch","error")}finally{u(!1)}}},[a,r,confirm]),Ft=i.useMemo(()=>{if(!ne.trim())return U;const ae=ne.toLowerCase();return U.filter(Pe=>Pe.name.toLowerCase().includes(ae))},[U,ne]),Jt=i.useCallback(async ae=>{if(Ne===ae){Se(null),Ye([]),re(null),we(null);return}Se(ae),Ye([]),re(null),we(null),ke(!0);try{const Pe=await Xw(ae,10,r);Ye(Pe)}catch{Ye([])}finally{ke(!1)}},[Ne,r]),Vt=i.useCallback(async ae=>{if(De===ae){re(null),we(null);return}re(ae),we(null),qe(!0);try{const Pe=await Xo(ae,r);we(Pe)}catch{we(null)}finally{qe(!1)}},[De,r]),Yt=i.useCallback(()=>{Se(null),Ye([]),re(null),we(null)},[]),Kt=i.useCallback(async ae=>{ae.preventDefault(),Te("create");try{await ak(wt.trim()||void 0,r),a("Changes stashed","success"),ye("");const Pe=await po(r);Xe(Pe)}catch(Pe){a(Me(Pe)||"Failed to stash changes","error")}finally{Te(null)}},[wt,a,r]),qt=i.useCallback(async(ae,Pe=!1)=>{Te(`apply-${ae}`);try{await rk(ae,Pe,r),a(Pe?"Stash popped":"Stash applied","success");const Ae=await po(r);Xe(Ae)}catch(Ae){a(Me(Ae)||"Failed to apply stash","error")}finally{Te(null)}},[a,r]),Bt=i.useCallback(async ae=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${ae}}? This cannot be undone.`,danger:!0})){Te(`drop-${ae}`);try{await ok(ae,r),a("Stash dropped","success");const Ae=await po(r);Xe(Ae)}catch(Ae){a(Me(Ae)||"Failed to drop stash","error")}finally{Te(null)}}},[a,r,confirm]),Xt=i.useCallback(async()=>{Le("fetch");try{const ae=await nk(void 0,r);nt(ae),a(ae.message||"Fetch completed",ae.fetched?"success":"info");const Pe=await ei(r);v(Pe)}catch(ae){a(Me(ae)||"Fetch failed","error")}finally{Le(null)}},[a,r]),an=i.useCallback(async()=>{Le("pull");try{const ae=await sk(r);nt(ae),ae.conflict?a("Merge conflict detected. Resolve manually.","error"):a(ae.message||"Pull completed","success");const Pe=await ei(r);v(Pe)}catch(ae){a(Me(ae)||"Pull failed","error")}finally{Le(null)}},[a,r]),Qt=i.useCallback(async()=>{Le("push");try{const ae=await ik(r);nt(ae),a(ae.message||"Push completed","success");const Pe=await ei(r);v(Pe)}catch(ae){a(Me(ae)||"Push failed","error")}finally{Le(null)}},[a,r]),fe=i.useMemo(()=>x.filter(ae=>ae.staged),[x]),Fe=i.useMemo(()=>x.filter(ae=>!ae.staged),[x]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Xc,{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:mt,disabled:d,title:"Refresh",children:t.jsx(Qn,{size:14,className:d?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Wt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:hr.map(ae=>{const Pe=ae.icon;return t.jsxs("button",{role:"tab","aria-selected":l===ae.id,className:`gm-nav-item${l===ae.id?" active":""}`,onClick:()=>c(ae.id),children:[t.jsx(Pe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:ae.label})]},ae.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[d&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!d&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ts,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:mt,children:"Retry"})]}),l==="status"&&!d&&b&&t.jsx(SI,{status:b,copyToClipboard:g}),l==="changes"&&!d&&t.jsx(CI,{status:b,stagedFiles:fe,unstagedFiles:Fe,selectedFiles:k,toggleFileSelection:Et,onStageFiles:Ie,onUnstageFiles:ze,onDiscardChanges:st,onSelectDiffFile:kt,selectedDiffTarget:S,changeDiff:T,loadingChangeDiff:C,changeDiffError:O,commitMessage:R,setCommitMessage:w,onCommit:yt,onStageAllAndCommit:Re,committing:A}),l==="commits"&&!d&&t.jsx(EI,{commits:Dt,commitSearch:B,setCommitSearch:ve,selectedCommit:M,commitDiff:L,loadingDiff:H,onCommitClick:jt,onLoadMore:Rt,canLoadMore:G.length>=de&&de<100,copyToClipboard:g}),l==="branches"&&!d&&t.jsx(MI,{branches:Ft,branchSearch:ne,setBranchSearch:_e,newBranchName:ee,setNewBranchName:ie,branchBase:te,setBranchBase:xe,onCreateBranch:Tt,onCheckoutBranch:It,onDeleteBranch:Ut,loading:d,allBranches:U,selectedBranch:Ne,branchCommits:He,loadingBranchCommits:Oe,expandedBranchCommit:De,branchCommitDiff:oe,loadingBranchCommitDiff:Z,onSelectBranch:Jt,onBranchCommitClick:Vt,onCloseBranchDetails:Yt}),l==="worktrees"&&!d&&t.jsx(_I,{worktrees:Qe}),l==="stashes"&&!d&&t.jsx(AI,{stashes:Ue,stashMessage:wt,setStashMessage:ye,onCreateStash:Kt,onApplyStash:qt,onDropStash:Bt,stashLoading:le}),l==="remotes"&&!d&&t.jsx(PI,{status:b,remoteLoading:be,lastRemoteResult:Je,onFetch:Xt,onPull:an,onPush:Qt,addToast:a,projectId:r,copyToClipboard:g})]})]})]})}):null}function SI({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(Hs,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(Zi,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(Ts,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Tn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Qi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Br,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Tn,{size:12}),"Up to date"]})]})]})]})]})}function CI({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:b,onStageAllAndCommit:v,committing:x}){const y=s.filter(N=>a.has(`unstaged:${N.file}`)),k=n.filter(N=>a.has(`staged:${N.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(Hs,{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(N=>N.file)),title:"Stage selected",children:[t.jsx(xn,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(N=>N.file)),title:"Discard selected",children:t.jsx(qr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(N=>N.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(N=>{const R=u?.file===N.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>d(N.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),d(N.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${N.file}`),onChange:()=>r(`unstaged:${N.file}`)})}),t.jsx(lp,{status:N.status}),t.jsx("span",{className:"gm-file-name",title:N.file,children:t.jsx("bdo",{dir:"ltr",children:N.file})}),t.jsx(cp,{status:N.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([N.file])},title:"Stage file",children:t.jsx(xn,{size:12})})]},`unstaged:${N.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:[k.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(k.map(N=>N.file)),title:"Unstage selected",children:["Unstage (",k.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(N=>N.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(N=>{const R=u?.file===N.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>d(N.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),d(N.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${N.file}`),onChange:()=>r(`staged:${N.file}`)})}),t.jsx(lp,{status:N.status}),t.jsx("span",{className:"gm-file-name",title:N.file,children:t.jsx("bdo",{dir:"ltr",children:N.file})}),t.jsx(cp,{status:N.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([N.file])},title:"Unstage file",children:t.jsx(Wt,{size:12})})]},`staged:${N.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(Qc,{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(bt,{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(Qc,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:N=>g(N.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Yi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function EI({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(Si,{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:Da(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(Zi,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{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 MI({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:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:y,onBranchCommitClick:k,onCloseBranchDetails:N}){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(Si,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:R=>s(R.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:R=>r(R.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:R=>l(R.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(R=>t.jsx("option",{value:R.name,children:R.name},R.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(xn,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(R=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${R.isCurrent?" current":""}${f===R.name?" selected":""}`,onClick:()=>y(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx(Wn,{size:14,className:"gm-current-icon"}),R.name]}),R.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",R.remote]}),R.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Da(R.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!R.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),d(R.name)},disabled:m,title:"Checkout",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),u(R.name)},disabled:m,title:"Delete",children:t.jsx(vn,{size:14})})]})})]}),f===R.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Vr,{size:14}),"Commits on ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:N,title:"Close","data-testid":"close-branch-details",children:t.jsx(Wt,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>k(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Da(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},R.name))})]})}function _I({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:Ud(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Hs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function AI({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(bt,{size:14,className:"spin"}):t.jsx(Ur,{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(Hs,{size:12}),c.branch]}),t.jsx("span",{children:Da(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(bt,{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(bt,{size:14,className:"spin"}):t.jsx(vn,{size:14})})]})]},c.index))})]})}function PI({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=Z=>{try{return new URL(Z).hostname}catch{return Z.replace(/^git@/,"").split(":")[0]||Z}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,b]=i.useState(null),[v,x]=i.useState(""),[y,k]=i.useState(""),[N,R]=i.useState(null),[w,A]=i.useState(""),[P,T]=i.useState(""),[_,C]=i.useState(!1),[$,O]=i.useState([]),[E,S]=i.useState(!1),[I,F]=i.useState(null),[G,X]=i.useState([]),[M,z]=i.useState(!1),[L,j]=i.useState(null),H=m.find(Z=>Z.name===I),[Q,de]=i.useState(null),[pe,B]=i.useState(null),[ve,U]=i.useState(!1),[se,ee]=i.useState(null),[ie,te]=i.useState(null),[xe,ne]=i.useState(!1);i.useEffect(()=>{_e()},[]),i.useEffect(()=>{e&&e.ahead>0?Ne():e&&e.ahead===0&&O([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!I&&F(m[0].name)},[m]),i.useEffect(()=>{I?Se(I):(X([]),j(null))},[I]),i.useEffect(()=>{I&&!m.find(Z=>Z.name===I)&&F(m.length>0?m[0].name:null)},[m,I]);const _e=async()=>{p(!0);try{const Z=await Fw(c);h(Z)}catch(Z){l(Me(Z)||"Failed to load remotes","error")}finally{p(!1)}},Ne=async()=>{S(!0);try{const Z=await Yw(c);O(Z)}catch{O([])}finally{S(!1)}},Se=async Z=>{z(!0),j(null);try{const qe=await Qw(Z,void 0,10,c);X(qe)}catch(qe){j(Me(qe)||"Failed to load remote commits"),X([])}finally{z(!1)}},He=qs(),Ye=async Z=>{if(Z.preventDefault(),!(!v.trim()||!y.trim())){b("add");try{await Uw(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),k(""),C(!1),await _e()}catch(qe){l(Me(qe)||"Failed to add remote","error")}finally{b(null)}}},Oe=async Z=>{if(await He.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${Z}'?`,danger:!0})){b(`remove-${Z}`);try{await Bw(Z,c),l(`Remote '${Z}' removed`,"success"),await _e()}catch(Qe){l(Me(Qe)||"Failed to remove remote","error")}finally{b(null)}}},ke=async Z=>{if(P.trim()){b(`rename-${Z}`);try{await Hw(Z,P.trim(),c),l(`Remote renamed to '${P.trim()}'`,"success"),R(null),T(""),await _e()}catch(qe){l(Me(qe)||"Failed to rename remote","error")}finally{b(null)}}},De=async Z=>{if(w.trim()){b(`url-${Z}`);try{await qw(Z,w.trim(),c),l("Remote URL updated","success"),R(null),A(""),await _e()}catch(qe){l(Me(qe)||"Failed to update remote URL","error")}finally{b(null)}}},re=i.useCallback(async(Z,qe)=>{if(qe==="ahead"){if(Q===Z){de(null),B(null);return}de(Z),B(null),U(!0);try{const Qe=await Xo(Z);B(Qe)}catch{B(null)}finally{U(!1)}}else{if(se===Z){ee(null),te(null);return}ee(Z),te(null),ne(!0);try{const Qe=await Xo(Z);te(Qe)}catch{te(null)}finally{ne(!1)}}},[Q,se]),oe=Z=>{R(`url-${Z.name}`),A(Z.pushUrl||Z.fetchUrl)},we=Z=>{R(`name-${Z.name}`),T(Z.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:()=>C(!_),disabled:g!==null,title:_?"Cancel":"Add Remote",children:_?t.jsx(Wt,{size:14}):t.jsx(xn,{size:14})})]}),_&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ye,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:Z=>x(Z.target.value),disabled:g==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:Z=>k(Z.target.value),disabled:g==="add",className:"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(bt,{size:12,className:"spin"}):t.jsx(xn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Z=>t.jsxs("div",{className:`gm-remote-selector-item${I===Z.name?" selected":""}`,onClick:()=>F(Z.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[Z.name,Z.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:u(Z.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:qe=>{qe.stopPropagation(),Oe(Z.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(vn,{size:14})})]},Z.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[I&&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:I}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx(Qi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(Br,{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(bt,{size:14,className:"spin"}):t.jsx(Qn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Os,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(bt,{size:14,className:"spin"}):t.jsx(Qi,{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:"}),N===`url-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:Z=>A(Z.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>De(I),disabled:g===`url-${I}`,children:g===`url-${I}`?t.jsx(bt,{size:12,className:"spin"}):t.jsx(Wn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),A("")},title:"Cancel",children:t.jsx(Wt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:H.fetchUrl,children:H.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(H.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Zi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>oe(H),disabled:g!==null,title:"Edit remote URL",children:t.jsx(vs,{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:H.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(H.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Zi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:N===`name-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:P,onChange:Z=>T(Z.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>ke(I),disabled:g===`rename-${I}`,children:g===`rename-${I}`?t.jsx(bt,{size:12,className:"spin"}):t.jsx(Wn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),T("")},title:"Cancel",children:t.jsx(Wt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>we(H),disabled:g!==null,title:"Edit remote name",children:t.jsx(vs,{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(Qi,{size:14}),"Commits to Push (",e.ahead,")"]})}),E?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading..."]}):$.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:$.map(Z=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>re(Z.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Z.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Z.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Da(Z.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Q===Z.hash?t.jsx(rn,{size:14}):t.jsx(_n,{size:14})})]}),Q===Z.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):pe?t.jsxs(t.Fragment,{children:[Z.message&&t.jsx("div",{className:"gm-commit-message-full",children:Z.message}),pe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:pe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:pe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.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(Yp,{size:14}),"Recent commits on ",I]})}),M?t.jsxs("div",{className:"gm-loading",children:[t.jsx(bt,{size:14,className:"spin"}),"Loading commits..."]}):L?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ts,{size:14}),L]}):G.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",I,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:G.map(Z=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>re(Z.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Z.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Z.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Da(Z.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:se===Z.hash?t.jsx(rn,{size:14}):t.jsx(_n,{size:14})})]}),se===Z.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:xe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(bt,{size:16,className:"spin"}),"Loading diff..."]}):ie?t.jsxs(t.Fragment,{children:[Z.message&&t.jsx("div",{className:"gm-commit-message-full",children:Z.message}),ie.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ie.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ie.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.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 pr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function RI(e,n){return e&&n?`${e}/${n}`:""}function TI(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 II(e){switch(e){case"file-text":return Li;case"check-circle":return Tn;case"shield":return ry;case"zap":return Kn;case"eye":return Ba;case"globe":return fl;case"layout-grid":return zi;default:return Tn}}function $I(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 DI({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,b]=i.useState(null),[v,x]=i.useState(!1),[y,k]=i.useState(pr),[N,R]=i.useState(!1),[w,A]=i.useState(!1),[P,T]=i.useState(null),[_,C]=i.useState(null),[$,O]=i.useState({}),[E,S]=i.useState([]),I=i.useRef(null);xi(I,e,"fusion:workflow-steps-modal-size");const F=i.useCallback(async()=>{try{u(!0);const U=await Jr(a);o(U)}catch(U){s(Me(U)||"Failed to load workflow steps","error")}finally{u(!1)}},[s,a]),G=i.useCallback(async()=>{try{const U=await Dr(a);O(U||{})}catch{}},[a]),X=i.useCallback(async()=>{try{const U=await As();S(U.models||[])}catch{}},[]),M=i.useCallback(async()=>{try{h(!0);const U=await Jk();c(U.templates)}catch(U){s(Me(U)||"Failed to load templates","error")}finally{h(!1)}},[s]);i.useEffect(()=>{e&&(F(),M(),G(),X())},[e,F,M,G,X]);const z=i.useCallback(()=>{x(!0),b(null),k(pr)},[]),L=i.useCallback(U=>{b(U.id),x(!1),k({name:U.name,description:U.description,mode:U.mode||"prompt",phase:U.phase||"pre-merge",prompt:U.prompt,scriptName:U.scriptName||"",enabled:U.enabled,defaultOn:U.defaultOn||!1,modelProvider:U.modelProvider||"",modelId:U.modelId||""})},[]),j=i.useCallback(()=>{b(null),x(!1),k(pr)},[]),H=i.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}R(!0);try{const U=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 se={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,...U};await Pu(se,a),s("Workflow step created","success")}else g&&(await Wk(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,...U},a),s("Workflow step updated","success"));x(!1),b(null),k(pr),await F()}catch(U){s(Me(U)||"Failed to save workflow step","error")}finally{R(!1)}},[y,v,g,s,F]),Q=i.useCallback(async U=>{try{await Kk(U,a),s("Workflow step deleted","success"),T(null),g===U&&(b(null),k(pr)),await F()}catch(se){s(Me(se)||"Failed to delete workflow step","error")}},[g,s,F]),de=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}R(!0);try{const U=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},se={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U},ee=await Pu(se,a);x(!1),b(ee.id),A(!0);const ie=await Ru(ee.id,a);k(te=>({...te,prompt:ie.prompt})),s("Prompt refined with AI","success"),await F()}catch(U){s(Me(U)||"Failed to refine prompt","error")}finally{R(!1),A(!1)}return}if(g){A(!0);try{const U=await Ru(g,a);k(se=>({...se,prompt:U.prompt})),s("Prompt refined with AI","success"),await F()}catch(U){s(Me(U)||"Failed to refine prompt","error")}finally{A(!1)}}}},[g,v,y,s,F]),pe=i.useCallback(async U=>{C(U.id);try{await Yk(U.id,a),s(`Added ${U.name} workflow step`,"success"),await F(),p("my-steps")}catch(se){const ee=Me(se);ee?.includes("already exists")?s(`A workflow step named '${U.name}' already exists`,"error"):s(ee||"Failed to add workflow step from template","error")}finally{C(null)}},[s,F]),B=Ai(n);if(!e)return null;const ve=v||g!==null;return t.jsx("div",{className:"modal-overlay open",...B,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:I,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:d?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!ve&&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(Gb,{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(zi,{size:14}),"Templates (",l.length,")"]})]}),f==="my-steps"&&!ve&&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(U=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${U.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:U.name}),t.jsx("span",{className:`wfm-badge ${U.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:U.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(U.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(U.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(U.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(U.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),U.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:U.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>L(U),title:"Edit","aria-label":`Edit ${U.name}`,children:t.jsx(vs,{size:14})}),P===U.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>Q(U.id),title:"Confirm delete","aria-label":`Confirm delete ${U.name}`,children:t.jsx(Wn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>T(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Wt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>T(U.id),title:"Delete","aria-label":`Delete ${U.name}`,children:t.jsx(vn,{size:14})})]})]})},U.id))})]}),f==="templates"&&!ve&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(bt,{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(U=>{const se=II(U.icon),ee=$I(U.category),ie=_===U.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${U.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(se,{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:U.name}),t.jsx("span",{className:ee,children:U.category})]}),t.jsx("div",{className:"wfm-template-desc",children:U.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>pe(U),disabled:ie,"data-testid":`add-template-${U.id}`,children:ie?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(xn,{size:12}),"Add"]})})]})]})},U.id)})})}),ve&&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:U=>k(se=>({...se,name:U.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:U=>k(se=>({...se,description:U.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:()=>k(U=>({...U,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ci,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>k(U=>({...U,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Ei,{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:()=>k(U=>({...U,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:()=>k(U=>({...U,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:de,disabled:!y.description.trim()||w,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[w?t.jsx(bt,{size:12,className:"spin"}):t.jsx(ms,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:U=>k(se=>({...se,prompt:U.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:()=>k(U=>({...U,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Wt,{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(hs,{models:E,value:RI(y.modelProvider,y.modelId),onChange:U=>{const se=TI(U);k(ee=>({...ee,modelProvider:se.provider,modelId:se.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($).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:U=>k(se=>({...se,scriptName:U.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries($).map(([U,se])=>t.jsxs("option",{value:U,children:[U," (",se,")"]},U))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:U=>k(se=>({...se,enabled:U.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:U=>k(se=>({...se,defaultOn:U.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:j,disabled:N,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:H,disabled:N||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:N?"Saving...":v?"Create":"Save"})]})]})]})]})}),!ve&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:z,"data-testid":"add-workflow-step",children:[t.jsx(xn,{size:14}),"Add Workflow Step"]})})]})})}const LI=36e5,zI=3e5,Uc=[{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 OI(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 FI(e){return typeof e!="number"||!Number.isFinite(e)?LI:Math.max(zI,Math.round(e))}function L6(e){if(Uc.some(s=>s.value===e))return[...Uc];const n={value:e,label:`${OI(e)} (custom)`};return[...Uc,n].sort((s,a)=>s.value-a.value)}const UI=4,BI=5*6e4;function HI(e){const n=FI(e?.heartbeatIntervalMs);return Math.max(n*UI,BI)}function qI(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 VI(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=qI(e),c=l||o?.enabled!==!1;if(n==="terminated")return{label:"Terminated",icon:t.jsx(zs,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:a??"Error",icon:t.jsx(Fs,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(ii,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Fs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(ii,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Mn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=HI(o);return u>m?{label:"Unresponsive",icon:t.jsx(Fs,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(lv,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const fr=[{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 WI({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,b]=i.useState("all"),[v,x]=i.useState(()=>{if(typeof window>"u")return"list";const L=Gn("fn-agent-view",a);return L==="board"||L==="list"?L:"list"});i.useEffect(()=>{const L=Gn("fn-agent-view",a);if(L==="board"||L==="list"){x(L);return}x("list")},[a]),i.useEffect(()=>{us("fn-agent-view",v,a)},[a,v]);const[y,k]=i.useState(null),N=i.useRef(null),[R,w]=i.useState(new Set),[A,P]=i.useState(new Map),{confirm:T}=qs(),_=i.useMemo(()=>A.size===0?r:r.map(L=>{const j=A.get(L.id);return j?{...L,state:j}:L}),[r,A]),C=i.useMemo(()=>g==="all"?_.filter(L=>L.state!=="terminated"):_,[_,g]),$=i.useCallback(async()=>{c(!0);try{const j=await oa(g!=="all"?{state:g}:void 0,a);o(j)}catch(L){s(`Failed to load agents: ${Me(L)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&$()},[e,$]),i.useEffect(()=>{if(!e)return;const L=setInterval(()=>{$()},3e4);return()=>{clearInterval(L)}},[e,$]);const O=async()=>{if(m.trim())try{await aj({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),$()}catch(L){s(`Failed to create agent: ${Me(L)}`,"error")}},E=async(L,j)=>{if(!R.has(L)){w(H=>new Set(H).add(L)),P(H=>{const Q=new Map(H);return Q.set(L,j),Q});try{await oj(L,j,a),s(`Agent state updated to ${j}`,"success"),await $(),P(H=>{const Q=new Map(H);return Q.delete(L),Q})}catch(H){P(Q=>{const de=new Map(Q);return de.delete(L),de}),s(`Failed to update state: ${Me(H)}`,"error")}finally{w(H=>{const Q=new Set(H);return Q.delete(L),Q})}}},S=async(L,j)=>{if(await T({title:"Delete Agent",message:`Delete agent "${j}"? This cannot be undone.`,danger:!0}))try{await lj(L,a),s(`Agent "${j}" deleted`,"success"),$()}catch(Q){s(`Failed to delete agent: ${Me(Q)}`,"error")}},I=async(L,j)=>{const H=r.find(Q=>Q.id===L);if(H){if(H.role===j){k(null);return}try{await rj(L,{role:j},a),s(`Agent role updated to ${fr.find(Q=>Q.value===j)?.label??j}`,"success"),k(null),$()}catch(Q){s(`Failed to update role: ${Me(Q)}`,"error")}}},F=(L,j)=>{L.key==="Escape"&&k(null)},G=L=>fr.find(j=>j.value===L)?.label??L,X=L=>fr.find(j=>j.value===L)?.icon??"◆",M=L=>VI(L),z=L=>L.color==="var(--state-active-text)"?"active":L.color==="var(--state-paused-text)"?"paused":L.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:L=>L.target===L.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(Mn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>x("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(zi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>x("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(ed,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void $(),title:"Refresh",disabled:l,children:t.jsx(Qn,{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(Wo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:L=>b(L.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(xn,{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:L=>h(L.target.value),onKeyDown:L=>L.key==="Enter"&&O(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:L=>p(L.target.value),children:fr.map(L=>t.jsxs("option",{value:L.value,children:[L.icon," ",L.label]},L.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void O(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:C.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Mn,{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"?C.map(L=>{const j=M(L),H=z(j);return t.jsxs("div",{className:"agent-board-card","data-state":L.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:X(L.role)}),t.jsx("span",{className:"agent-board-badge","data-state":L.state,children:L.state}),t.jsx("span",{className:"agent-board-health","data-health":H,title:j.label,children:j.icon})]}),t.jsx("div",{className:"agent-board-name",title:L.name,children:L.name}),t.jsx("div",{className:"agent-board-id",children:L.id}),t.jsxs("div",{className:"agent-board-actions",children:[L.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Activate",children:t.jsx(On,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(L.id,L.name),title:"Delete",children:t.jsx(vn,{size:14})})]}),L.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"paused"),disabled:R.has(L.id),title:"Pause",children:t.jsx(ii,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:t.jsx(zs,{size:14})})]}),L.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Resume",children:t.jsx(On,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:t.jsx(zs,{size:14})})]}),L.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"paused"),disabled:R.has(L.id),title:"Pause",children:t.jsx(ii,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:t.jsx(zs,{size:14})})]}),L.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Retry",children:t.jsx(On,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:t.jsx(zs,{size:14})})]}),L.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(L.id,L.name),title:"Delete",children:t.jsx(vn,{size:14})})]})]},L.id)}):C.map(L=>{const j=M(L),H=z(j);return t.jsxs("div",{className:"agent-card","data-state":L.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===L.id?t.jsx("select",{ref:N,className:"select agent-role-select",value:L.role,onChange:Q=>void I(L.id,Q.target.value),onKeyDown:Q=>F(Q,L.id),onBlur:()=>k(null),autoFocus:!0,children:fr.map(Q=>t.jsxs("option",{value:Q.value,children:[Q.icon," ",Q.label]},Q.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>k(L.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&k(L.id)},children:X(L.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:L.name}),t.jsx("span",{className:"agent-id text-secondary",children:L.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":L.state,children:L.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":H,title:j.label,children:[j.icon,!j.stateDerived&&` ${j.label}`]}),t.jsx("span",{className:"badge text-secondary",children:G(L.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[L.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:L.taskId})]}),L.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(L.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[L.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Activate",children:[t.jsx(On,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(L.id,L.name),title:"Delete",children:[t.jsx(vn,{size:14})," Delete"]})]}),L.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"paused"),disabled:R.has(L.id),title:"Pause",children:[t.jsx(ii,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:[t.jsx(zs,{size:14})," Stop"]})]}),L.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Resume",children:[t.jsx(On,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:[t.jsx(zs,{size:14})," Stop"]})]}),L.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"paused"),disabled:R.has(L.id),title:"Pause",children:[t.jsx(ii,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:[t.jsx(zs,{size:14})," Stop"]})]}),L.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Retry",children:[t.jsx(On,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void E(L.id,"terminated"),disabled:R.has(L.id),title:"Stop",children:[t.jsx(zs,{size:14})," Stop"]})]}),L.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void E(L.id,"active"),disabled:R.has(L.id),title:"Start",children:[t.jsx(On,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(L.id,L.name),title:"Delete",children:[t.jsx(vn,{size:14})," Delete"]})]})]})]},L.id)})})]})]})}):null}function KI({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 x=await ww();return u.current&&r(x),x}catch(x){return u.current&&d({kind:"error",message:x instanceof Error?x.message:String(x)}),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 x=>{l(x?"enabling":"disabling"),d(null);try{const y=await Sw(x);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,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(bt,{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(Fn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(GI,{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:[b,t.jsx(dp,{status:a,authenticated:e}),c&&t.jsx(up,{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(Fn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,t.jsx(dp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(up,{action:c})]})}function GI({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 dp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(bt,{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 up({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 JI({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 x=await Nw();return u.current&&r(x),x}catch(x){return u.current&&d({kind:"error",message:x instanceof Error?x.message:String(x)}),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 x=>{l(x?"enabling":"disabling"),d(null);try{const y=await Cw(x);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,b=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(bt,{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(Fn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(YI,{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:[b,t.jsx(mp,{status:a,authenticated:e}),c&&t.jsx(hp,{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(Fn,{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"}),b,t.jsx(mp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(hp,{action:c})]})}function YI({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 mp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(bt,{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 hp({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 QI(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 Bc({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=QI(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(Wn,{size:12}):t.jsx(Zi,{size:12})})]})]},u))}):e})}const XI=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"]),ZI=/^[a-z][a-z0-9-]*$/,pp=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function fp(){return{id:"",name:"",reasoning:!1}}function e4({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,b]=i.useState(e?.apiKey??""),[v,x]=i.useState(e?.models?.length?e.models:[fp()]),[y,k]=i.useState(null),N=v.length>1,R=i.useMemo(()=>y??r??null,[y,r]);function w(_,C){x($=>$.map((O,E)=>E===_?{...O,...C}:O))}function A(_){x(C=>C.length<=1?C:C.filter(($,O)=>O!==_))}function P(){if(!l.trim())return"Provider ID is required.";if(!ZI.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&XI.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const _=new URL(m.trim());if(_.protocol!=="http:"&&_.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return pp.includes(f)?v.length===0?"At least one model is required.":v.some(_=>!_.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function T(_){_.preventDefault();const C=P();k(C),!C&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map($=>({id:$.id.trim(),name:$.name?.trim()||void 0,reasoning:!!$.reasoning,contextWindow:$.contextWindow,maxTokens:$.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:_=>c(_.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:_=>u(_.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:_=>h(_.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:_=>p(_.target.value),disabled:a,children:pp.map(_=>t.jsx("option",{value:_,children:_},_))})]}),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:_=>b(_.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((_,C)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${C+1}`,placeholder:"Model ID",value:_.id,onChange:$=>w(C,{id:$.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${C+1}`,placeholder:"Display name",value:_.name??"",onChange:$=>w(C,{name:$.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!_.reasoning,onChange:$=>w(C,{reasoning:$.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${C+1}`,placeholder:"Context window",type:"number",value:_.contextWindow??"",onChange:$=>w(C,{contextWindow:$.target.value?Number($.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${C+1}`,placeholder:"Max tokens",type:"number",value:_.maxTokens??"",onChange:$=>w(C,{maxTokens:$.target.value?Number($.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(C),disabled:a||!N,"aria-label":`Remove model ${C+1}`,children:"×"})]},`${C}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>x(_=>[..._,fp()]),disabled:a,children:"+ Add model"})]}),R?t.jsx("div",{className:"form-error",children:R}):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 t4=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function n4(e){return!t4.has(e)}function gp(e){return e.filter(n=>n4(n.id))}const aa="fusion_model_onboarding_state",La=[],za=[],dl=!1,ul=!1,Oa={},s4=void 0,$i=["ai-setup","github","project-setup","first-task"],i4={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Bs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(aa);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?a4(n):null}catch{return null}}function a4(e){const n=e.postOnboardingDismissedAt??s4;return{...e,completedSteps:e.completedSteps??La,skippedSteps:e.skippedSteps??za,dismissed:e.dismissed??dl,completed:e.completed??ul,stepData:e.stepData??Oa,...n?{postOnboardingDismissedAt:n}:{}}}function Do(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:La,skippedSteps:za,dismissed:dl,completed:ul,stepData:Oa};try{localStorage.setItem(aa,JSON.stringify(s))}catch{}return}try{const s=Bs(),a=new Date().toISOString(),r=n.completed??ul;let o=n.dismissed??dl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??La,c=n.skippedSteps??s?.skippedSteps??za,d={...s?.stepData??Oa};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(aa,JSON.stringify(u))}catch{}}}function r4(e){if(!(typeof window>"u"))try{const n=Bs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:La,skippedSteps:[e],dismissed:dl,completed:ul,stepData:Oa};localStorage.setItem(aa,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(aa,JSON.stringify(r))}catch{}}function bp(){if(!(typeof window>"u"))try{const e=Bs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:La,skippedSteps:za,dismissed:!1,completed:!0,stepData:Oa};localStorage.setItem(aa,JSON.stringify(s))}catch{}}function Fa(){const e=Bs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function o4(){if(!(typeof window>"u"))try{const e=Bs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:La,skippedSteps:za,dismissed:!1,completed:!1,stepData:Oa,postOnboardingDismissedAt:n};localStorage.setItem(aa,JSON.stringify(s))}catch{}}function ub(){const e=Bs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function l4(){const e=Bs();return!e||Fa()?!1:e.currentStep!=="complete"}function c4(){const e=Bs();if(!e||Fa()||e.currentStep==="complete")return null;const n=e.currentStep,s=i4[n]??m4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function d4(){const e=Bs();return e?e.skippedSteps:za}function u4(e){const n=Bs();return!n||!n.stepData?null:n.stepData[e]??null}function m4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const mb="fusion_onboarding_events",xp="fusion_onboarding_session_id",h4=200,p4=50;function Ys(e,n={}){if(!(typeof window>"u"))try{const s=g4(),a=v4(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:f4()},o=x4([...s,r]);b4(o)}catch{}}function f4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(xp);if(e)return e;const n=vp();return sessionStorage.setItem(xp,n),n}catch{return vp()}}function vp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function g4(){try{const e=localStorage.getItem(mb);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(y4):[]}catch{return[]}}function b4(e){try{localStorage.setItem(mb,JSON.stringify(e))}catch{}}function x4(e){const n=[...e];for(;n.length>h4;)n.splice(0,p4);return n}function v4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function y4(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 w4=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}))??[]}),k4={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"}}},hb={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:"..."}},j4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},yp={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 Ed(e){if(yp[e])return yp[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 Hc=["anthropic","openai","google","gemini","ollama"],N4=["anthropic","claude-cli","droid-cli","openai-codex","gemini","minimax","kimi","zai"],S4={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"},C4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Md(e){return S4[e]??e}function wp(e){const n=Md(e),s=N4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function kp(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=wp(e.id),a=wp(n.id);if(s!==a)return s-a;const r=Md(e.id),o=Md(n.id);if(r!==o)return r.localeCompare(o);const l=C4[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 E4(e,n){const s=n.trim();if(!s)return"API key is required";const a=hb[e]??j4;return a.pattern.test(s)?null:`${Ed(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const pb={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"},M4={description:"AI provider — connect to start using AI models",apiKeyInfo:pb};function _d(e){return k4[e]??M4}function _4(e){return _d(e.id).apiKeyInfo??pb}function A4({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 P4({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=hb[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(Qs,{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:b=>c(e.id,b.target.value),onKeyDown:b=>{b.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(Qs,{summary:"Advanced setup details",children:g})]})}const R4=150;function T4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Bs(),u=d?.currentStep,m=u==="complete"?"ai-setup":$i.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??d4(),[p,g]=i.useState(!0),[b,v]=i.useState(m),[x,y]=i.useState(h),[k,N]=i.useState(f),[R,w]=i.useState(!1),[A,P]=i.useState(""),[T,_]=i.useState(!1),[C,$]=i.useState(null),[O,E]=i.useState(null),[S,I]=i.useState([]),[F,G]=i.useState(void 0),[X,M]=i.useState(!0),[z,L]=i.useState(null),[j,H]=i.useState({}),[Q,de]=i.useState([]),[pe,B]=i.useState(""),[ve,U]=i.useState(!1),[se,ee]=i.useState({}),[ie,te]=i.useState({}),[xe,ne]=i.useState({}),[_e,Ne]=i.useState([]),[Se,He]=i.useState(!1),[Ye,Oe]=i.useState(!1),[ke,De]=i.useState(),re=i.useRef({}),oe=i.useRef(null),we=i.useRef(null),Z=i.useRef(null),[qe,Qe]=i.useState({}),[ge,Ue]=i.useState(()=>Bs()?.stepData?.github?.skipped===!0),Xe=i.useRef(0),wt=i.useRef(l),ye=i.useRef(!1),le=d?.currentStep,Te=!!d&&d.currentStep!=="complete";xi(we,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const K=oe.current;K&&(K.scrollTop=0)},[b]);const[be,Le]=i.useState(()=>Bs()?.stepData?.["ai-setup"]?.skippedProviders??{}),Je=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],nt=Je.findIndex(K=>K.key===b),mt=b==="complete"?Je.length:nt;i.useEffect(()=>{b!=="complete"&&Do(b,{completedSteps:x,skippedSteps:k})},[b,x,k]),i.useEffect(()=>{ye.current||(ye.current=!0,Ys("onboarding:wizard-opened",{source:Te?"resume":"initial",resumedFromStep:le}))},[Te,le]),i.useEffect(()=>{const K=wt.current!=null,Ve=l!=null;!K&&Ve&&w(!0),Ve||w(!1),wt.current=l},[l]);const Ie=i.useRef(m);i.useEffect(()=>{if(Ie.current==="ai-setup"&&b!=="ai-setup"&&!S.some(Ve=>Ve.id!=="github"&&Ve.authenticated)){const Ve={};for(const pt of S)pt.id!=="github"&&!pt.authenticated&&!be[pt.id]&&(Ve[pt.id]=!0);if(Object.keys(Ve).length>0){const pt={...be,...Ve};Le(pt),Do(b,{stepData:{"ai-setup":{skippedProviders:pt}}})}}Ie.current=b},[b,S,be]);const ze=i.useCallback(async()=>{try{const{providers:K,ghCli:Ve}=await $r(),pt=gp(K);I(pt),G(Ve),H(ht=>{const Nt={};for(const[Mt,$t]of Object.entries(ht)){const wn=pt.find(ls=>ls.id===Mt);wn&&!wn.authenticated&&wn.loginInProgress&&(Nt[Mt]=$t)}return Object.keys(Nt).length===Object.keys(ht).length?ht:Nt}),Qe(ht=>{let Nt=!1;const Mt={...ht};for(const[$t,wn]of Object.entries(ht)){if(wn!=="pending")continue;pt.find(Cs=>Cs.id===$t)?.loginInProgress||(delete Mt[$t],Nt=!0)}return Nt?Mt:ht}),Le(ht=>{const Nt={...ht};for(const Mt of pt)Mt.authenticated&&Nt[Mt.id]&&delete Nt[Mt.id];return Object.keys(Nt).length===Object.keys(ht).length?ht:Nt})}catch{}},[]),st=i.useCallback(async()=>{try{const K=await Ew();Ne((K.providers??[]).map(w4))}catch{}},[]),yt=i.useCallback(async K=>{Oe(!0),De(void 0);try{await _w(K),await st(),await As().then(Ve=>de(Ve.models??[])),He(!1)}catch(Ve){De(Me(Ve)||"Failed to create custom provider")}finally{Oe(!1)}},[st]),Re=i.useRef(!1);i.useEffect(()=>{b==="ai-setup"&&st(),Re.current&&ze(),Re.current=b!=="ai-setup"},[b,ze,st]),i.useEffect(()=>{if(!S.some(pt=>pt.loginInProgress))return;const Ve=setInterval(()=>{ze()},2e3);return()=>clearInterval(Ve)},[S,ze]);const kt=S.find(K=>K.id==="github"),Et=!!kt,jt=kt?.authenticated??!1,Rt=kt?.loginInProgress??!1,Dt=F?.authenticated??!1,Tt=jt||Dt,It=!jt&&Dt,Ut=i.useCallback(K=>{if(K.authenticated)return"connected";const Ve=qe?.[K.id];return Ve==="timeout"||Ve==="failed"?"retry":be[K.id]?"skipped":"not-connected"},[qe,be]);function Ft({status:K}){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:pt,className:ht}=Ve[K];return t.jsx("span",{"data-testid":"provider-status-badge",className:ht,"data-status":K,children:pt})}const Jt=i.useCallback(()=>{if(Tt)return"connected";const K=qe.github;return K==="pending"?"pending":K==="failed"||K==="timeout"?"failed":ge?"skipped":"not-connected"},[Tt,qe,ge]);function Vt({status:K}){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:pt,className:ht}=Ve[K];return t.jsx("span",{"data-testid":"github-status-badge",className:ht,"data-status":K,children:pt})}const Yt=i.useCallback(async()=>{try{const K=await As();de(K.models)}catch{}},[]),Kt=i.useCallback(async()=>{try{const K=await ra();if(K.defaultProvider&&K.defaultModelId){const Ve=`${K.defaultProvider}/${K.defaultModelId}`;B(Ve)}}catch{}},[]);i.useEffect(()=>{Promise.all([ze(),Yt(),Kt()]).finally(()=>M(!1))},[ze,Yt,Kt]),i.useEffect(()=>{const K=u4("ai-setup");if(K?.loginOutcomes){const Ve=K.loginOutcomes,pt={};for(const[ht,Nt]of Object.entries(Ve))Nt!=="pending"&&(pt[ht]=Nt);Object.keys(pt).length>0&&Qe(pt)}},[]);const qt=i.useCallback((K,Ve)=>{Do(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[K]:Ve}}}})},[b,x]);i.useEffect(()=>{const K=Object.entries(qe).filter(([Ve,pt])=>pt!=="pending");for(const[Ve,pt]of K)qt(Ve,pt)},[qe,qt]),i.useEffect(()=>()=>{Z.current&&clearInterval(Z.current),Object.values(re.current).forEach(clearTimeout),re.current={}},[]);const Bt=i.useCallback(K=>{Ue(K),Do(b,{completedSteps:x,stepData:{github:{skipped:K}}})},[b,x]),Xt=i.useCallback(K=>K==="complete"?-1:$i.indexOf(K),[]),an=i.useCallback(()=>{y(Ve=>[...new Set([...Ve,b])]),N(Ve=>Ve.filter(pt=>pt!==b)),Ys("onboarding:step-completed",{step:b}),b==="github"&&!jt&&Bt(!1);const K=Xt(b);K>=0&&K<$i.length-1&&v($i[K+1])},[b,jt,Bt,Xt]),Qt=i.useCallback(()=>{N(Ve=>[...new Set([...Ve,b])]),r4(b),Ys("onboarding:step-skipped",{step:b}),b==="github"&&!jt&&Bt(!0);const K=Xt(b);K>=0&&K<$i.length-1&&v($i[K+1])},[b,jt,Bt,Xt]),fe=i.useCallback(()=>{const K=b;y(pt=>pt.filter(ht=>ht!==K)),N(pt=>pt.filter(ht=>ht!==K)),K==="github"&&!jt&&Bt(!1);const Ve=Xt(b);Ve>0&&v($i[Ve-1])},[b,jt,Bt,Xt]),Fe=i.useCallback(()=>{Qt()},[Qt]),ae=i.useCallback(async K=>{Qe(Ve=>{const pt=Ve[K];if(pt&&pt!=="pending"){const{[K]:ht,...Nt}=Ve;return Nt}return Ve}),H(Ve=>{if(!(K in Ve))return Ve;const pt={...Ve};return delete pt[K],pt}),Qe(Ve=>({...Ve,[K]:"pending"})),L(K),Xe.current=0;try{const{url:Ve,instructions:pt}=await Aw(K);pt?.trim()&&H(ht=>({...ht,[K]:pt})),window.open(fi(Ve),"_blank"),Z.current=setInterval(async()=>{if(Xe.current++,Xe.current>=R4){Z.current&&(clearInterval(Z.current),Z.current=null),L(null),Qe(ht=>({...ht,[K]:"timeout"})),H(ht=>{if(!(K in ht))return ht;const Nt={...ht};return delete Nt[K],Nt}),n("Login timed out. Please try again.","warning");return}try{const{providers:ht,ghCli:Nt}=await $r(),Mt=gp(ht);I(Mt),G(Nt),Mt.find(wn=>wn.id===K)?.authenticated&&(Z.current&&(clearInterval(Z.current),Z.current=null),L(null),Qe(wn=>({...wn,[K]:"success"})),H(wn=>{if(!(K in wn))return wn;const ls={...wn};return delete ls[K],ls}),K==="github"&&Bt(!1),n("Login successful","success"))}catch{}},2e3)}catch(Ve){Ve instanceof Error&&Ve.message.includes("already in progress")||Ve&&typeof Ve=="object"&&"status"in Ve&&Ve.status===409?(n("Login already in progress. Cancel it to retry.","warning"),Qe(ht=>({...ht,[K]:"pending"})),ze()):(n(Ve instanceof Error?Ve.message:"Login failed","error"),Qe(ht=>({...ht,[K]:"failed"}))),L(null),H(ht=>{if(!(K in ht))return ht;const Nt={...ht};return delete Nt[K],Nt})}},[n,ze,Bt]),Pe=i.useCallback(async K=>{Z.current&&(clearInterval(Z.current),Z.current=null),L(K),Xe.current=0;try{await Rw(K),await ze(),Qe(Ve=>({...Ve,[K]:"cancelled"})),n("Login cancelled","success")}catch(Ve){n(Me(Ve)||"Failed to cancel login","error")}finally{L(null),H(Ve=>{if(!(K in Ve))return Ve;const pt={...Ve};return delete pt[K],pt})}},[n,ze]),Ae=i.useCallback((K,Ve)=>{ee(ht=>({...ht,[K]:Ve}));const pt=re.current[K];pt&&(clearTimeout(pt),delete re.current[K]),te(ht=>{if(!ht[K])return ht;const Nt={...ht};return delete Nt[K],Nt}),ne(ht=>{if(!ht[K])return ht;const Nt={...ht};return delete Nt[K],Nt})},[]),W=i.useCallback(()=>{const K=oe.current;if(!K)return;const Ve=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof K.scrollTo=="function"){K.scrollTo({top:0,behavior:Ve?"auto":"smooth"});return}}catch{}K.scrollTop=0},[]),je=i.useCallback(async(K,Ve)=>{const pt=(Ve??se[K]??"").trim(),ht=E4(K,pt);if(ht){te(Mt=>({...Mt,[K]:ht}));return}const Nt=re.current[K];Nt&&(clearTimeout(Nt),delete re.current[K]),L(K),te(Mt=>{const $t={...Mt};return delete $t[K],$t}),ne(Mt=>{if(!Mt[K])return Mt;const $t={...Mt};return delete $t[K],$t});try{await Tw(K,pt),await ze(),W(),ee(Mt=>{const $t={...Mt};return delete $t[K],$t}),te(Mt=>{if(!Mt[K])return Mt;const $t={...Mt};return delete $t[K],$t}),ne(Mt=>({...Mt,[K]:"✓ Key saved"})),re.current[K]=setTimeout(()=>{ne(Mt=>{if(!Mt[K])return Mt;const $t={...Mt};return delete $t[K],$t}),delete re.current[K]},3e3),n("API key saved","success")}catch(Mt){const $t=Mt instanceof TypeError&&Mt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Mt instanceof Error?Mt.message:"Failed to save API key";te(wn=>({...wn,[K]:$t})),ne(wn=>{if(!wn[K])return wn;const ls={...wn};return delete ls[K],ls}),n($t,"error")}finally{L(null)}},[se,n,ze,W]),ce=i.useCallback(async K=>{L(K);try{await Iw(K),await ze(),n("API key removed","success")}catch(Ve){n(Ve instanceof Error?Ve.message:"Failed to clear API key","error")}finally{L(null)}},[n,ze]),$e=i.useCallback(async K=>{L(K);try{await Pw(K),await ze(),n("Logged out","success")}catch(Ve){n(Ve instanceof Error?Ve.message:"Logout failed","error")}finally{L(null)}},[n,ze]),it=i.useCallback(K=>{B(K)},[]),vt=i.useCallback(async()=>{try{const K={modelOnboardingComplete:!0};if(pe){const Ve=pe.indexOf("/"),pt=Ve!==-1?pe.slice(0,Ve):void 0,ht=Ve!==-1?pe.slice(Ve+1):pe,Nt=Q.find(Mt=>Mt.id===ht);Nt?(K.defaultProvider=Nt.provider,K.defaultModelId=Nt.id):pt&&ht&&(K.defaultProvider=pt,K.defaultModelId=ht)}await Cn(K),bp()}catch{}},[pe,Q,Cn,bp]),tn=i.useCallback(async()=>{const K=[...new Set([...x,"first-task"])];U(!0);try{await vt(),Ys("onboarding:completed",{completedSteps:K,skippedSteps:k}),y(K),N(Ve=>Ve.filter(pt=>pt!=="first-task")),v("complete")}finally{U(!1)}},[vt,x,k]),Pt=i.useCallback(async()=>{if(!s)return;const K=A.trim();if(!K){$("Please enter a task description.");return}$(null),_(!0);let Ve=!1;try{const pt=await Qo({description:K,source:{sourceType:"dashboard_ui"}},s);E(pt),w(!0),Ys("onboarding:first-task-created",{taskId:pt?.id}),n("Task created","success"),Ve=!0}catch(pt){const ht=pt instanceof Error?pt.message:"Something went wrong creating your task. Please try again.";$(ht),n(ht,"error")}finally{_(!1)}Ve&&vt()},[s,A,n,vt]),Lt=i.useCallback(async()=>{U(!0);try{await vt()}finally{U(!1)}Ys("onboarding:open-new-task",{}),r?.()},[vt,r]),zt=i.useCallback(async()=>{if(Tt){U(!0);try{await vt()}finally{U(!1)}g(!1),e(),Ys("onboarding:open-github-import",{}),o?.()}},[vt,Tt,e,o]),yn=i.useCallback(async()=>{Ys("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:k}),U(!0);try{await Cn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[b,x,k,e]),ue=i.useCallback(()=>{Ys("onboarding:finished",{}),g(!1),e()},[e]),lt=i.useCallback(()=>{const K=l??O;K&&(vt(),c?.(K),e())},[l,O,vt,c,e]),ut=i.useCallback(()=>{vt(),e()},[vt,e]);if(!p)return null;const dt=Jt(),at=S.filter(K=>K.id!=="github"),St=[...at].sort(kp),he=St.some(K=>!K.type||K.type==="oauth"),ct=St.some(K=>K.type==="api_key"),Zt=at.filter(K=>K.authenticated),Sn=Zt.length>0,In=!!s,Hn=b==="github"&&!Sn,Xn=(()=>{if(!pe)return"";const K=pe.indexOf("/"),Ve=K===-1?void 0:pe.slice(0,K),pt=K===-1?pe:pe.slice(K+1),ht=Q.find(Nt=>Nt.id===pt&&(!Ve||Nt.provider===Ve));return ht?.name?ht.name:Ve?`${Ed(Ve)} ${pt}`:pe})(),jn=[];if(In?jn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):jn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Sn){const K=Ed(Zt[0]?.id??"");jn.push({label:"AI Provider",status:"connected",detail:`${K} connected — AI agents can work on tasks`})}else at.length>0&&at.some(K=>be[K.id])?jn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):jn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Tt?jn.push({label:"GitHub",status:"connected",detail:It?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Et||ge?jn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):jn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Xn&&jn.push({label:"Default Model",status:"connected",detail:Xn});const Pn=l??O,rs=Pn?.description?.split(`
682
- `)[0]?.trim()||Pn?.title||"",os=new Set(Hc),cn=St.filter(K=>os.has(K.id)).sort((K,Ve)=>{const pt=Hc.indexOf(K.id),ht=Hc.indexOf(Ve.id);return pt!==ht?pt-ht:kp(K,Ve)}),$n=St.filter(K=>K.authenticated&&!os.has(K.id)),nn=St.filter(K=>!K.authenticated&&!os.has(K.id)),_t=K=>{if(K.id==="droid-cli"&&K.type==="cli")return t.jsx(JI,{authenticated:K.authenticated,onToggled:()=>{ze()}},K.id);if(K.id==="claude-cli"&&K.type==="cli")return t.jsx(KI,{authenticated:K.authenticated,onToggled:()=>{ze()}},K.id);if(K.type==="api_key"){const Ve=_d(K.id),pt=_4(K);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Fn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Gp,{size:14,className:"onboarding-provider-key-icon"}),K.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Ve.description}),t.jsx(Ft,{status:Ut(K)}),K.authenticated&&K.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",K.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(P4,{provider:K,apiKeyInfo:pt,inputValue:se[K.id]??"",isSaving:z===K.id,error:ie[K.id],success:xe[K.id],isConnected:K.authenticated,onInputChange:Ae,onSave:je,onClear:ce})})]},K.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Fn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:K.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:_d(K.id).description}),t.jsx(Ft,{status:Ut(K)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===K.id?K.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 Pe(K.id),children:"Cancel"})]}):K.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 Pe(K.id),children:"Cancel"})]}):K.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>$e(K.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>ae(K.id),children:"Login"})}),(z===K.id||K.loginInProgress)&&j[K.id]&&t.jsx(Bc,{instructions:j[K.id],"data-testid":`onboarding-login-instructions-${K.id}`}),qe[K.id]==="timeout"&&z!==K.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),qe[K.id]==="failed"&&z!==K.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},K.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:we,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Kn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Os,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(pu,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(pu,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Tn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:yn,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Wt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Je.map((K,Ve)=>{const pt=mt>Ve,ht=x.includes(K.key)&&pt,Nt=k.includes(K.key)&&!x.includes(K.key)&&pt,Mt=ht||Nt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Ve>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Ve<=mt?"done":""}`}),Mt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${ht?"done":""} ${Nt?"skipped":""}`,onClick:()=>v(K.key),"aria-label":`Go back to ${K.label}`,title:`Review ${K.label}`,children:[t.jsx("span",{className:"step-number",children:ht?t.jsx(Tn,{size:14}):Nt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ve+1}),t.jsx("span",{className:"step-label",children:K.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${ht?"done":""} ${Nt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:ht?t.jsx(Tn,{size:14}):Nt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ve+1}),t.jsx("span",{className:"step-label",children:K.label})]})]},K.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:oe,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!X&&S.length>0&&(()=>{const K=S.filter(Mt=>Mt.id!=="github"&&Mt.authenticated).length,Ve=S.filter(Mt=>Mt.id!=="github").length,pt=Object.keys(be).filter(Mt=>!S.find($t=>$t.id===Mt)?.authenticated).length;if(Ve===0)return null;let ht="onboarding-provider-summary",Nt="";return K>0?(ht+=" onboarding-provider-summary--connected",Nt=`✓ ${K} of ${Ve} provider${Ve!==1?"s":""} connected`):pt>0?(ht+=" onboarding-provider-summary--skipped",Nt=`${pt} provider${pt!==1?"s":""} skipped`):(ht+=" onboarding-provider-summary--none",Nt="No providers connected yet"),t.jsx("div",{className:ht,"data-testid":"provider-summary",children:Nt})})(),t.jsx(Qs,{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."})}),S.length>0&&!S.some(K=>K.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),X?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(bt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):S.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),cn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:cn.map(K=>_t(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),$n.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:$n.map(K=>_t(K))})]}),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(Qs,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Q.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(hs,{models:Q,value:pe,onChange:it,placeholder:"Select a default model…",label:"Default model"})}),pe&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Q.find(K=>K.id===pe)?.name??pe]})})]}),t.jsx(Qs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[nn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:nn.map(K=>_t(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),_e.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:_e.map(K=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Fn,{provider:K.id,size:"sm"}),t.jsx("span",{children:K.name||K.id})]},K.id))}):null,Se?t.jsx(e4,{onSave:yt,onCancel:()=>{He(!1),De(void 0)},saving:Ye,error:ke}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>He(!0),children:"Add custom provider"})]})}),he&&t.jsx(Qs,{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."})}),ct&&t.jsx(Qs,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Tt?t.jsx("p",{className:"model-onboarding-description",children:It?"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."}),!Tt&&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"})]})}),Hn&&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(Qs,{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."})}),Et?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(Os,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Vt,{status:dt})})]}),jt&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>$e("github"),children:"Disconnect"}))]}),(dt==="not-connected"||dt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="github"||Rt?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 Pe("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>ae("github"),children:[t.jsx(Os,{size:16}),"Connect"]}),(z==="github"||Rt)&&j.github&&t.jsx(Bc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]}),dt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:It?"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."}),dt==="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:()=>ae("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Fe,children:"Skip for now"})]})]}),dt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),dt==="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:()=>ae("github"),children:"Connect anyway"})})]}),dt==="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(Fn,{provider:"github",size:"lg"})}),It?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:It?"Continue with gh CLI auth →":"Continue without GitHub →"}),It&&(z==="github"||Rt?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(bt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>ae("github"),children:[t.jsx(Fn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),It&&(z==="github"||Rt)&&j.github&&t.jsx(Bc,{instructions:j.github,"data-testid":"onboarding-login-instructions-github"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),In?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(Qs,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&Pn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Tn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:Pn.id}),rs&&t.jsx("p",{className:"onboarding-task-created__description",children:rs}),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:lt,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:ut,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[In?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:A,onChange:K=>{P(K.target.value),$(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:Pt,disabled:T,"data-testid":"onboarding-first-task-submit",children:T?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),C&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:C}),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(A4,{items:jn}),In&&t.jsxs(t.Fragment,{children:[t.jsx(Qs,{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:Lt,disabled:ve,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(xn,{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${Tt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:zt,disabled:ve||!Tt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Os,{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"}),!Tt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Tn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yn,disabled:ve,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Qt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:an,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:fe,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Qt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:an,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:fe,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:an,disabled:!In,children:"Next →"})]}),b==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:fe,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,disabled:ve,children:ve?t.jsxs(t.Fragment,{children:[t.jsx(bt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:ue,children:[t.jsx(Tn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function fb({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 I4=i.lazy(()=>kn(()=>import("./SetupWizardModal-tTXAm1Wb.js"),__vite__mapDeps([9,1,10,11,12,4,5,13])).then(e=>({default:e.SetupWizardModal}))),$4=i.lazy(()=>kn(()=>import("./SettingsModal-c9MG4sxl.js"),__vite__mapDeps([14,1,15,16,17,2,4,5,18])).then(e=>({default:e.SettingsModal})));function D4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{kn(()=>import("./SettingsModal-c9MG4sxl.js"),__vite__mapDeps([14,1,15,16,17,2,4,5,18]))},{timeout:1500})}function L4({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[b,v]=i.useState(null),x=c.detailTask?(()=>{const A=n.find(P=>P.id===c.detailTask?.id);return A?"prompt"in c.detailTask?{...c.detailTask,...A,prompt:c.detailTask.prompt,log:c.detailTask.log}:A:c.detailTask})():null,y=p??c.closeSettings,k=i.useCallback(()=>{c.openNewTask()},[c]),N=i.useCallback(()=>{c.openGitHubImport()},[c]),R=i.useCallback(A=>{v(null),c.closeModelOnboarding(),c.openDetailTask(A)},[c]),w=i.useCallback(async A=>{const P=await u.handleModalCreate(A);return c.modelOnboardingOpen&&v(P),P},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),i.useEffect(()=>{D4()},[]),t.jsxs(t.Fragment,{children:[x&&t.jsx(Vi,{children:t.jsx(kP,{task:x,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,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(Vi,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx($4,{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(jR,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Vi,{children:t.jsx(ER,{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(Vi,{children:t.jsx(LR,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(aT,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(oT,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(_T,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(TT,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(BT,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(bI,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(lI,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Vi,{children:t.jsx(mI,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(kI,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:A=>{const P=n.find(T=>T.id===A);P&&c.openDetailTask(P)}}),t.jsx(Vi,{children:t.jsx(NI,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Vi,{children:t.jsx(DI,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(WI,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(I4,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(T4,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:N,firstCreatedTask:b,onViewTask:R}),t.jsx(fb,{toasts:o,onRemove:l})]})}function z4({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 Ad=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function O4(e,n){if(n==="ready")return"done";const s=Ad.findIndex(r=>r.id===n),a=Ad.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function F4({stage:e}){const[n]=i.useState(()=>Cy());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:Ad.map(s=>{const a=O4(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(bt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const U4=5e3;function B4(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function H4(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++,nl(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 q4(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 fj(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()},U4),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=H4(e,s,a),g=B4(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const V4={planning:oi,subtask:ea,mission_interview:ks,milestone_interview:ks,slice_interview:ks},W4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function K4({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=qs(),[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}=Ka(),g=i.useMemo(()=>da(),[]);if(i.useEffect(()=>{if(!l)return;const x=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[l]),i.useEffect(()=>{const x=new Set,y=new Map;for(const k of e){const N=p.get(k.id),R=[k.status,k.updatedAt,N?.tabId??k.lockedByTab??"",N?.stale?"stale":"fresh"].join("|"),w=h.current.get(k.id);w&&w!==R&&x.add(k.id),y.set(k.id,R)}if(h.current=y,x.size!==0)return u(x),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 b=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(x=>!x),title:`${b} background AI task${b!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(bt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Jc,{size:12}),t.jsxs("span",{children:["AI ",b]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(x=>{const y=V4[x.type],k=x.status==="generating",N=x.status==="awaiting_input",R=x.status==="error",w=p.get(x.id),A=w?.tabId??x.lockedByTab??null,P=!!(A&&A!==g&&!w?.stale),T=d.has(x.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()=>{P&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(x),c(!1))},children:[R?t.jsx(Ts,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:x.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[R?"Failed":W4[x.type],k&&" — generating...",N&&!P&&" — needs input",N&&P&&" — active in another tab"]})]}),k&&t.jsx(bt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),N&&!P&&t.jsx(Jc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),N&&P&&t.jsx(vl,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(x.id)},title:"Dismiss",children:t.jsx(Wt,{size:12})})]},x.id)})})]})]})}function G4(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 J4(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:On};case"paused":return{label:"Paused",color:"var(--triage)",icon:ii};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Kn}}}function Y4({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}=q4(e,n,s,d),[g,b]=i.useState(!1),v=i.useMemo(()=>J4(h.executorState),[h.executorState]),x=i.useMemo(()=>G4(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(wl,{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(K4,{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:()=>b(k=>!k),"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(as,{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(Mi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const Q4={planning:oi,subtask:ea,mission_interview:ks,milestone_interview:ks,slice_interview:ks},X4={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},gb="fusion:session-banner-dismissed";function Nr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Z4(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(gb);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:Nr(r);s.set(a,o)}return s}catch{return new Map}}function e$(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(gb,JSON.stringify(n))}catch{}}const Ni=Z4();function t$({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{e$(Ni),o(g=>g+1)};i.useEffect(()=>{if(Ni.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let b=!1;for(const[v,x]of Ni){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Ni.delete(v),b=!0;continue}Nr(y.updatedAt)>x&&(Ni.delete(v),b=!0)}b&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const b=Ni.get(g.id);return b===void 0?!0:Nr(g.updatedAt)>b}),[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=>{Ni.set(g.id,Math.max(Nr(g.updatedAt),Date.now())),l()},f=g=>{Ni.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const b of c)Ni.set(b.id,Math.max(Nr(b.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(Ts,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Wt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const b=Q4[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(Ts,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":X4[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(Wt,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const bb="fusion:cli-binary-banner-dismissed";function n$(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(bb)==="1"}catch{return!1}}function s$(){if(!(typeof window>"u"))try{window.localStorage.setItem(bb,"1")}catch{}}function i$({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>n$()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let h=!1;return kw().then(f=>{h||s(f)}).catch(()=>{}),()=>{h=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const h=await jw();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(()=>{s$(),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(Wt,{size:16})})]})}function a$({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(Wt,{size:16,"aria-hidden":"true"})})]})}function r$({onResume:e}){const n=c4();if(!n)return null;const s=n.completedSteps.length,a=$i.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(ms,{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:()=>{Ys("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(On,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function o$({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Fa(),a=ub(),[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 x=!1;return(async()=>{try{o(!0),c(!1);const[k,N]=await Promise.all([$r(),ra()]);if(x)return;const R=k.providers??[],w=R.find(C=>C.id==="github"),P=!R.some(C=>C.id!=="github"&&C.authenticated),T=!N.defaultProvider&&!N.defaultModelId,_=w?!w.authenticated:!1;h({needsAiProvider:P,needsDefaultModel:T,needsGitHub:_})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,a]);const f=i.useCallback(()=>{o4(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),b=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Kn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:Gp}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:Os}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,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(oi,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const y=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.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:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(Wt,{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 qc(e){return e>99?"99+":String(e)}function c$({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:b,onOpenTodos:v,todosOpen:x=!1,onOpenGitHubImport:y,onOpenPlanning:k,onResumePlanning:N,activePlanningSessionCount:R=0,onOpenUsage:w,onRunScript:A,projectId:P,onViewAllProjects:T,showSkillsTab:_,experimentalFeatures:C,onOpenNodes:$,pluginDashboardViews:O=[]}){const E=la(),[S,I]=i.useState(!1),[F,G]=i.useState(!1),[X,M]=i.useState({}),[z,L]=i.useState(!1),j=i.useMemo(()=>Object.entries(X).sort(([ke],[De])=>ke.localeCompare(De)),[X]);i.useEffect(()=>{if(!F)return;let ke=!1;return L(!0),Dr(P).then(De=>{ke||M(De)}).catch(()=>{ke||M({})}).finally(()=>{ke||L(!1)}),()=>{ke=!0}},[F,P]);const H=i.useCallback(()=>I(!1),[]),Q=i.useCallback(ke=>{H(),ke?.()},[H]);if(i.useEffect(()=>{if(!S)return;const ke=De=>{De.key==="Escape"&&I(!1)};return document.addEventListener("keydown",ke),()=>document.removeEventListener("keydown",ke)},[S]),E!=="mobile"||a||r)return null;const de=R>0&&N?N:k,pe=O.some(ke=>ke.pluginId==="fusion-plugin-roadmap"),B=!!C?.roadmap&&!pe,ve=!!_,U=!!C?.todoView,se=B&&(!ve||e==="roadmaps"),ee=ve&&(!B||e!=="roadmaps"),ie=ve&&!ee,te=ke=>ke.pluginId==="fusion-plugin-dependency-graph"&&ke.view.viewId==="graph",xe=O.filter(ke=>ke.view.placement==="primary").sort((ke,De)=>(ke.view.order??Number.MAX_SAFE_INTEGER)-(De.view.order??Number.MAX_SAFE_INTEGER)),ne=O.find(te)??null,Se=(ne?[ne,...xe.filter(ke=>!te(ke))]:xe).slice(0,1),He=new Set(Se.map(ke=>`${ke.pluginId}:${ke.view.viewId}`)),Ye=O.filter(ke=>!He.has(`${ke.pluginId}:${ke.view.viewId}`)).sort((ke,De)=>(ke.view.order??Number.MAX_SAFE_INTEGER)-(De.view.order??Number.MAX_SAFE_INTEGER)),Oe=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||x&&U||e==="roadmaps"&&!se||e==="skills"&&!ee||e.startsWith("plugin:")&&!Se.some(ke=>Er(ke.pluginId,ke.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(zi,{}),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(Mn,{}),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(ks,{}),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(Ci,{}),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(ta,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:qc(u)})]}),ee&&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(Kn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),se&&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(td,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),Se.map(ke=>{const De=Er(ke.pluginId,ke.view.viewId),re=el(ke.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===De?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ke.pluginId}-${ke.view.viewId}`,role:"tab","aria-selected":e===De,onClick:()=>n(De),children:[t.jsx(re,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ke.view.label})]},`${ke.pluginId}:${ke.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Oe?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>I(ke=>!ke),children:[t.jsx(Yc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),S&&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:()=>Q(d),children:[t.jsx(ta,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:qc(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>Q(l),children:[t.jsx(Fs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>Q(c),children:[t.jsx(Ma,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>Q(m),children:[t.jsx(Hs,{}),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:()=>Q(g),children:[t.jsx(Ei,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>G(ke=>!ke),"aria-expanded":F,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(_n,{size:14,className:`mobile-more-chevron${F?" mobile-more-chevron--open":""}`})})]}),F&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:z?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(bt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):j.length>0?t.jsxs(t.Fragment,{children:[j.map(([ke,De])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ke}`,onClick:()=>{A&&A(ke,De),H(),G(!1)},children:[t.jsx(On,{}),t.jsx("span",{children:ke})]},ke)),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(),G(!1),p()},children:[t.jsx(si,{}),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(),G(!1),p()},children:[t.jsx(si,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>Q(b),children:[t.jsx(as,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>Q(de),children:[t.jsx(oi,{}),t.jsx("span",{children:"Planning"}),R>0&&t.jsx("span",{className:"mobile-more-item-badge",children:qc(R)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>Q(h),children:[t.jsx(Jo,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>Q(f),children:[t.jsx(Mi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>Q(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:()=>Q(w),children:[t.jsx(Fs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>Q(T),children:[t.jsx(gl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>Q(()=>n("documents")),children:[t.jsx(Li,{}),t.jsx("span",{children:"Documents"})]}),ie&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>Q(()=>n("skills")),children:[t.jsx(Kn,{}),t.jsx("span",{children:"Skills"})]}),B&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>Q(()=>n("roadmaps")),children:[t.jsx(td,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>Q(()=>n("research")),children:[t.jsx(Si,{}),t.jsx("span",{children:"Research"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>Q(()=>n("insights")),children:[t.jsx(ms,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>Q(()=>n("memory")),children:[t.jsx(Pr,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{Q(()=>n("dev-server"))},children:[t.jsx(Ma,{}),t.jsx("span",{children:"Dev Server"})]}),C?.nodesView&&$&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>Q($),children:[t.jsx(zv,{}),t.jsx("span",{children:"Nodes"})]}),U&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>Q(()=>v?.()),children:[t.jsx(Ko,{}),t.jsx("span",{children:"Todos"})]}),Ye.map(ke=>{const De=Er(ke.pluginId,ke.view.viewId),re=el(ke.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ke.pluginId}-${ke.view.viewId}`,onClick:()=>Q(()=>n(De)),children:[t.jsx(re,{}),t.jsx("span",{children:ke.view.label})]},`${ke.pluginId}:${ke.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:()=>Q(o),children:[t.jsx(Sr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function d$({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(Mn,{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 Sa="__fn_agent__";function xb(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Lo(e,n,s){const a=typeof e=="string"?e.trim():"",r=xb(n,s),o=a||(r.modelProvider&&r.modelId?Sa:"");return o?{agentId:o,...r}:null}function zo(e,n,s){const a=xb(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}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 jp(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:u$(e.metadata),createdAt:e.createdAt}}function m$(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,b]=i.useState(""),[v,x]=i.useState(""),[y,k]=i.useState([]),[N,R]=i.useState(""),w=i.useRef(null),A=i.useRef(!1),P=i.useRef(null),T=i.useRef(""),_=i.useRef(null),C=i.useRef(""),$=i.useRef(null);i.useEffect(()=>{T.current=N},[N]);const O=i.useCallback(async()=>{c(!0);try{const de=await Ou(e);o(de.sessions)}catch(de){console.error("[useQuickChat] Failed to refresh sessions:",de)}finally{c(!1)}},[e]),E=i.useCallback(async de=>{const pe={agentId:de.agentId};return de.modelProvider&&de.modelId&&(pe.modelProvider=de.modelProvider,pe.modelId=de.modelId),(await HN(pe,e)).session},[e]),S=i.useCallback(async(de,pe,B)=>{const ve=Lo(de,pe,B);if(!ve)return;const U=zo(ve.agentId,ve.modelProvider,ve.modelId);c(!0);try{const{session:se}=await BN({agentId:ve.agentId,modelProvider:ve.modelProvider,modelId:ve.modelId},e);if(se)a(se),C.current=U;else{const ee=await E(ve);a(ee),C.current=U}}catch(se){console.error("[useQuickChat] Failed to initialize session:",se),n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,E]),I=i.useCallback(async()=>{if(s){h(!0);try{const de=await Fu(s.id,{limit:50},e);u(de.messages.map(jp))}catch(de){console.error("[useQuickChat] Failed to load messages:",de)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?I():u([])},[s,I]);const F=i.useCallback(async()=>{if(s){h(!0);try{const de=await Fu(s.id,{limit:50},e);u(de.messages.map(jp))}catch(de){console.error("[useQuickChat] Failed to reload messages:",de)}finally{h(!1)}}},[s,e]),G=i.useCallback(()=>{P.current?.(),P.current=null,T.current="",R(""),b(""),x(""),k([]),p(!1)},[]),X=i.useCallback(async(de,pe,B)=>{const ve=Lo(de,pe,B);if(!ve)return;const U=zo(ve.agentId,ve.modelProvider,ve.modelId);$.current=ve;const se=U===C.current&&s;if(se||(w.current&&(w.current.close(),w.current=null),G()),se){await F();return}a(null),u([]),C.current=U,await S(ve.agentId,ve.modelProvider,ve.modelId)},[s,S,F,G]),M=i.useCallback(async de=>{const pe=Lo(de.agentId,de.modelProvider??void 0,de.modelId??void 0);pe&&($.current=pe,C.current=zo(pe.agentId,pe.modelProvider,pe.modelId),w.current&&(w.current.close(),w.current=null),G(),a(de))},[G]),z=i.useCallback(async(de,pe)=>{await X(Sa,de,pe)},[X]),L=i.useCallback(async(de,pe,B)=>{const U=Lo(de??"",pe,B)??$.current;if(!U)return;$.current=U;const se=zo(U.agentId,U.modelProvider,U.modelId);w.current&&(w.current.close(),w.current=null),G(),u([]),a(null),c(!0);try{const ee=await E(U);a(ee),C.current=se;const ie=await Ou(e);o(ie.sessions)}catch(ee){console.error("[useQuickChat] Failed to start a fresh session:",ee),n?.("Failed to start a new chat","error")}finally{c(!1)}},[n,E,e,G]),j=i.useCallback(()=>{s&&(A.current=!0,P.current?.(),P.current=null,w.current?.close(),w.current=null,qN(s.id,e).catch(()=>{}),p(!1),b(""),x(""),k([]))},[s,e]),H=i.useCallback(()=>{T.current="",R("")},[]),Q=i.useCallback((de,pe)=>{if(!s||!de.trim()&&(!pe||pe.length===0))return Promise.resolve();if(f)return pe&&pe.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(T.current=de,R(de),Promise.resolve());const B=new Promise((ve,U)=>{_.current={resolve:ve,reject:U},A.current=!1,w.current&&(w.current.close(),w.current=null);const ee={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:de,createdAt:new Date().toISOString()};u(Oe=>[...Oe,ee]),b(""),x(""),k([]),p(!0);let ie="",te="",xe=[],ne=null,_e=null;const Ne=()=>{ne=null,b(ie)},Se=()=>{_e=null,x(te)},He=()=>{ne!==null&&(cancelAnimationFrame(ne),ne=null),_e!==null&&(cancelAnimationFrame(_e),_e=null)};P.current=He;const Ye={onThinking:Oe=>{te+=Oe,_e===null&&(_e=requestAnimationFrame(Se))},onText:Oe=>{ie+=Oe,ne===null&&(ne=requestAnimationFrame(Ne))},onToolStart:Oe=>{xe=[...xe,{toolName:Oe.toolName,args:Oe.args,isError:!1,status:"running"}],k(xe)},onToolEnd:Oe=>{const ke=[...xe];for(let De=ke.length-1;De>=0;De--){const re=ke[De];if(re?.toolName===Oe.toolName&&re.status==="running"){ke[De]={...re,status:"completed",isError:Oe.isError,result:Oe.result},xe=ke,k(ke);return}}xe=[...ke,{toolName:Oe.toolName,isError:Oe.isError,result:Oe.result,status:"completed"}],k(xe)},onDone:Oe=>{He();const ke={id:Oe.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:ie,thinkingOutput:te||void 0,toolCalls:xe.length>0?xe:void 0,createdAt:new Date().toISOString()};u(re=>[...re,ke]),b(""),x(""),k([]),p(!1),w.current=null,_.current?.resolve(),_.current=null;const De=T.current.trim();De&&(T.current="",R(""),Q(De))},onError:Oe=>{if(He(),b(""),x(""),k([]),p(!1),w.current=null,console.error("[useQuickChat] Stream error:",Oe),n?.("Failed to get response","error"),_.current?.reject(new Error(typeof Oe=="string"?Oe:"Failed to get response")),_.current=null,!A.current){const ke=T.current.trim();ke&&(T.current="",R(""),Q(ke))}F()}};w.current=VN(s.id,de,Ye,pe,e)});return B.catch(()=>{}),B},[s,f,e,n,F]);return i.useEffect(()=>()=>{w.current&&(w.current.close(),w.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:N,sendMessage:Q,stopStreaming:j,clearPendingMessage:H,switchSession:X,selectSession:M,startModelChat:z,startFreshSession:L,refreshSessions:O,loadMessages:I,reloadMessages:F}),[s,r,l,d,m,f,g,v,y,N,Q,j,H,X,M,z,L,O,I,F])}function h$(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,b=n?.showSystemAgents??!1,v=await oa({...g,...f,includeEphemeral:f?.includeEphemeral??b},e),x=Array.from(new Map(v.map(y=>[y.id,y])).values());a(x)}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 cj(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 li(`/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||!C1(f));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:d,loadStats:u}}function p$({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=QN(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(Wp,{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 f$=200;function g$(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),b=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=i.useCallback((w,A)=>{if(A<0||A>w.length){r(!1);return}const P=T=>/[a-zA-Z0-9/_.-]/.test(T);for(let T=A-1;T>=0;T--){if(w[T]==="#")if(T===0){const _=w.slice(T+1,A);d(T),l(_),g(0),r(!0);return}else{const _=w[T-1];if(/[\s,.;:!?'"()[\]{}]/.test(_)){const C=w.slice(T+1,A);d(T),l(C),g(0),r(!0);return}r(!1);return}if(!P(w[T])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),k=i.useCallback(async w=>{if(!w.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const A=await fk(w,s,n);m(A.files),g(0)}catch(A){A.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{k(o)},f$),()=>{b.current&&clearTimeout(b.current)}},[o,a,k]);const N=i.useCallback((w,A)=>{if(!a||c<0)return A;const P=A.slice(0,c),T=A.slice(c+1),_=T.match(/[\s]|$/),C=_?_.index:T.length,$=T.slice(C);return`${P}#${w.path}${$}`},[a,c]),R=i.useCallback((w,A)=>{if(!a||u.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),g(P=>Math.min(P+1,u.length-1)),!0;case"ArrowUp":return w.preventDefault(),g(P=>Math.max(P-1,0)),!0;case"Enter":case"Tab":return u[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:x,selectFile:N,dismissMention:y,handleKeyDown:R}}const b$=30,x$=16,v$=16;function y$(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ho=null;function vb(){return Ho===null&&(Ho=window.visualViewport?.height??window.innerHeight),Ho}function w$(e){const n=vb();e>n&&(Ho=e)}function k$(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 j$(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=k$(document.activeElement),s=e.offsetTop;n||w$(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=vb(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=b$)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=x$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=v$?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function yb({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||!y$()){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=j$();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}}function N$(e){return`${e.name?.trim()||e.id} (${e.role})`}function Oo(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 S$(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 qo(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function C$(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}=${qo(r,50)}`}).join(", ")}function E$(e){if(e===void 0)return null;if(typeof e=="string")return qo(e,200);try{return qo(JSON.stringify(e),200)}catch{return qo(String(e),200)}}function wb(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",b=f.status==="completed"&&f.isError,v=C$(f.args),x=E$(f.result),y=g?v:x?`result: ${x}`:v?`args: ${v}`:null,k=n?null:y,N=g?"running":b?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${b?" 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}),k&&t.jsx("span",{className:"chat-tool-call-preview",title:k,children:k}),t.jsx("span",{className:"chat-tool-call-status-text",children:N})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),x&&t.jsxs("div",{className:`chat-tool-call-row${b?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:x})]})]})]},`${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(gu,{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(gu,{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 kb={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 Np(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 M$(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 Fo={width:320,height:400},_$=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"]),A$=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function P$(e){return e.type.startsWith("image/")}function R$(e){if(_$.has(e.type))return!0;const n=e.name.toLowerCase();return A$.some(s=>n.endsWith(s))}const wa={width:280,height:260},ws=768,ka=8;function T$(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||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 b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=n??i.useRef(!1),m=i.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,k=window.innerWidth>768?s():0,N=window.innerWidth-v-x,R=window.innerHeight-v-x-y-k;return{x:Math.max(x,Math.min(N,b.x)),y:Math.max(x,Math.min(R,b.y))}},[s]),h=i.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),f=i.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),d.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},u.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=i.useCallback(b=>{if(!d.current||!l)return;const v=b.clientX-d.current.pointerX,x=b.clientY-d.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(u.current=!0),u.current){const y=d.current.x-v,k=d.current.y-x,N=m({x:y,y:k});o(N)}},[l,m]),g=i.useCallback(b=>{if(!d.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!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 I$(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>ws,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const b=Math.max(wa.width,window.innerWidth-p-ka),v=Math.max(wa.height,window.innerHeight-g-ka);return{width:Math.max(wa.width,Math.min(b,f.width)),height:Math.max(wa.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=ws)return Fo;try{const f=localStorage.getItem(a);if(!f)return Fo;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Fo:{width:p.width,height:p.height}}catch{return Fo}},[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 b={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 k=y.clientX-b.pointerX,N=y.clientY-b.pointerY;let R=b.width,w=b.height,A=b.anchorRight,P=b.anchorBottom;if(p.includes("w")&&(R=b.width-k),p.includes("e")){const E=k;R=b.width+E,A=b.anchorRight-E}if(p.includes("n")&&(w=b.height-N),p.includes("s")){const E=N;w=b.height+E,P=b.anchorBottom-E}const T=n+A,_=s+P,C=o({width:R,height:w},T,_),$=Math.max(ka-n,Math.min(window.innerWidth-n-wa.width-ka,A)),O=Math.max(ka-s,Math.min(window.innerHeight-s-wa.height-ka,P));d(C),m({right:$,bottom:O})},x=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",x)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Sp=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,b=f.index;b>h&&m.push(d.slice(h,b));const v=g.replace(/_/g," ").toLowerCase(),x=a.get(v);x?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",x.name.replace(/\s+/g,"_")]},`${x.id}-${b}`)):m.push(p),h=b+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(gi,{remarkPlugins:[bi],components:kb,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(Id,{size:14}):t.jsx(Ba,{size:14})})]}),wb(n.toolCalls,!0)]})});function $$({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=h$(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;yb({enabled:p});const b=la(),[v,x]=i.useState("agent"),[y,k]=i.useState(""),[N,R]=i.useState(!1),[w,A]=i.useState("model"),[P,T]=i.useState(""),[_,C]=i.useState(""),[$,O]=i.useState([]),[E,S]=i.useState(!1),[I,F]=i.useState(""),[G,X]=i.useState(""),[M,z]=i.useState(""),[L,j]=i.useState([]),[H,Q]=i.useState(!1),[de,pe]=i.useState(!1),[B,ve]=i.useState(""),[U,se]=i.useState(0),[ee,ie]=i.useState(""),[te,xe]=i.useState(!1),[ne,_e]=i.useState(0),[Ne,Se]=i.useState(-1),[He,Ye]=i.useState(()=>new Set),[Oe,ke]=i.useState(!1),[De,re]=i.useState([]),[oe,we]=i.useState(!1),[,Z]=i.useState(!1),[qe,Qe]=i.useState({top:0,left:0}),ge=g$({projectId:e}),Ue=i.useCallback(me=>{if(!me||!ge.mentionActive)return;const We=me.getBoundingClientRect();Qe({top:We.top-260,left:We.left+8})},[ge.mentionActive]),Xe=i.useRef(!1),wt=i.useRef(!1),ye=i.useRef(""),le=i.useRef(0),Te=i.useRef(null),be=i.useRef(null),Le=i.useRef(0),{position:Je,isDragging:nt,handlePointerDown:mt,handlePointerMove:Ie,handlePointerUp:ze}=T$(e,Xe),st=Je.y+60,{panelSize:yt,anchorOffset:Re,handleResizeStart:kt}=I$(e,Je.x,st),Et=typeof window<"u"&&window.innerWidth>ws,{activeSession:jt,messages:Rt,isStreaming:Dt,streamingText:Tt,streamingThinking:It,streamingToolCalls:Ut,sessions:Ft,sessionsLoading:Jt,messagesLoading:Vt,sendMessage:Yt,stopStreaming:Kt,pendingMessage:qt,clearPendingMessage:Bt,switchSession:Xt,selectSession:an,startModelChat:Qt,startFreshSession:fe,refreshSessions:Fe}=m$(e,n),ae=i.useRef(null),Pe=i.useRef(null),Ae=i.useRef(null),W=i.useRef(null),je=i.useRef(null),ce=i.useRef([]),$e=i.useRef(!1),it=i.useRef(!1),vt=i.useRef(!1),tn=i.useRef(null),Pt=i.useRef(!1);i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>ws)return;const me=window.scrollY,We=document.documentElement,ot=document.body,sn={htmlOverflow:We.style.overflow,bodyOverflow:ot.style.overflow};return window.scrollTo(0,0),We.style.overflow="hidden",ot.style.overflow="hidden",()=>{We.style.overflow=sn.htmlOverflow,ot.style.overflow=sn.bodyOverflow,window.scrollTo(0,me)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const me=ae.current;if(!me)return;const We=window.visualViewport,ot=()=>{Pt.current||(me.style.setProperty("--vv-height",`${We.height}px`),me.style.setProperty("--vv-offset-top",`${We.offsetTop||0}px`))};return ot(),We.addEventListener("resize",ot),We.addEventListener("scroll",ot),()=>{We.removeEventListener("resize",ot),We.removeEventListener("scroll",ot)}},[p]);const Lt=I||G,zt=i.useMemo(()=>Oo(Lt),[Lt]),yn=i.useMemo(()=>$.find(me=>`${me.provider}/${me.id}`===Lt)??null,[$,Lt]),ue=i.useMemo(()=>S$(yn,zt),[yn,zt]),lt=i.useMemo(()=>v==="model"?zt?`${Sa}::${zt.modelProvider}/${zt.modelId}`:"":y?`${y}::`:"",[v,zt,y]),dt=!(v==="agent"?!!y:!!zt)||!jt;i.useEffect(()=>{if(u.length===0){k(""),x("model");return}u.some(We=>We.id===y)||k(u[0]?.id??"")},[u,y]),i.useEffect(()=>{!p||wt.current||(wt.current=!0,S(!0),As().then(me=>{const We=me.models??[];if(O(We),I||We.length===0)return;const ot=me.defaultProvider,sn=me.defaultModelId;if(ot&&sn){const Y=`${ot}/${sn}`;if(We.some(rt=>`${rt.provider}/${rt.id}`===Y)){X(Y),F(Y),x("model");return}}X("");const Dn=We[0];Dn&&F(`${Dn.provider}/${Dn.id}`)}).catch(me=>{console.error("[QuickChatFAB] Failed to load models:",me),O([]),X("")}).finally(()=>{S(!1)}))},[p,u.length,I]),i.useEffect(()=>{!p||!e||(Q(!0),UN(e).then(me=>{j(me)}).catch(()=>{j([])}).finally(()=>{Q(!1)}))},[p,e]),i.useEffect(()=>{p&&Fe()},[p,Fe]),i.useEffect(()=>{if(!p){ye.current="";return}if(!lt){ye.current="";return}const me=lt===ye.current&&!jt&&!Jt;if(!(lt===ye.current&&!me)){if(ye.current=lt,v==="model"&&zt){Qt(zt.modelProvider,zt.modelId);return}v==="agent"&&y&&Xt(y)}},[p,v,zt,y,lt,jt,Jt,Qt,Xt]),i.useEffect(()=>{p||(xe(!1),ie(""),Se(-1),pe(!1),ve(""),se(0),ce.current.forEach(me=>{me.previewUrl&&URL.revokeObjectURL(me.previewUrl)}),re([]))},[p]),i.useEffect(()=>{ce.current=De},[De]),i.useEffect(()=>{if(!p){$e.current=!1;return}typeof window>"u"||($e.current=window.innerWidth<=ws)},[p]),i.useEffect(()=>{if(!p||dt||!$e.current)return;const me=W.current;if(!me)return;const We=document.activeElement,ot=We?ae.current?.contains(We):!1,sn=We===document.body,Dn=We===tn.current;if(!ot&&!sn&&!Dn){$e.current=!1;return}if(Dn){me.focus({preventScroll:!0}),$e.current=!1;return}const Y=requestAnimationFrame(()=>{me.focus(),$e.current=!1});return()=>cancelAnimationFrame(Y)},[p,dt]),i.useEffect(()=>()=>{ce.current.forEach(me=>{me.previewUrl&&URL.revokeObjectURL(me.previewUrl)})},[]);const at=i.useCallback(()=>{R(!0),A("model"),T(u[0]?.id??""),C(I||G||"")},[u,G,I]),St=i.useMemo(()=>u.find(me=>me.id===y)??null,[u,y]),he=i.useMemo(()=>{const me=B.trim().toLowerCase();return(me?L.filter(ot=>ot.name.toLowerCase().includes(me)):L).slice(0,10)},[L,B]),ct=i.useMemo(()=>{const me=ee.trim().toLowerCase();return me?u.filter(We=>We.name.toLowerCase().includes(me)):u},[u,ee]),Zt=i.useMemo(()=>{const me=new Map;for(const We of u)me.set(We.name.toLowerCase(),We);return me},[u]);i.useEffect(()=>{se(0)},[he]),i.useEffect(()=>{_e(0)},[ee,te]),i.useEffect(()=>()=>{Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),i.useEffect(()=>{if(!p)return;const me=ot=>{const sn=ot.target;ae.current?.contains(sn)||Pe.current?.contains(sn)||sn.closest(".model-combobox-dropdown--portal")||g(!1)},We=ot=>{ot.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",me),document.addEventListener("keydown",We),()=>{document.removeEventListener("mousedown",me),document.removeEventListener("keydown",We)}},[p,g]),i.useEffect(()=>{if(!p)return;const me=Ae.current;me&&(me.scrollTop=me.scrollHeight)},[Rt,Tt,It,Dt,p]);const Sn=i.useMemo(()=>{const me=new Map(u.map(ot=>[ot.id,ot.name?.trim()||ot.id])),We=new Map($.map(ot=>[`${ot.provider}/${ot.id}`,ot.name?.trim()||""]));return Ft.map((ot,sn)=>{const Dn=ot.title?.trim()||`Session ${sn+1}`;let Y=null;if(ot.agentId&&ot.agentId!==Sa)Y=me.get(ot.agentId)||ot.agentId;else if(ot.modelProvider&&ot.modelId){const Ee=`${ot.modelProvider}/${ot.modelId}`,rt=We.get(Ee);Y=rt?`${rt} [${Ee}]`:Ee}return{id:ot.id,label:Y?`${Dn} — ${Y}`:Dn}})},[u,$,Ft]),In=i.useMemo(()=>v==="agent"?St?`Message ${St.name||St.id}`:"Select an agent to start chatting":ue?`Message ${ue}`:"Select a model to start chatting",[v,St,ue]),Hn=i.useCallback(me=>{const We=Ft.find(ot=>ot.id===me);We&&(We.modelProvider&&We.modelId?(x("model"),F(`${We.modelProvider}/${We.modelId}`)):(x("agent"),k(We.agentId)),an(We))},[an,Ft]),Xn=i.useCallback(async()=>{if(!Jt){if(w==="agent"){if(!P)return;x("agent"),k(P),await fe(P)}else{const me=Oo(_||I||G);if(!me)return;x("model"),F(`${me.modelProvider}/${me.modelId}`),await fe(Sa,me.modelProvider,me.modelId)}await Fe(),R(!1),A("model")}},[G,P,w,_,Fe,I,Jt,fe]),jn=qt.length>50?`${qt.slice(0,50)}…`:qt,Pn=i.useCallback(me=>{if(!me||me.length===0)return;const We=[];for(let ot=0;ot<me.length;ot+=1){const sn=me[ot];R$(sn)&&We.push({file:sn,previewUrl:P$(sn)?URL.createObjectURL(sn):""})}We.length>0&&re(ot=>[...ot,...We])},[]),rs=i.useCallback(me=>{re(We=>{const ot=We[me];return ot?.previewUrl&&URL.revokeObjectURL(ot.previewUrl),We.filter((sn,Dn)=>Dn!==me)})},[]),os=i.useCallback(me=>{Pn(me.clipboardData?.files)},[Pn]),cn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>ws)return;const me=W.current;!me||me.disabled||me.focus({preventScroll:!0})},[]),$n=i.useCallback(()=>{typeof window>"u"||window.innerWidth>ws||(vt.current=!0)},[]),nn=i.useCallback(async()=>{const me=M.trim(),We=ce.current;if(!(!me&&We.length===0)&&!dt){if(z(""),xe(!1),ie(""),Se(-1),me==="/help"){ke(!0),cn(),vt.current=!1;return}if(me==="/clear"){Kt(),Bt(),We.forEach(ot=>{ot.previewUrl&&URL.revokeObjectURL(ot.previewUrl)}),re(ot=>ot.filter(sn=>!We.includes(sn)));try{if(v==="model"){const ot=Oo(Lt);if(!ot)return;await fe(Sa,ot.modelProvider,ot.modelId)}else y&&await fe(y)}catch{n("Failed to clear conversation","error")}finally{cn(),vt.current=!1}return}try{ke(!1),await Yt(me,We.map(ot=>ot.file)),We.forEach(ot=>{ot.previewUrl&&URL.revokeObjectURL(ot.previewUrl)}),re(ot=>ot.filter(sn=>!We.includes(sn)))}catch{}finally{cn(),vt.current=!1}}},[n,v,Bt,cn,dt,M,Lt,y,Yt,fe,Kt]),_t=i.useCallback(me=>{me.preventDefault(),Le.current+=1,we(!0)},[]),K=i.useCallback(me=>{me.preventDefault(),me.dataTransfer.dropEffect="copy",we(!0)},[]),Ve=i.useCallback(me=>{me.preventDefault(),Le.current=Math.max(0,Le.current-1),Le.current===0&&we(!1)},[]),pt=i.useCallback(me=>{me.preventDefault(),Le.current=0,we(!1),Pn(me.dataTransfer?.files)},[Pn]),ht=i.useCallback((me,We)=>{const ot=M$(me,We);if(ot){xe(!0),ie(ot.filter),Se(ot.start);return}xe(!1),ie(""),Se(-1)},[]),Nt=i.useCallback(me=>{z(We=>{const ot=Np(We);if(!ot)return We;const sn=`/skill:${me.name} `,Dn=We.slice(0,ot.start)+sn+We.slice(ot.end);return window.requestAnimationFrame(()=>{W.current&&W.current.focus()}),Dn}),pe(!1),ve(""),se(0)},[]),Mt=i.useCallback(me=>{const We=W.current;if(!We||Ne<0)return;const ot=We.selectionStart??le.current,sn=We.selectionEnd??ot,Dn=Math.max(ot,sn),Y=Math.min(Ne,Dn),rt=`${`@${me.name.replace(/\s+/g,"_")}`} `,Be=M.slice(0,Y)+rt+M.slice(Dn),ft=Y+rt.length;z(Be),xe(!1),ie(""),_e(0),Se(-1),window.requestAnimationFrame(()=>{W.current&&(W.current.focus(),W.current.setSelectionRange(ft,ft))})},[Ne,M]),$t=i.useCallback(me=>{const We=me.target.value,ot=me.target.selectionStart??We.length;le.current=ot,z(We),Oe&&We.trim().length>0&&ke(!1),ht(We,ot);const sn=Np(We);sn?(pe(!0),ve(sn.filter)):(pe(!1),ve("")),ge.detectMention(We,ot),Z(ge.mentionActive),ge.mentionActive&&Ue(me.target)},[Oe,ht,ge,Ue]),wn=i.useCallback(()=>{if(vt.current){window.requestAnimationFrame(()=>{cn()});return}typeof window<"u"&&window.innerWidth<=ws&&ae.current&&(Pt.current=!0,ae.current.style.removeProperty("--vv-height"),ae.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Pt.current=!1},450)),Te.current!==null&&window.clearTimeout(Te.current),Te.current=window.setTimeout(()=>{xe(!1),ie(""),Se(-1),Z(!1),ge.dismissMention(),Te.current=null},120),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{pe(!1),be.current=null},120)},[ge,cn]),ls=i.useCallback(()=>{Pt.current=!1,Te.current!==null&&(window.clearTimeout(Te.current),Te.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),Cs=i.useCallback(me=>{const We=me.currentTarget,ot=We.selectionStart??We.value.length;le.current=ot,ht(We.value,ot),ge.detectMention(We.value,ot),Z(ge.mentionActive),ge.mentionActive&&Ue(We)},[ht,ge,Ue]),$s=i.useCallback(me=>{me.key!=="Escape"&&Cs(me)},[Cs]),ps=i.useCallback(me=>{Ye(We=>{const ot=new Set(We);return ot.has(me)?ot.delete(me):ot.add(me),ot})},[]),Vs=i.useCallback((me,We=!1)=>We?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(gi,{remarkPlugins:[bi],components:kb,children:me})}),[]),dn=i.useCallback(me=>{if(le.current=me.currentTarget.selectionStart??le.current,ge.mentionActive&&ge.files.length>0){if(ge.handleKeyDown(me,M),me.key==="Enter"||me.key==="Tab"){const We=ge.files[ge.selectedIndex];if(We){const ot=ge.selectFile(We,M);z(ot),ge.dismissMention(),Z(!1)}}return}if(te&&me.key==="ArrowDown"){me.preventDefault(),ct.length>0&&_e(We=>(We+1)%ct.length);return}if(te&&me.key==="ArrowUp"){me.preventDefault(),ct.length>0&&_e(We=>We===0?ct.length-1:We-1);return}if(te&&me.key==="Enter"){me.preventDefault();const We=ct[ne]??ct[0];We&&Mt(We);return}if(te&&me.key==="Escape"){me.preventDefault(),me.stopPropagation(),xe(!1),ie(""),Se(-1);return}if(de&&he.length>0&&me.key==="ArrowDown"){me.preventDefault(),se(We=>(We+1)%he.length);return}if(de&&he.length>0&&me.key==="ArrowUp"){me.preventDefault(),se(We=>We===0?he.length-1:We-1);return}if(de&&(me.key==="Enter"||me.key==="Tab")){me.preventDefault();const We=he[U]??he[0];We&&Nt(We);return}if(de&&me.key==="Escape"){me.preventDefault(),pe(!1),ve("");return}me.key!=="Enter"||me.shiftKey||(me.preventDefault(),nn())},[te,ct,ne,Mt,nn,ge,M,de,he,U,Nt]),yi=i.useCallback(()=>{if(Xe.current){Xe.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=ws&&tn.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:tn,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":nt?"true":"false",style:{right:Je.x,bottom:Je.y},onPointerDown:mt,onPointerMove:Ie,onPointerUp:ze,onClick:yi,children:t.jsx(Ci,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:ae,"data-testid":"quick-chat-panel",style:{...Et?{right:Je.x+Re.right,bottom:st+Re.bottom,width:yt.width,height:yt.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:kt,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:kt,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:kt,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:kt,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:kt,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:kt,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:kt,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:kt,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"&&ue&&(()=>{const me=yn?.provider??zt?.modelProvider??"";return b==="mobile"&&ue.length>12&&me?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:ue,"aria-label":ue,children:t.jsx(Fn,{provider:me,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:ue,children:ue})})()]}),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:at,disabled:Jt,children:t.jsx(xn,{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(Wt,{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:jt?.id??"",onChange:me=>Hn(me.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Jt?"Loading sessions…":"Select a session"}),Sn.map(me=>t.jsx("option",{value:me.id,children:me.label},me.id))]})]}),N&&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${w==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>A("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${w==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>A("agent"),children:"Agent"})]}),w==="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:P,onChange:me=>T(me.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(me=>t.jsx("option",{value:me.id,children:N$(me)},me.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(hs,{id:"quick-chat-new-model-select",models:$,value:_,onChange:C,label:"Select model override",placeholder:E?"Loading models…":"Select a model",disabled:E||$.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:()=>{R(!1),A("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void Xn(),disabled:Jt||(w==="agent"?!P:!Oo(_||I||G)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ae,"data-testid":"quick-chat-messages",children:Jt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Dt?t.jsxs(t.Fragment,{children:[Rt.map(me=>t.jsx(Sp,{message:me,forcePlain:me.role!=="user"&&He.has(me.id),mentionAgentsByName:Zt,onToggleRender:ps},me.id)),Oe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Vs("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:[Tt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Vs(Tt,He.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${He.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":He.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>ps("__streaming__"),children:He.has("__streaming__")?t.jsx(Id,{size:14}):t.jsx(Ba,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:It?"Thinking…":"Connecting…"}),wb(Ut,!0),It&&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:It})]})]})]}):Vt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Rt.length===0&&!Tt&&!It&&!Dt&&!Oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Rt.map(me=>t.jsx(Sp,{message:me,forcePlain:me.role!=="user"&&He.has(me.id),mentionAgentsByName:Zt,onToggleRender:ps},me.id)),Oe&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Vs("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),De.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:De.map((me,We)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${We}`,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-${We}`,"aria-label":`Remove ${me.file.name}`,onClick:()=>rs(We),children:"×"})]},`${me.file.name}-${We}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${oe?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:_t,onDragOver:K,onDragLeave:Ve,onDrop:pt,children:[t.jsx("input",{ref:je,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=>{Pn(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:()=>je.current?.click(),children:t.jsx(Jp,{size:16})}),t.jsx("input",{ref:W,type:"text",value:M,onChange:$t,onKeyDown:dn,onKeyUp:$s,onClick:Cs,onBlur:wn,onFocus:ls,onPaste:os,onTouchStart:me=>{typeof window>"u"||window.innerWidth>ws||document.activeElement!==me.currentTarget&&(me.preventDefault(),me.currentTarget.focus({preventScroll:!0}))},placeholder:In,disabled:dt,"data-testid":"quick-chat-input"}),Dt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:me=>{typeof window>"u"||window.innerWidth>ws||(me.preventDefault(),me.pointerType&&me.pointerType!=="mouse"&&(it.current=!0,Kt()))},onTouchStart:me=>{typeof window>"u"||window.innerWidth>ws||(me.preventDefault(),it.current=!0,Kt())},onMouseDown:me=>{typeof window>"u"||window.innerWidth>ws||me.preventDefault()},onClick:()=>{if(it.current){it.current=!1;return}Kt()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(zs,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:me=>{typeof window>"u"||window.innerWidth>ws||(me.preventDefault(),me.pointerType&&me.pointerType!=="mouse"&&(it.current=!0,$n(),cn(),nn()))},onTouchStart:me=>{typeof window>"u"||window.innerWidth>ws||(me.preventDefault(),it.current=!0,$n(),cn(),nn())},onMouseDown:me=>{typeof window>"u"||window.innerWidth>ws||me.preventDefault()},onClick:()=>{if(it.current){it.current=!1;return}nn()},disabled:dt||M.trim().length===0&&De.length===0,"data-testid":"quick-chat-send",children:t.jsx(Yi,{size:16})})]}),t.jsx(d$,{agents:u,filter:ee,highlightedIndex:ne,visible:te,onSelect:Mt,position:"above"}),t.jsx(p$,{visible:ge.mentionActive&&!te,position:qe,files:ge.files,selectedIndex:ge.selectedIndex,onSelect:me=>{const We=ge.selectFile(me,M);z(We),ge.dismissMention(),Z(!1),W.current?.focus()},loading:ge.loading}),de&&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…"}):he.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:B?"No skills found":"No skills available"}):he.map((me,We)=>t.jsxs("button",{type:"button",role:"option","aria-selected":We===U,className:`chat-skill-menu-item${We===U?" chat-skill-menu-item--highlighted":""}`,onMouseDown:ot=>ot.preventDefault(),onMouseEnter:()=>se(We),onClick:()=>Nt(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))}),qt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${jn}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Bt,children:"×"})]})]})})]})]})}function gr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Cp(e){return e.status==="generating"||e.status==="awaiting_input"}function br(e){return e==="complete"||e==="error"}function D$(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Ka(),u=i.useCallback(()=>{zd(e).then(p=>{const g=p.filter(v=>{const x=gr(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:x<=y?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of g)b.set(v.id,gr(v.updatedAt));a.current=b,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 b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(x<y)continue;const k=r.current.get(v.sessionId);if(k!==void 0&&x<=k)continue;if(k!==void 0&&x>k&&!br(v.status)&&r.current.delete(v.sessionId),br(v.status)){b.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,x);continue}const N=b.get(v.sessionId),R=v.type??N?.type,w=v.title??N?.title;if(!N&&(!R||!w))continue;const A={id:v.sessionId,type:R??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??N?.projectId??e??null,lockedByTab:v.owningTabId??N?.lockedByTab??null,updatedAt:v.updatedAt??N?.updatedAt??new Date(x).toISOString()},P=b.get(v.sessionId);(!P||P.status!==A.status||P.title!==A.title||P.type!==A.type||P.projectId!==A.projectId||P.lockedByTab!==A.lockedByTab||P.updatedAt!==A.updatedAt)&&(b.set(v.sessionId,A),a.current.set(v.sessionId,x),g=!0)}return g?[...b.values()].sort((v,x)=>gr(x.updatedAt)-gr(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const x=JSON.parse(v.data),y=gr(x.updatedAt)||Date.now();s(k=>{const N=a.current.get(x.id)??0;if(y<N)return k;const R=r.current.get(x.id);if(R!==void 0&&y<=R)return k;if(R!==void 0&&y>R&&!br(x.status)&&r.current.delete(x.id),a.current.set(x.id,y),br(x.status))return k.filter(A=>A.id!==x.id);const w=k.findIndex(A=>A.id===x.id);if(w>=0){const A=[...k];return A[w]=x,A}return Cp(x)?[x,...k]:k}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:y}),br(x.status)&&c({sessionId:x.id,status:x.status,timestamp:y})}catch{}},b=v=>{try{const x=JSON.parse(v.data),y=Date.now();r.current.set(x,y),a.current.set(x,Math.max(a.current.get(x)??0,y)),c({sessionId:x,status:"complete",timestamp:y}),s(k=>k.filter(N=>N.id!==x))}catch{}};return li(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":b},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const b=n.find(k=>k.id===p)?.type,v=da();let x=!1;if(b==="planning")try{await sf(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(b==="subtask")try{await of(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(b==="mission_interview")try{await uf(p,e,v)}catch(k){x=!0,k instanceof Error&&k.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await mf(p)}catch{}s(k=>k.filter(N=>N.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Cp(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 ml="fusion:hide-session-banners",Pd="fusion:session-banner-pref-changed";function L$(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(ml)==="1"}catch{return!1}}function z$(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===ml&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Pd,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Pd,s)}}function z6(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(ml,"1"):window.localStorage.removeItem(ml),window.dispatchEvent(new Event(Pd))}catch{}}function O$(){return i.useSyncExternalStore(z$,L$,()=>!1)}function ds(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 Ep(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function F$(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 Vc(e,n){if(Ep(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return F$(e,n);const a=Ep(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 U$(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),b=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,y=i.useCallback(async G=>{const X=++m.current,M=n,z=G?.searchQueryOverride??f.current,L=G?.includeArchivedOverride??d.current;try{const j=await Gy(void 0,void 0,M,z,L);if(m.current!==X||n!==M)return;o(j.map(ds)),g.current=Date.now()}catch{if(m.current!==X||n!==M)return;if(G?.clearOnError){o([]);return}o(j=>j)}},[n]);p.current=y;const k=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),N=i.useRef(s);i.useEffect(()=>{if(s===void 0&&N.current===void 0)return;N.current=s;const G=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(G)},[s]),i.useEffect(()=>{y({clearOnError:!0});const G=()=>{if(document.visibilityState!=="visible")return;const X=Date.now();X-h.current<x||(h.current=X,y())};return document.addEventListener("visibilitychange",G),()=>{document.removeEventListener("visibilitychange",G)}},[y]),i.useEffect(()=>{if(a===!1)return;const G=b.current,X=n?`?projectId=${encodeURIComponent(n)}`:"",M=()=>b.current!==G;let z=!0;const L=B=>{if(M())return;const ve=ds(JSON.parse(B.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(U=>{const se=U.findIndex(xe=>xe.id===ve.id);if(se===-1)return[...U,ve];const ee=U[se],ie=Vc(ee,ve);if(ie===ee)return U;const te=[...U];return te[se]=ie,te}),g.current=Date.now()},j=B=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ve,to:U}=JSON.parse(B.data),se=ds(ve);o(ee=>ee.map(ie=>ie.id===se.id?{...se,column:U}:ie)),g.current=Date.now()},H=B=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ve=ds(JSON.parse(B.data));o(U=>U.map(se=>se.id!==ve.id?se:Vc(se,ve))),g.current=Date.now()},Q=B=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const ve=ds(JSON.parse(B.data));o(U=>U.filter(se=>se.id!==ve.id))},de=B=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:ve}=JSON.parse(B.data),U=ds(ve);o(se=>se.map(ee=>ee.id===U.id?{...U,column:"done"}:ee))},pe=li(`/api/events${X}`,{events:{"task:created":L,"task:moved":j,"task:updated":H,"task:deleted":Q,"task:merged":de},onReconnect:()=>{z&&(M()||p.current())}});return()=>{z=!1,pe()}},[n,a]);const R=i.useCallback(async G=>{const X=ds(await Qo(G,n));return o(M=>M.some(z=>z.id===X.id)?M:[...M,X]),X},[n]),w=i.useCallback(async(G,X,M)=>ds(await Yy(G,X,n,M)),[n]),A=i.useCallback(async G=>ds(await ef(G,n)),[n]),P=i.useCallback(async G=>ds(await Qy(G,n)),[n]),T=i.useCallback(async G=>Xy(G,n),[n]),_=i.useCallback(async G=>ds(await Zy(G,n)),[n]),C=i.useCallback(async G=>ds(await ew(G,n)),[n]),$=i.useCallback(async G=>{const X=ds(await tw(G,n));return o(M=>M.some(z=>z.id===X.id)?M:[...M,X]),X},[n]),O=i.useCallback(async(G,X)=>{const M=u.current.find(L=>L.id===G),z=M?{...M,...X,updatedAt:new Date().toISOString()}:void 0;z&&o(L=>L.map(j=>j.id===G?z:j));try{const L=ds(await ni(G,X,n));return o(j=>j.map(H=>H.id===G?L:H)),L}catch(L){throw M&&o(j=>j.map(H=>H.id===G?M:H)),L}},[n]),E=i.useCallback(async G=>{const X=ds(await sw(G,n));return o(M=>M.map(z=>z.id===G?X:z)),X},[n]),S=i.useCallback(async G=>{const X=ds(await iw(G,n));return o(M=>M.map(z=>z.id===G?X:z)),X},[n]),I=i.useCallback(async()=>{const X=(await aw(n)).map(ds);return o(M=>M.map(z=>X.find(j=>j.id===z.id)||z)),X},[n]),F=i.useCallback(G=>{if(G.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const X=G.map(ds);o(M=>{let z=M;for(const L of X){const j=z.findIndex(de=>de.id===L.id);if(j===-1){z===M&&(z=[...M]),z.push(L);continue}const H=z[j],Q=Vc(H,L);Q!==H&&(z===M&&(z=[...M]),z[j]=Q)}return z}),g.current=Date.now()},[]);return{tasks:r,createTask:R,moveTask:w,pauseTask:A,deleteTask:P,mergeTask:T,retryTask:_,resetTask:C,duplicateTask:$,updateTask:O,archiveTask:E,unarchiveTask:S,archiveAllDone:I,loadArchivedTasks:k,includeArchived:l,ingestCreatedTasks:F,lastFetchTimeMs:g.current}}const B$=5e3,H$=1e3;function q$(){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 Iu();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 b=performance.now();try{const v=await Iu(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),Cr("[useProjects]",y),f||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),Cr("[useProjects]",y),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<H$||(c.current=b,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},B$),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await pj(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await yj(f,p);return n(b=>b.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await lf(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 V$="kb-dashboard-current-project";function W$(e){return e??"local"}function K$(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=W$(s);i.useEffect(()=>{let p=!1;async function g(){try{const b=await ra();if(p)return;u.current=b.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const x=e.find(y=>y.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(V$);if(x){const y=JSON.parse(x);y?.id&&e.some(N=>N.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await Cn({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(b=>b.id===a.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Cn({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,Cn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Cn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const jb=i.createContext(null);function G$({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()},[]),Vo.createElement(jb.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function J$(){const e=i.useContext(jb);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Nb="kb-dashboard-theme-mode",Sb="kb-dashboard-color-theme",Cb="kb-dashboard-font-scale-pct",Rd=100,Y$=85,Q$=125,Eb=[...N1],Td="theme-data",Wc="theme-data.css";function X$(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Wc}`:e.replace(/\/[^/]+$/,`/${Wc}`):`/${Wc}`}const Rs=typeof window<"u",Z$=Rs?i.useLayoutEffect:i.useEffect;function Mb(e){return e==="dark"||e==="light"||e==="system"}function Mp(){if(!Rs)return"dark";try{const e=localStorage.getItem(Nb);if(Mb(e))return e}catch{}return"dark"}function _p(){if(!Rs)return"default";try{const e=localStorage.getItem(Sb);if(e&&Eb.includes(e))return e}catch{}return"default"}function Ap(e){if(Rs)try{localStorage.setItem(Nb,e)}catch{}}function Pp(e){if(Rs)try{localStorage.setItem(Sb,e)}catch{}}function Fr(e){return typeof e!="number"||!Number.isFinite(e)?Rd:Math.min(Q$,Math.max(Y$,Math.round(e)))}function Rp(){if(!Rs)return Rd;try{const e=Number(localStorage.getItem(Cb));return Fr(e)}catch{return Rd}}function Tp(e){if(Rs)try{localStorage.setItem(Cb,String(Fr(e)))}catch{}}function eD(e,n){return e==="system"?n?"dark":"light":e}function tD(e,n,s,a){if(!Rs)return;const r=eD(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Fr(s)}%`}function Ip(){if(!Rs)return;const e=X$(),n=document.getElementById(Td);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=Td,document.head.appendChild(s)}function $p(){if(!Rs)return;const e=document.getElementById(Td);e&&e.remove()}function nD(){const[e,n]=i.useState(()=>Mp()),[s,a]=i.useState(()=>_p()),[r,o]=i.useState(()=>Rp()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Rs?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),b=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Rs||!l)return;let k=!1;return ra().then(N=>{if(!k&&(Mb(N.themeMode)&&!p.current&&(m.current!==N.themeMode&&(m.current=N.themeMode,n(N.themeMode)),Mp()!==N.themeMode&&Ap(N.themeMode)),N.colorTheme&&Eb.includes(N.colorTheme)&&!g.current&&(h.current!==N.colorTheme&&(h.current=N.colorTheme,a(N.colorTheme)),_p()!==N.colorTheme&&Pp(N.colorTheme)),!b.current)){const R=Fr(N.dashboardFontScalePct);f.current!==R&&(f.current=R,o(R)),Rp()!==R&&Tp(R)}}).catch(N=>{console.warn("[useTheme] Failed to hydrate theme from global settings",N)}).finally(()=>{k||c(!1)}),()=>{k=!0}},[l]),i.useEffect(()=>{if(!Rs)return;const k=window.matchMedia("(prefers-color-scheme: dark)"),N=R=>{u(R.matches)};return k.addEventListener("change",N),()=>k.removeEventListener("change",N)},[]),Z$(()=>{tD(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Rs||l||(s!=="default"?Ip():$p())},[s,l]);const v=i.useCallback(k=>{p.current=!0,m.current=k,n(k),Ap(k),Cn({themeMode:k}).catch(N=>{console.warn("[useTheme] Failed to persist themeMode to global settings",N)})},[]),x=i.useCallback(k=>{g.current=!0,h.current=k,a(k),Pp(k),k!=="default"?Ip():$p(),Cn({colorTheme:k}).catch(N=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",N)})},[]),y=i.useCallback(k=>{const N=Fr(k);b.current=!0,f.current=N,o(N),Tp(N),Cn({dashboardFontScalePct:N}).catch(R=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",R)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:x,setDashboardFontScalePct:y,isSystemDark:d}}function sD(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,b]=i.useState(void 0),[v,x]=i.useState(null),[y,k]=i.useState("definition"),[N,R]=i.useState(!1),[w,A]=i.useState(void 0),[P,T]=i.useState(!1),[_,C]=i.useState(!1),[$,O]=i.useState(!1),[E,S]=i.useState(null),[I,F]=i.useState(!1),[G,X]=i.useState(!1),[M,z]=i.useState(void 0),[L,j]=i.useState(!1),[H,Q]=i.useState(!1),[de,pe]=i.useState("project"),[B,ve]=i.useState(!1),[U,se]=i.useState(!1),[ee,ie]=i.useState(!1),[te,xe]=i.useState(!1),[ne,_e]=i.useState(!1),[Ne,Se]=i.useState(!1),[He,Ye]=i.useState(!1),Oe=!!(v||N||s||r||m||G||L||H||B||U||ee||ne||te||$||I||P||_||Ne||He),ke=i.useCallback(()=>a(!0),[]),De=i.useCallback(()=>a(!1),[]),re=i.useCallback(()=>o(!0),[]),oe=i.useCallback(je=>{c(je),o(!0)},[]),we=i.useCallback(()=>{const je=n[0];je&&(u(je.id),o(!0))},[n]),Z=i.useCallback(je=>{u(je),o(!0)},[]),qe=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),Qe=i.useCallback(je=>{p(je),h(!0)},[]),ge=i.useCallback(je=>{b(je),h(!0)},[]),Ue=i.useCallback(()=>{h(!1),p(null),b(void 0)},[]),Xe=i.useCallback((je,ce="definition")=>{x(je),k(ce)},[]),wt=i.useCallback(je=>{x(je),k("changes")},[]),ye=i.useCallback(je=>{x(ce=>ce&&{...ce,...je})},[]),le=i.useCallback(()=>{x(null)},[]),Te=i.useCallback(je=>{A(je),R(!0)},[]),be=i.useCallback(()=>{R(!1),A(void 0)},[]),Le=i.useCallback(()=>T(!0),[]),Je=i.useCallback(()=>T(!1),[]),nt=i.useCallback(()=>C(!0),[]),mt=i.useCallback(()=>C(!1),[]),Ie=i.useCallback(je=>{S(je??null),O(!0)},[]),ze=i.useCallback(()=>{O(!1),S(null)},[]),st=i.useCallback(()=>F(!0),[]),yt=i.useCallback(()=>F(!1),[]),Re=i.useCallback(()=>{X(je=>!je)},[]),kt=i.useCallback(()=>{X(!1),z(void 0)},[]),Et=i.useCallback(()=>j(!0),[]),jt=i.useCallback(()=>j(!1),[]),Rt=i.useCallback(()=>Q(!0),[]),Dt=i.useCallback(()=>Q(!1),[]),Tt=i.useCallback(je=>{pe(je)},[]),It=i.useCallback(()=>ve(!0),[]),Ut=i.useCallback(()=>ve(!1),[]),Ft=i.useCallback(()=>se(!0),[]),Jt=i.useCallback(()=>se(!1),[]),Vt=i.useCallback(()=>ie(!0),[]),Yt=i.useCallback(()=>ie(!1),[]),Kt=i.useCallback(()=>xe(!0),[]),qt=i.useCallback(()=>xe(!1),[]),Bt=i.useCallback(()=>_e(!0),[]),Xt=i.useCallback(()=>_e(!1),[]),an=i.useCallback(async(je,ce)=>{_e(!1),z(ce),X(!0)},[]),Qt=i.useCallback(()=>Se(!0),[]),fe=i.useCallback(()=>Se(!1),[]),Fe=i.useCallback(()=>Ye(!0),[]),ae=i.useCallback(()=>Ye(!1),[]),Pe=i.useCallback((je,ce)=>{ce(`Created ${je.id} from planning mode`,"success"),o(!1),c(null)},[]),Ae=i.useCallback((je,ce)=>{const $e=je.map(it=>it.id).join(", ");ce(`Created ${$e} from planning mode`,"success"),o(!1),c(null)},[]),W=i.useCallback((je,ce)=>{const $e=je.map(it=>it.id).join(", ");ce(`Created ${$e} 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,settingsOpen:N,settingsInitialSection:w,schedulesOpen:P,githubImportOpen:_,usageOpen:$,usageAnchorRect:E,systemStatsOpen:I,terminalOpen:G,terminalInitialCommand:M,filesOpen:L,todosOpen:H,fileBrowserWorkspace:de,activityLogOpen:B,gitManagerOpen:U,workflowStepsOpen:ee,agentsOpen:te,scriptsOpen:ne,setupWizardOpen:Ne,modelOnboardingOpen:He,anyModalOpen:Oe,openNewTask:ke,closeNewTask:De,openPlanning:re,openPlanningWithInitialPlan:oe,resumePlanning:we,openPlanningWithSession:Z,closePlanning:qe,openSubtaskBreakdown:Qe,openSubtaskWithSession:ge,closeSubtask:Ue,openDetailTask:Xe,openDetailWithChangesTab:wt,updateDetailTask:ye,closeDetailTask:le,openSettings:Te,closeSettings:be,openSchedules:Le,closeSchedules:Je,openGitHubImport:nt,closeGitHubImport:mt,openUsage:Ie,closeUsage:ze,openSystemStats:st,closeSystemStats:yt,toggleTerminal:Re,closeTerminal:kt,openFiles:Et,closeFiles:jt,openTodos:Rt,closeTodos:Dt,setFileWorkspace:Tt,openActivityLog:It,closeActivityLog:Ut,openGitManager:Ft,closeGitManager:Jt,openWorkflowSteps:Vt,closeWorkflowSteps:Yt,openAgents:Kt,closeAgents:qt,openScripts:Bt,closeScripts:Xt,runScript:an,openSetupWizard:Qt,closeSetupWizard:fe,openModelOnboarding:Fe,closeModelOnboarding:ae,onPlanningTaskCreated:Pe,onPlanningTasksCreated:Ae,onSubtaskTasksCreated:W}}function iD(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),[b,v]=i.useState(!1),[x,y]=i.useState(!1),[k,N]=i.useState({}),[R,w]=i.useState(!1),[A,P]=i.useState(!1),[T,_]=i.useState(!1),[C,$]=i.useState(!1),[O,E]=i.useState(!1),S=i.useCallback(async()=>{const[M,z]=await Promise.allSettled([lw(e),jl(e)]);if(M.status==="fulfilled"&&(s(M.value.maxConcurrent),r(M.value.rootDir)),z.status==="fulfilled"){const L=z.value;l(!!L.autoMerge),d(!!L.globalPause),m(!!L.enginePaused),v(!!L.prAuthAvailable),f(L.taskStuckTimeoutMs),g(L.showQuickChatFAB===!0),N(L.experimentalFeatures??{});const j=L.experimentalFeatures??{};w(j.insights===!0),P(j.roadmap===!0),_(j.memoryView===!0),$(j.devServerView===!0||j.devServer===!0),E(j.todoView===!0)}y(!0)},[e]);i.useEffect(()=>{y(!1),N({}),w(!1),P(!1),_(!1),$(!1),E(!1),S()},[S]);const I=i.useCallback(async()=>{const M=!o;l(M);try{await mo({autoMerge:M},e)}catch{l(!M)}},[o,e]),F=i.useCallback(async()=>{const M=!c;d(M);try{await mo({globalPause:M,globalPauseReason:M?"manual":void 0},e)}catch{d(!M)}},[c,e]),G=i.useCallback(async()=>{const M=!u;m(M);try{await mo({enginePaused:M},e)}catch{m(!M)}},[u,e]),X=i.useCallback(async()=>{const M=!p;g(M);try{await mo({showQuickChatFAB:M},e)}catch{g(!M)}},[p,e]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,settingsLoaded:x,experimentalFeatures:k,insightsEnabled:R,roadmapEnabled:A,memoryEnabled:T,devServerEnabled:C,todosEnabled:O,toggleAutoMerge:I,toggleGlobalPause:F,toggleEnginePause:G,toggleShowQuickChatFAB:X,refresh:S}}function aD(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(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(u.current)return;u.current=!0,Aa(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 rD(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{As().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 Cn({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 Cn({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 oD({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;$r().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return ra().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Fa()?l=!0:!u&&!Fa()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Ys("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(Ys("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Dp="kb-update-banner-dismissed";function lD(){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(Dp)==="true";u(h);let f=!1;return cw().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(Dp,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const cD=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function dD(e){return e!==null&&cD.includes(e)}function uD(e){return e!==null&&/^plugin:[^:]+:.+$/u.test(e)}function Lp(e){return dD(e)||uD(e)}function mD(e){return e==="devserver"?"dev-server":e}function hD(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 x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[f,p]=i.useState(()=>{const x=Gn("kb-dashboard-task-view");return Lp(x)?x:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const x=Gn("kb-dashboard-task-view",r?.id);if(Lp(x)){const y=!g.current&&x==="devserver";p(y?"devserver":mD(x))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{us("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 x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,a,r,l,c]);const b=i.useCallback(x=>{p(x)},[]),v=i.useCallback(()=>{const x=["dark","light","system"],y=x.indexOf(d),k=x[(y+1)%x.length];u(k)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}const zp=new Map,pD=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=zp.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 FN(e);if(u)return;zp.set(d,{views:f,expiresAt:Date.now()+pD}),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 gD({taskView:e,context:n}){const s=c1(e);if(!s)return null;const a=d1(s.pluginId,s.viewId);return a?t.jsx(a,{context:n}):t.jsx(t.Fragment,{children:u1({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(P=>{n(P),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),b=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),x=i.useCallback(P=>{h(),n(P),a("project"),d(`Project ${P.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),k=i.useCallback(async P=>{try{await xj(P.id),d(`Project ${P.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${P.name}`,"error")}},[d,o]),N=i.useCallback(async P=>{try{await vj(P.id),d(`Project ${P.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${P.name}`,"error")}},[d,o]),R=i.useCallback(async P=>{try{await lf(P.id),d(`Project ${P.name} removed`,"success"),r?.id===P.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${P.name}`,"error")}},[r,s,a,d,o]),w=i.useCallback(async P=>{try{await l(P)}catch{d("Failed to update favorites","error")}},[l,d]),A=i.useCallback(async P=>{try{await c(P)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:y,handlePauseProject:k,handleResumeProject:N,handleRemoveProject:R,handleToggleFavorite:w,handleToggleModelFavorite:A}}function xD(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 vD(e){return Nl("/health",{nodeId:e})}async function yD(e){return Nl("/projects",{nodeId:e})}async function wD(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Nl(`/tasks?${a.toString()}`,{nodeId:e})}async function kD(e,n){return Nl(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function O6(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function F6(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function U6(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function B6(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function jD(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),b=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const x=new AbortController;g.current=x,h(!0),p(null);try{const y=[vD(e),yD(e)];s&&(y.push(wD(e,s,a)),y.push(kD(e,s)));const k=await Promise.allSettled(y);if(x.signal.aborted)return;const N=k[0],R=k[1];if(N.status==="rejected"){p(`Failed to fetch node health: ${N.reason}`),h(!1);return}if(u(N.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&k[2]){const w=k[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.value)}h(!1)}catch(y){x.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(b(),()=>{g.current?.abort()}),[b]);const v=i.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function ND(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 li(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 SD="fusion-dashboard-current-node",_b=i.createContext(null);function CD({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 ra();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(SD);if(g){const b=JSON.parse(g);b?.id&&b?.type==="remote"&&(l.current=b.id,await Cn({dashboardCurrentNodeId:b.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,Cn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Cn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Cn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(_b.Provider,{value:u,children:e})}function ED(){const e=i.useContext(_b);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function MD({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&&(Ly(l),window.location.reload())},[n]),o=i.useCallback(()=>{zy(),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 _D=200,AD=i.lazy(()=>kn(()=>import("./AgentsView-8Xo-c04o.js"),__vite__mapDeps([19,1,0,2,3,20,11,4,5,21])).then(e=>({default:e.AgentsView}))),PD=i.lazy(()=>kn(()=>import("./DocumentsView-CcJNmH06.js"),__vite__mapDeps([22,1,4,5,23])).then(e=>({default:e.DocumentsView}))),RD=i.lazy(()=>kn(()=>import("./InsightsView-B0DKRIYV.js"),__vite__mapDeps([24,1,17,4,5,25])).then(e=>({default:e.InsightsView}))),TD=i.lazy(()=>kn(()=>import("./ResearchView-s3SrjNBm.js"),__vite__mapDeps([26,1,4,5,27])).then(e=>({default:e.ResearchView}))),ID=i.lazy(()=>kn(()=>import("./NodesView-BqtHfXsl.js"),__vite__mapDeps([28,1,20,4,5,29])).then(e=>({default:e.NodesView}))),$D=i.lazy(()=>kn(()=>import("./ChatView-CjgOh8x7.js"),__vite__mapDeps([30,1,4,5])).then(e=>({default:e.ChatView}))),DD=i.lazy(()=>kn(()=>import("./RoadmapsView-BlbAZTdi.js"),__vite__mapDeps([31,1,4,5,32])).then(e=>({default:e.RoadmapsView}))),LD=i.lazy(()=>kn(()=>import("./SkillsView-CS4ONN3D.js"),__vite__mapDeps([33,1,4,5,34])).then(e=>({default:e.SkillsView}))),zD=i.lazy(()=>kn(()=>import("./MemoryView-DDbr1DaJ.js"),__vite__mapDeps([35,1,15,16,4,5,36])).then(e=>({default:e.MemoryView}))),OD=i.lazy(()=>kn(()=>import("./DevServerView-BOPrzi-j.js"),__vite__mapDeps([37,1,4,5,38])).then(e=>({default:e.DevServerView})));i.lazy(()=>kn(()=>Promise.resolve().then(()=>tb),void 0).then(e=>({default:e.TodoView})));function FD(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{kn(()=>import("./AgentsView-8Xo-c04o.js"),__vite__mapDeps([19,1,0,2,3,20,11,4,5,21])),kn(()=>import("./DocumentsView-CcJNmH06.js"),__vite__mapDeps([22,1,4,5,23])),kn(()=>import("./InsightsView-B0DKRIYV.js"),__vite__mapDeps([24,1,17,4,5,25])),kn(()=>import("./ResearchView-s3SrjNBm.js"),__vite__mapDeps([26,1,4,5,27])),kn(()=>import("./NodesView-BqtHfXsl.js"),__vite__mapDeps([28,1,20,4,5,29])),kn(()=>import("./ChatView-CjgOh8x7.js"),__vite__mapDeps([30,1,4,5])),kn(()=>import("./RoadmapsView-BlbAZTdi.js"),__vite__mapDeps([31,1,4,5,32])),kn(()=>import("./SkillsView-CS4ONN3D.js"),__vite__mapDeps([33,1,4,5,34])),kn(()=>import("./MemoryView-DDbr1DaJ.js"),__vite__mapDeps([35,1,15,16,4,5,36])),kn(()=>import("./DevServerView-BOPrzi-j.js"),__vite__mapDeps([37,1,4,5,38])),kn(()=>Promise.resolve().then(()=>tb),void 0)})}const Kc="kb-setup-warning-dismissed";function UD(){const{toasts:e,addToast:n,removeToast:s}=J$(),a=typeof window<"u"&&!!window.electronAPI;i.useEffect(()=>{FD()},[]);const{projects:r,loading:o,error:l,refresh:c}=q$(),{nodes:d}=El(),{currentNode:u,currentNodeId:m,isRemote:h,setCurrentNode:f,clearCurrentNode:p}=ED(),{currentProject:g,setCurrentProject:b,clearCurrentProject:v,loading:x}=K$(r,{nodeId:m}),{hasAiProvider:y,hasGithub:k,loading:N,hasWarnings:R}=cb(g?.id),{updateAvailable:w,latestVersion:A,currentVersion:P,dismissed:T,dismiss:_}=lD();i.useEffect(()=>{if(m&&!u&&d.length>0){const Be=d.find(ft=>ft.id===m);if(Be){f(Be);return}}m&&d.length>0&&(d.some(ft=>ft.id===m)||p())},[m,u,d,f,p]);const[C,$]=i.useState(""),O=jD(m,{projectId:g?.id,searchQuery:C||void 0});ND(m);const E=h&&O.projects.length>0?O.projects:r,{themeMode:S,colorTheme:I,dashboardFontScalePct:F,setThemeMode:G,setColorTheme:X,setDashboardFontScalePct:M}=nD(),{sessions:z,generating:L,needsInput:j,planningSessions:H,dismissSession:Q}=D$(g?.id),de=z.filter(Be=>Be.status==="awaiting_input"||Be.status==="error"),pe=O$(),B=sD({projectId:g?.id,planningSessions:H}),{viewMode:ve,setViewMode:U,taskView:se,handleChangeTaskView:ee}=hD({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:g,projectsLength:r.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:S,setThemeMode:G}),{views:ie}=fD(g?.id),te=i.useCallback(Be=>{Be==="missions"&&(Dt(void 0),It(void 0),Ft(void 0)),ee(Be)},[ee]),xe=se==="board"||se==="list",{tasks:ne,createTask:_e,moveTask:Ne,pauseTask:Se,deleteTask:He,mergeTask:Ye,retryTask:Oe,resetTask:ke,updateTask:De,duplicateTask:re,archiveTask:oe,unarchiveTask:we,archiveAllDone:Z,loadArchivedTasks:qe,ingestCreatedTasks:Qe,lastFetchTimeMs:ge}=U$({...g?{projectId:g.id}:{},searchQuery:C||void 0,sseEnabled:xe}),[Ue,Xe]=i.useState(!1),[wt,ye]=i.useState(0),le=i.useRef(performance.now()),Te=i.useRef(!1),be=i.useRef(!1),Le=i.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);i.useEffect(()=>{if(!o&&!Te.current){Te.current=!0;const Be=`projects loaded at ${Math.round(performance.now()-le.current)}ms from mount`;console.log(`[App] ${Be}`),Cr("[App]",Be)}if(!x&&!be.current){be.current=!0;const Be=`current-project resolved at ${Math.round(performance.now()-le.current)}ms from mount`;console.log(`[App] ${Be}`),Cr("[App]",Be)}},[o,x]),i.useEffect(()=>{if(Ue||o||x)return;const Be=performance.now(),ft=window.setTimeout(()=>{const mn=`dashboard ready at ${Math.round(performance.now()-le.current)}ms from mount (settle delay=${Math.round(performance.now()-Be)}ms)`;console.log(`[App] ${mn}`),Cr("[App]",mn),Xe(!0)},_D);return()=>{window.clearTimeout(ft)}},[Ue,o,x]);const nt=la()==="mobile",{keyboardOpen:mt}=yb({enabled:nt}),Ie=nt&&mt,[ze,st]=i.useState(0),yt=i.useCallback(()=>{hf(g?.id).then(Be=>{st(Be.unreadCount)}).catch(Be=>{console.warn("[App] Failed to fetch mailbox unread count:",Be)})},[g?.id]);i.useEffect(()=>{yt();const Be=new URLSearchParams;g?.id&&Be.set("projectId",g.id);const ft=Be.size>0?`?${Be.toString()}`:"";return li(`/api/events${ft}`,{events:{"message:sent":yt,"message:received":yt,"message:read":yt,"message:deleted":yt}})},[g?.id,yt]);const[Re,kt]=i.useState(!1),[Et,jt]=i.useState(!1),[Rt,Dt]=i.useState(void 0),[Tt,It]=i.useState(void 0),[Ut,Ft]=i.useState(void 0),[Jt,Vt]=i.useState(!1),[Yt,Kt]=i.useState(!1),[qt,Bt]=i.useState(()=>Gn(Kc,g?.id)==="true");i.useEffect(()=>{Bt(Gn(Kc,g?.id)==="true")},[g?.id]),i.useEffect(()=>{const Be=()=>{Kt(!0)};return window.addEventListener(ad,Be),()=>{window.removeEventListener(ad,Be)}},[]);const Xt=i.useCallback(()=>{us(Kc,"true",g?.id),Bt(!0)},[g?.id]),{maxConcurrent:an,autoMerge:Qt,globalPaused:fe,enginePaused:Fe,taskStuckTimeoutMs:ae,showQuickChatFAB:Pe,prAuthAvailable:Ae,settingsLoaded:W,experimentalFeatures:je,insightsEnabled:ce,roadmapEnabled:$e,memoryEnabled:it,devServerEnabled:vt,todosEnabled:tn,toggleAutoMerge:Pt,toggleGlobalPause:Lt,toggleEnginePause:zt,refresh:yn}=iD(g?.id),ue=je.skillsView===!0,lt=je.nodesView===!0,ut=je.researchView===!0,dt=je.agentOnboarding===!0,at=!0;i.useEffect(()=>{W&&(se==="skills"&&!ue&&ee("board"),se==="insights"&&!ce&&ee("board"),se==="roadmaps"&&!$e&&ee("board"),se==="memory"&&!it&&ee("board"),(se==="devserver"||se==="dev-server")&&!vt&&ee("board"),se==="research"&&!ut&&ee("board"))},[se,W,ue,ce,$e,ee,at,it,vt,ut]),i.useEffect(()=>{Re&&!lt&&kt(!1)},[Re,lt]);const{availableModels:St,favoriteProviders:he,favoriteModels:ct,toggleFavoriteProvider:Zt,toggleFavoriteModel:Sn}=rD();oD({projectId:g?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:In,handleViewAllProjects:Hn,handleOpenSettings:Xn,handleAddProject:jn,handleSetupComplete:Pn,handleModelOnboardingComplete:rs,handlePauseProject:os,handleResumeProject:cn,handleRemoveProject:$n,handleToggleFavorite:nn,handleToggleModelFavorite:_t}=bD({setCurrentProject:b,clearCurrentProject:v,setViewMode:U,currentProject:g,refreshProjects:c,toggleFavoriteProvider:Zt,toggleFavoriteModel:Sn,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:K}=aD({projectId:g?.id,projects:r,projectsLoading:o,currentProject:g,setCurrentProject:b,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),{handleBoardQuickCreate:Ve,handleModalCreate:pt,handlePlanningTaskCreated:ht,handlePlanningTasksCreated:Nt,handleSubtaskTasksCreated:Mt,handleGitHubImport:$t}=xD({createTask:_e,ingestCreatedTasks:Qe,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),wn=i.useCallback((Be,ft)=>{if(ft==="changes"){B.openDetailWithChangesTab(Be);return}B.openDetailTask(Be,ft)},[B]),ls=i.useCallback(async Be=>{try{const ft=await Aa(Be,g?.id);B.openDetailTask(ft,"logs")}catch(ft){n(`Failed to open task logs: ${ft.message}`,"error")}},[B,g?.id,n]),[Cs,$s]=i.useState([]);i.useEffect(()=>{let Be=!1;return Jr(g?.id).then(ft=>{Be||$s(ft)}).catch(()=>{Be||$s([])}),()=>{Be=!0}},[g?.id]);const ps=i.useMemo(()=>new Map(Cs.map(Be=>[Be.id,Be.name])),[Cs]),Vs=i.useCallback(()=>{lt&&kt(Be=>!Be)},[lt]),dn=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),yi=i.useCallback(async()=>{jt(!0);try{await c()}finally{jt(!1)}},[c]),me=i.useCallback(Be=>{It(Be),Dt(void 0),ee("missions")},[ee]),We=i.useCallback(Be=>{Be.type==="planning"?B.openPlanningWithSession(Be.id):Be.type==="subtask"?B.openSubtaskWithSession(Be.id):Be.type==="mission_interview"?(It(void 0),Dt(Be.id),Ft(void 0),ee("missions")):(Be.type==="milestone_interview"||Be.type==="slice_interview")&&(Dt(void 0),It(void 0),Ft(Be.id),ee("missions"))},[ee,B]),ot=i.useCallback(()=>{},[]),sn=i.useCallback(()=>{},[]),Dn=!o&&!x&&r.length===0&&!g&&!!l,Y=()=>Dn?t.jsx(z4,{errorMessage:l??"Failed to fetch projects",isRetrying:Et,onRetry:yi}):Re?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(ID,{addToast:n,onClose:()=>kt(!1)})})})}):ve==="overview"?t.jsx(ys,{children:t.jsx(LP,{projects:r,loading:o,onSelectProject:In,onAddProject:jn,onPauseProject:os,onResumeProject:cn,onRemoveProject:$n,nodes:d})}):se.startsWith("plugin:")?t.jsx(ys,{children:t.jsx(gD,{taskView:se,context:{projectId:g?.id,tasks:h&&O.tasks.length>0?O.tasks:ne,workflowSteps:Cs,openTaskDetail:(Be,ft)=>B.openDetailTask(Be,ft),renderTaskCard:Be=>t.jsx(Lr,{task:Be,projectId:g?.id,onOpenDetail:ft=>B.openDetailTask(ft),addToast:n,workflowStepNameLookup:ps})}})}):se==="skills"?!W||!ue?null:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(LD,{addToast:n,projectId:g?.id,onClose:()=>ee("board")})})}):se==="chat"?t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx($D,{addToast:n,projectId:g?.id})})}):se==="mailbox"?t.jsx(ys,{children:t.jsx(wR,{projectId:g?.id,addToast:n,onUnreadCountChange:st})}):se==="roadmaps"?!W||!$e?null:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(DD,{addToast:n,projectId:g?.id})})}):se==="missions"?t.jsx(ys,{children:t.jsx(bR,{isInline:!0,isOpen:!0,onClose:()=>{It(void 0),Dt(void 0),Ft(void 0),ee("board")},addToast:n,projectId:g?.id,onSelectTask:Be=>{const ft=ne.find(mn=>mn.id===Be);ft&&B.openDetailTask(ft)},availableTasks:ne.map(Be=>({id:Be.id,title:Be.title})),resumeSessionId:Rt,targetMissionId:Tt,milestoneSliceResumeSessionId:Ut,onMilestoneSliceResumeFetchError:()=>Ft(void 0)})}):se==="agents"&&at?t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(AD,{addToast:n,projectId:g?.id,onOpenTaskLogs:ls,agentOnboardingEnabled:dt})})}):se==="documents"?t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(PD,{projectId:g?.id,addToast:n,onOpenDetail:B.openDetailTask})})}):se==="insights"?!W||!ce?null:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(RD,{projectId:g?.id,addToast:n,onClose:()=>ee("board")})})}):se==="research"?!W||!ut?null:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(TD,{projectId:g?.id,addToast:n,onOpenSettings:Be=>B.openSettings(Be),readinessVersion:wt})})}):se==="memory"?!W||!it?null:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(zD,{addToast:n,projectId:g?.id})})}):se==="devserver"||se==="dev-server"?!W||!vt?null:t.jsx(ys,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(OD,{addToast:n,projectId:g?.id})})}):se==="board"?t.jsx(ys,{children:t.jsx(HS,{tasks:h&&O.tasks.length>0?O.tasks:ne,projectId:g?.id,maxConcurrent:an,onMoveTask:Ne,onPauseTask:Se,onOpenDetail:B.openDetailTask,addToast:n,onQuickCreate:Ve,onNewTask:B.openNewTask,onPlanningMode:B.openPlanningWithInitialPlan,onSubtaskBreakdown:B.openSubtaskBreakdown,autoMerge:Qt,onToggleAutoMerge:Pt,globalPaused:fe,onUpdateTask:De,onRetryTask:Oe,onArchiveTask:oe,onUnarchiveTask:we,onDeleteTask:He,onArchiveAllDone:Z,onLoadArchivedTasks:qe,searchQuery:C,availableModels:St,onOpenDetailWithTab:wn,favoriteProviders:he,favoriteModels:ct,onToggleFavorite:nn,onToggleModelFavorite:_t,taskStuckTimeoutMs:ae,onOpenMission:me,lastFetchTimeMs:ge})}):t.jsx(ys,{children:t.jsx(EP,{tasks:h&&O.tasks.length>0?O.tasks:ne,projectId:g?.id,onMoveTask:Ne,onRetryTask:Oe,onDeleteTask:He,onMergeTask:Ye,onResetTask:ke,onDuplicateTask:re,onOpenDetail:B.openDetailTask,addToast:n,globalPaused:fe,onNewTask:B.openNewTask,onQuickCreate:Ve,onPlanningMode:B.openPlanningWithInitialPlan,onSubtaskBreakdown:B.openSubtaskBreakdown,availableModels:St,favoriteProviders:he,favoriteModels:ct,onToggleFavorite:nn,onToggleModelFavorite:_t,taskStuckTimeoutMs:ae,searchQuery:C,lastFetchTimeMs:ge,prAuthAvailable:Ae})});if(!Ue)return t.jsxs(t.Fragment,{children:[t.jsx(F4,{stage:Le}),t.jsx(fb,{toasts:e,onRemove:s})]});const Ee=!B.modelOnboardingOpen&&l4(),rt=!B.modelOnboardingOpen&&!Ee&&Fa()&&!ub();return t.jsxs(t.Fragment,{children:[t.jsx(f1,{isElectron:a,onOpenSettings:Xn,onOpenGitHubImport:B.openGitHubImport,onOpenPlanning:B.openPlanning,onResumePlanning:B.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:B.openUsage,onOpenActivityLog:B.openActivityLog,onOpenSystemStats:B.openSystemStats,onOpenMailbox:()=>te("mailbox"),mailboxUnreadCount:ze,onOpenSchedules:B.openSchedules,onOpenGitManager:B.openGitManager,onOpenNodes:Vs,showNodesButton:lt,onOpenWorkflowSteps:B.openWorkflowSteps,onOpenScripts:B.openScripts,onRunScript:B.runScript,onToggleTerminal:B.toggleTerminal,onOpenFiles:B.openFiles,filesOpen:B.filesOpen,onOpenTodos:B.openTodos,todosOpen:B.todosOpen,todosEnabled:tn,globalPaused:fe,enginePaused:Fe,onToggleGlobalPause:Lt,onToggleEnginePause:zt,view:se,onChangeView:ve==="project"&&g?te:void 0,showSkillsTab:ue,showAgentsTab:at,searchQuery:C,onSearchChange:$,projects:E,currentProject:g,onSelectProject:In,onViewAllProjects:Hn,projectId:g?.id,mobileNavEnabled:nt,availableNodes:d,currentNode:u,onSelectNode:Be=>{Be===null?p():f(Be)},isRemote:h,experimentalFeatures:{insights:ce,roadmap:$e,memoryView:it,devServer:vt,devServerView:vt,researchView:ut},pluginDashboardViews:ie}),ve==="project"&&g&&!Re&&se!=="missions"&&!B.isPlanningOpen&&!pe&&t.jsx(t$,{sessions:de,onResumeSession:We,onDismissSession:ot,onDismissAll:sn}),ve==="project"&&g&&t.jsx(i$,{onOpenSettings:()=>B.openSettings("general")}),ve==="project"&&g&&Ee&&t.jsx(r$,{onResume:B.openModelOnboarding}),ve==="project"&&g&&rt&&t.jsx(o$,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Be=>B.openSettings(Be)}),ve==="project"&&g&&w&&A&&P&&!T&&t.jsx(a$,{latestVersion:A,currentVersion:P,onDismiss:_}),ve==="project"&&g&&!N&&R&&!qt&&t.jsx(db,{hasAiProvider:y,hasGithub:k,onDismiss:Xt}),t.jsx("div",{className:`project-content${ve==="project"&&g?" project-content--with-footer":""}${nt&&!Ie?" project-content--with-mobile-nav":""}`,children:Y()}),ve==="project"&&g&&!Re&&t.jsx(Y4,{tasks:h&&O.tasks.length>0?O.tasks:ne,projectId:g.id,taskStuckTimeoutMs:ae,backgroundSessions:z,backgroundGenerating:L,backgroundNeedsInput:j,onOpenBackgroundSession:We,onDismissBackgroundSession:Q,lastFetchTimeMs:ge,currentProjectPath:g.path,onOpenProjectDirectory:dn}),t.jsx(c$,{view:se,onChangeView:ve==="project"&&g?te:()=>{},footerVisible:ve==="project"&&!!g,modalOpen:B.anyModalOpen,keyboardOpen:Ie,onOpenSettings:Xn,onOpenActivityLog:B.openActivityLog,onOpenSystemStats:B.openSystemStats,onOpenMailbox:()=>te("mailbox"),onOpenNodes:Vs,mailboxUnreadCount:ze,onOpenGitManager:B.openGitManager,onOpenWorkflowSteps:B.openWorkflowSteps,onOpenSchedules:B.openSchedules,onOpenScripts:B.openScripts,onToggleTerminal:B.toggleTerminal,onOpenFiles:B.openFiles,onOpenTodos:B.openTodos,todosOpen:B.todosOpen,onOpenGitHubImport:B.openGitHubImport,onOpenPlanning:B.openPlanning,onResumePlanning:B.resumePlanning,activePlanningSessionCount:H.length,onOpenUsage:()=>B.openUsage(null),onViewAllProjects:Hn,onRunScript:B.runScript,projectId:g?.id,showSkillsTab:ue,experimentalFeatures:{insights:ce,roadmap:$e,memoryView:it,devServer:vt,devServerView:vt,todoView:tn,researchView:ut,nodesView:lt},pluginDashboardViews:ie}),ve==="project"&&g&&se!=="chat"&&se!=="mailbox"&&se!=="insights"&&se!=="devserver"&&se!=="dev-server"&&!se.startsWith("plugin:")&&t.jsx($$,{projectId:g.id,addToast:n,showFAB:Pe,open:Jt,onOpenChange:Vt,favoriteProviders:he,favoriteModels:ct,onToggleFavorite:nn,onToggleModelFavorite:_t}),t.jsx(L4,{projectId:g?.id,tasks:ne,projects:r,currentProject:g,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:jn,handleSetupComplete:Pn,handleModelOnboardingComplete:rs},taskHandlers:{handleModalCreate:pt,handlePlanningTaskCreated:ht,handlePlanningTasksCreated:Nt,handleSubtaskTasksCreated:Mt,handleGitHubImport:$t},taskOperations:{moveTask:Ne,deleteTask:He,mergeTask:Ye,retryTask:Oe,resetTask:ke,duplicateTask:re},deepLink:{handleDetailClose:K},settings:{prAuthAvailable:Ae,themeMode:S,colorTheme:I,dashboardFontScalePct:F,setThemeMode:G,setColorTheme:X,setDashboardFontScalePct:M},onSettingsClose:()=>{B.closeSettings(),ye(Be=>Be+1),yn()},onReopenOnboarding:()=>{B.closeSettings(),B.openModelOnboarding()}}),t.jsx(MD,{open:Yt})]})}function BD(){return t.jsx(G$,{children:t.jsx(CD,{children:t.jsx(_1,{children:t.jsx(UD,{})})})})}function Ab(e){e.postMessage({type:"SKIP_WAITING"})}function Op(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&Ab(e)})}function HD(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,$d("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&Ab(n.waiting),n.installing&&Op(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&Op(s)})}).catch(n=>{console.log("SW registration failed:",n)})}Vy();Ay();Pb.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(Py,{children:t.jsx(BD,{})})}));HD();export{VI as $,Fs as A,Mn as B,Tn as C,Me as D,C1 as E,Li as F,fl as G,gz as H,ed as I,xn as J,Wo as K,bt as L,L6 as M,zv as N,_n as O,Fn as P,Uc as Q,Qn as R,Si as S,wl as T,On as U,ii as V,vn as W,Wt as X,OI as Y,Kn as Z,hl as _,kz as a,yb as a$,rj as a0,zI as a1,oj as a2,hz as a3,lj as a4,kn as a5,ML as a6,_L as a7,hk as a8,Id as a9,Gy as aA,$r as aB,U6 as aC,O6 as aD,F6 as aE,B6 as aF,Tr as aG,ry as aH,Sr as aI,zs as aJ,Qv as aK,Sx as aL,vs as aM,Qp as aN,Ez as aO,Mz as aP,El as aQ,q$ as aR,Ou as aS,Fu as aT,Ta as aU,HN as aV,g6 as aW,b6 as aX,qN as aY,VN as aZ,g$ as a_,Ba as aa,Ua as ab,gi as ac,bi as ad,rn as ae,ri as af,x6 as ag,w6 as ah,y6 as ai,v6 as aj,k6 as ak,ms as al,Ts as am,by as an,oi as ao,Ax as ap,Ur as aq,Mi as ar,j6 as as,S6 as at,A6 as au,_6 as av,M6 as aw,E6 as ax,C6 as ay,N6 as az,yz as b,yl as b$,UN as b0,Jp as b1,d$ as b2,p$ as b3,Yi as b4,Wp as b5,gu as b6,Ci as b7,Rz as b8,Iz as b9,vL as bA,fL as bB,mL as bC,hL as bD,pL as bE,uL as bF,dL as bG,aL as bH,gL as bI,kT as bJ,JL as bK,GL as bL,tz as bM,KL as bN,YL as bO,QL as bP,XL as bQ,ZL as bR,Lk as bS,ez as bT,Ld as bU,Ik as bV,$k as bW,Dk as bX,Tk as bY,WL as bZ,Wr as b_,Tz as ba,$z as bb,Dz as bc,Lz as bd,zz as be,Oz as bf,Fz as bg,Uz as bh,Bz as bi,Hz as bj,qz as bk,Vz as bl,Kz as bm,Gz as bn,Wz as bo,Wn as bp,bl as bq,Zi as br,p6 as bs,h6 as bt,f6 as bu,lL as bv,oL as bw,rL as bx,cL as by,xL as bz,Ze as c,ZD as c$,iy as c0,Ma as c1,_a as c2,pj as c3,Ly as c4,zy as c5,kw as c6,jw as c7,c6 as c8,PL as c9,GD as cA,YD as cB,iL as cC,sL as cD,Fw as cE,Aw as cF,fi as cG,Rw as cH,Pw as cI,Tw as cJ,Iw as cK,jL as cL,Nz as cM,Sz as cN,Cz as cO,Ai as cP,R6 as cQ,T6 as cR,Pz as cS,QD as cT,Jc as cU,as as cV,yT as cW,KI as cX,JI as cY,Bc as cZ,Sl as c_,AL as ca,d6 as cb,RL as cc,FL as cd,LL as ce,TL as cf,zL as cg,IL as ch,OL as ci,$L as cj,DL as ck,Gb as cl,Ew as cm,UL as cn,Mw as co,BL as cp,Qs as cq,xi as cr,O$ as cs,lT as ct,yL as cu,Az as cv,WD as cw,KD as cx,gp as cy,jz as cz,As as d,SL as d$,JD as d0,eL as d1,XD as d2,tL as d3,nL as d4,na as d5,z6 as d6,k1 as d7,Cl as d8,I6 as d9,lz as dA,oz as dB,LI as dC,pz as dD,CA as dE,az as dF,iz as dG,pk as dH,rz as dI,cz as dJ,s6 as dK,sz as dL,i6 as dM,Jv as dN,nd as dO,u6 as dP,o6 as dQ,r6 as dR,l6 as dS,a6 as dT,_z as dU,P6 as dV,NL as dW,wL as dX,kL as dY,CL as dZ,EL as d_,fh as da,$6 as db,D6 as dc,bL as dd,Jz as de,Qz as df,e6 as dg,Xz as dh,Yz as di,Zz as dj,t6 as dk,od as dl,wu as dm,dz as dn,mz as dp,Zc as dq,Hs as dr,lv as ds,n6 as dt,fz as du,qr as dv,uz as dw,xz as dx,bz as dy,Vp as dz,oa as e,Aa as f,wz as g,m6 as h,hs as i,aj as j,nz as k,Zs as l,VL as m,HL as n,qL as o,vz as p,la as q,FI as r,li as s,h$ as t,Cn as u,Gn as v,qs as w,us as x,jl as y,mo as z};